upleb.uk

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

summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorVonsek <45567075+Vonsek@users.noreply.github.com>2026-11-22 15:51:40 +0100
committerVonsek <45567075+Vonsek@users.noreply.github.com>2026-11-22 15:51:40 +0100
commitdf91c6624b69ee4e6c6eeca20ed68d331ed0e728 (patch)
tree323c88b9df89bf8abaa2b98d10808474ab675dc2
parentb40d8039a98f57b26bd05860febbabbe59b97873 (diff)
parent6a6704df1592e1dc4a3215ddf1423a78adb52045 (diff)
Merge main into test/valu-int-misc (#1492)
Conflicted files: runtime/test/shaders/check.py, scripts/run_gpu_tests.py AI-assisted.
-rw-r--r--.github/workflows/ci.yml7
-rw-r--r--.github/workflows/runtime.yml5
-rw-r--r--README.md10
-rw-r--r--docs/animation.md71
-rw-r--r--docs/audio.md22
-rw-r--r--docs/bvh.md15
-rw-r--r--docs/character_models.md14
-rw-r--r--docs/character_skeleton.md10
-rw-r--r--docs/d3d12_command_objects.md27
-rw-r--r--docs/d3d12_vulkan.md117
-rw-r--r--docs/design.md59
-rw-r--r--docs/fspx.md20
-rw-r--r--docs/gameinput.md36
-rw-r--r--docs/pipeline_check.md43
-rw-r--r--docs/rbf0.md8
-rw-r--r--docs/related_projects.md1
-rw-r--r--docs/rpf.md7
-rw-r--r--docs/runtime_imports.md10
-rw-r--r--docs/shader_validation.md138
-rw-r--r--docs/testing.md5
-rw-r--r--make_game.py44
-rw-r--r--runtime/CMakeLists.txt168
-rw-r--r--runtime/README.md11
-rw-r--r--runtime/shims/d3d12_com.cpp20
-rw-r--r--runtime/shims/d3d12_com.h6
-rw-r--r--runtime/shims/d3d12_vulkan_device.cpp328
-rw-r--r--runtime/shims/d3d12_xs_device.cpp188
-rw-r--r--runtime/shims/d3d12_xs_device.h32
-rw-r--r--runtime/shims/dxgi_com.cpp63
-rw-r--r--runtime/shims/file_system.cpp4
-rw-r--r--runtime/shims/gameinput.cpp96
-rw-r--r--runtime/shims/gameinput_abi.h42
-rw-r--r--runtime/shims/library_loader.cpp28
-rw-r--r--runtime/shims/process.cpp40
-rw-r--r--runtime/src/base_reservation.h139
-rw-r--r--runtime/src/main.cpp5
-rw-r--r--runtime/src/pe_loader.cpp8
-rw-r--r--runtime/src/resource_tiling.h25
-rw-r--r--runtime/src/retire_tickets.h7
-rw-r--r--runtime/src/shader_library.h11
-rw-r--r--runtime/src/subgroup_size.h152
-rw-r--r--runtime/src/vulkan_backend.h35
-rw-r--r--runtime/src/vulkan_bindless.h64
-rw-r--r--runtime/src/vulkan_depth24.h13
-rw-r--r--runtime/src/vulkan_present.h60
-rw-r--r--runtime/src/vulkan_replay.h193
-rw-r--r--runtime/src/vulkan_scratch.h13
-rw-r--r--runtime/src/xdxr_build.comp73
-rw-r--r--runtime/src/xdxr_build.h59
-rw-r--r--runtime/src/xdxr_build.inc7391
-rw-r--r--runtime/test/allocator_proxy_test.cpp382
-rw-r--r--runtime/test/bindless_sizing_test.cpp31
-rw-r--r--runtime/test/check_d3d12_trace.py5
-rw-r--r--runtime/test/check_vk_pipeline_cli.cmake33
-rw-r--r--runtime/test/d3d12_clear_test.cpp3
-rw-r--r--runtime/test/d3d12_compute_test.cpp182
-rw-r--r--runtime/test/d3d12_copy_compare.h25
-rw-r--r--runtime/test/d3d12_descriptor_test.cpp163
-rw-r--r--runtime/test/d3d12_draw_test.cpp136
-rw-r--r--runtime/test/d3d12_gcl8_test.cpp9
-rw-r--r--runtime/test/d3d12_m2_textured_test.cpp24
-rw-r--r--runtime/test/d3d12_present_test.cpp32
-rw-r--r--runtime/test/d3d12_queue_wait_test.cpp38
-rw-r--r--runtime/test/d3d12_set0_compute_test.cpp337
-rw-r--r--runtime/test/d3d12_subgroup_test.cpp672
-rw-r--r--runtime/test/d3d12_vulkan_device_test.cpp751
-rw-r--r--runtime/test/d3d12_xdxr_rt_test.cpp90
-rw-r--r--runtime/test/depth24_convert_test.cpp91
-rw-r--r--runtime/test/device_proxy_test.cpp41
-rw-r--r--runtime/test/dxgi_swapchain_test.cpp205
-rw-r--r--runtime/test/file_system_test.cpp11
-rw-r--r--runtime/test/fsr_dispatch_test.cpp4
-rw-r--r--runtime/test/gameinput_probe.cpp5
-rw-r--r--runtime/test/gameinput_test.cpp136
-rw-r--r--runtime/test/glsl/cs_set0_sample.comp77
-rw-r--r--runtime/test/glsl/cs_sg_probe.comp29
-rw-r--r--runtime/test/glsl/cs_user_data.comp14
-rw-r--r--runtime/test/glsl/ps_sg_probe.frag11
-rw-r--r--runtime/test/glsl/vs_sg_fullscreen.vert6
-rw-r--r--runtime/test/process_cmdline_test.cpp70
-rw-r--r--runtime/test/queue_proxy_test.cpp74
-rw-r--r--runtime/test/resource_tiling_test.cpp15
-rw-r--r--runtime/test/root_signature_oracle_test.cpp42
-rw-r--r--runtime/test/shader_library_corpus_test.cpp159
-rw-r--r--runtime/test/shader_library_test.cpp14
-rw-r--r--runtime/test/shaders/build.py4
-rw-r--r--runtime/test/shaders/check.py69
-rw-r--r--runtime/test/shaders/cs_fmt_sint32.asm90
-rw-r--r--runtime/test/shaders/cs_w32_sincos.asm60
-rw-r--r--runtime/test/shaders/ps_f16_pack_mods.asm19
-rw-r--r--runtime/test/shaders/ps_imgatomic.asm44
-rw-r--r--runtime/test/shaders/ps_m2_uoff.asm5
-rw-r--r--runtime/test/shaders/ps_scc_logic32.asm44
-rw-r--r--runtime/test/shaders/ps_scc_logic64.asm49
-rw-r--r--runtime/test/shaders/ps_w64x_readlane.asm27
-rw-r--r--runtime/test/subgroup_size_test.cpp256
-rw-r--r--runtime/test/vk_bc_zero_init_test.cpp388
-rw-r--r--runtime/test/vk_bindless_test.cpp179
-rw-r--r--runtime/test/vk_pipeline_check.cpp44
-rw-r--r--runtime/test/vk_presenter_sync_test.cpp42
-rw-r--r--runtime/test/vk_queue_query_sync_test.cpp351
-rw-r--r--runtime/test/vk_sync_validation_selftest.cpp93
-rw-r--r--runtime/test/vk_test_device.h15
-rw-r--r--runtime/test/vk_xdxr_build_test.cpp121
-rw-r--r--runtime/test/xgameruntime_test.cpp34
-rw-r--r--runtime/test/xs_proxy_mock_test.cpp93
-rw-r--r--scripts/build_runtime.ps16
-rw-r--r--scripts/run_gpu_tests.py40
-rw-r--r--scripts/run_wine_tests.py70
-rw-r--r--tests/semantic/README.md4
-rw-r--r--tests/semantic/fixtures/disasm/cs_fmt_sint32.s64
-rw-r--r--tests/semantic/fixtures/disasm/ps_f16_pack_mods.s9
-rw-r--r--tests/semantic/regen_fixtures.py3
-rw-r--r--tests/semantic/spirv_mini_interp.py34
-rw-r--r--tests/semantic/spirv_wave_interp.py16
-rw-r--r--tests/semantic/test_alu_bitop_folding.py159
-rw-r--r--tests/semantic/test_alu_dot4_i8.py138
-rw-r--r--tests/semantic/test_alu_min3_max3_med3_16.py537
-rw-r--r--tests/semantic/test_alu_sincos.py183
-rw-r--r--tests/semantic/test_alu_swaprel.py92
-rw-r--r--tests/semantic/test_buffer_oob_select.py53
-rw-r--r--tests/semantic/test_f16_interp_fallback.py46
-rw-r--r--tests/semantic/test_interp_merge_check.py78
-rw-r--r--tests/semantic/test_interp_p1lv_f16.py470
-rw-r--r--tests/semantic/test_lds_bitwise_b64.py83
-rw-r--r--tests/semantic/test_pack_b32_f16_mods.py136
-rw-r--r--tests/semantic/test_salu_cmov_b64.py247
-rw-r--r--tests/semantic/test_salu_movrels_lane_mask.py117
-rw-r--r--tests/semantic/test_scalar_alu_and_smem_folding.py193
-rw-r--r--tests/semantic/test_scalar_noop_waitcnt.py636
-rw-r--r--tests/semantic/test_valu_cvt_pk_u8_f32.py757
-rw-r--r--tests/semantic/test_valu_f32_class_rndne.py57
-rw-r--r--tests/semantic/test_valu_fma_mix.py66
-rw-r--r--tests/semantic/test_valu_fract_f16.py703
-rw-r--r--tests/semantic/test_valu_permlane16.py814
-rw-r--r--tests/semantic/test_valu_rcp_fdiv.py824
-rw-r--r--tests/semantic/test_value_semantics.py24
-rw-r--r--tests/semantic/test_vop3_const_mods.py13
-rw-r--r--tests/semantic/test_w64x_scalar_load_order.py133
-rw-r--r--tests/test_anim_rigs.py134
-rw-r--r--tests/test_awc_opus.py81
-rw-r--r--tests/test_build_runtime_fallback.py5
-rw-r--r--tests/test_calibrated_texture_extra.py2192
-rw-r--r--tests/test_cf_ref_edge_fixes.py294
-rw-r--r--tests/test_csv_line_endings.py70
-rw-r--r--tests/test_d3d12_xs_surface.py5
-rw-r--r--tests/test_f16_hw_words.py14
-rw-r--r--tests/test_f16_op_sel.py2
-rw-r--r--tests/test_f16_op_sel_values.py2
-rw-r--r--tests/test_fma_mix_probe.py11
-rw-r--r--tests/test_fspx_unpack.py18
-rw-r--r--tests/test_gamedata_index.py19
-rw-r--r--tests/test_hashdict.py26
-rw-r--r--tests/test_imhex_patterns.py170
-rw-r--r--tests/test_int_hw_probe.py119
-rw-r--r--tests/test_make_game_assets_pools.py2
-rw-r--r--tests/test_make_game_preflight.py21
-rw-r--r--tests/test_make_game_wave64.py54
-rw-r--r--tests/test_manifest.py53
-rw-r--r--tests/test_navmesh_index.py35
-rw-r--r--tests/test_opus_tags.py11
-rw-r--r--tests/test_pe_inspect.py28
-rw-r--r--tests/test_rdna2spirv_cli.py51
-rw-r--r--tests/test_run_gpu_tests.py44
-rw-r--r--tests/test_run_wine_tests.py68
-rw-r--r--tests/test_shader_checks.py27
-rw-r--r--tests/test_shader_link_check.py459
-rw-r--r--tests/test_spirv_gs_to_compute.py8
-rw-r--r--tests/test_spirv_metal_set0.py6
-rw-r--r--tests/test_spirv_metal_set0_extra.py1043
-rw-r--r--tests/test_story_index.py4
-rw-r--r--tests/test_tex_export.py76
-rw-r--r--tests/test_text_tables.py56
-rw-r--r--tests/test_values.py4
-rw-r--r--tests/test_vk_subgroup_info.py96
-rw-r--r--tests/test_world_index.py63
-rw-r--r--tools/anim_index.py2
-rw-r--r--tools/anim_rigs.py172
-rw-r--r--tools/awc_names.py3
-rw-r--r--tools/awc_opus.py43
-rw-r--r--tools/bink_index.py2
-rw-r--r--tools/bink_names.py2
-rw-r--r--tools/bvh_index.py2
-rw-r--r--tools/cf_ref.py25
-rw-r--r--tools/f32_fuzz.py11
-rw-r--r--tools/fspx_unpack.py6
-rw-r--r--tools/gamedata_index.py10
-rw-r--r--tools/gamedata_xml.py2
-rw-r--r--tools/hashdict.py15
-rw-r--r--tools/imhex/rbf0.hexpat96
-rw-r--r--tools/imhex/rpf9.hexpat32
-rw-r--r--tools/int_hw_probe.py767
-rw-r--r--tools/manifest.py34
-rw-r--r--tools/navmesh_decode.py2
-rw-r--r--tools/navmesh_index.py12
-rw-r--r--tools/opus_tags.py4
-rw-r--r--tools/page_index.py2
-rw-r--r--tools/pe_inspect.py4
-rw-r--r--tools/rbf0_index.py2
-rw-r--r--tools/rbf0_tree.py2
-rw-r--r--tools/rdna2spirv.py615
-rw-r--r--tools/restofworld_index.py2
-rw-r--r--tools/rsc8_audio.py2
-rw-r--r--tools/salu_diff.py7
-rw-r--r--tools/shader_link_check.py313
-rw-r--r--tools/spirv_gs_to_compute.py8
-rw-r--r--tools/spirv_interface.py522
-rw-r--r--tools/spirv_metal_set0.py5
-rw-r--r--tools/story_index.py2
-rw-r--r--tools/tex_export.py29
-rw-r--r--tools/text_tables.py87
-rw-r--r--tools/valu_fuzz.py4
-rw-r--r--tools/vk_subgroup_info.py55
-rw-r--r--tools/world_index.py27
-rw-r--r--tools/world_names.py2
-rw-r--r--tools/xdxr_bvh.py10
216 files changed, 26822 insertions, 4183 deletions
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 0154733a0..46156fef9 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -45,6 +45,13 @@ jobs:
45 } 45 }
46 "docs-only=$($docsOnly.ToString().ToLowerInvariant())" >> $env:GITHUB_OUTPUT 46 "docs-only=$($docsOnly.ToString().ToLowerInvariant())" >> $env:GITHUB_OUTPUT
47 exit 0 # GitHub's pwsh wrapper would otherwise forward git diff's status. 47 exit 0 # GitHub's pwsh wrapper would otherwise forward git diff's status.
48 # A docs-only diff still needs the tests that read those documents: the link checker walks every tracked
49 # Markdown file, and the i18n index checks docs/i18n/README.md. Both are standard library only.
50 - name: Check documentation when only documentation changed
51 if: steps.paths.outputs.docs-only == 'true'
52 run: |
53 python3 -I tests/test_docs_links.py
54 python3 -I tests/test_i18n_index.py
48 55
49 check: 56 check:
50 needs: change-scope 57 needs: change-scope
diff --git a/.github/workflows/runtime.yml b/.github/workflows/runtime.yml
index 8637d79dd..3faae7e06 100644
--- a/.github/workflows/runtime.yml
+++ b/.github/workflows/runtime.yml
@@ -107,7 +107,9 @@ jobs:
107 } 107 }
108 } 108 }
109 # For the wine job: the test list, the checkout it was made in, and the built executables, DLLs and synthetic 109 # For the wine job: the test list, the checkout it was made in, and the built executables, DLLs and synthetic
110 # occlusion test shaders. There is no game data on the runner. 110 # test shaders: the occlusion ones the tests are given as arguments, and generated/*.spv (compiled from
111 # runtime/test/glsl), which tests open through the absolute paths compiled into them. There is no game data
112 # on the runner.
111 - name: List tests for Wine 113 - name: List tests for Wine
112 shell: bash 114 shell: bash
113 run: | 115 run: |
@@ -124,6 +126,7 @@ jobs:
124 runtime/build/binary_occlusion.frag.spv 126 runtime/build/binary_occlusion.frag.spv
125 runtime/build/overlapping_occlusion.vert.spv 127 runtime/build/overlapping_occlusion.vert.spv
126 runtime/build/overlapping_occlusion.frag.spv 128 runtime/build/overlapping_occlusion.frag.spv
129 runtime/build/generated/*.spv
127 runtime/build/ctest.json 130 runtime/build/ctest.json
128 runtime/build/windows-root.txt 131 runtime/build/windows-root.txt
129 retention-days: 7 132 retention-days: 7
diff --git a/README.md b/README.md
index e41522899..a487c847f 100644
--- a/README.md
+++ b/README.md
@@ -44,9 +44,10 @@ work on booting can start as soon as one is available to a developer.
44 44
45| What | Status | 45| What | Status |
46|---|---| 46|---|---|
47| Booting, story mode, anything playable | ❌ No |
47| Finding and checking your copy (Xbox Series 1.0.2.1) | ✅ Works | 48| Finding and checking your copy (Xbox Series 1.0.2.1) | ✅ Works |
48| Shaders: carve, unpack native RDNA2 code, disassemble | ✅ All 26,503 | 49| Shaders: carve, unpack native RDNA2 code, disassemble | ✅ All 26,503 |
49| Shaders: RDNA2 → SPIR-V translation | ✅ **All 26,503 translated**: 2,236 VS, 12,101 PS, 2,689 CS, 9,282 mesh, 195 geometry, with a per-shader metadata index for pipeline creation. All 26,503 passed `spirv-val` in the [LLVM 23.1.5 Linux run at `c432cdc`](https://github.com/ItsNotRexed/Leonida/issues/644#issuecomment-7072972586). A [full-corpus run at `43d4703`](https://github.com/ItsNotRexed/Leonida/issues/881#issuecomment-7075507328) also validated all 26,503 after the SPIR-V ID-bound fix. ⚠️ 21,545 are wave64: exact on 64-wide subgroups (AMD). On 32-wide subgroups (NVIDIA, Intel), compute and mesh shaders are exact with wave64 emulation (`--wave64-emulate`, on by default there); cross-half wave ops in vertex, pixel and geometry shaders are still approximate | 50| Shaders: RDNA2 → SPIR-V translation | ✅ **All 26,503 translated**: 2,236 VS, 12,101 PS, 2,689 CS, 9,282 mesh, 195 geometry, with a per-shader metadata index for pipeline creation. All 26,503 passed `spirv-val` in the [LLVM 23.1.5 Linux run at `c432cdc`](https://github.com/ItsNotRexed/Leonida/issues/644#issuecomment-7072972586). A [full-corpus run at `43d4703`](https://github.com/ItsNotRexed/Leonida/issues/881#issuecomment-7075507328) also validated all 26,503 after `dcd8ecf` fixed the SPIR-V ID bound; the intervening `dedd75c` run was 26,501. ⚠️ 21,545 are wave64: exact on 64-wide subgroups (AMD). On 32-wide subgroups (NVIDIA, Intel), compute and mesh shaders are exact with wave64 emulation (`--wave64-emulate`, on by default there); cross-half wave ops in vertex, pixel and geometry shaders are still approximate |
50| Shader translator checked on a real GPU | ⚠️ The hand-written GPU tests (vertex fetch, texture sampling, exports, ALU ops, partial-register ops, barycentrics, wave-uniform branches, compute LDS/barriers/buffer stores, wave64 masks) have been run on more than 30 GPU and driver combinations, with results in [#166](https://github.com/ItsNotRexed/Leonida/issues/166): NVIDIA Turing, Ampere, Ada and Blackwell (Windows and Linux); AMD GCN3, RDNA1, RDNA2, RDNA3 and RDNA4 (Windows driver and RADV); Intel Gen9 (ANV); Apple M1 (MoltenVK, no geometry or mesh stages); and Mesa llvmpipe. Wave64 tests need 64-wide subgroups (AMD) or `LEONIDA_W64_EMULATE=1`. These are small test shaders: the game's own shaders are checked by `spirv-val` and by driver pipeline creation (`vk_pipeline_check`), not by their output | 51| Shader translator checked on a real GPU | ⚠️ The hand-written GPU tests (vertex fetch, texture sampling, exports, ALU ops, partial-register ops, barycentrics, wave-uniform branches, compute LDS/barriers/buffer stores, wave64 masks) have been run on more than 30 GPU and driver combinations, with results in [#166](https://github.com/ItsNotRexed/Leonida/issues/166): NVIDIA Turing, Ampere, Ada and Blackwell (Windows and Linux); AMD GCN3, RDNA1, RDNA2, RDNA3 and RDNA4 (Windows driver and RADV); Intel Gen9 (ANV); Apple M1 (MoltenVK, no geometry or mesh stages); and Mesa llvmpipe. Wave64 tests need 64-wide subgroups (AMD) or `LEONIDA_W64_EMULATE=1`. These are small test shaders: the game's own shaders are checked by `spirv-val` and by driver pipeline creation (`vk_pipeline_check`), not by their output |
51| Models (OBJ with real names, UVs, material references) | ✅ Exported. Not all layouts are decoded yet | 52| Models (OBJ with real names, UVs, material references) | ✅ Exported. Not all layouts are decoded yet |
52| Texture dictionaries and world texture pools (DDS) | ✅ Exported. Pool entries stored as BCPack are still skipped by the export; a clean-room decoder (`tools/bcpack.py`) rebuilds BC1, BC3, BC4, BC5, BC6H and BC7 (most BC6H/BC7 chunks need a local history table, which the repo does not ship), and is not wired into `rpf9dump` yet ([notes](docs/textures.md)) | 53| Texture dictionaries and world texture pools (DDS) | ✅ Exported. Pool entries stored as BCPack are still skipped by the export; a clean-room decoder (`tools/bcpack.py`) rebuilds BC1, BC3, BC4, BC5, BC6H and BC7 (most BC6H/BC7 chunks need a local history table, which the repo does not ship), and is not wired into `rpf9dump` yet ([notes](docs/textures.md)) |
@@ -54,7 +55,7 @@ work on booting can start as soon as one is available to a developer.
54| Music/radio config | ? Measured. **1,589** audio-config records with exact durations and AWC stream ids; station grouping and content-id lists; no per-track start offsets ([notes](docs/audio_config.md)) | 55| Music/radio config | ? Measured. **1,589** audio-config records with exact durations and AWC stream ids; station grouping and content-id lists; no per-track start offsets ([notes](docs/audio_config.md)) |
55| PE loader and import shims | ⚠️ Runs a stand-in executable end to end (`gta6rt --run`: CRT startup, statics, heap, files, threads, GDK imports through the shims, exit code back). Controllers through a GameInput shim on SDL3 (any controller SDL supports, rumble, DualSense trigger effects and lightbar; built when SDL3 is installed or with `-DLEONIDA_SDL3_FETCH=ON`, [notes](docs/gameinput.md)). `--trace-d3d12` logs every D3D12 call and its outcome for the first boot. Untested against the real executable | 56| PE loader and import shims | ⚠️ Runs a stand-in executable end to end (`gta6rt --run`: CRT startup, statics, heap, files, threads, GDK imports through the shims, exit code back). Controllers through a GameInput shim on SDL3 (any controller SDL supports, rumble, DualSense trigger effects and lightbar; built when SDL3 is installed or with `-DLEONIDA_SDL3_FETCH=ON`, [notes](docs/gameinput.md)). `--trace-d3d12` logs every D3D12 call and its outcome for the first boot. Untested against the real executable |
56| Xbox D3D12 → Vulkan | ⚠️ In progress. A Vulkan-backed device behind the Xbox-ABI proxy creates queues, command lists, fences, descriptor heaps, committed and reserved resources, render-target and depth views (3D targets included), texture views and samplers (2D, cube and 3D views, the depth and stencil planes of depth-stencil textures, packed formats such as B5G6R5, B4G4R4A4 and R9G9B9E5; they go into the bindless set), and query heaps. Barriers, clears, uploads, copies (BC included), colour resolves, predication, CPU-side texture reads and writes, and occlusion, timestamp and pipeline-statistics queries run on Vulkan, checked on one GPU. No buffer views, root signatures, pipelines, draws, placed resources, 1D textures or swapchain yet ([plan](docs/d3d12_vulkan.md)) | 57| Xbox D3D12 → Vulkan | ⚠️ In progress. A Vulkan-backed device behind the Xbox-ABI proxy creates queues, command lists, fences, descriptor heaps, committed and reserved resources, render-target and depth views (3D targets included), texture views and samplers (2D, cube and 3D views, the depth and stencil planes of depth-stencil textures, packed formats such as B5G6R5, B4G4R4A4 and R9G9B9E5; they go into the bindless set), and query heaps. Barriers, clears, uploads, copies (BC included), colour resolves, predication, CPU-side texture reads and writes, and occlusion, timestamp and pipeline-statistics queries run on Vulkan, checked on one GPU. No buffer views, root signatures, pipelines, draws, placed resources, 1D textures or swapchain yet ([plan](docs/d3d12_vulkan.md)) |
57| Booting, story mode, anything playable | ❌ No | 58
58 59
59## How to build 60## How to build
60 61
@@ -110,7 +111,10 @@ python -I make_game.py --wave64-emulate off # auto (default), on or o
110(see "Wave64 emulation" in [docs/design.md](docs/design.md)). NVIDIA and Intel GPUs have 32-wide subgroups and need 111(see "Wave64 emulation" in [docs/design.md](docs/design.md)). NVIDIA and Intel GPUs have 32-wide subgroups and need
111it. The default, `auto`, asks `vulkaninfo` (part of the Vulkan SDK) and turns it on unless every GPU reports 64-wide 112it. The default, `auto`, asks `vulkaninfo` (part of the Vulkan SDK) and turns it on unless every GPU reports 64-wide
112subgroups, or when it can't tell; it also turns it on when the GPU the runtime would use can't be made to run 113subgroups, or when it can't tell; it also turns it on when the GPU the runtime would use can't be made to run
113compute and mesh shaders 64-wide. The mode is saved next to the translated shaders, and changing it translates them 114compute and mesh shaders 64-wide. One exception keeps it off: when the runtime's GPU is an RDNA2 card or iGPU
115(RX 6000, Ryzen 6000/7000/9000 graphics) on AMD's Windows driver and runs wave64 natively, because that driver's
116shader compiler crashes on emulated LDS code (#857); an Intel iGPU next to an RX 6000 card would otherwise turn it on.
117The mode is saved next to the translated shaders, and changing it translates them
114again. With `auto`, a work folder that previously used emulation keeps it for later translations and retries, even if 118again. With `auto`, a work folder that previously used emulation keeps it for later translations and retries, even if
115the current GPU supports native wave64. Use `--wave64-emulate off` to translate it natively. 119the current GPU supports native wave64. Use `--wave64-emulate off` to translate it natively.
116 120
diff --git a/docs/animation.md b/docs/animation.md
index 8cf132bd3..7dc30c950 100644
--- a/docs/animation.md
+++ b/docs/animation.md
@@ -278,7 +278,8 @@ blob to its last byte and confirms the counts above: 9 descriptors, 28,962 eleme
278string values, 6,677 integer values and maximum element depth 6. The 1,126 string values are the `key` attributes 278string values, 6,677 integer values and maximum element depth 6. The 1,126 string values are the `key` attributes
279on the rig-set `Item` elements. Each of the 6,677 entry `Item` elements contains `Dictionary`, `Rig` and `Group` 279on the rig-set `Item` elements. Each of the 6,677 entry `Item` elements contains `Dictionary`, `Rig` and `Group`
280text children followed by a `Priority` integer. The record framing is consumed exactly; the numeric field 280text children followed by a `Priority` integer. The record framing is consumed exactly; the numeric field
281semantics and the rig-to-skeleton link remain unresolved. 281semantics remain unresolved. The `Dictionary` text names one of the four rig dictionaries and `Rig` is a key
282there; see [Rig dictionaries](#rig-dictionaries).
282 283
283Mapping to the name tables: 284Mapping to the name tables:
284 285
@@ -328,7 +329,8 @@ are in the same stream. It is not a rig → skeleton link for RBF0:
328- The four motionmatcher paths are not in the 2,298 `.clip`/`.anim`/`.motion` name-table paths. 329- The four motionmatcher paths are not in the 2,298 `.clip`/`.anim`/`.motion` name-table paths.
329 330
330So RBF0 gives rig-set → source → rig, and the motion matcher resources show how a clip can carry its own bone 331So RBF0 gives rig-set → source → rig, and the motion matcher resources show how a clip can carry its own bone
331table. The link from an RBF0 rig to that table is still missing; it is the main unresolved binding. 332table. The RBF0 rig itself resolves into a rig dictionary ([Rig dictionaries](#rig-dictionaries)); what it does not
333give is a whole skeleton for the clips.
332 334
333### Magics not found 335### Magics not found
334 336
@@ -380,7 +382,8 @@ as a clip dictionary; all 36 do, so no root is left unresolved. That recovery ru
380has been read from listed streams: a root whose page map is in such an unlisted last page stays unresolved ("page 382has been read from listed streams: a root whose page map is in such an unlisted last page stays unresolved ("page
381map not in the next stream"). No anim.rpf root has that layout. In `story000.rpf` 5 roots do, with the page map in 383map not in the next stream"). No anim.rpf root has that layout. In `story000.rpf` 5 roots do, with the page map in
382a 32- or 48-byte zlib tail, and none of the 5 is a clip dictionary once that tail is joined. Of the joined resources, 61,505 are clip 384a 32- or 48-byte zlib tail, and none of the 5 is a clip dictionary once that tail is joined. Of the joined resources, 61,505 are clip
383dictionaries. 4 have `RIG` plus a version at +0x70 instead of a pack array (rig dictionaries, not decoded here), and 385dictionaries. 4 have `RIG` plus a version at +0x70 instead of a pack array (rig dictionaries, [decoded
386below](#rig-dictionaries) by `tools/anim_rigs.py`), and
3841 has some other value there. Together the dictionaries use 87,234 listed streams plus the 36 unlisted pages 3871 has some other value there. Together the dictionaries use 87,234 listed streams plus the 36 unlisted pages
385(3,802,124,713 stored / 7,077,351,104 inflated bytes in the listed streams). By `anim_index.py` class those 388(3,802,124,713 stored / 7,077,351,104 inflated bytes in the listed streams). By `anim_index.py` class those
386streams are: zero-prefix 66,115, raw 20,845, name-table 273, skeleton-names 1. 389streams are: zero-prefix 66,115, raw 20,845, name-table 273, skeleton-names 1.
@@ -595,6 +598,68 @@ one of the 1,902 hashes anim.rpf refers to without having them.
595python -I tools/anim_clips.py <package>\pack\story000\story000.rpf <work>\story000-clips.json --jobs 20 598python -I tools/anim_clips.py <package>\pack\story000\story000.rpf <work>\story000-clips.json --jobs 20
596``` 599```
597 600
601## Rig dictionaries
602
603`tools/anim_rigs.py` reads the four `RIG` roots above (ASSET-20). Run on the 1.0.2.1 copy:
604
605```powershell
606python -I tools/anim_index.py <package>\anim.rpf <work>\anim-index.json --rigs <work>\rigs.json
607python -I tools/anim_rigs.py <package>\anim.rpf <work>\anim-rigs.json --rigs <work>\rigs.json
608```
609
610The output holds counts and one row per rig dictionary (offset, name, hash, entry count), no table items.
611
612**Layout.** The root is the clip dictionary's: `+0x38` atString name, `+0x48` atMap, `+0x68` `joaat32(name)` (4 of
6134), and at `+0x70` the bytes `RIG` and a version byte (2 in all four). Every map key has a zero high half (3,897 of
6143,897). Every map value has a pointer at `+0x20` to a **`RIG` block** (3,897 of 3,897): `RIG`, a version byte (2),
615a u32 length of what follows, then tables `{u32 kind hash; u32 size = 0xC + 8 × count; u32 count; u32 word}`, each
616followed by `count` 8-byte items `{u32 hash; u32 word}`, with other bytes between the tables. The other bytes and
617the item words are not mapped.
618
619**The four dictionaries are the four RBF0 sources.** Their names are the four source strings of the rig-set
620manager:
621
622| Name | Entries | Keys that are `joaat32` of an RBF0 rig |
623|---|---:|---:|
624| `canonical@legacy` | 22 | 16 |
625| `canonical@source` | 543 | 534 |
626| `generated@source` | 1,256 | 1,188 |
627| `pipelined@source` | 2,076 | 1,931 |
628
629These are the distinct-rig counts per source in [the RBF0 table above](#tail-rbf0-rig-set-manager). The other 228
630keys are not named by any RBF0 entry. **All 6,677 RBF0 entries resolve**: the entry's `Dictionary` text is the
631rig dictionary's name, and `joaat32(lowercase Rig path)` is a key in it (6,677 of 6,677; 0 in another dictionary,
6320 missing). So a rig set reaches its rigs' `RIG` blocks through rig-set → `{Dictionary, Rig}` → rig dictionary →
633key → `+0x20`.
634
635**Tables.** 6,606 tables are found in the 3,897 blocks. Four kind hashes hold all but 5 of them; the 5 are single
636hits whose "kind" is an f32 near 1.0 (`0x3f7f....`, `0x3f76....`) or a small integer, so they are float data that
637happens to fit the header rule. The kind names are not resolved:
638
639| Kind | Tables | Items | Items that are a clip track's bone hash |
640|---|---:|---:|---:|
641| `0x74d00508` | 2,642 | 13,210 | 0 |
642| `0x2316833f` | 2,437 | 118,853 | 91,559 |
643| `0xb688b77e` | 1,427 | 72,528 | 39,880 |
644| `0x5e25d3bf` | 95 | 4,416 | 0 |
645
646"A clip track's bone hash" means the hash is the bone of some track in the 191,042 decoded animations.
647
648**Rigs are not the clips' skeletons.** The clip side was measured with a local script over the same
649`anim_clips.py` parse: for each of the 52,752 clip dictionaries with bone tracks, the union of its
650`bonerotation`/`bonetranslation` bone hashes (mover track 0 left out).
651
652- Against the 596 hashed names of the shared humanoid skeleton ([character_skeleton.md](character_skeleton.md)),
653 44,359 dictionaries have at least 90% of their bones in it (16 have all of them).
654- Against the rigs (the items of the two bone-bearing kinds above), no rig set covers the clips of a humanoid
655 dictionary. Even the union over all the rigs of one rig set reaches 80% of a dictionary's bones for 11 of those
656 44,359. Only 4 dictionaries, all of objects, are covered completely by a rig set.
657
658So humanoid clips bind to the fragment skeleton, not to a `RIG` block. The rig tables look like per-rig bone or
659channel subsets (the RBF0 groups are `deformation`, `pose`, `identity`, `facial` and others); that reading is not
660measured. Still open in ASSET-20: the `0DRP` "2/3 packed clip streams" ([above](#packed-clip-streams)) and which
661model or skeleton each non-humanoid clip dictionary drives.
662
598## Readable, compressed and still opaque 663## Readable, compressed and still opaque
599 664
600- **Readable:** all 273 name tables (2,298 paths), the `0DRP` version/page count, 1,371 type-hash headers, 665- **Readable:** all 273 name tables (2,298 paths), the `0DRP` version/page count, 1,371 type-hash headers,
diff --git a/docs/audio.md b/docs/audio.md
index ffc6c66b4..481157c9d 100644
--- a/docs/audio.md
+++ b/docs/audio.md
@@ -88,15 +88,23 @@ The exporters ignore the remaining bytes.
88| `5` | XMA2 | `.xma.wav`, RIFF XMA2; ffmpeg decodes it to PCM WAV | 88| `5` | XMA2 | `.xma.wav`, RIFF XMA2; ffmpeg decodes it to PCM WAV |
89 89
90Opus data is stored in 2048-byte blocks. Each block is a sequence of `[u16 length][packet]`; a zero length pads 90Opus data is stored in 2048-byte blocks. Each block is a sequence of `[u16 length][packet]`; a zero length pads
91the rest of the block. The first 312 decoded samples are the encoder's lookahead (libopus at 48 kHz); the AWC does 91the rest of the block. The first 312 decoded samples are the encoder's lookahead. Measured on 30 real streams from
92not store it, so the exporter writes that value as `OpusHead` pre-skip and sets the last page's granule to 92four banks: decoded with pre-skip 0, the 5% and 10% attack points are at 312 samples (median 312; the 10% point
93`pre-skip + declared samples`. Decoders then drop the priming and stop at the real end instead of the padded final 93ranges 278..868, none near 1920), so 312 is the exporter's default. The AWC does not store the value, so
94frame. `--pre-skip` overrides the 312 default for a stream encoded with a different lookahead. 94`--pre-skip` overrides it for a stream encoded with a different lookahead.
95
96The exporter writes that value as `OpusHead` pre-skip and emits the EOS page at the first packet that reaches
97`pre-skip + declared samples`; later packets are encoder padding and are dropped. Clamping only the last page
98would let its granule go backwards when the trim point falls before that page starts, and decoders would keep the
99excess: a 27-packet real-libopus fixture decoded 24,960 frames for 24,000 declared, while the reaching-packet
100form decodes exactly 24,000. An oversized `--pre-skip` is clamped to the stream length so the final granule never
101falls below it.
95 102
96The format tag's sample count is already in 48 kHz frames even when its rate field is 32 kHz, and `+0x0C` is the 103The format tag's sample count is already in 48 kHz frames even when its rate field is 32 kHz, and `+0x0C` is the
97per-channel frame count (equal to `+0` for mono and half of it for stereo in all 7,451 measured streams). The 104per-channel frame count (equal to `+0` for mono and half of it for stereo in all 7,451 measured streams, 0.5% of
98exporter uses `+0x0C` and falls back to `+0 / channels` when a block leaves it zero; it never scales either count 105the 1.6M-stream corpus). The exporter uses `+0x0C` only when it agrees with `+0` (`frames * channels == samples`)
99by the rate field, because scaling a 32 kHz stream by 48000/32000 leaves up to a frame of padding untrimmed. 106and otherwise falls back to `+0 / channels`, so a malformed block cannot silently truncate audio. It never scales
107either count by the rate field, because scaling a 32 kHz stream by 48000/32000 leaves padding untrimmed.
100 108
101Codec `5` is not handled by `tools/awc_opus.py`. `rpf9dump xma` writes it as RIFF XMA2, and ffmpeg does the decode. 109Codec `5` is not handled by `tools/awc_opus.py`. `rpf9dump xma` writes it as RIFF XMA2, and ffmpeg does the decode.
102 110
diff --git a/docs/bvh.md b/docs/bvh.md
index 23e046221..16472f49a 100644
--- a/docs/bvh.md
+++ b/docs/bvh.md
@@ -339,8 +339,9 @@ the destination buffer:
339 339
3401. one thread per triangle (TRI0 leaves, remap `0x09`) or per instance (128-byte records, the world-to-object 3401. one thread per triangle (TRI0 leaves, remap `0x09`) or per instance (128-byte records, the world-to-object
341 inverse, the BLAS root and identity-rotation flag); 341 inverse, the BLAS root and identity-rotation flag);
3422. a 30-bit Morton key of each box centre, then a stable radix sort: 8 passes of 4-bit digits, 24 dispatches 3422. a 30-bit Morton key of each box centre, then a stable sort: up to 1,024 keys in one workgroup's shared memory
343 whatever the count, with no padding to a power of two; 343 (one dispatch), more with a radix sort of 8 passes of 4-bit digits over 256-element tiles (24 dispatches
344 whatever the count, no padding to a power of two);
3443. BOX32 nodes, built level by level from four consecutive sorted children, with the parent table and each 3453. BOX32 nodes, built level by level from four consecutive sorted children, with the parent table and each
345 instance's `ParentNode`; 346 instance's `ParentNode`;
3464. the header. 3474. the header.
@@ -360,8 +361,14 @@ them the same way.
360scene. `xdxr_bvh.py check-build <dir>` validates them and traces rays against brute force. `ctest` runs both as 361scene. `xdxr_bvh.py check-build <dir>` validates them and traces rays against brute force. `ctest` runs both as
361`xdxr_build` and `xdxr_build_check`. 362`xdxr_build` and `xdxr_build_check`.
362 363
363Not done yet: pairing triangles into TRI1 leaves, BOX16 nodes, updates, compaction and copies. A higher-quality 364**Updates** (D3D12 `PERFORM_UPDATE`) refit: the source structure is copied to the destination unless it is the
364build (SAH) would also come later. 365destination, the elements are rewritten at their slots, and each node's boxes are recomputed bottom-up from the
366children it already points to. The tree is kept, so a refit is valid for any motion and skips the Morton pass and
367the sort. It takes 0.07 ms for 1,000 triangles and 9.8 ms for 1,000,000 on an RTX 2050, against 0.19 ms and 22 ms for
368a build, but the tree traverses more slowly as the geometry moves away from where it was built.
369
370Not done yet: pairing triangles into TRI1 leaves, BOX16 nodes, compaction and copies. A higher-quality build (SAH)
371would also come later.
365 372
366```powershell 373```powershell
367python -I tools/xdxr_bvh.py selftest --seed 1 --rays 400 # build BLASes, compare closest hits with brute force 374python -I tools/xdxr_bvh.py selftest --seed 1 --rays 400 # build BLASes, compare closest hits with brute force
diff --git a/docs/character_models.md b/docs/character_models.md
index 671c6b298..1838a0522 100644
--- a/docs/character_models.md
+++ b/docs/character_models.md
@@ -50,8 +50,8 @@ Two caveats that matter for any render:
50 `cs_lucia_legacypedcs` clothed legacy ped. The decoded part is 1,748 vertices / 1,816 50 `cs_lucia_legacypedcs` clothed legacy ped. The decoded part is 1,748 vertices / 1,816
51 triangles, and the manifest lists 874- and 640-vertex rows of the same drawable. Do not present 51 triangles, and the manifest lists 874- and 640-vertex rows of the same drawable. Do not present
52 it as Lucia's hero body. 52 it as Lucia's hero body.
53- **The head drawable has no texture references.** Its face cannot be textured from the material 53- **The head drawable has no material texture references**, but its face comes from a **head-skin
54 keys alone. 54 preset** keyed by the head name's `joaat32` (see Textures).
55 55
56`player_story000_00` (Lucia's slot prefix) has 104 unique names: **63 drawables** plus **41 56`player_story000_00` (Lucia's slot prefix) has 104 unique names: **63 drawables** plus **41
57`char_bipedbounds` fragments**. The largest drawables: 57`char_bipedbounds` fragments**. The largest drawables:
@@ -97,7 +97,15 @@ and `0x8ADB8480` is a BC4 mask. A part without an explicit albedo keeps a flat m
97it must not be painted with a normal or ORM map. 97it must not be painted with a normal or ORM map.
98 98
99The hands and feet keys (`0x4D89F2311DBBB7A8`, `0xA54D9F8B51CA6034`) did not resolve in the 99The hands and feet keys (`0x4D89F2311DBBB7A8`, `0xA54D9F8B51CA6034`) did not resolve in the
100scanned TTPF pools. The head has no texture reference at all. 100scanned TTPF pools. The head drawable has no material texture reference, but its face is selected by
101a **head-skin preset** keyed by the head name's `joaat32`:
102
103| Head | Face albedo | Face normal |
104|---|---|---|
105| `player_story000_00_head_fr1_lat_000_m` | `0x8EDB5664DA38C47E` | `0x953715153D75447C` |
106| `cs_monalisa_head_fr1_afr_000_m_full` | `0x53A2896F4E5A6BA6` | `0xE82C7F6E02C8B701` |
107
108The preset library covers 897 heads; `cs_lucia_head_fr1_lat_000_y_full` is not in it.
101 109
102## Materials 110## Materials
103 111
diff --git a/docs/character_skeleton.md b/docs/character_skeleton.md
index db9e78b71..757c11521 100644
--- a/docs/character_skeleton.md
+++ b/docs/character_skeleton.md
@@ -229,6 +229,16 @@ The name controls resolve `cs_kenton`, `u_f_o_rhonda`, `cs_monalisa` and `cs_luc
229not. The delivered `mandy/` preview export is therefore a clearly labelled `cs_monalisa` proxy, 229not. The delivered `mandy/` preview export is therefore a clearly labelled `cs_monalisa` proxy,
230not a verified Mandy model. 230not a verified Mandy model.
231 231
232Two further checks refine that negative. A missing `mandy` name is the common case, not an
233anomaly: of the 13 `KeyLento/Perschars/Peds/Unique` entries, two resolve cleanly by name
234(`kenton` -> `cs_kenton`, `rhonda` -> `u_f_o_rhonda`), one plausibly maps (`Bert` ->
235`hc_cs_herbert_watson`), and the other ten, including `Mandy`, have no name hit. Also, the
236package manifest lists 108 files and its `pack/` directory contains only `story000`,
237`core_restofworld`, `core_restofworld001`, `shared_minigame000` and their `_bvh4`/`_licenses`
238companions; there is no `psp_*` archive, so the `PSP_KeyLento_perschars_peds` pack named by the
239schedule is not present in this build. Mandy is therefore not disproven: her appearance is either
240a generic ped assembled at runtime or in a pack this package does not include.
241
232Caveats: `levels.rpf` was prefix-bounded at 4 MiB per inflated stream, raw RSC8 bodies and 242Caveats: `levels.rpf` was prefix-bounded at 4 MiB per inflated stream, raw RSC8 bodies and
233Bink/opaque regions were not decoded, and the encrypted RPF9 table of contents prevents a full 243Bink/opaque regions were not decoded, and the encrypted RPF9 table of contents prevents a full
234path enumeration (27 top-level entries remain). The evidence supports a shared ped-appearance 244path enumeration (27 top-level entries remain). The evidence supports a shared ped-appearance
diff --git a/docs/d3d12_command_objects.md b/docs/d3d12_command_objects.md
index a55c3d964..93f0b39a0 100644
--- a/docs/d3d12_command_objects.md
+++ b/docs/d3d12_command_objects.md
@@ -371,9 +371,10 @@ vtable pointer of a public object.
371- **Slot 67** (call at `0x56d9`) is **not** the PC `CreateProtectedResourceSession1`: it takes `(desc, riid, out)` 371- **Slot 67** (call at `0x56d9`) is **not** the PC `CreateProtectedResourceSession1`: it takes `(desc, riid, out)`
372 with `IID_ID3D12PipelineState`. The DLL's own messages name it `DeserializeComputePipelineStateX`. Its desc is the 372 with `IID_ID3D12PipelineState`. The DLL's own messages name it `DeserializeComputePipelineStateX`. Its desc is the
373 root signature at `+0x00`, then pointer and size pairs for the shader's `FSPX` entries: kind 0 at `+0x08`, kind 1 373 root signature at `+0x00`, then pointer and size pairs for the shader's `FSPX` entries: kind 0 at `+0x08`, kind 1
374 at `+0x18`, a copy of the kind-6 program at `+0x28`, and kind 7 at `+0x38` ([fspx.md](fspx.md)). The proxy used to 374 at `+0x18`, a copy of the kind-6 program at `+0x28`, and kind 7 at `+0x38` ([fspx.md](fspx.md)). The proxy maps the
375 forward it to the PC method at the same index; it now refuses it (`E_NOTIMPL`). When it fails, the DLL takes 375 console desc to `D3D12_COMPUTE_PIPELINE_STATE_DESC` and routes it to `CreateComputePipelineState` (PC slot 11). On a
376 slot 62; its message for that failure calls the fallback "NewBE". 376 PC device that call fails (`E_FAIL`) because the code is not a PC shader, so the DLL falls back to slot 62; its message
377 for that failure calls the fallback "NewBE".
377- **Slot 62** (call at `0x5825`) takes the measured `(D3D12_COMPUTE_PIPELINE_STATE_DESC*, 0, 0, riid, out)`. The PC 378- **Slot 62** (call at `0x5825`) takes the measured `(D3D12_COMPUTE_PIPELINE_STATE_DESC*, 0, 0, riid, out)`. The PC
378 runtime refuses the DLL's code (`E_FAIL`): it is not a PC shader. The DLL's pipeline function then returns 379 runtime refuses the DLL's code (`E_FAIL`): it is not a PC shader. The DLL's pipeline function then returns
379 `0x8000000d` (`0x4b85`), but the dispatch goes on, records the null pipeline and faults (`0x65ff`), which is where a 380 `0x8000000d` (`0x4b85`), but the dispatch goes on, records the null pipeline and faults (`0x65ff`), which is where a
@@ -563,6 +564,26 @@ Queues and fences are wrapped the same way.
563 and a heap proxy given to a list's `SetDescriptorHeaps` reaches the real list unchanged. The command-list 564 and a heap proxy given to a list's `SetDescriptorHeaps` reaches the real list unchanged. The command-list
564 proxy of §3.5a adds the unwrap at both places. 565 proxy of §3.5a adds the unwrap at both places.
565 566
567Command allocators get the same kind of proxy: device slot 9 (`CreateCommandAllocator`) returns one.
568
569- **What is forwarded.** The public chain, 9 slots: the base chain and `Reset` at 8. A slot past it, up to the
570 end of a 64-slot table, is logged and refused, and a read past the table faults in its own guard region.
571 The console allocator's extra methods are not measured.
572- **Where a list takes it.** A list takes an allocator from the title in `CreateCommandList` and `Reset`, so
573 the proxy is safe only where the list side resolves it. Slot 9 therefore wraps an allocator only when it
574 answers `kLeonidaCommandAllocatorTag` (`d3d12_xs_device.h`). That is the Vulkan layer's own allocator, whose
575 `CommandAllocator::from()` resolves the proxy for both list calls.
576- **On the host runtime.** A PC runtime allocator comes back unwrapped, logged once, because the PC runtime's
577 lists would take a proxy for their own allocator. A command-list proxy that unwraps at `Reset` (§3.5a) is
578 what lets the host backend wrap allocators too.
579- **Residency.** An allocator is a pageable, so `MakeResident`/`Evict`/`SetResidencyPriority`/
580 `EnqueueMakeResident` unwrap allocator proxies like heap, queue and fence proxies.
581
582`allocator_proxy_test` checks this on the Vulkan device and on the host runtime, and the mock test checks it
583over allocators with and without the tag. On the Vulkan device it checks forwarding, the refused tail, the guard
584region, identity, and D3D12's allocator rules through the proxy, and runs a list created and `Reset` on the
585proxy whose copies go through the queue and fence proxies and are read back.
586
566Which of this is measured: the slot numbers and signatures are the SDK's (public). That the console 587Which of this is measured: the slot numbers and signatures are the SDK's (public). That the console
567keeps the public queue and fence slots, and device slots 8/32/36/75, is an assumption the package cannot 588keeps the public queue and fence slots, and device slots 8/32/36/75, is an assumption the package cannot
568test, as above. The proxies make a wrong assumption visible in the log; they do not prove it right. 589test, as above. The proxies make a wrong assumption visible in the log; they do not prove it right.
diff --git a/docs/d3d12_vulkan.md b/docs/d3d12_vulkan.md
index 83951f226..6834672b7 100644
--- a/docs/d3d12_vulkan.md
+++ b/docs/d3d12_vulkan.md
@@ -323,6 +323,11 @@ What is implemented (all of it testable without the game):
323 `d3d12_uav_clear_test`); 323 `d3d12_uav_clear_test`);
324 - the descriptor shader samples `B5G5R5A1_UNORM` through a 2D SRV. Opaque and transparent red check bit 15, 324 - the descriptor shader samples `B5G5R5A1_UNORM` through a 2D SRV. Opaque and transparent red check bit 15,
325 and mixed-channel texels check the five-bit color fields; 325 and mixed-channel texels check the five-bit color fields;
326 - `B8G8R8X8_UNORM`, `_UNORM_SRGB` and `_TYPELESS` (D3D-87) are `B8G8R8A8` images: clears, copies and footprints
327 keep all four bytes (WARP writes the clear's alpha into the X byte too), and shader views read alpha as 1. Its
328 typeless family is its own, so views to or from `B8G8R8A8` are refused (a castable-format list that names the
329 other family is not consulted yet). As on the host runtime, the family has no typed UAV, and a typed
330 `B8G8R8X8` texture cannot allow unordered access;
326 - `R10G10B10_XR_BIAS_A2_UNORM` maps to `VK_FORMAT_A2B10G10R10_UNORM_PACK32`, the same packed 10:10:10:2 331 - `R10G10B10_XR_BIAS_A2_UNORM` maps to `VK_FORMAT_A2B10G10R10_UNORM_PACK32`, the same packed 10:10:10:2
327 layout; the bias and scale are the application's shader work. Like the PC runtime, it accepts only a 332 layout; the bias and scale are the application's shader work. Like the PC runtime, it accepts only a
328 single-mip, single-sample 2D texture: extra mips, multisampling and 3D are refused in creation, allocation 333 single-mip, single-sample 2D texture: extra mips, multisampling and 3D are refused in creation, allocation
@@ -472,7 +477,9 @@ side inwards:
472 477
473 Growth leaves 64 descriptors of each limit to the other sets of a pipeline layout. It also stays within 478 Growth leaves 64 descriptors of each limit to the other sets of a pipeline layout. It also stays within
474 `maxPerSetDescriptors`, which never shrinks the default counts, because a layout past it may still be 479 `maxPerSetDescriptors`, which never shrinks the default counts, because a layout past it may still be
475 supported. The other arrays keep their default counts. On an RTX 5070 (driver 621.24, 1048576 of each type 480 supported: past it, the device grows only where `vkGetDescriptorSetLayoutSupport` accepts the grown layout.
481 Intel's UHD 770 (101.7092) reports 6159 and accepts the full sizes, so it gets the same set as an RTX (D3D-219).
482 The other arrays keep their default counts. On an RTX 5070 (driver 621.24, 1048576 of each type
476 and 4000 samplers) the set has 65536 2D images, 3936 samplers and 4096 storage indices in 2D: 93793 483 and 4000 samplers) the set has 65536 2D images, 3936 samplers and 4096 storage indices in 2D: 93793
477 descriptors, 3-6 MiB at 32-64 bytes a descriptor. The device prints the counts it chose, and 484 descriptors, 3-6 MiB at 32-64 bytes a descriptor. The device prints the counts it chose, and
478 `bindless_sizing_test` checks the rules on synthetic limits. 485 `bindless_sizing_test` checks the rules on synthetic limits.
@@ -661,14 +668,57 @@ The compute path, end to end:
661 - With `VK_EXT_conditional_rendering`, the arena is created with the conditional-rendering usage, and 668 - With `VK_EXT_conditional_rendering`, the arena is created with the conditional-rendering usage, and
662 `SetPredication` on a default-heap buffer reads at the buffer's offset in the arena plus the call's offset. 669 `SetPredication` on a default-heap buffer reads at the buffer's offset in the arena plus the call's offset.
663 - `CreateHeap` reserves the requested size in the arena at 64 KiB, and a buffer placed in it gets the heap's 670 - `CreateHeap` reserves the requested size in the arena at 64 KiB, and a buffer placed in it gets the heap's
664 place plus the placed offset as its console VA. A placed texture keeps its own `VkDeviceMemory` and a null VA, 671 place plus the placed offset as its console VA. A placed texture keeps its own `VkDeviceMemory` and a null VA;
665 and a tiled (`64KB_UNDEFINED_SWIZZLE`) placement is refused with `E_NOTIMPL`. `CreatePlacedResource2`'s 672 tiled (`64KB_UNDEFINED_SWIZZLE` and Xbox `0x101`) 2D/3D placed textures are backed the same way with
666 castable-format list reaches the placed texture's image as the committed path's does (D3D-90). 673 tile-multiple `GetResourceAllocationInfo`, `GetResourceTiling`, and host-matched `E_INVALIDARG` checks
674 (D3D-191). Multisampled 2D placed textures (`UNKNOWN` and `4x` tiled) share that backing with host-matched heap
675 and offset alignment checks (`4 MiB` vs `64 KiB`, `D3D-222`). `CreatePlacedResource2`'s castable-format list
676 reaches the placed texture's image as the committed path's does (D3D-90).
667 677
668Known gaps: set 0 in pipelines (the device keeps the bindless set, but no pipeline declares or binds it yet) and 678Known gaps: set 0 in pipelines (the device keeps the bindless set, but no pipeline declares or binds it yet) and
669therefore every translated shader that declares bindings; tessellation, geometry and mesh pipelines, 679therefore every translated shader that declares bindings; tessellation, geometry and mesh pipelines,
670multisampled pipelines, several viewports, primitive restart; `requiredSubgroupSize = 64` for wave64 compute; 680multisampled pipelines, several viewports, primitive restart; `requiredSubgroupSize = 64` for wave64 compute;
671the game's present entry point (`PresentX`; the DXGI factory/swapchain and the presenter above are what it 681the game's present entry point (`PresentX`; the DXGI factory/swapchain and the presenter above are what it
682- **Subgroup size (compute and graphics PSOs).** A translated shader assumes one subgroup size, and a GPU whose
683 default differs runs it inexact: a wave64 shader reads lanes 32-63 of a 32-wide subgroup, and a wave32 pixel
684 shader on a 64-wide default reads the other half's lanes (AnyPS5 #487 on RDNA4). `runtime/src/subgroup_size.h`
685 decides, per stage, from the shader's index entry and what the device offers; the PSO chains the result.
686 - **Index fields:** `wave64`, `subgroup_size` (64 for wave64, 32 otherwise, `null` when emulated) and
687 `wave64_exchange` (present: translated with `--wave64-emulate`, exact on any size).
688 - **Device:** `subgroupSizeControl` and `computeFullSubgroups` are enabled where supported;
689 `minSubgroupSize`, `maxSubgroupSize`, `maxComputeWorkgroupSubgroups`, `requiredSubgroupSizeStages` (from
690 `VkPhysicalDeviceSubgroupSizeControlProperties`) and the default `subgroupSize` are kept in
691 `VulkanDeviceInfo::subgroup` and printed at device creation.
692 - **Emulated shaders:** nothing is required.
693 - **Native shaders:** `VkPipelineShaderStageRequiredSubgroupSizeCreateInfo{subgroup_size}` when the feature is
694 enabled, the stage is in `requiredSubgroupSizeStages`, the size is a power of two in [min, max] and, for
695 compute and mesh, the workgroup fits in size x `maxComputeWorkgroupSubgroups` (VUID-VkPipelineShaderStageCreateInfo-pNext-02755
696 and -02756, VUID-VkPipelineShaderStageRequiredSubgroupSizeCreateInfo-requiredSubgroupSize-02760..02762).
697 A compute stage also gets `VK_PIPELINE_SHADER_STAGE_CREATE_REQUIRE_FULL_SUBGROUPS_BIT` when
698 `computeFullSubgroups` is enabled and local size X is a multiple of the size (-flags-02785 for the feature,
699 -flags-08988 for the stage, -pNext-02757 for X). Wave32 shaders ask for 32 the same way. A device whose only size is the wanted one (NVIDIA,
700 wave32) needs no chain. Where the size cannot be required (stage not listed, feature off) but the device default is
701 the wanted one, the shader works as it is (`device_default`; nothing guarantees the default, so it is not logged
702 as inexact); any other size is `unavailable` and logged.
703 - **Which stages can be required:** it is the driver's list, not a fixed rule. The AMD Windows driver reports
704 FRAGMENT | COMPUTE | TASK | MESH (measured on a Radeon 880M, 26.11.2, sizes 32..64), so wave64 and wave32 pixel
705 shaders run exact there; so does current Mesa RADV on GFX10+ (COMPUTE | FRAGMENT | task/mesh, Mesa main at
706 152b9cde, `src/amd/vulkan/radv_physical_device.c`, `requiredSubgroupSizeStages`; older Mesa reported compute only).
707 NVIDIA lists every stage but only size 32, so a native wave64 shader cannot get 64 there. Vertex and geometry
708 stages are in neither list.
709 - **A size the device cannot give** is logged once per stage with the first shader's name (and again at 10, 100,
710 1000 shaders of that stage): `[rt] d3d12: <name> (<stage>) is a 64-wide shader but this device cannot require that
711 subgroup size ...`. For compute and mesh the fix is the build, `--wave64-emulate` (`make_game.py
712 --wave64-emulate auto` picks it for this GPU); a wave64 vertex, geometry or pixel shader has no emulation yet
713 (the ~10,000 wave64 pixel shaders are the open case on NVIDIA, SHADER-10).
714 - **Test:** `subgroup_size_test` (CPU) checks the decision against AMD-like, NVIDIA-like and old-RADV
715 properties and the resulting create-info chain; `d3d12_subgroup_test` (GPU) runs `cs_w64x_readlane` natively
716 and with `--wave64-emulate`, and `cs_wqm_w32`, through D3D12 PSOs and compares the read-back words.
717
718Known gaps: set 0 in pipelines (the device keeps the bindless set, but no pipeline declares or binds it yet) and
719therefore every translated shader that declares bindings; tessellation, geometry and mesh pipelines,
720multisampled pipelines, several viewports, primitive restart; subgroup size for mesh pipelines (the decision covers them, no mesh PSO exists to chain it into), and for wave64 vertex, geometry and, on a GPU that cannot require 64 for pixel shaders (NVIDIA), pixel shaders, which have no emulation (SHADER-10);
721the game's present entry point (DXGI factory/swapchain or `PresentX`; the presenter above is what either
672calls), HDR and fullscreen; buffer and constant-buffer views (UAV clears read the descriptor bytes, so they do 722calls), HDR and fullscreen; buffer and constant-buffer views (UAV clears read the descriptor bytes, so they do
673not wait on view creation), typeless volume RTVs, depth-stencil resolves to a destination offset other than 723not wait on view creation), typeless volume RTVs, depth-stencil resolves to a destination offset other than
674the source rectangle's; 724the source rectangle's;
@@ -679,8 +729,6 @@ depth SRVs are sampled next to a read-only DSV, M2); the index buffer is bound w
679(`vkCmdBindIndexBuffer2`, Vulkan 1.4, takes one). 729(`vkCmdBindIndexBuffer2`, Vulkan 1.4, takes one).
680 730
681Known gaps found in review, not fixed here: 731Known gaps found in review, not fixed here:
682- **Wave64:** a wave64 compute shader runs at whatever subgroup size the driver picks, because no
683 `requiredSubgroupSize` is requested (claimed as a follow-up in #313).
684- **Queues:** every D3D12 queue submits to one `VkQueue`, which runs batches in order. So a queue that waits on a 732- **Queues:** every D3D12 queue submits to one `VkQueue`, which runs batches in order. So a queue that waits on a
685 fence another queue signals later (`B->Wait(f, n)` recorded before `A->Signal(f, n)`) holds back that signal, 733 fence another queue signals later (`B->Wait(f, n)` recorded before `A->Signal(f, n)`) holds back that signal,
686 and the GPU never progresses (woreksami's probe). Queues on separate Vulkan queues (#306 for copy and compute) 734 and the GPU never progresses (woreksami's probe). Queues on separate Vulkan queues (#306 for copy and compute)
@@ -699,6 +747,10 @@ CPU tests:
699- `gfx10_descriptors_test` covers the T#, S# and V#: every field alone at its bit position, round trips, what 747- `gfx10_descriptors_test` covers the T#, S# and V#: every field alone at its bit position, round trips, what
700 decoding refuses and ignores, the T#s the image test shaders build, sampler words as radv writes them, and the 748 decoding refuses and ignores, the T#s the image test shaders build, sampler words as radv writes them, and the
701 format table. `tests/test_gfx10_descriptors.py` compares that table with `tools/gfx10_formats.json`. 749 format table. `tests/test_gfx10_descriptors.py` compares that table with `tools/gfx10_formats.json`.
750- `subgroup_size_test` covers the subgroup-size decision of section 3.2 without a GPU: synthetic index entries
751 (native and emulated wave64, wave32; compute, pixel, mesh, vertex) against AMD-like (32..64, FRAGMENT | COMPUTE |
752 TASK | MESH), NVIDIA-like (32 only, every stage) and old-RADV (COMPUTE only) properties, the limits (feature off,
753 `maxComputeWorkgroupSubgroups`, a size that is not a power of two), and the create-info chain.
702 754
703The GPU tests read their results back. With `LEONIDA_VK_VALIDATION=1` they run under `VK_LAYER_KHRONOS_validation`, 755The GPU tests read their results back. With `LEONIDA_VK_VALIDATION=1` they run under `VK_LAYER_KHRONOS_validation`,
704and any validation error fails them. 756and any validation error fails them.
@@ -859,6 +911,25 @@ and any validation error fails them.
859- `xbox_present_test`: `PresentX` and the frame events (section 4.5, "what is implemented"), checked on swapchain pixels. 911- `xbox_present_test`: `PresentX` and the frame events (section 4.5, "what is implemented"), checked on swapchain pixels.
860 there is one. A host that reports no non-normalized samplers is compared only on the 3 cases without the 912 there is one. A host that reports no non-normalized samplers is compared only on the 3 cases without the
861 flag. The other 19 are then checked against their recorded answers only. 913 flag. The other 19 are then checked against their recorded answers only.
914- `d3d12_subgroup_test`: subgroup size control through D3D12 PSOs, on the PSOs of the device proxy.
915 - **Shaders:** `cs_w64x_readlane` (a `v_readlane` across both halves of a wave64) translated natively and with
916 `--wave64-emulate`, and `cs_wqm_w32`, built by `test/shaders/build.py` (needs `llvm-mc`: `LLVM_MC`).
917 - **Check:** each is dispatched through a PSO found by FSSM hash and the eight words it stores are compared. The
918 PSO's request (`pipeline_subgroup_requests`) must equal the decision function's. The native wave64 shader
919 must be exact where the device can give 64 (AMD: required size 64 plus full subgroups) and is reported, not
920 judged, where it cannot (NVIDIA); the emulated one must be exact everywhere.
921 - **Control:** a second run with nothing requested is printed. On the Radeon 880M the default compute subgroup is
922 already 64, so the wave64 controls are exact as well.
923 - **Probes:** GLSL shaders (`cs_sg_probe.comp`, `ps_sg_probe.frag`, `vs_sg_fullscreen.vert`) store `gl_SubgroupSize`,
924 so the size the driver used is observed for a wave64 entry, a wave32 entry and an emulated one. Where the PSO
925 required a size, the observed size must equal it. For a wave32 compute shader on a device whose default is not 32,
926 the control is asserted to differ (the request matters); a wave32 pixel shader on the 880M goes from 64-wide to
927 32-wide with the request.
928 - **Wave64 pixel shader:** `ps_w64x_readlane.asm` (`v_readlane` of lanes 40, 5, 33 and 63) is drawn over 64x64
929 pixels through a graphics PSO into a float target, and every pixel must carry the four values derived in the
930 .asm header where the PSO required 64: 4096 of 4096 on the 880M. The control is asserted to differ only where the
931 default pixel subgroup is not 64; the 880M runs pixel shaders 64-wide by default, so its control is exact too. On
932 the RTX 5070 the shader gets no 64 (0 of 4096 exact, not judged).
862- `d3d12_descriptor_test`: descriptors through the proxy. 933- `d3d12_descriptor_test`: descriptors through the proxy.
863 - Copies, checked on the slots' bytes: one run, range lists of different shapes on each side, null size 934 - Copies, checked on the slots' bytes: one run, range lists of different shapes on each side, null size
864 arrays, and a destination longer than its source. 935 arrays, and a destination longer than its source.
@@ -892,6 +963,17 @@ and any validation error fails them.
892 - the index has an entry with set-0 bindings for the same program ahead of the binding-free one, and the PSO 963 - the index has an entry with set-0 bindings for the same program ahead of the binding-free one, and the PSO
893 must take the binding-free one; 964 must take the binding-free one;
894 - a device that reports 128 bytes of push constants refuses the PSO. 965 - a device that reports 128 bytes of push constants refuses the PSO.
966- `d3d12_set0_compute_test`: set 0 from the compute bind point, through the proxy and D3D12 alone. The index entry
967 of its shader lists set-0 bindings, so the PSO's layout holds the device's bindless set and replay binds it at
968 each dispatch; nothing in the test binds it. Four dispatches of `test/glsl/cs_set0_sample.comp` (GLSL written to
969 the translator's contract) load a T# and an S# from two descriptor tables and sample one tile to the right in U:
970 - two SRVs give their textures texel for texel, so the T# decides the image;
971 - 32 bytes no view was made for give the fallback image, one colour everywhere;
972 - a clamping sampler gives the texture's right edge, so the S# decides the sampler;
973 - a device without the bindless set refuses the PSO.
974
975 Removing the set-0 bind from the dispatch path makes this test fail (`VUID-vkCmdDispatch-None-08600`, measured on
976 llvmpipe); `d3d12_m2_textured_test` covers the bind at draws in the same way.
895- `d3d12_draw_test`: milestone M1, through the proxy. 977- `d3d12_draw_test`: milestone M1, through the proxy.
896 - **Pipeline:** a VS+PS PSO found by FSSM hash. The input layout is POSITION then COLOR, while the VS has them in 978 - **Pipeline:** a VS+PS PSO found by FSSM hash. The input layout is POSITION then COLOR, while the VS has them in
897 the opposite register order, so a match by position would fail. 979 the opposite register order, so a match by position would fail.
@@ -962,7 +1044,7 @@ The layer therefore owns the console VAs. It returns them from `ID3D12Resource::
962| Address space | Two ranges. A **BDA arena** holds buffers, descriptor heaps and shader code; its device address is `heap_base`. A separate **image key range** supplies unique console VAs for images; those keys are never added to `heap_base`. The arena's `VkBuffer` is created with all buffer usages the game can bind (uniform, storage, vertex, index, indirect, transfer) plus `SHADER_DEVICE_ADDRESS`, and its memory with `VK_MEMORY_ALLOCATE_DEVICE_ADDRESS_BIT`. | 1044| Address space | Two ranges. A **BDA arena** holds buffers, descriptor heaps and shader code; its device address is `heap_base`. A separate **image key range** supplies unique console VAs for images; those keys are never added to `heap_base`. The arena's `VkBuffer` is created with all buffer usages the game can bind (uniform, storage, vertex, index, indirect, transfer) plus `SHADER_DEVICE_ADDRESS`, and its memory with `VK_MEMORY_ALLOCATE_DEVICE_ADDRESS_BIT`. |
963| Buffers | A buffer resource is a range in the arena's single `VkBuffer`: offset = its console VA, size = the resource size. Buffer commands bind the arena buffer with that offset, so its device address is exactly `arena_bda + offset`; no per-resource `VkBuffer` object is needed. | 1045| Buffers | A buffer resource is a range in the arena's single `VkBuffer`: offset = its console VA, size = the resource size. Buffer commands bind the arena buffer with that offset, so its device address is exactly `arena_bda + offset`; no per-resource `VkBuffer` object is needed. |
964| Images | Each image gets a unique console VA key and lives in its own `VkDeviceMemory` (or a suballocated device-local image heap) with optimal tiling. Shader image access goes through the T#/hash table, so nothing dereferences the key. Keeping images out of the arena avoids forcing optimal-tiled images into the arena's memory type and keeps the arena sized by buffers, not textures. | 1046| Images | Each image gets a unique console VA key and lives in its own `VkDeviceMemory` (or a suballocated device-local image heap) with optimal tiling. Shader image access goes through the T#/hash table, so nothing dereferences the key. Keeping images out of the arena avoids forcing optimal-tiled images into the arena's memory type and keeps the arena sized by buffers, not textures. |
965| Heaps and placed resources | `CreateHeap` reserves the requested size in the arena, so a buffer placed at a 64 KiB-aligned offset is that offset into the arena and its console VA is the heap's place plus the offset. A placed texture gets its own `VkDeviceMemory` and a null VA, as in D3D12. Tiled (`64KB_UNDEFINED_SWIZZLE`) placements are refused with `E_NOTIMPL`; reserved resources are not implemented. | 1047| Heaps and placed resources | `CreateHeap` reserves the requested size in the arena, so a buffer placed at a 64 KiB-aligned offset is that offset into the arena and its console VA is the heap's place plus the offset. A placed texture gets its own `VkDeviceMemory` and a null VA, as in D3D12. Tiled (`64KB_UNDEFINED_SWIZZLE` and Xbox `0x101`) 2D/3D placed textures (D3D-191) and multisampled 2D placed textures (D3D-222) share that backing, answer `GetResourceAllocationInfo` and `GetResourceTiling`, and check heap/offset alignments. |
966| Descriptor heaps | Shader-visible CBV/SRV/UAV and sampler heaps are allocated in the low 4 GB of the arena. RTV/DSV heaps are host-side only. | 1048| Descriptor heaps | Shader-visible CBV/SRV/UAV and sampler heaps are allocated in the low 4 GB of the arena. RTV/DSV heaps are host-side only. |
967| Shader code | Each FSSM blob is uploaded to the arena; its console VA is the code base. | 1049| Shader code | Each FSSM blob is uploaded to the arena; its console VA is the code base. |
968| Upload/readback | `D3D12_HEAP_TYPE_UPLOAD`/`READBACK` resources are separate host-visible buffers outside the arena. Their console VAs are only used by copy APIs; if the game binds one as a vertex/index buffer or reads it in a shader, the layer biases the view/descriptor by `-heap_base` so the shader's addition lands on the host BDA (**Assumption**; **measured to fail for a V#**, see below). | 1050| Upload/readback | `D3D12_HEAP_TYPE_UPLOAD`/`READBACK` resources are separate host-visible buffers outside the arena. Their console VAs are only used by copy APIs; if the game binds one as a vertex/index buffer or reads it in a shader, the layer biases the view/descriptor by `-heap_base` so the shader's addition lands on the host BDA (**Assumption**; **measured to fail for a V#**, see below). |
@@ -1088,6 +1170,9 @@ The layer's descriptor model:
1088 `VK_EXT_image_view_min_lod`. Vulkan allows the image-view minimum to be rounded down to an integer. 1170 `VK_EXT_image_view_min_lod`. Vulkan allows the image-view minimum to be rounded down to an integer.
1089 With nearest mip filtering, the UHD 770 and Arrow Lake Xe-LPG returned mip 0 for a 2D minimum of 0.75. 1171 With nearest mip filtering, the UHD 770 and Arrow Lake Xe-LPG returned mip 0 for a 2D minimum of 0.75.
1090 The Xe-LPG also returned mip 1 for a 2D-array minimum of 1.75. RTX and Radeon returned mips 1 and 2. 1172 The Xe-LPG also returned mip 1 for a 2D-array minimum of 1.75. RTX and Radeon returned mips 1 and 2.
1173 On Intel integrated GPUs the layer therefore passes the clamp rounded to the nearest level
1174 (`ceil(minLod + 0.5) - 1`), which point mip filtering selects exactly; linear mip filtering then blends from that
1175 whole level instead of the fraction (D3D-219). `LEONIDA_MIN_LOD_INTEGER=1` or `0` forces the rounding on or off.
1091 See [Vulkan image-level selection](https://docs.vulkan.org/spec/latest/chapters/textures.html#textures-image-level-selection) 1176 See [Vulkan image-level selection](https://docs.vulkan.org/spec/latest/chapters/textures.html#textures-image-level-selection)
1092 and the [Intel readbacks](https://github.com/ItsNotRexed/Leonida/pull/1015#issuecomment-7075135647). 1177 and the [Intel readbacks](https://github.com/ItsNotRexed/Leonida/pull/1015#issuecomment-7075135647).
1093 If the logical device lacks the feature, the runtime logs the unsupported view 1178 If the logical device lacks the feature, the runtime logs the unsupported view
@@ -1261,8 +1346,8 @@ Pipeline creation:
1261 `InputSlotClass`/`InstanceDataStepRate`. The index entry needs the semantic map (section 3.5). 1346 `InputSlotClass`/`InstanceDataStepRate`. The index entry needs the semantic map (section 3.5).
1262- Enable the features the index entry lists: barycentrics, fragment interlock, mesh, geometry, Float64, Int64, 1347- Enable the features the index entry lists: barycentrics, fragment interlock, mesh, geometry, Float64, Int64,
1263 buffer device address, storage image without format, maintenance8. 1348 buffer device address, storage image without format, maintenance8.
1264- Request `requiredSubgroupSize = 64` for wave64 shaders when `VK_EXT_subgroup_size_control` offers it (AMD). 1349- Request the subgroup size each shader was translated for (`requiredSubgroupSize` 64 or 32) where the device lists the stage
1265 Otherwise use the translator's 32-wide approximation and say so in the log. 1350 in `requiredSubgroupSizeStages`, and say so in the log where it cannot (section 3.2, "Subgroup size").
1266- Pipeline caches: use a `VkPipelineCache` keyed by driver/pipeline-cache UUID; the `pipelines` build stage already 1351- Pipeline caches: use a `VkPipelineCache` keyed by driver/pipeline-cache UUID; the `pipelines` build stage already
1267 produces one. D3D12 `CachedPSO` blobs are driver-specific and are ignored (the PSO is rebuilt from its 1352 produces one. D3D12 `CachedPSO` blobs are driver-specific and are ignored (the PSO is rebuilt from its
1268 descriptors). `ID3D12PipelineLibrary` is an in-memory map plus the Vulkan cache. 1353 descriptors). `ID3D12PipelineLibrary` is an in-memory map plus the Vulkan cache.
@@ -2097,8 +2182,8 @@ Vulkan AS would be invisible to them. Two paths:
2097 the GPU and is checked against that reference. The standalone device uses it for `BuildRaytracingAccelerationStructure` 2182 the GPU and is checked against that reference. The standalone device uses it for `BuildRaytracingAccelerationStructure`
2098 and answers `GetRaytracingAccelerationStructurePrebuildInfo` from its layout, exactly. Acceleration-structure 2183 and answers `GetRaytracingAccelerationStructurePrebuildInfo` from its layout, exactly. Acceleration-structure
2099 buffers then keep their console VAs, the addresses the records name each other by. `LEONIDA_RT_AS=khr` keeps 2184 buffers then keep their console VAs, the addresses the records name each other by. `LEONIDA_RT_AS=khr` keeps
2100 #743's `VkAccelerationStructureKHR` builds (for `RayQueryKHR`), which the game's shaders can't read. Updates rebuild 2185 #743's `VkAccelerationStructureKHR` builds (for `RayQueryKHR`), which the game's shaders can't read. Updates refit
2101 the structure; compaction, copies, serialization and the Xbox batched/streaming builds are not implemented. The 2186 the source structure instead of rebuilding it ([bvh.md](bvh.md) §7a); compaction, copies, serialization and the Xbox batched/streaming builds are not implemented. The
2102 reported `RaytracingTier` is unchanged (`NOT_SUPPORTED`). Checked by `runtime/test/d3d12_xdxr_rt_test.cpp` through 2187 reported `RaytracingTier` is unchanged (`NOT_SUPPORTED`). Checked by `runtime/test/d3d12_xdxr_rt_test.cpp` through
2103 the D3D12 API. 2188 the D3D12 API.
2104 2189
@@ -2175,7 +2260,7 @@ store, load, mesh, geometry and BVH tests; this layer is the other half.
2175| PS system inputs | `FragCoord` (xy/z/w), `FrontFacing`, barycentrics; enable `fragmentShaderBarycentric` and `fragmentShaderPixelInterlock` when the index entry asks. | 2260| PS system inputs | `FragCoord` (xy/z/w), `FrontFacing`, barycentrics; enable `fragmentShaderBarycentric` and `fragmentShaderPixelInterlock` when the index entry asks. |
2176| Mesh/geometry stages | `VK_EXT_mesh_shader`; the index's max vertices/primitives size the SPIR-V output arrays and are checked against the device's mesh properties; geometry stage for the 195 voxelize shaders; `DispatchMesh` → `vkCmdDrawMeshTasksEXT`. | 2261| Mesh/geometry stages | `VK_EXT_mesh_shader`; the index's max vertices/primitives size the SPIR-V output arrays and are checked against the device's mesh properties; geometry stage for the 195 voxelize shaders; `DispatchMesh` → `vkCmdDrawMeshTasksEXT`. |
2177| POPS collision | The runtime puts 0 (no collision, bit 31 clear) in the POPS collision SGPR; the translator uses fragment-shader interlock for ordering. **Open:** the exact SGPR location is a translator/driver detail not named in the current contract. | 2262| POPS collision | The runtime puts 0 (no collision, bit 31 clear) in the POPS collision SGPR; the translator uses fragment-shader interlock for ordering. **Open:** the exact SGPR location is a translator/driver detail not named in the current contract. |
2178| Wave size | `requiredSubgroupSize = 64` when supported (AMD); otherwise the translator's 32-wide approximation is explicit in the log. | 2263| Wave size | The PSO asks for the size the shader was translated for (`requiredSubgroupSize` 64 or 32, section 3.2 "Subgroup size") where the stage is in `requiredSubgroupSizeStages`; a shader translated with `--wave64-emulate` asks for nothing. A size the device cannot give is named in the log. |
2179| Code-embedded data | The whole FSSM blob is in the arena; `s_getpc_b64` becomes `code_base + next-instruction offset`. | 2264| Code-embedded data | The whole FSSM blob is in the arena; `s_getpc_b64` becomes `code_base + next-instruction offset`. |
2180 2265
2181### 5.1 Descriptor hash table details 2266### 5.1 Descriptor hash table details
@@ -2518,6 +2603,12 @@ Xodus is LGPL-2.1 and is cited only for its coverage number, not as a code sourc
2518- **Hash-table cost.** Every image/sampler access hashes a T#/S# and probes a storage buffer. **Measured (D3D-56, section 5.1)** on an RTX 5080 (driver 616.56): in `DEVICE_LOCAL` VRAM the lookup itself stays fast up to 100k entries (`3.0–3.7 us/1M` net wave-uniform full sweeps, `17.2–28.9 us/1M` net divergent hits), whereas `HOST_VISIBLE | HOST_COHERENT` system memory drops 9.6x–28x on uniform full sweeps and 59x–755x on divergent lookups at 10k–100k entries, and linear probing's 8-probe limit doubles a 100k table to `80.00 MiB` (`4.8%` load). **The runtime now keeps that table in `DEVICE_LOCAL` memory** and uploads only the slots that changed, from a mapped staging copy, with the copy and its barrier in the command buffer that will read it (D3D-76; 46.2x on a divergent miss at 100k on an RTX 2060 SUPER). Improving slot placement within the 8-probe window is the open optimisation (SHADER-100); Intel, RTX 5070 Ti Laptop and AMD RDNA3 are measured in section 5.1; Apple numbers remain open via `vk_descriptor_bench`. 2603- **Hash-table cost.** Every image/sampler access hashes a T#/S# and probes a storage buffer. **Measured (D3D-56, section 5.1)** on an RTX 5080 (driver 616.56): in `DEVICE_LOCAL` VRAM the lookup itself stays fast up to 100k entries (`3.0–3.7 us/1M` net wave-uniform full sweeps, `17.2–28.9 us/1M` net divergent hits), whereas `HOST_VISIBLE | HOST_COHERENT` system memory drops 9.6x–28x on uniform full sweeps and 59x–755x on divergent lookups at 10k–100k entries, and linear probing's 8-probe limit doubles a 100k table to `80.00 MiB` (`4.8%` load). **The runtime now keeps that table in `DEVICE_LOCAL` memory** and uploads only the slots that changed, from a mapped staging copy, with the copy and its barrier in the command buffer that will read it (D3D-76; 46.2x on a divergent miss at 100k on an RTX 2060 SUPER). Improving slot placement within the 8-probe window is the open optimisation (SHADER-100); Intel, RTX 5070 Ti Laptop and AMD RDNA3 are measured in section 5.1; Apple numbers remain open via `vk_descriptor_bench`.
2519- **Wave64.** On NVIDIA, wave64 shaders use the translator's 32-wide approximation; cross-half ops are approximate. 2604- **Wave64.** On NVIDIA, wave64 shaders use the translator's 32-wide approximation; cross-half ops are approximate.
2520 AMD GPUs with 64-wide subgroups are exact. This is a known fidelity gap, not specific to the layer. 2605 AMD GPUs with 64-wide subgroups are exact. This is a known fidelity gap, not specific to the layer.
2606- **Hash-table cost.** Every image/sampler access hashes a T#/S# and probes a storage buffer. **Measured (D3D-56, section 5.1)** on an RTX 5080 (driver 616.56): in `DEVICE_LOCAL` VRAM the lookup itself stays fast up to 100k entries (`3.0–3.7 us/1M` net wave-uniform full sweeps, `17.2–28.9 us/1M` net divergent hits), whereas `HOST_VISIBLE | HOST_COHERENT` system memory drops 9.6x–28x on uniform full sweeps and 59x–755x on divergent lookups at 10k–100k entries, and linear probing's 8-probe limit doubles a 100k table to `80.00 MiB` (`4.8%` load). **The runtime now keeps that table in `DEVICE_LOCAL` memory** and uploads only the slots that changed, from a mapped staging copy, with the copy and its barrier in the command buffer that will read it (D3D-76; 46.2x on a divergent miss at 100k on an RTX 2060 SUPER). Improving slot placement within the 8-probe window is the open optimisation (SHADER-100); AMD/Intel/Apple numbers remain open via `vk_descriptor_bench`.
2607- **Wave64.** A native wave64 shader needs a 64-wide subgroup in its stage: AMD (Windows driver, RADV on GFX10+) can require
2608 it for compute, mesh and pixel shaders, NVIDIA cannot (32 only). There, compute and mesh shaders translated with
2609 `--wave64-emulate` are exact; wave64 pixel, vertex and geometry shaders have no emulation and keep the
2610 translator's 32-wide approximation (cross-half ops are approximate). This is a known fidelity gap, not specific to
2611 the layer.
2521- **Xbox tiling/DCC.** Slot 76 and layout `0x101` are known, but the tiled data layout, detile path and DCC remain 2612- **Xbox tiling/DCC.** Slot 76 and layout `0x101` are known, but the tiled data layout, detile path and DCC remain
2522 unknown. If the game assumes console tiling or compression metadata, the layer needs a detile/repack step. 2613 unknown. If the game assumes console tiling or compression metadata, the layer needs a detile/repack step.
2523- **BVH builder DXIL.** 44 of the builder's 53 Xbox DXIL shaders fail the PC compiler; 22 have been lowered to 2614- **BVH builder DXIL.** 44 of the builder's 53 Xbox DXIL shaders fail the PC compiler; 22 have been lowered to
@@ -2735,7 +2826,7 @@ on a PC device behind the Xbox-ABI proxy). Measured:
2735 (`+0x18`, `+0x28`, `+0x30`) the DLL writes commands through while there is room. Table and evidence: 2826 (`+0x18`, `+0x28`, `+0x30`) the DLL writes commands through while there is room. Table and evidence:
2736 [d3d12_command_objects.md §3.5a](d3d12_command_objects.md). 2827 [d3d12_command_objects.md §3.5a](d3d12_command_objects.md).
2737 Device slot 67 is a console-only compute-pipeline call, `DeserializeComputePipelineStateX` in the DLL's own 2828 Device slot 67 is a console-only compute-pipeline call, `DeserializeComputePipelineStateX` in the DLL's own
2738 messages, not the PC method at that index; the proxy now refuses it. The dispatch stops where the PC runtime 2829 messages, not the PC method at that index; the proxy routes it to `CreateComputePipelineState`. The dispatch stops where the PC runtime
2739 refuses the DLL's compute code at slot 62: the DLL's shaders carry an `ACCC` part instead of DXIL, an `FSPX` 2830 refuses the DLL's compute code at slot 62: the DLL's shaders carry an `ACCC` part instead of DXIL, an `FSPX`
2740 payload with an RDNA2 program ([fspx.md](fspx.md)). 2831 payload with an RDNA2 program ([fspx.md](fspx.md)).
2741 - Its `throw 1` reaches the caller. Before #965 the throw carried an image base of 0, because `_CxxThrowException` 2832 - Its `throw 1` reaches the caller. Before #965 the throw carried an image base of 0, because `_CxxThrowException`
diff --git a/docs/design.md b/docs/design.md
index a9e99f4e4..3f0dfbe8e 100644
--- a/docs/design.md
+++ b/docs/design.md
@@ -107,7 +107,7 @@ add a source file, add it to `runtime\CMakeLists.txt` and to the file list in `b
107| Texture dictionaries | Same tool: TXD resources become DDS per texture. | `<work>\assets\<archive>\textures\` | 107| Texture dictionaries | Same tool: TXD resources become DDS per texture. | `<work>\assets\<archive>\textures\` |
108| World textures (TTPF) | **Done: 308,895 textures from all 57 pools, 0 failures, 48,220 entries skipped by the original exporter** (33,507 BCPack, 14,030 compact mapping, 678 arrays/volumes, 5 unsupported format, 0 unmapped). The compact-tail tool resolves 14,011 of the 14,030 layouts and reconstructs 305,264 complete chains (206,661 newly complete, 1,100,865 mips, 4.59 GiB), and the multi-slice pass resolves all 697 arrays/cubemaps/volumes ([textures_arrays.md](textures_arrays.md)). BCPack was the hard blocker: `tools/bcpack.py` decodes all six active modes (BC1, BC3, BC4, BC5, BC6H, BC7), and `rpf9dump`'s C# `TtpfReader` (`e293917` pin, `breadbbbb/rpf9-explorer#7`) now decodes compact tails, multi-slice layouts, DXGI 11, and strict BCPack BC1/BC3/BC4/BC5 directly; BC6H/BC7 and provisional-history chunks remain skipped by `rpf9dump` and can be completed by `tools/ttpf_assets.py` ([textures.md](textures.md)). 46 pools are in `data\ttdb\**`, 11 in `pack\<name>\data\ttdb\**` (exported under `ttpf_pack\<pack>\`). `data\ttdb\**\*.ttpf` (57 pools, 58 GiB) are loose RDS5 texture pools, **not** inside RPFs. rpf9-explorer's `TtpfReader` reads the catalog and detiles them; checked visually (`ttdb_graphics`: scope reticles, clean lines). Names are generated (`texture_N_<assetkey>`); models reference textures by asset key. Some rows are skipped; the measured breakdown and next steps are in [textures.md](textures.md). | `<work>\assets\ttpf\<pool>\` + `manifest.json` | 108| World textures (TTPF) | **Done: 308,895 textures from all 57 pools, 0 failures, 48,220 entries skipped by the original exporter** (33,507 BCPack, 14,030 compact mapping, 678 arrays/volumes, 5 unsupported format, 0 unmapped). The compact-tail tool resolves 14,011 of the 14,030 layouts and reconstructs 305,264 complete chains (206,661 newly complete, 1,100,865 mips, 4.59 GiB), and the multi-slice pass resolves all 697 arrays/cubemaps/volumes ([textures_arrays.md](textures_arrays.md)). BCPack was the hard blocker: `tools/bcpack.py` decodes all six active modes (BC1, BC3, BC4, BC5, BC6H, BC7), and `rpf9dump`'s C# `TtpfReader` (`e293917` pin, `breadbbbb/rpf9-explorer#7`) now decodes compact tails, multi-slice layouts, DXGI 11, and strict BCPack BC1/BC3/BC4/BC5 directly; BC6H/BC7 and provisional-history chunks remain skipped by `rpf9dump` and can be completed by `tools/ttpf_assets.py` ([textures.md](textures.md)). 46 pools are in `data\ttdb\**`, 11 in `pack\<name>\data\ttdb\**` (exported under `ttpf_pack\<pack>\`). `data\ttdb\**\*.ttpf` (57 pools, 58 GiB) are loose RDS5 texture pools, **not** inside RPFs. rpf9-explorer's `TtpfReader` reads the catalog and detiles them; checked visually (`ttdb_graphics`: scope reticles, clean lines). Names are generated (`texture_N_<assetkey>`); models reference textures by asset key. Some rows are skipped; the measured breakdown and next steps are in [textures.md](textures.md). | `<work>\assets\ttpf\<pool>\` + `manifest.json` |
109| Animation | Indexed without the TOC: 130,470 zlib streams (4,203,762,662 stored / 11,593,460,132 inflated), 95.4% readable. New RAGE page directories (`0DRP`, version 122), `MoVE` (version 19), 273 `pack:/` name tables (2,298 paths), and a tail `RBF0` rig-set manager (`rage__crRigSetManager`: 1,126 rig sets, 6,677 source→rig entries, 3,669 distinct rigs; 56 empty). Bone data: one standalone 28-name table and 3 motion-matcher streams with embedded bone tables (30-name union, 19 joaat32 hashes present, 4 motionmatcher paths); no rig→skeleton link was found. Clip dictionaries are system-only RAGE resources (page map at the `+0x08` pointer). `tools/anim_clips.py` decodes 191,042 of 191,042 animations in 61,505 of them to per-frame values (channel types 0–5, 7, 8 and the GTA VI type 10) and resolves 111,948 of 159,584 `.motion` children to a clip. For each `.motion` it reads the per-child durations and time curves and, on 10,171 of 17,247, the one-axis parameter node (axis name hash, sorted sample values, range). The 2/3 packed streams are second pages of `0DRP` resources, which are not decoded. No `YCD`/`RSC7` at any stream start. The `rpf9_carve` tail overread is measured in `docs/animation.md`. | `tools\anim_index.py`, `<work>\anim-index\` | 109| Animation | Indexed without the TOC: 130,470 zlib streams (4,203,762,662 stored / 11,593,460,132 inflated), 95.4% readable. New RAGE page directories (`0DRP`, version 122), `MoVE` (version 19), 273 `pack:/` name tables (2,298 paths), and a tail `RBF0` rig-set manager (`rage__crRigSetManager`: 1,126 rig sets, 6,677 source→rig entries, 3,669 distinct rigs; 56 empty). Bone data: one standalone 28-name table and 3 motion-matcher streams with embedded bone tables (30-name union, 19 joaat32 hashes present, 4 motionmatcher paths); no rig→skeleton link was found. Clip dictionaries are system-only RAGE resources (page map at the `+0x08` pointer). `tools/anim_clips.py` decodes 191,042 of 191,042 animations in 61,505 of them to per-frame values (channel types 0–5, 7, 8 and the GTA VI type 10) and resolves 111,948 of 159,584 `.motion` children to a clip. For each `.motion` it reads the per-child durations and time curves and, on 10,171 of 17,247, the one-axis parameter node (axis name hash, sorted sample values, range). The 2/3 packed streams are second pages of `0DRP` resources, which are not decoded. No `YCD`/`RSC7` at any stream start. The `rpf9_carve` tail overread is measured in `docs/animation.md`. | `tools\anim_index.py`, `<work>\anim-index\` |
110| Audio | `audio.rpf` holds raw (not zlib) **AWC** banks: Opus (codec 0x0B) and XMA2 streams. Exported as whole `.awc` files plus `audio_manifest.json` (stream ids, codec, channels, rate, duration). **Done: 7,162 banks, 27 GiB, 1,603,231 streams, about 1,324 hours** (codec 0x0B Opus 1,601,167; 5: 1,818; 2: 227; 0 PCM: 19). `tools/awc_opus.py` repackages every Opus stream **losslessly** into a standard Ogg Opus file (no re-encode; PCM streams become .wav). The AWC framing is 2048-byte blocks of [u16 length][packet], with a zero length padding the block (as rpf9-explorer's OpusPreview reads it). The final granule is `pre-skip + declared samples`, so decoders drop the 312-sample libopus priming and stop at the declared end. Checked: 300 random streams decode with ffmpeg with no errors, lengths match the declared counts. XMA2 streams (codec 5, 1,818) are written as RIFF XMA2 files by `rpf9dump xma` (rpf9-explorer's `AwcRecovery.WriteXmaWave`) and decoded to PCM WAV by ffmpeg: all 1,818 decode. Streamed music (tag 0x48: chunks with a per-channel record table, each channel's 2048-byte subblocks after the aligned header, and a repeated-prefix skip per chunk) becomes one Ogg Opus per descriptor channel (3,008 banks contain music). The Opus TOC stereo bit gives the packet channel count; a 1-channel descriptor can carry stereo packets, whose interleaved sample count is halved for the end granule. Checked: a 4-channel bank gives four 42.0 s mono channels; 1-channel stereo banks export at the config duration. Output: `<work>\assets\audio\ogg\<bank>\<stream id>.ogg`. **Done: 1,598,051 Opus streams + 3,116 music channels as Ogg Opus (22 GB), 19 PCM16 and 227 codec-2 streams (32-bit float PCM, 4 bytes per sample; values can exceed ±1) as WAV, 1,818 XMA2 as WAV. Every audio stream is converted; all WAVs decode.** `make_game.py --wav` also decodes the Ogg Opus output to 16-bit PCM WAV with `tools/audio_wav.py` (ffmpeg required; existing WAVs are skipped on resume). | `<work>\assets\audio\awc\` | 110| Audio | `audio.rpf` holds raw (not zlib) **AWC** banks: Opus (codec 0x0B) and XMA2 streams. Exported as whole `.awc` files plus `audio_manifest.json` (stream ids, codec, channels, rate, duration). **Done: 7,162 banks, 27 GiB, 1,603,231 streams, about 1,324 hours** (codec 0x0B Opus 1,601,167; 5: 1,818; 2: 227; 0 PCM: 19). `tools/awc_opus.py` repackages every Opus stream **losslessly** into a standard Ogg Opus file (no re-encode; PCM streams become .wav). The AWC framing is 2048-byte blocks of [u16 length][packet], with a zero length padding the block (as rpf9-explorer's OpusPreview reads it). The final granule is `pre-skip + declared samples`; the EOS page is emitted at the packet that reaches that target and later padding packets are dropped, so decoders stop at the declared end. Checked: 20 real streams at 48 and 32 kHz decode to exactly their declared counts; 300 random streams decode with ffmpeg with no errors. XMA2 streams (codec 5, 1,818) are written as RIFF XMA2 files by `rpf9dump xma` (rpf9-explorer's `AwcRecovery.WriteXmaWave`) and decoded to PCM WAV by ffmpeg: all 1,818 decode. Streamed music (tag 0x48: chunks with a per-channel record table, each channel's 2048-byte subblocks after the aligned header, and a repeated-prefix skip per chunk) becomes one Ogg Opus per descriptor channel (3,008 banks contain music). The Opus TOC stereo bit gives the packet channel count; a 1-channel descriptor can carry stereo packets, whose interleaved sample count is halved for the end granule. Checked: a 4-channel bank gives four 42.0 s mono channels; 1-channel stereo banks export at the config duration. Output: `<work>\assets\audio\ogg\<bank>\<stream id>.ogg`. **Done: 1,598,051 Opus streams + 3,116 music channels as Ogg Opus (22 GB), 19 PCM16 and 227 codec-2 streams (32-bit float PCM, 4 bytes per sample; values can exceed ±1) as WAV, 1,818 XMA2 as WAV. Every audio stream is converted; all WAVs decode.** `make_game.py --wav` also decodes the Ogg Opus output to 16-bit PCM WAV with `tools/audio_wav.py` (ffmpeg required; existing WAVs are skipped on resume). | `<work>\assets\audio\awc\` |
111| World placement | **Full census of `levels.rpf`:** 23,535 map resources / 1,670,442 entities; all maps/entities exact, 36/36 shards, 98.32% stream coverage. Map files occupy a continuous band from ~7.5 to ~62.9 GiB; the earlier 9,918 / 680,228 sample was a 55% lower bound. `0x7a` resources: `CMapData` root, 0x90-byte `CEntityDef` with position/quaternion/scale/archetype/flags/per-entity id/per-archetype key/LOD fields; names and most archetypes are hash-only. Archetype and map names are lower-cased joaat, confirmed by a MurmurHash3 x64 low-64 key; see [world_names.md](world_names.md). | `tools\world_index.py`, `tools\world_census.py`, `tools\world_names.py`; [world.md](world.md), [world_census.md](world_census.md), [world_names.md](world_names.md) | 111| World placement | **Full census of `levels.rpf`:** 23,535 map resources / 1,670,442 entities; all maps/entities exact, 36/36 shards, 98.32% stream coverage. Map files occupy a continuous band from ~7.5 to ~62.9 GiB; the earlier 9,918 / 680,228 sample was a 55% lower bound. `0x7a` resources: `CMapData` root, 0x90-byte `CEntityDef` with position/quaternion/scale/archetype/flags/per-entity id/per-archetype key/LOD fields; names and most archetypes are hash-only. Archetype and map names are lower-cased joaat, confirmed by a MurmurHash3 x64 low-64 key; see [world_names.md](world_names.md). | `tools\world_index.py`, `tools\world_census.py`, `tools\world_names.py`; [world.md](world.md), [world_census.md](world_census.md), [world_names.md](world_names.md) |
112| Navmeshes | `navmeshes.rpf`: 90,295 zlib streams (6,540,238,392 stored / 20,551,068,624 inflated), 97.5% readable; 9,603 `0DRP` pages and 27,644 `0x00010015` pages, no `NAVM`/`CNavMesh`/`NVMS` magic. `0DRP` is generic RPF paging, not a navmesh container. | `tools\navmesh_index.py`; [navmesh.md](navmesh.md) | 112| Navmeshes | `navmeshes.rpf`: 90,295 zlib streams (6,540,238,392 stored / 20,551,068,624 inflated), 97.5% readable; 9,603 `0DRP` pages and 27,644 `0x00010015` pages, no `NAVM`/`CNavMesh`/`NVMS` magic. `0DRP` is generic RPF paging, not a navmesh container. | `tools\navmesh_index.py`; [navmesh.md](navmesh.md) |
113| BVH | `core_bvh4.rpf`: 565,596 streams, 271,627 complete BVH4 streams + 10 eight-MiB split continuations, 269,106 instance records. Header `0x81020006` at +0x100, 64-byte node units, 208-byte instances with a 3x4 transform; prebuilt acceleration data, not source meshes or shaders. | `tools\bvh_index.py`; [bvh.md](bvh.md) | 113| BVH | `core_bvh4.rpf`: 565,596 streams, 271,627 complete BVH4 streams + 10 eight-MiB split continuations, 269,106 instance records. Header `0x81020006` at +0x100, 64-byte node units, 208-byte instances with a 3x4 transform; prebuilt acceleration data, not source meshes or shaders. | `tools\bvh_index.py`; [bvh.md](bvh.md) |
@@ -228,12 +228,13 @@ How the generated SPIR-V expects the runtime to work:
228| Global atomics (`global_atomic_*`, 32-bit) | `add`, `sub`, `smin/umin`, `smax/umax`, `and`, `or`, `xor`, `swap` and `cmpswap` at the `global_load/store` address (same `Gen.global_address`: saddr pair plus zero-extended vaddr, or a 64-bit vaddr with `off`, plus the signed 12-bit offset), as one `OpAtomic*` on the PhysicalStorageBuffer dword, device scope, guarded so inactive lanes don't touch memory. With `glc` the pre-op value lands in `vdst`, the first operand; without `glc` there is no `vdst`, and the first-read analysis counts operand 0 as the address (a source). `cmpswap` takes `vdata` as the pair {DATA, CMP}: `M = (M == CMP) ? DATA : M`, as `buffer_atomic_cmpswap`. Still `Unsupported`: the `_x2` 64-bit forms, `inc`/`dec`, the float atomics, and `slc`/`dlc`. Until 2026-11-22 every global atomic was rejected. CPU-checked by `tests/semantic/test_global_atomics.py` (all ten ops on a value grid with and without `glc`, `cmpswap`, offsets from -2048 to 2044, `off` addressing, seeded values, rejected forms, the first-read analysis). **Not GPU-verified.** | 228| Global atomics (`global_atomic_*`, 32-bit) | `add`, `sub`, `smin/umin`, `smax/umax`, `and`, `or`, `xor`, `swap` and `cmpswap` at the `global_load/store` address (same `Gen.global_address`: saddr pair plus zero-extended vaddr, or a 64-bit vaddr with `off`, plus the signed 12-bit offset), as one `OpAtomic*` on the PhysicalStorageBuffer dword, device scope, guarded so inactive lanes don't touch memory. With `glc` the pre-op value lands in `vdst`, the first operand; without `glc` there is no `vdst`, and the first-read analysis counts operand 0 as the address (a source). `cmpswap` takes `vdata` as the pair {DATA, CMP}: `M = (M == CMP) ? DATA : M`, as `buffer_atomic_cmpswap`. Still `Unsupported`: the `_x2` 64-bit forms, `inc`/`dec`, the float atomics, and `slc`/`dlc`. Until 2026-11-22 every global atomic was rejected. CPU-checked by `tests/semantic/test_global_atomics.py` (all ten ops on a value grid with and without `glc`, `cmpswap`, offsets from -2048 to 2044, `off` addressing, seeded values, rejected forms, the first-read analysis). **Not GPU-verified.** |
229| 8/16-bit global stores and d16 loads | `global_store_byte`/`short` write the low 8/16 bits of the data VGPR (the `_d16_hi` forms its high half). `global_load_{u,s}byte_d16` and `global_load_short_d16` write the low 16 bits of `vdst` (the `_hi` forms the high 16) and keep the other half; `ubyte` zero-extends and `sbyte` sign-extends the byte to 16 bits. The address is the `global_load/store` one (`Gen.global_address`). The access goes one byte at a time, so a 16-bit access that crosses a dword (at byte 3) is exact too. A store merges each byte into its dword with atomic and/or, which keeps neighbouring bytes even when another lane writes them, as buffer byte stores do. A load reads each byte. Inactive lanes neither store nor load. The first-read analysis counts a d16 load's `vdst` as read, for the half it keeps. `global_load/store_dword_addtid` (lane-id and M0 addressing) raise `Unsupported`; until 2026-11-22 they crashed with `IndexError`, and the ten sub-dword ops raised `Unsupported`. CPU-checked by `tests/semantic/test_global_sub_dword.py` (every byte offset 0 to 7 for each op, an inactive lane, rejected forms, the first-read analysis). **Not GPU-verified.** | 229| 8/16-bit global stores and d16 loads | `global_store_byte`/`short` write the low 8/16 bits of the data VGPR (the `_d16_hi` forms its high half). `global_load_{u,s}byte_d16` and `global_load_short_d16` write the low 16 bits of `vdst` (the `_hi` forms the high 16) and keep the other half; `ubyte` zero-extends and `sbyte` sign-extends the byte to 16 bits. The address is the `global_load/store` one (`Gen.global_address`). The access goes one byte at a time, so a 16-bit access that crosses a dword (at byte 3) is exact too. A store merges each byte into its dword with atomic and/or, which keeps neighbouring bytes even when another lane writes them, as buffer byte stores do. A load reads each byte. Inactive lanes neither store nor load. The first-read analysis counts a d16 load's `vdst` as read, for the half it keeps. `global_load/store_dword_addtid` (lane-id and M0 addressing) raise `Unsupported`; until 2026-11-22 they crashed with `IndexError`, and the ten sub-dword ops raised `Unsupported`. CPU-checked by `tests/semantic/test_global_sub_dword.py` (every byte offset 0 to 7 for each op, an inactive lane, rejected forms, the first-read analysis). **Not GPU-verified.** |
230| Literal samplers | Some shaders build their S# from immediates (for example `0x92, 0xC00000, 0x14500000, 0`). The runtime registers those in the descriptor hash table too, by scanning the translated shaders' constant S# values, not only S#s the game binds. | 230| Literal samplers | Some shaders build their S# from immediates (for example `0x92, 0xC00000, 0x14500000, 0`). The runtime registers those in the descriptor hash table too, by scanning the translated shaders' constant S# values, not only S#s the game binds. |
231| Scalar/buffer memory | `s_load*`, `s_buffer_load*`, `buffer_load*` and `buffer_store*` use buffer device addresses (`PhysicalStorageBuffer64`). The base comes from the 64-bit SGPR pointer or the V# (dword0 \| dword1[15:0] << 32), and the stride is V# dword1[29:16]. **The runtime must put the game's GPU heap in buffer-device-addressable memory at the same addresses the game writes into descriptors** (or remap them). `s_load*` and `s_buffer_load*` take an immediate or an SGPR offset, or both at once (llvm-mc prints `sOFF offset:IMM`). Rules, measured on AMD Radeon RX 6800 (gfx1030, Windows driver 32.0.21045.29003) by running the instructions as a raw compute kernel, wave32 and wave64 (155 runs, every result either 0 or the stored data, wave32 = wave64 in every dword): **address** = (base & ~3) + (sOFF & ~3) + (IMM & ~3) + 4·i for dword i: base, sOFF and IMM are each truncated to a multiple of 4, then added (`s_buffer_load_dword s9, s[24:27], 0x3` with base & 3 = 1 reads +0, not bytes 4..7; sOFF 3 + IMM 3 reads +0 and sOFF 2 + IMM 6 reads +4, where truncating the sum gives +4 and +8; sOFF 8 + IMM 4 reads +12; the same for `s_load*` with pointer & 3 = 1 or 3). **`s_buffer_load*` bound**: dword i is 0, and memory is not read, when (sOFF & ~3) + (IMM & ~3) + 4·i + 4 > limit, with limit = NUM_RECORDS (V# dword2) bytes when the stride is 0 and NUM_RECORDS × stride bytes when it is not. Per dword (x4 at 0xc with NUM_RECORDS 21: data, data, 0, 0; x8 at 0 with 21: five data, three 0), on the truncated offset (IMM 0x10 with NUM_RECORDS 18: 0; IMM 0x13 with 21: the dword at +0x10; sOFF 0xe + IMM 2 with 16: the dword at +0xc; sOFF 0x10 + IMM 4 with 20: 0), not seeing base & 3 (base & 3 = 3, IMM 0x13, NUM_RECORDS 20: data); with a stride the test is still on bytes (stride 4, NUM_RECORDS 5: IMM 0x10 data, 0x14 0; stride 1, NUM_RECORDS 17: IMM 0x10 is 0, so it is not an index test). IMM is unsigned (0xffffc reads +0xffffc). OOB_SELECT (V# word3[29:28]) 0, 1, 2 and 3 gave the same pattern (7 probes per value). **`s_load*`**: no bound (+0x1ffffc reads the dword there); IMM is sign-extended from 21 bits and added in 64 bits (sOFF 8 + IMM −4 reads +4 where zero-extension reads 4 GiB further; sOFF 0xb + IMM −1 reads +4, so the negative IMM is truncated on its own: −1 → −4). Not measured: `s_load`/`s_buffer_load` with sOFF + IMM < 0 (a negative IMM without sOFF included; the translator uses the 64-bit signed sum, an inference), an `s_buffer_load` IMM with bit 20 set (llvm-mc rejects it) or a negative one (kept as the 32-bit value: for stride 0 that is past any NUM_RECORDS below 4 GiB), `x16` (gets the x8 rule), sOFF ≥ 2^31, NUM_RECORDS ≥ 2^31 and NUM_RECORDS × stride ≥ 2^32, V# dword1[31:30], and gfx1013 (PS5) itself. The translator checks each `s_buffer_load` dword with its own structured `if` and an `OpPhi` with 0, so an out-of-range dword issues no load; `s_load` stays straight-line. Before this the translator added base + sOFF + IMM unaligned, had no `s_buffer_load` bound and zero-extended a negative `s_load` IMM. Checked by `tests/semantic/test_scalar_mem_smem.py` (`SmemHardwareRuleTests`, the measurement's rows, values and the addresses read; `SmemSoffsetImmTranslatorTests`) and by the GPU tests `runtime/test/shaders/cs_smem_soffset_imm.asm`, `cs_smem_bounds.asm`, `cs_smem_stride_align.asm` and `cs_smem_sload_neg.asm` (never run that one with a translator that zero-extends the immediate: it reads 4 GiB past the heap), all in `check.py` and `scripts/run_gpu_tests.py`, which pass on the RX 6800 (Vulkan, driver 26.11.2). See *Buffer bounds checking* below for the MUBUF `num_records` checks. | 231| Scalar/buffer memory | `s_load*`, `s_buffer_load*`, `buffer_load*` and `buffer_store*` use buffer device addresses (`PhysicalStorageBuffer64`). The base comes from the 64-bit SGPR pointer or the V# (dword0 \| dword1[15:0] << 32), and the stride is V# dword1[29:16]. **The runtime must put the game's GPU heap in buffer-device-addressable memory at the same addresses the game writes into descriptors** (or remap them). `s_load*` and `s_buffer_load*` take an immediate or an SGPR offset, or both at once (llvm-mc prints `sOFF offset:IMM`). Rules, measured on AMD Radeon RX 6800 (gfx1030, Windows driver 32.0.21045.29003) by running the instructions as a raw compute kernel, wave32 and wave64 (155 runs, every result either 0 or the stored data, wave32 = wave64 in every dword): **address** = (base & ~3) + (sOFF & ~3) + (IMM & ~3) + 4·i for dword i: base, sOFF and IMM are each truncated to a multiple of 4, then added (`s_buffer_load_dword s9, s[24:27], 0x3` with base & 3 = 1 reads +0, not bytes 4..7; sOFF 3 + IMM 3 reads +0 and sOFF 2 + IMM 6 reads +4, where truncating the sum gives +4 and +8; sOFF 8 + IMM 4 reads +12; the same for `s_load*` with pointer & 3 = 1 or 3). **`s_buffer_load*` bound**: dword i is 0, and memory is not read, when (sOFF & ~3) + (IMM & ~3) + 4·i + 4 > limit, with limit = NUM_RECORDS (V# dword2) bytes when the stride is 0 and NUM_RECORDS × stride bytes when it is not. Per dword (x4 at 0xc with NUM_RECORDS 21: data, data, 0, 0; x8 at 0 with 21: five data, three 0), on the truncated offset (IMM 0x10 with NUM_RECORDS 18: 0; IMM 0x13 with 21: the dword at +0x10; sOFF 0xe + IMM 2 with 16: the dword at +0xc; sOFF 0x10 + IMM 4 with 20: 0), not seeing base & 3 (base & 3 = 3, IMM 0x13, NUM_RECORDS 20: data); with a stride the test is still on bytes (stride 4, NUM_RECORDS 5: IMM 0x10 data, 0x14 0; stride 1, NUM_RECORDS 17: IMM 0x10 is 0, so it is not an index test). IMM is unsigned (0xffffc reads +0xffffc). OOB_SELECT (V# word3[29:28]) 0, 1, 2 and 3 gave the same pattern (7 probes per value). **`s_load*`**: no bound (+0x1ffffc reads the dword there); IMM is sign-extended from 21 bits and added in 64 bits (sOFF 8 + IMM −4 reads +4 where zero-extension reads 4 GiB further; sOFF 0xb + IMM −1 reads +4, so the negative IMM is truncated on its own: −1 → −4). Not measured: `s_load`/`s_buffer_load` with sOFF + IMM < 0 (a negative IMM without sOFF included; the translator uses the 64-bit signed sum, an inference), an `s_buffer_load` IMM with bit 20 set (llvm-mc rejects it) or a negative one (kept as the 32-bit value: for stride 0 that is past any NUM_RECORDS below 4 GiB), `x16` (gets the x8 rule), sOFF ≥ 2^31, NUM_RECORDS ≥ 2^31 and NUM_RECORDS × stride ≥ 2^32, V# dword1[31:30], and gfx1013 (PS5) itself. The translator checks each `s_buffer_load` dword with its own structured `if` and an `OpPhi` with 0, so an out-of-range dword issues no load (when descriptor limit and offset are compile-time constants, in-range dwords fold to straight-line loads and out-of-range dwords emit constant zero without branches); `s_load` stays straight-line. Before this the translator added base + sOFF + IMM unaligned, had no `s_buffer_load` bound and zero-extended a negative `s_load` IMM. Checked by `tests/semantic/test_scalar_mem_smem.py` (`SmemHardwareRuleTests`, the measurement's rows, values and the addresses read; `SmemSoffsetImmTranslatorTests`) and by the GPU tests `runtime/test/shaders/cs_smem_soffset_imm.asm`, `cs_smem_bounds.asm`, `cs_smem_stride_align.asm` and `cs_smem_sload_neg.asm` (never run that one with a translator that zero-extends the immediate: it reads 4 GiB past the heap), all in `check.py` and `scripts/run_gpu_tests.py`, which pass on the RX 6800 (Vulkan, driver 26.11.2). See *Buffer bounds checking* below for the MUBUF `num_records` checks. |
232| 2D array resource dimensions | For `image_get_resinfo` on a 2D array, X/Y are the width/height at the requested mip, Z is the view layer count and W is its mip count. The query reads the sampled array at binding 3. A native gfx1036 kernel returned (19,11,5,3), (9,5,5,3) and (4,2,5,3) for the three mips of a synthetic array. On RTX 5080 and Radeon Graphics the translated query matched those tuples and returned (4,2,3,2) at relative mip 1 with a view starting at mip 1 and covering three layers. The registered `ps_array_resinfo` draw checks all 4096 pixels against (8,8,12,1). | 232| 2D array resource dimensions | For `image_get_resinfo` on a 2D array, X/Y are the width/height at the requested mip, Z is the view layer count and W is its mip count. The query reads the sampled array at binding 3. A native gfx1036 kernel returned (19,11,5,3), (9,5,5,3) and (4,2,5,3) for the three mips of a synthetic array. On RTX 5080 and Radeon Graphics the translated query matched those tuples and returned (4,2,3,2) at relative mip 1 with a view starting at mip 1 and covering three layers. The registered `ps_array_resinfo` draw checks all 4096 pixels against (8,8,12,1). |
233| Scalar/buffer memory | `s_load*`, `s_buffer_load*`, `buffer_load*` and `buffer_store*` use buffer device addresses (`PhysicalStorageBuffer64`). The base comes from the 64-bit SGPR pointer or the V# (dword0 \| dword1[15:0] << 32), and the stride is V# dword1[29:16]. **The runtime must put the game's GPU heap in buffer-device-addressable memory at the same addresses the game writes into descriptors** (or remap them). `s_load*` and `s_buffer_load*` take an immediate or an SGPR offset, or both at once (llvm-mc prints `sOFF offset:IMM`). Rules, measured on AMD Radeon RX 6800 (gfx1030, Windows driver 32.0.21045.29003) by running the instructions as a raw compute kernel, wave32 and wave64 (155 runs, every result either 0 or the stored data, wave32 = wave64 in every dword): **address** = (base & ~3) + (sOFF & ~3) + (IMM & ~3) + 4·i for dword i: base, sOFF and IMM are each truncated to a multiple of 4, then added (`s_buffer_load_dword s9, s[24:27], 0x3` with base & 3 = 1 reads +0, not bytes 4..7; sOFF 3 + IMM 3 reads +0 and sOFF 2 + IMM 6 reads +4, where truncating the sum gives +4 and +8; sOFF 8 + IMM 4 reads +12; the same for `s_load*` with pointer & 3 = 1 or 3). **`s_buffer_load*` bound**: dword i is 0, and memory is not read, when (sOFF & ~3) + (IMM & ~3) + 4·i + 4 > limit, with limit = NUM_RECORDS (V# dword2) bytes when the stride is 0 and NUM_RECORDS × stride bytes when it is not. Per dword (x4 at 0xc with NUM_RECORDS 21: data, data, 0, 0; x8 at 0 with 21: five data, three 0), on the truncated offset (IMM 0x10 with NUM_RECORDS 18: 0; IMM 0x13 with 21: the dword at +0x10; sOFF 0xe + IMM 2 with 16: the dword at +0xc; sOFF 0x10 + IMM 4 with 20: 0), not seeing base & 3 (base & 3 = 3, IMM 0x13, NUM_RECORDS 20: data); with a stride the test is still on bytes (stride 4, NUM_RECORDS 5: IMM 0x10 data, 0x14 0; stride 1, NUM_RECORDS 17: IMM 0x10 is 0, so it is not an index test). IMM is unsigned (0xffffc reads +0xffffc). OOB_SELECT (V# word3[29:28]) 0, 1, 2 and 3 gave the same pattern (7 probes per value). **`s_load*`**: no bound (+0x1ffffc reads the dword there); IMM is sign-extended from 21 bits and added in 64 bits (sOFF 8 + IMM −4 reads +4 where zero-extension reads 4 GiB further; sOFF 0xb + IMM −1 reads +4, so the negative IMM is truncated on its own: −1 → −4). Not measured: `s_load`/`s_buffer_load` with sOFF + IMM < 0 (a negative IMM without sOFF included; the translator uses the 64-bit signed sum, an inference), an `s_buffer_load` IMM with bit 20 set (llvm-mc rejects it) or a negative one (kept as the 32-bit value: for stride 0 that is past any NUM_RECORDS below 4 GiB), `x16` (gets the x8 rule), sOFF ≥ 2^31, NUM_RECORDS ≥ 2^31 and NUM_RECORDS × stride ≥ 2^32, V# dword1[31:30], and gfx1013 (PS5) itself. The translator checks each `s_buffer_load` dword with its own structured `if` and an `OpPhi` with 0, so an out-of-range dword issues no load (when descriptor limit and offset are compile-time constants, in-range dwords fold to straight-line loads and out-of-range dwords emit constant zero without branches); `s_load` stays straight-line. Before this the translator added base + sOFF + IMM unaligned, had no `s_buffer_load` bound and zero-extended a negative `s_load` IMM. Checked by `tests/semantic/test_scalar_mem_smem.py` (`SmemHardwareRuleTests`, the measurement's rows, values and the addresses read; `SmemSoffsetImmTranslatorTests`) and by the GPU tests `runtime/test/shaders/cs_smem_soffset_imm.asm`, `cs_smem_bounds.asm`, `cs_smem_stride_align.asm` and `cs_smem_sload_neg.asm` (never run that one with a translator that zero-extends the immediate: it reads 4 GiB past the heap), all in `check.py` and `scripts/run_gpu_tests.py`, which pass on the RX 6800 (Vulkan, driver 26.11.2). See *Buffer bounds checking* below for the MUBUF `num_records` checks. |
233| Images and samplers | `image_sample_l` on 2D arrays used to read its LOD from the array layer; it now reads the LOD after all coordinates. `image_get_lod` and `image_gather4_lz` also work on 2D arrays. With `d16` every sample result is f16, packed two to a VGPR from the low half (the packed D16 of GFX10, as LLVM returns D16 image data); `image_sample_c_lz`/`_c_lz_o` follow it too, and until 2026-11-21 their compare result was written as f32 bits, which read as 0 in the low half. Checked by `tests/test_translate.py` (`test_depth_compare_sample_result_width`) and GPU-checked with `runtime/test/shaders/ps_sample_c_lz.asm` (`vk_texture_test dref`: a D32 texture and a LESS_OR_EQUAL compare sampler) on an NVIDIA GeForce RTX 2060 SUPER (Linux, driver 620.70.06): 4096/4096 pixels exact for f32 and `d16`; with the old translator the `d16` result read 0 in the 2048 pixels whose compare passes. | 234| Images and samplers | `image_sample_l` on 2D arrays used to read its LOD from the array layer; it now reads the LOD after all coordinates. `image_get_lod` and `image_gather4_lz` also work on 2D arrays. With `d16` every sample result is f16, packed two to a VGPR from the low half (the packed D16 of GFX10, as LLVM returns D16 image data); `image_sample_c_lz`/`_c_lz_o` follow it too, and until 2026-11-21 their compare result was written as f32 bits, which read as 0 in the low half. Checked by `tests/test_translate.py` (`test_depth_compare_sample_result_width`) and GPU-checked with `runtime/test/shaders/ps_sample_c_lz.asm` (`vk_texture_test dref`: a D32 texture and a LESS_OR_EQUAL compare sampler) on an NVIDIA GeForce RTX 2060 SUPER (Linux, driver 620.70.06): 4096/4096 pixels exact for f32 and `d16`; with the old translator the `d16` result read 0 in the 2048 pixels whose compare passes. |
234| Typed buffer loads | The format is V# word3[18:12] (GFX10_FORMAT, from Mesa's `gfx10-rsrc.json`, saved as `tools\gfx10_formats.json`). Supported: f32 ×1–4, u32 ×1/2/4, f16 ×1/2/4, unorm8 ×1/2/4, snorm8 ×1/2/4, uint8 ×4, unorm16 ×1/2/4, snorm16 ×1/2/4, 10-10-10-2 and 2-10-10-10 unorm. Others give 0. DST_SEL swizzle is applied (0→0, 1→1.0f for float/norm or integer 1 for UINT/SINT, 4..7→X..W). Missing channels repeat the format's own (component *c* = *c* mod *n*), measured on an RX 6700 (SHADER-86). UNORM/SNORM give the correctly rounded quotient by (2ⁿ−1), as the hardware does (0 mismatches vs hardware over 395,776 conversions on that GPU). It is built with integer ops (`Gen.norm_bits`): x/(2ⁿ−1) in binary is x's bits repeated, so a 64-bit multiply by the repeat pattern, `FindUMsb` and the round bit give the f32 exactly (the tail never ends, so there are no ties). `OpFDiv` is not enough on the GPU: Vulkan allows it 2.5 ULP, and on an RX 6700 (AMD Windows 26.11.2) and an RTX 5090 it returned the reciprocal-multiply bits (8_UNORM 130/256 exact, #599). Checked against exact values in `tests/semantic/test_norm_decode.py` (every value up to 8 bits, edges and the reciprocal-multiply misses for 10, 15 and 16 bits). 8_SNORM (2), 16_SNORM (8) and 8_8_SNORM (15) were missing until 2026-11-22 and decoded to 0. Format names list the channel widths from the top bit, so `2_10_10_10` (50) is R10G10B10A2 and `10_10_10_2` (44) has a 2-bit x (Mesa `gfx10_format_table.py`, `ac_formats.c`). Until 2026-11-22 the two were swapped, in stores too. Until 2026-11-21 an element that started mid-dword re-read dword 0 for its tail (`need` was `ceil(size/4)` and only the first dword was shifted); loads now take `need = ceil((byte_shift + size) / 4)` dwords and shift the whole window so the packed stream starts at the element (FUZZ-5, leftover from #234). The 10:10:10:2 order is checked by `cs_fmt_1010102` in `tests/semantic/test_value_semantics.py` (the shader decodes the format, so a GPU run can't check it). Mid-dword spanning elements are checked by `tests/semantic/test_buffer_load_format.py` (`CrossingDwordBoundary`); repeat / UNORM / DST_SEL 1 by the SHADER-86 cases in the same file. | 235| Typed buffer loads | The format is V# word3[18:12] (GFX10_FORMAT, from Mesa's `gfx10-rsrc.json`, saved as `tools\gfx10_formats.json`). Supported: f32 ×1–4, u32 ×1–4, i32 ×1–4 (formats 21/63/73/76), f16 ×1/2/4, unorm8 ×1/2/4, snorm8 ×1/2/4, uint8 ×4, unorm16 ×1/2/4, snorm16 ×1/2/4, 10-10-10-2 and 2-10-10-10 unorm. Others give 0. Full-width SINT accesses preserve integer bits. D16 SINT loads saturate to signed 16-bit and D16 stores sign-extend, covered by the synthetic `cs_fmt_sint32.asm` readback. DST_SEL swizzle is applied (0→0, 1→1.0f for float/norm or integer 1 for UINT/SINT, 4..7→X..W). Missing channels repeat the format's own (component *c* = *c* mod *n*), measured on an RX 6700 (SHADER-86). UNORM/SNORM give the correctly rounded quotient by (2ⁿ−1), as the hardware does (0 mismatches vs hardware over 395,776 conversions on that GPU). It is built with integer ops (`Gen.norm_bits`): x/(2ⁿ−1) in binary is x's bits repeated, so a 64-bit multiply by the repeat pattern, `FindUMsb` and the round bit give the f32 exactly (the tail never ends, so there are no ties). `OpFDiv` is not enough on the GPU: Vulkan allows it 2.5 ULP, and on an RX 6700 (AMD Windows 26.11.2) and an RTX 5090 it returned the reciprocal-multiply bits (8_UNORM 130/256 exact, #599). Checked against exact values in `tests/semantic/test_norm_decode.py` (every value up to 8 bits, edges and the reciprocal-multiply misses for 10, 15 and 16 bits). 8_SNORM (2), 16_SNORM (8) and 8_8_SNORM (15) were missing until 2026-11-22 and decoded to 0. Format names list the channel widths from the top bit, so `2_10_10_10` (50) is R10G10B10A2 and `10_10_10_2` (44) has a 2-bit x (Mesa `gfx10_format_table.py`, `ac_formats.c`). Until 2026-11-22 the two were swapped, in stores too. Until 2026-11-21 an element that started mid-dword re-read dword 0 for its tail (`need` was `ceil(size/4)` and only the first dword was shifted); loads now take `need = ceil((byte_shift + size) / 4)` dwords and shift the whole window so the packed stream starts at the element (FUZZ-5, leftover from #234). The 10:10:10:2 order is checked by `cs_fmt_1010102` in `tests/semantic/test_value_semantics.py` (the shader decodes the format, so a GPU run can't check it). Mid-dword spanning elements are checked by `tests/semantic/test_buffer_load_format.py` (`CrossingDwordBoundary`); repeat / UNORM / DST_SEL 1 by the SHADER-86 cases in the same file. |
235| Images and samplers (core) | Bindless. Set 0: binding 0 = 2D sampled images, 1 = samplers, 2 = descriptor hash table (storage buffer), 3 = 2D-array images (**cube textures are bound here as 6-layer 2D-array views**, cube arrays as 6N layers: the shader already selected the face with `v_cube*`), 4 = r32ui storage images, 5 = 1D, 6 = 3D. A cube sample's s and t come in [1, 2] and its third coordinate is 8·slice + face, as the hardware takes them (Mesa `ac_nir_lower_tex_coords.c`, LLPC `ImageBuilder.cpp`); the view is read at (s − 1, t − 1), layer 6·slice + face. GPU-checked with `runtime/test/shaders/ps_cube_sample.asm` (`vk_texture_test cube`). For a native Metal path, `tools/spirv_metal_set0.py` sizes set 0's runtime arrays from `vulkan_bindless.h` and moves each binding to its own argument-buffer ID range (binding b starts at the capacities of bindings 0..b-1 added up), to convert with SPIRV-Cross `--msl-decoration-binding`: SPIRV-Cross 1.4.363.0 otherwise puts every runtime array at one ID and comments all but one out as "Overlapping binding" (SHADER-161). `cs_imgstore` converted this way writes all 3×64 texels correctly in a native Metal dispatch on an Apple A18 Pro. | 236| Images and samplers (core) | Bindless. Set 0: binding 0 = 2D sampled images, 1 = samplers, 2 = descriptor hash table (storage buffer), 3 = 2D-array images (**cube textures are bound here as 6-layer 2D-array views**, cube arrays as 6N layers: the shader already selected the face with `v_cube*`), 4 = r32ui storage images, 5 = 1D, 6 = 3D. A cube sample's s and t come in [1, 2] and its third coordinate is 8·slice + face, as the hardware takes them (Mesa `ac_nir_lower_tex_coords.c`, LLPC `ImageBuilder.cpp`); the view is read at (s − 1, t − 1), layer 6·slice + face. GPU-checked with `runtime/test/shaders/ps_cube_sample.asm` (`vk_texture_test cube`). For a native Metal path, `tools/spirv_metal_set0.py` sizes set 0's runtime arrays from `vulkan_bindless.h` and moves each binding to its own argument-buffer ID range (binding b starts at the capacities of bindings 0..b-1 added up), to convert with SPIRV-Cross `--msl-decoration-binding`: SPIRV-Cross 1.4.363.0 otherwise puts every runtime array at one ID and comments all but one out as "Overlapping binding" (SHADER-161). `cs_imgstore` converted this way writes all 3×64 texels correctly in a native Metal dispatch on an Apple A18 Pro. |
236| Typed buffer loads | The format is V# word3[18:12] (GFX10_FORMAT, from Mesa's `gfx10-rsrc.json`, saved as `tools\gfx10_formats.json`). Supported: f32 ×1–4, u32 ×1/2/4, f16 ×1/2/4, unorm8 ×1/2/4, snorm8 ×1/2/4, uint8 ×4, unorm16 ×1/2/4, snorm16 ×1/2/4, 10-10-10-2 and 2-10-10-10 unorm. Others give 0. DST_SEL swizzle is applied (0→0, 1→1.0f for float/norm or integer 1 for UINT/SINT, 4..7→X..W). Missing channels repeat the format's own (component *c* = *c* mod *n*), measured on an RX 6700 (SHADER-86). UNORM/SNORM give the correctly rounded quotient by (2ⁿ−1), as the hardware does (0 mismatches vs hardware over 395,776 conversions on that GPU). It is built with integer ops (`Gen.norm_bits`): x/(2ⁿ−1) in binary is x's bits repeated, so a 64-bit multiply by the repeat pattern, `FindUMsb` and the round bit give the f32 exactly (the tail never ends, so there are no ties). `OpFDiv` is not enough on the GPU: Vulkan allows it 2.5 ULP, and on an RX 6700 (AMD Windows 26.11.2) and an RTX 5090 it returned the reciprocal-multiply bits (8_UNORM 130/256 exact, #599). Checked against exact values in `tests/semantic/test_norm_decode.py` (every value up to 8 bits, edges and the reciprocal-multiply misses for 10, 15 and 16 bits). 8_SNORM (2), 16_SNORM (8) and 8_8_SNORM (15) were missing until 2026-11-22 and decoded to 0. Format names list the channel widths from the top bit, so `2_10_10_10` (50) is R10G10B10A2 and `10_10_10_2` (44) has a 2-bit x (Mesa `gfx10_format_table.py`, `ac_formats.c`). Until 2026-11-22 the two were swapped, in stores too. Until 2026-11-21 an element that started mid-dword re-read dword 0 for its tail (`need` was `ceil(size/4)` and only the first dword was shifted); loads now take `need = ceil((byte_shift + size) / 4)` dwords and shift the whole window so the packed stream starts at the element (FUZZ-5, leftover from #234). The 10:10:10:2 order is checked by `cs_fmt_1010102` in `tests/semantic/test_value_semantics.py` (the shader decodes the format, so a GPU run can't check it). Mid-dword spanning elements are checked by `tests/semantic/test_buffer_load_format.py` (`CrossingDwordBoundary`); repeat / UNORM / DST_SEL 1 by the SHADER-86 cases in the same file. The `_xy` and `_xyz` forms (buffer and tbuffer) are GPU-checked by `cs_fmt_xy_xyz.asm`, whose words were measured natively on a Radeon 680M (gfx1035, RDNA2): they write only their 2 or 3 VGPRs, and missing channels repeat there too (TEST-185). | 237| Typed buffer loads | The format is V# word3[18:12] (GFX10_FORMAT, from Mesa's `gfx10-rsrc.json`, saved as `tools\gfx10_formats.json`). Supported: f32 ×1–4, u32 ×1–4, i32 ×1–4 (formats 21/63/73/76), f16 ×1/2/4, unorm8 ×1/2/4, snorm8 ×1/2/4, uint8 ×4, unorm16 ×1/2/4, snorm16 ×1/2/4, 10-10-10-2 and 2-10-10-10 unorm. Others give 0. Full-width SINT accesses preserve integer bits. D16 SINT loads saturate to signed 16-bit and D16 stores sign-extend, covered by the synthetic `cs_fmt_sint32.asm` readback. DST_SEL swizzle is applied (0→0, 1→1.0f for float/norm or integer 1 for UINT/SINT, 4..7→X..W). Missing channels repeat the format's own (component *c* = *c* mod *n*), measured on an RX 6700 (SHADER-86). UNORM/SNORM give the correctly rounded quotient by (2ⁿ−1), as the hardware does (0 mismatches vs hardware over 395,776 conversions on that GPU). It is built with integer ops (`Gen.norm_bits`): x/(2ⁿ−1) in binary is x's bits repeated, so a 64-bit multiply by the repeat pattern, `FindUMsb` and the round bit give the f32 exactly (the tail never ends, so there are no ties). `OpFDiv` is not enough on the GPU: Vulkan allows it 2.5 ULP, and on an RX 6700 (AMD Windows 26.11.2) and an RTX 5090 it returned the reciprocal-multiply bits (8_UNORM 130/256 exact, #599). Checked against exact values in `tests/semantic/test_norm_decode.py` (every value up to 8 bits, edges and the reciprocal-multiply misses for 10, 15 and 16 bits). 8_SNORM (2), 16_SNORM (8) and 8_8_SNORM (15) were missing until 2026-11-22 and decoded to 0. Format names list the channel widths from the top bit, so `2_10_10_10` (50) is R10G10B10A2 and `10_10_10_2` (44) has a 2-bit x (Mesa `gfx10_format_table.py`, `ac_formats.c`). Until 2026-11-22 the two were swapped, in stores too. Until 2026-11-21 an element that started mid-dword re-read dword 0 for its tail (`need` was `ceil(size/4)` and only the first dword was shifted); loads now take `need = ceil((byte_shift + size) / 4)` dwords and shift the whole window so the packed stream starts at the element (FUZZ-5, leftover from #234). The 10:10:10:2 order is checked by `cs_fmt_1010102` in `tests/semantic/test_value_semantics.py` (the shader decodes the format, so a GPU run can't check it). Mid-dword spanning elements are checked by `tests/semantic/test_buffer_load_format.py` (`CrossingDwordBoundary`); repeat / UNORM / DST_SEL 1 by the SHADER-86 cases in the same file. The `_xy` and `_xyz` forms (buffer and tbuffer) are GPU-checked by `cs_fmt_xy_xyz.asm`, whose words were measured natively on a Radeon 680M (gfx1035, RDNA2): they write only their 2 or 3 VGPRs, and missing channels repeat there too (TEST-185). |
237| Images and samplers (core) | Bindless. Set 0: binding 0 = 2D sampled images, 1 = samplers, 2 = descriptor hash table (storage buffer), 3 = 2D-array images (**cube textures are bound here as 6-layer 2D-array views**, cube arrays as 6N layers: the shader already selected the face with `v_cube*`), 4 = r32ui storage images, 5 = 1D, 6 = 3D. A cube sample's s and t come in [1, 2] and its third coordinate is 8·slice + face, as the hardware takes them (Mesa `ac_nir_lower_tex_coords.c`, LLPC `ImageBuilder.cpp`); the view is read at (s − 1, t − 1), layer 6·slice + face. GPU-checked with `runtime/test/shaders/ps_cube_sample.asm` (`vk_texture_test cube`). | 238| Images and samplers (core) | Bindless. Set 0: binding 0 = 2D sampled images, 1 = samplers, 2 = descriptor hash table (storage buffer), 3 = 2D-array images (**cube textures are bound here as 6-layer 2D-array views**, cube arrays as 6N layers: the shader already selected the face with `v_cube*`), 4 = r32ui storage images, 5 = 1D, 6 = 3D. A cube sample's s and t come in [1, 2] and its third coordinate is 8·slice + face, as the hardware takes them (Mesa `ac_nir_lower_tex_coords.c`, LLPC `ImageBuilder.cpp`); the view is read at (s − 1, t − 1), layer 6·slice + face. GPU-checked with `runtime/test/shaders/ps_cube_sample.asm` (`vk_texture_test cube`). |
238| Descriptor hash table | `uint mask; entries[mask+1] of 10 uints: key[0..7], index, pad`. The key is a T# or a padded S#. FNV-1a over the eight key words selects the first slot. The shared SPIR-V lookup probes up to eight slots and returns index 0 on a miss. The runtime supplies a fallback at index 0 and maps live descriptor keys to bindless indices. | 239| Descriptor hash table | `uint mask; entries[mask+1] of 10 uints: key[0..7], index, pad`. The key is a T# or a padded S#. FNV-1a over the eight key words selects the first slot. The shared SPIR-V lookup probes up to eight slots and returns index 0 on a miss. The runtime supplies a fallback at index 0 and maps live descriptor keys to bindless indices. |
239| Packed sample addresses | GFX10 `image_sample_d` with `a16` keeps the non-G16 gradients as f32 and packs the following coordinates as f16 pairs, following LLVM's GFX10 operand layout. `test_a16_sample_gradients_use_full_vgprs` checks the emitted gradient operands, and `ps_texture_grad_a16` checks coordinate selection with a single-mip texture on RTX 5080. The same holds for every extra argument before the coordinates (LLVM `getAddrSizeMIMGOp`: one word each, then the gradients, then the packed halves; llvm-mc takes `v[0:2]` for a 2D `image_sample_c_b ... a16`): an `image_sample_b` bias keeps its VGPR with the f16 in the low half, an `image_sample_c_lz` z-compare its f32 VGPR, and `image_sample_d_cl` its four f32 gradients, with the clamp the half right after the coordinates (an f16 pad may follow it). Until 2026-11-21 those were unpacked as pairs too, and the clamp was taken from the last half. GPU-checked on an NVIDIA GeForce RTX 2060 SUPER (Linux, driver 620.70.06) with `ps_texture_bias_a16`, `ps_sample_c_lz_a16` (`vk_texture_test dref_a16`) and `ps_texture_grad_cl_a16`, which draws on the `--two-mip` texture with the clamp 0 on the left half and 1 on the right: 4096/4096 pixels exact each. The old reading got 4,032 bias pixels and both depth-compare results in 2,048 pixels wrong, a clamp taken from the pad read mip 1 on the left half, and the sample without its clamp mip 0 on the right half (2,048 pixels each). | 240| Packed sample addresses | GFX10 `image_sample_d` with `a16` keeps the non-G16 gradients as f32 and packs the following coordinates as f16 pairs, following LLVM's GFX10 operand layout. `test_a16_sample_gradients_use_full_vgprs` checks the emitted gradient operands, and `ps_texture_grad_a16` checks coordinate selection with a single-mip texture on RTX 5080. The same holds for every extra argument before the coordinates (LLVM `getAddrSizeMIMGOp`: one word each, then the gradients, then the packed halves; llvm-mc takes `v[0:2]` for a 2D `image_sample_c_b ... a16`): an `image_sample_b` bias keeps its VGPR with the f16 in the low half, an `image_sample_c_lz` z-compare its f32 VGPR, and `image_sample_d_cl` its four f32 gradients, with the clamp the half right after the coordinates (an f16 pad may follow it). Until 2026-11-21 those were unpacked as pairs too, and the clamp was taken from the last half. GPU-checked on an NVIDIA GeForce RTX 2060 SUPER (Linux, driver 620.70.06) with `ps_texture_bias_a16`, `ps_sample_c_lz_a16` (`vk_texture_test dref_a16`) and `ps_texture_grad_cl_a16`, which draws on the `--two-mip` texture with the clamp 0 on the left half and 1 on the right: 4096/4096 pixels exact each. The old reading got 4,032 bias pixels and both depth-compare results in 2,048 pixels wrong, a clamp taken from the pad read mip 1 on the left half, and the sample without its clamp mip 0 on the right half (2,048 pixels each). |
@@ -247,9 +248,11 @@ How the generated SPIR-V expects the runtime to work:
247| PS system inputs | v0–v1 = barycentrics (consumed by `v_interp`, which becomes attribute inputs). **v2.. = the `SV_Position` components the shader reads, packed in order**. Verified on 2,531 of 3,000 PS: the VGPRs they read before writing equal exactly the position components their input signature reads. Filled from `FragCoord`: xy/z directly, and **w directly too**, because AMD's position-w register holds 1/w (Mesa lowers `load_frag_coord_w_rcp` straight to `frag_pos[3]`, `ac_nir_lower_intrinsics_to_args.c`), the same as Vulkan's `FragCoord.w`. **Front face** follows the used position components when the signature declares `SV_IsFrontFace`, as ±1.0 (Mesa: `load_front_face` = `front_face > 0`). Only enabled inputs are packed, in hardware order (Mesa `radv_shader_args.c`: barycentric pairs, POS_X/Y/Z/W, FRONT_FACE, ANCILLARY, SAMPLE_COVERAGE, POS_FIXED_PT). That explains the earlier "unverified" shaders: 102 read pos.xy + front face, and 76 read pos.x/y/w + front face. **Raw barycentric reads** (321 PS, e.g. `v_readfirstlane_b32 s41, v1`): AMD interpolates P = P0 + i(P1 − P0) + j(P2 − P0), so i/j are the weights of vertices 1/2, which is `BaryCoordKHR.y`/`.z` (`VK_KHR_fragment_shader_barycentric`). GPU-checked with `runtime/test/shaders/ps_bary.asm`: raw i/j equal the interpolated weights on every pixel. The pair is perspective-center, the only pair this layout models; that holds for every corpus PS (row "PS interpolation modes"). A PS that reads any other unexplained register inside the system-input range is still rejected (none left in the corpus). Reads past the last hardware input are values undefined on some path, so zero stands in for them. All register arrays start at zero, so translated shaders are deterministic. | 248| PS system inputs | v0–v1 = barycentrics (consumed by `v_interp`, which becomes attribute inputs). **v2.. = the `SV_Position` components the shader reads, packed in order**. Verified on 2,531 of 3,000 PS: the VGPRs they read before writing equal exactly the position components their input signature reads. Filled from `FragCoord`: xy/z directly, and **w directly too**, because AMD's position-w register holds 1/w (Mesa lowers `load_frag_coord_w_rcp` straight to `frag_pos[3]`, `ac_nir_lower_intrinsics_to_args.c`), the same as Vulkan's `FragCoord.w`. **Front face** follows the used position components when the signature declares `SV_IsFrontFace`, as ±1.0 (Mesa: `load_front_face` = `front_face > 0`). Only enabled inputs are packed, in hardware order (Mesa `radv_shader_args.c`: barycentric pairs, POS_X/Y/Z/W, FRONT_FACE, ANCILLARY, SAMPLE_COVERAGE, POS_FIXED_PT). That explains the earlier "unverified" shaders: 102 read pos.xy + front face, and 76 read pos.x/y/w + front face. **Raw barycentric reads** (321 PS, e.g. `v_readfirstlane_b32 s41, v1`): AMD interpolates P = P0 + i(P1 − P0) + j(P2 − P0), so i/j are the weights of vertices 1/2, which is `BaryCoordKHR.y`/`.z` (`VK_KHR_fragment_shader_barycentric`). GPU-checked with `runtime/test/shaders/ps_bary.asm`: raw i/j equal the interpolated weights on every pixel. The pair is perspective-center, the only pair this layout models; that holds for every corpus PS (row "PS interpolation modes"). A PS that reads any other unexplained register inside the system-input range is still rejected (none left in the corpus). Reads past the last hardware input are values undefined on some path, so zero stands in for them. All register arrays start at zero, so translated shaders are deterministic. |
248| Inputs and outputs | VS: `v0` = `VertexIndex` (**unverified**: if the console runs vertex shaders as NGG, the input VGPR layout differs). `exp pos0` → `Position`, `exp pos1..pos3` → `ClipDistance` / `CullDistance` (and `Layer`/`ViewportIndex` in VS when `pos1` is the misc vector), `exp paramN` → location N. RDNA2/GFX10 packs clip distances before cull distances contiguously across 4-component `pos` exports (up to 8 floats total), starting at `pos2` when a misc vector (`PointSize`, `EdgeFlag`, `ShadingRate`, `Layer`, `ViewportIndex`; GFX9+ packs `Layer` in `z[10:0]` and `ViewportIndex` in `z[19:16]`) occupies `pos1`, and at `pos1` otherwise (Mesa `src/amd/common/nir/ac_nir_prerast_utils.c`: `ac_nir_export_position`; AMD LLPC `lgc/lowering/LowerInOut.cpp`: `LowerInOut::visitReturnInst`). Slot assignment follows the DXBC `OSG1` signature (`SV_ClipDistance` = 2, `SV_CullDistance` = 3, `SV_RenderTargetArrayIndex` = 4, `SV_ViewportArrayIndex` = 5, `SV_ShadingRate` = 23), ordered by `(semantic_index, register, component)` with clip before cull; when `OSG1` is absent (or declares none of those system values), `pos1..pos3` exports are discarded. PS: `v_interp_*` attribute N → input location N (a location any `*_f16` interp reads is a `PerVertexKHR` array of the producer's raw words instead: see "16-bit interpolation"). A param channel carries the export's raw 32 bits either way. `exp mrtN` → location N, `exp mrtz` x → `FragDepth` when x is on and the export isn't `compr` (RGBA = Z, stencil, sample mask, alpha: Mesa `ac_get_spi_shader_z_format`; the 16-bit compressed mrtz holds stencil and sample mask and never Z, `ac_nir_lower_ps_late.c` `emit_ps_mrtz_export`). Until 2026-11-22 an mrtz export without a depth wrote one anyway (0.0, or an f16 half of the stencil word) and declared `DepthReplacing`. Checked by `tests/test_translate.py` (`test_mrtz_depth_only_from_an_enabled_x`). Stencil, sample mask and alpha exports aren't modelled. | 249| Inputs and outputs | VS: `v0` = `VertexIndex` (**unverified**: if the console runs vertex shaders as NGG, the input VGPR layout differs). `exp pos0` → `Position`, `exp pos1..pos3` → `ClipDistance` / `CullDistance` (and `Layer`/`ViewportIndex` in VS when `pos1` is the misc vector), `exp paramN` → location N. RDNA2/GFX10 packs clip distances before cull distances contiguously across 4-component `pos` exports (up to 8 floats total), starting at `pos2` when a misc vector (`PointSize`, `EdgeFlag`, `ShadingRate`, `Layer`, `ViewportIndex`; GFX9+ packs `Layer` in `z[10:0]` and `ViewportIndex` in `z[19:16]`) occupies `pos1`, and at `pos1` otherwise (Mesa `src/amd/common/nir/ac_nir_prerast_utils.c`: `ac_nir_export_position`; AMD LLPC `lgc/lowering/LowerInOut.cpp`: `LowerInOut::visitReturnInst`). Slot assignment follows the DXBC `OSG1` signature (`SV_ClipDistance` = 2, `SV_CullDistance` = 3, `SV_RenderTargetArrayIndex` = 4, `SV_ViewportArrayIndex` = 5, `SV_ShadingRate` = 23), ordered by `(semantic_index, register, component)` with clip before cull; when `OSG1` is absent (or declares none of those system values), `pos1..pos3` exports are discarded. PS: `v_interp_*` attribute N → input location N (a location any `*_f16` interp reads is a `PerVertexKHR` array of the producer's raw words instead: see "16-bit interpolation"). A param channel carries the export's raw 32 bits either way. `exp mrtN` → location N, `exp mrtz` x → `FragDepth` when x is on and the export isn't `compr` (RGBA = Z, stencil, sample mask, alpha: Mesa `ac_get_spi_shader_z_format`; the 16-bit compressed mrtz holds stencil and sample mask and never Z, `ac_nir_lower_ps_late.c` `emit_ps_mrtz_export`). Until 2026-11-22 an mrtz export without a depth wrote one anyway (0.0, or an f16 half of the stencil word) and declared `DepthReplacing`. Checked by `tests/test_translate.py` (`test_mrtz_depth_only_from_an_enabled_x`). Stencil, sample mask and alpha exports aren't modelled. |
249| 16-bit results | From Mesa ACO (`aco_ir.cpp`: `instr_is_16bit`, `can_use_opsel`) for GFX10: **f16 VOP1/VOP2 ops** (`v_add/sub/subrev/mul/max/min_f16`, `v_fmac_f16`, `v_cvt_f16_f32`, f16 unary) and **opsel-capable VOP3 ops** (`v_fma_f16`, `_e64` forms of the 16-bit integer ops) are **partial writes that keep the high half**. The **VOP2 (`_e32`) 16-bit integer ops** (`v_lshrrev_b16`…) define the whole register, so the high half is modelled as zero. An op_sel destination bit writes the high half. The translator used to clear the high half on f16 ops; that's fixed. **op_sel on f16 VOP3 ops** (`v_fma_f16`, `v_med3_f16`, `v_add/sub/subrev/mul/max/min_f16`, f16 unary, `v_fmac_f16`): bit i (i < number of sources) reads the high half of source i, the last bit writes the high half of the destination; neg/abs apply to the selected half. Source: Mesa ACO `can_use_opsel` and the RDNA2 ISA VOP3 `OP_SEL` field. Checked by the structural tests in `tests/test_f16_op_sel.py` (which half is read, where the result goes) and the value tests in `tests/test_f16_op_sel_values.py`. **Hardware-verified** on an AMD RX 6800 (gfx1030), the instructions run as a raw compute kernel in wave32 and in wave64 (IEEE off, DX10 clamp on, denormals kept, round to nearest; the bytes assemble identically for gfx1013 and gfx1030): **`v_med3_f16`** with all 16 `op_sel` patterns, with neg/abs on a selected high half, with `clamp`, and with the destination also a source; the **plain forms** `v_add/sub/mul/max/min_f16` (`_e32`, and `_e64` with neg/abs/`clamp`), `v_fmac_f16` (`_e32`, and `_e64` with neg/abs; the accumulator is the low half of the destination), `v_rndne/floor/ceil/trunc/fract/sqrt/rcp/rsq_f16` (`_e32` and `_e64`) and `v_cvt_f16_f32`: low halves in, low half out, high half of the destination kept. 336 words per wave size (plus `v_rsq_f16_e64` and `v_ceil_f16_e64` in a later run), all as the rule says and as the translator computes. **Vulkan** (AMD Radeon RX 6800, Windows, driver 26.11.2; the nine `ps_f16_*` fixtures also pass on an NVIDIA RTX 4050 Laptop and an AMD Radeon 740M (RADV), both Linux): `ps_f16_med3_opsel`, `ps_f16_med3_mods`, `ps_f16_vop2`, `ps_f16_vop2b`, `ps_f16_vop1`, `ps_f16_vop1b`, whose expected words are the hardware ones (`tests/test_f16_hw_words.py` checks them against the rule and the translator without a GPU). **Not expressible, so not verified:** `op_sel` on the VOP2 and VOP1 ops in VOP3 encoding (`v_add/sub/mul/max/min_f16_e64`, `v_fmac_f16_e64`, the unary `_e64` forms, `v_cvt_f16_f32_e64`): llvm-mc 21 rejects the modifier for gfx1013 and gfx1030, and its disassembler prints bytes that have those bits set without it (`03 08 32 d5 01 05 02 00` comes back as `v_add_f16_e64 v3, v1, v2`). The translator's `op_sel` handling for these forms is therefore never reached from a disassembly listing and rests on the ISA field description alone; whether the hardware honours the bits there is unknown, and a blob that set them would be translated as if they were clear. Also unverified: NaN and denormal operands, other rounding and IEEE modes, outside the f16 transcendentals (measured, see the f16 transcendentals row). **Driver quirk (AMD Windows driver 26.11.1, RX 9070):** `valu_fuzz` f16 seed 3 programme 38 loses the high half of v26: `v_add_f16_e32 v26, v29, v32` then `v_sub_nc_u16_e64 v28, v32, v27 op_sel:[1,1,0]` then `v_add_f16_e64 v26, v26, v28` — the final add should keep `0xCD52` in the high half, but the GPU returns `0xEEEEEEEE` (native) / `0x00000000` (`--emulate`), all 64 threads. Bisected to the pair: the add's two sources must both have been produced by earlier partial writes; either alone, a NaN input alone, or `dst==src0` alone all pass. The emitted SPIR-V was checked with `spirv-dis` in both modes: the keep (load old v26, `AND 0xFFFF0000`, `OR` new low half, store to index 26) is present and correctly addressed, so the translator is clear and this is the driver miscompiling the pattern. Minimal reproducer: the three ops above with programme 38's inits (v26 `0xCD524000`, v28 `0xC692D243`, v29 `0xBC004200`, v32 `0xB35ABD4B`, v27 `0xB48ABA06`). Pinned by `tests/test_values.py` (`v_add_f16_e64_keep_hi`, `v_add_f16_e32_keep_hi`), which check the translator's keep, not the driver. Found and bisected by 1TrickOmen, reported on #634. | 250| 16-bit results | From Mesa ACO (`aco_ir.cpp`: `instr_is_16bit`, `can_use_opsel`) for GFX10: **f16 VOP1/VOP2 ops** (`v_add/sub/subrev/mul/max/min_f16`, `v_fmac_f16`, `v_cvt_f16_f32`, f16 unary) and **opsel-capable VOP3 ops** (`v_fma_f16`, `_e64` forms of the 16-bit integer ops) are **partial writes that keep the high half**. The **VOP2 (`_e32`) 16-bit integer ops** (`v_lshrrev_b16`…) define the whole register, so the high half is modelled as zero. An op_sel destination bit writes the high half. The translator used to clear the high half on f16 ops; that's fixed. **op_sel on f16 VOP3 ops** (`v_fma_f16`, `v_med3_f16`, `v_add/sub/subrev/mul/max/min_f16`, f16 unary, `v_fmac_f16`): bit i (i < number of sources) reads the high half of source i, the last bit writes the high half of the destination; neg/abs apply to the selected half. Source: Mesa ACO `can_use_opsel` and the RDNA2 ISA VOP3 `OP_SEL` field. Checked by the structural tests in `tests/test_f16_op_sel.py` (which half is read, where the result goes) and the value tests in `tests/test_f16_op_sel_values.py`. **Hardware-verified** on an AMD RX 6800 (gfx1030), the instructions run as a raw compute kernel in wave32 and in wave64 (IEEE off, DX10 clamp on, denormals kept, round to nearest; the bytes assemble identically for gfx1013 and gfx1030): **`v_med3_f16`** with all 16 `op_sel` patterns, with neg/abs on a selected high half, with `clamp`, and with the destination also a source; the **plain forms** `v_add/sub/mul/max/min_f16` (`_e32`, and `_e64` with neg/abs/`clamp`), `v_fmac_f16` (`_e32`, and `_e64` with neg/abs; the accumulator is the low half of the destination), `v_rndne/floor/ceil/trunc/fract/sqrt/rcp/rsq_f16` (`_e32` and `_e64`) and `v_cvt_f16_f32`: low halves in, low half out, high half of the destination kept. 336 words per wave size (plus `v_rsq_f16_e64` and `v_ceil_f16_e64` in a later run), all as the rule says and as the translator computes. **Vulkan** (AMD Radeon RX 6800, Windows, driver 26.11.2; the nine `ps_f16_*` fixtures also pass on an NVIDIA RTX 4050 Laptop and an AMD Radeon 740M (RADV), both Linux): `ps_f16_med3_opsel`, `ps_f16_med3_mods`, `ps_f16_vop2`, `ps_f16_vop2b`, `ps_f16_vop1`, `ps_f16_vop1b`, whose expected words are the hardware ones (`tests/test_f16_hw_words.py` checks them against the rule and the translator without a GPU). **Not expressible, so not verified:** `op_sel` on the VOP2 and VOP1 ops in VOP3 encoding (`v_add/sub/mul/max/min_f16_e64`, `v_fmac_f16_e64`, the unary `_e64` forms, `v_cvt_f16_f32_e64`): llvm-mc 21 rejects the modifier for gfx1013 and gfx1030, and its disassembler prints bytes that have those bits set without it (`03 08 32 d5 01 05 02 00` comes back as `v_add_f16_e64 v3, v1, v2`). The translator's `op_sel` handling for these forms is therefore never reached from a disassembly listing and rests on the ISA field description alone; whether the hardware honours the bits there is unknown, and a blob that set them would be translated as if they were clear. Also unverified: NaN and denormal operands, other rounding and IEEE modes, outside the f16 transcendentals (measured, see the f16 transcendentals row). **Driver quirk (AMD Windows driver 26.11.1, RX 9070):** `valu_fuzz` f16 seed 3 programme 38 loses the high half of v26: `v_add_f16_e32 v26, v29, v32` then `v_sub_nc_u16_e64 v28, v32, v27 op_sel:[1,1,0]` then `v_add_f16_e64 v26, v26, v28` — the final add should keep `0xCD52` in the high half, but the GPU returns `0xEEEEEEEE` (native) / `0x00000000` (`--emulate`), all 64 threads. Bisected to the pair: the add's two sources must both have been produced by earlier partial writes; either alone, a NaN input alone, or `dst==src0` alone all pass. The emitted SPIR-V was checked with `spirv-dis` in both modes: the keep (load old v26, `AND 0xFFFF0000`, `OR` new low half, store to index 26) is present and correctly addressed, so the translator is clear and this is the driver miscompiling the pattern. Minimal reproducer: the three ops above with programme 38's inits (v26 `0xCD524000`, v28 `0xC692D243`, v29 `0xBC004200`, v32 `0xB35ABD4B`, v27 `0xB48ABA06`). Pinned by `tests/test_values.py` (`v_add_f16_e64_keep_hi`, `v_add_f16_e32_keep_hi`), which check the translator's keep, not the driver. Found and bisected by 1TrickOmen, reported on #634. |
250| f16 inline constants | An inline float constant (`0.5`, `1.0`, `2.0`, `4.0`, their negatives, `0.15915494`) in an operand of a 16-bit float op is the **f16 value in the low half with a zero high half**, not f32 bits (the translator used to unpack the f32 pattern, whose low half is 0, so `v_add_f16 d, 1.0, v` added 0.0). Measured on an AMD RX 6800 (gfx1030) raw kernel, wave32 and wave64: `v_add/mul/max_f16`, `v_sub_f16_e64`, `v_fma_f16`, `v_fmac_f16`, `v_rcp_f16`, `v_med3_f16`, `v_cmp_lt_f16`, `v_cvt_f32_f16` (`0.5` gives `0x3f000000`), `v_cos_f16`, `v_pk_add_f16`/`v_pk_mul_f16` (the high result half sees 0.0), `v_pack_b32_f16`; `0.15915494` is `0x3118`; the high half `op_sel` selects from a constant reads +0.0 (`v_med3_f16`, `v_fma_f16`, `v_pack_b32_f16`, `v_pk_add_f16` with swapped halves). GPU tests `ps_f16_const`, `ps_f16_const2` and `ps_f16_pack` (Vulkan: AMD Radeon RX 6800, Windows, driver 26.11.2; all three fail without the fix). Not measured, left as they were: constants in `v_fma_mix_f32`/`v_fma_mixlo/mixhi_f16` operands. | 251| f16 inline constants | An inline float constant (`0.5`, `1.0`, `2.0`, `4.0`, their negatives, `0.15915494`) in an operand of a 16-bit float op is the **f16 value in the low half with a zero high half**, not f32 bits (the translator used to unpack the f32 pattern, whose low half is 0, so `v_add_f16 d, 1.0, v` added 0.0). Measured on an AMD RX 6800 (gfx1030) raw kernel, wave32 and wave64: `v_add/mul/max_f16`, `v_sub_f16_e64`, `v_fma_f16`, `v_fmac_f16`, `v_rcp_f16`, `v_med3_f16`, `v_cmp_lt_f16`, `v_cvt_f32_f16` (`0.5` gives `0x3f000000`), `v_cos_f16`, `v_pk_add_f16`/`v_pk_mul_f16` (the high result half sees 0.0), `v_pack_b32_f16`; `0.15915494` is `0x3118`; the high half `op_sel` selects from a constant reads +0.0 (`v_med3_f16`, `v_fma_f16`, `v_pack_b32_f16`, `v_pk_add_f16` with swapped halves). GPU tests `ps_f16_const`, `ps_f16_const2` and `ps_f16_pack` (Vulkan: AMD Radeon RX 6800, Windows, driver 26.11.2; all three fail without the fix). Constants in `v_fma_mix_f32`/`v_fma_mixlo/mixhi_f16` operands follow the same rule per operand (measured on an RDNA2 iGPU, gfx1036, SHADER-135): f32 bits where `op_sel_hi` makes the operand f32, the f16 constant with a zero high half where it makes it f16, so `op_sel` with `op_sel_hi` reads +0.0; an integer constant is its 32-bit integer. The translator gives the same words (docs/shader_validation.md, "f16 output modifiers, clamp and `v_fma_mix*` operands on RDNA2"). |
251| `v_pack_b32_f16` input `neg` | A VOP3 `neg` on an operand of this instruction flips the sign bit of **the 16-bit half that operand contributes**, not of the whole 32-bit source, and only that half: measured on gfx1036 (RDNA2 iGPU, AMD Windows driver 32.0.21044.64) with 192 raw kernels, `0x7c01` gives `0xfc01` under IEEE mode 0 and `0xfe01` under mode 1, in either half and with `op_sel`. The translator moved the bits unchanged and refused every modifier; it now XORs `0x8000` into the selected half. `abs` is still refused, because its rule on this instruction is unmeasured (SHADER-260), and the mode-1 quieting of a signalling-NaN half is not modelled while SHADER-190 is open; under mode 0, where the bits move unchanged, the translation is exact. Checked on the CPU by `tests/test_values.py` and `tests/semantic/test_vop3_const_mods.py`; the gfx1036 measurement above is @Sanonymous01's, not repeated here. | 252| `v_pack_b32_f16` input `neg` | A VOP3 `neg` on an operand of this instruction flips the sign bit of **the 16-bit half that operand contributes**, not of the whole 32-bit source, and only that half: measured on gfx1036 (RDNA2 iGPU, AMD Windows driver 32.0.21044.64) with 192 raw kernels, `0x7c01` gives `0xfc01` under IEEE mode 0 and `0xfe01` under mode 1, in either half and with `op_sel`. The translator moved the bits unchanged and refused every modifier; it now XORs `0x8000` into the selected half. `abs` is still refused, because its rule on this instruction is unmeasured (SHADER-260), and the mode-1 quieting of a signalling-NaN half is not modelled while SHADER-190 is open; under mode 0, where the bits move unchanged, the translation is exact. Checked on the CPU by `tests/test_values.py` and `tests/semantic/test_vop3_const_mods.py`; the gfx1036 measurement above is @Sanonymous01's, not repeated here. |
252| Packed 16-bit integer ops (`v_pk_add/sub_u16/i16`, `v_pk_mul_lo_u16`, `v_pk_mad_u16/i16`, `v_pk_max/min_u16/i16`) | VOP3P: result half 0 takes each source's half from `op_sel[i]`, result half 1 from `op_sel_hi[i]` (defaults `[0,..]` and `[1,..]`), as for `v_pk_lshlrev_b16`. Each half is computed on its own and wraps to 16 bits. `clamp` (add, sub, mad) saturates the half to its type's range; the exact value fits in 32 bits. `neg_lo`/`neg_hi` are float-only and raise `Unsupported`, as does `clamp` on the other ops. A constant operand reads as its low 16 bits. Its high half under `op_sel`/`op_sel_hi` is **not measured** for integer ops (for f16 constants it reads +0.0, see the row above), so a constant whose high half would be read raises `Unsupported` instead of guessing; the compiler's usual form, `op_sel_hi:[1,0]` with the constant second, reads only the low half. Until 2026-11-22 all eleven ops raised `Unsupported`. CPU-checked by `tests/semantic/test_alu_pk_int16.py` (value grids, seeded `mad`, `op_sel`/`op_sel_hi` combinations, `clamp` including the unsigned `sub` floor, constants, rejected forms). **Not GPU-verified.** | 253| Packed 16-bit integer ops (`v_pk_add/sub_u16/i16`, `v_pk_mul_lo_u16`, `v_pk_mad_u16/i16`, `v_pk_max/min_u16/i16`) | VOP3P: result half 0 takes each source's half from `op_sel[i]`, result half 1 from `op_sel_hi[i]` (defaults `[0,..]` and `[1,..]`), as for `v_pk_lshlrev_b16`. Each half is computed on its own and wraps to 16 bits. `clamp` (add, sub, mad) saturates the half to its type's range; the exact value fits in 32 bits. `neg_lo`/`neg_hi` are float-only and raise `Unsupported`, as does `clamp` on the other ops. A constant operand reads as its low 16 bits. Its high half under `op_sel`/`op_sel_hi` is **not measured** for integer ops (for f16 constants it reads +0.0, see the row above), so a constant whose high half would be read raises `Unsupported` instead of guessing; the compiler's usual form, `op_sel_hi:[1,0]` with the constant second, reads only the low half. Until 2026-11-22 all eleven ops raised `Unsupported`. CPU-checked by `tests/semantic/test_alu_pk_int16.py` (value grids, seeded `mad`, `op_sel`/`op_sel_hi` combinations, `clamp` including the unsigned `sub` floor, constants, rejected forms). **Not GPU-verified.** |
254| `v_sin_f32`, `v_cos_f32`, `v_sin_f16`, `v_cos_f16` | The operand is an angle in turns (the ISA says valid over +-256; the measurement below finds no such limit on gfx1030). `turn_angle` reduces it in turns first, `x - RoundEven(x)` (exact in binary32, in [-0.5, 0.5]), then scales by `2*pi` and calls `Sin`/`Cos`, so the angle stays in [-pi, pi], the only range where GLSL guarantees them (2^-11 absolute). Scaling first rounded the fractional turn away (about 1.2e-4 rad near 255 turns, #594); the first fix (#1283) reduced with `Fract`, which rounds `1 - |x|` for a negative x and lost `-2^-26` (it returned +0; absolute errors up to ~1.7e-7 at -0.1 turns), so the reduction is `RoundEven`-centred. `RoundEven` rather than `Round` so +-0.5 turn reduce symmetrically. inf and NaN still give NaN, and a zero operand is passed through unreduced so `sin(-0)` stays -0. CPU-checked by `tests/semantic/test_alu_sincos.py` against `sin`/`cos(2*pi*x)` in double (large angles, tiny arguments, whole turns of either sign, +-0, inf/NaN, modifiers, f16) and `tests/semantic/test_valu_sin_cos_turns.py` (#1283). GPU test `cs_w32_sincos` (large angles within 1e-3, since the driver `Sin` is only good to 2^-11) is a regression guard, not proof the old form failed on a given driver. Measured on an AMD Radeon RX 6800 (gfx1030, not the console's gfx1013) by @shelbykb2 (#616): whole and half turns of either sign give +0 (only `sin(-0)` is -0, so no sign needs copying onto a zero result, as here); there is no +-256 limit on that card (any finite x reduces exactly: `sin(300.25)` = 1, `sin(2^24)` = +0); the f16 forms reduce the same way as the f32 ones; +-inf gives a NaN and a NaN passes through, quieted with IEEE mode on. Known differences from this translation: at half turns `Sin` of the rounded pi gives about -+8.7e-8 where the hardware returns exactly 0, likewise `cos` at quarter turns; for |x| <= 2^-12 the hardware multiplies by `0x40c90fd5`, not the rounded 2*pi; the inf/NaN words are whatever the host driver returns. Not checked on gfx1013. |
255| `v_pack_b32_f16` source modifiers | A VOP3 `abs` or `neg` on an operand of this instruction acts on **the 16-bit half that operand contributes**, not on the whole 32-bit source, and only on that half: `abs` clears bit 15 and `neg` flips it, `abs` first, both as plain bit moves — the operand is not converted to a float. Until 2026-11-22 any such operand was rejected as `Unsupported`. **`neg` is measured** on gfx1036 (RDNA2 iGPU, AMD Windows driver 32.0.21044.64) with 192 raw kernels: `0x7c01` gives `0xfc01` under IEEE mode 0 and `0xfe01` under mode 1, in either half and with `op_sel`, so the sign move does not depend on the mode. **`abs` rests on the ISA's definition of ABS on a float operand as the sign clear, applied before `neg`; no hardware run of this instruction with `abs` exists yet**, and `abs` on a NaN half is therefore unmeasured too. **Not modelled: IEEE mode 1 also quiets a signalling-NaN half** (`0x7c01` → `0x7e01`); which mode the game's shaders run in is SHADER-190, and under mode 0, where the bits move unchanged, the translation is exact. Checked by `tests/test_values.py`, `tests/semantic/test_vop3_const_mods.py`, `tests/semantic/test_pack_b32_f16_mods.py` (exact bits through the interpreter) and the GPU fixture `ps_f16_pack_mods` (words derived from the rule, not a readback); the gfx1036 measurement above is @Sanonymous01's, not repeated here. |
253| `v_med3_f32` output modifiers | The translator applies `mul:2`, `mul:4` or `div:2` to the median before clamping to [0, 1], following [LLVM’s modifier order](https://llvm.org/docs/AMDGPUModifierSyntax.html#omod). The finite-input fixture `ps_med3_mods.asm` produced 4,096 exact pixels on an Apple M3 Max with MoltenVK and on Mesa llvmpipe (software Vulkan); it also passes (4,096/4,096) on an NVIDIA RTX 4050 Laptop and an AMD Radeon 740M (RADV), both Linux, and on an RTX 2060 SUPER per #634. This uses the existing float MODE assumptions described above. | 256| `v_med3_f32` output modifiers | The translator applies `mul:2`, `mul:4` or `div:2` to the median before clamping to [0, 1], following [LLVM’s modifier order](https://llvm.org/docs/AMDGPUModifierSyntax.html#omod). The finite-input fixture `ps_med3_mods.asm` produced 4,096 exact pixels on an Apple M3 Max with MoltenVK and on Mesa llvmpipe (software Vulkan); it also passes (4,096/4,096) on an NVIDIA RTX 4050 Laptop and an AMD Radeon 740M (RADV), both Linux, and on an RTX 2060 SUPER per #634. This uses the existing float MODE assumptions described above. |
254| POPS | Primitive-ordered pixel shading (10 PS, `src_pops_exiting_wave_id` wait loop, `s_sleep`, `MSG_ORDERED_PS_DONE`) becomes **fragment-shader interlock** (`PixelInterlockOrderedEXT`). It begins at the end of the entry block and ends at shader exit: a longer critical section with the same ordering. `src_pops_exiting_wave_id` reads 0, and **the runtime must put 0 (no collision, bit 31 clear) in the POPS collision SGPR**, so the hardware wait loop is skipped. Needs `VK_EXT_fragment_shader_interlock` (`fragmentShaderPixelInterlock`). | 257| POPS | Primitive-ordered pixel shading (10 PS, `src_pops_exiting_wave_id` wait loop, `s_sleep`, `MSG_ORDERED_PS_DONE`) becomes **fragment-shader interlock** (`PixelInterlockOrderedEXT`). It begins at the end of the entry block and ends at shader exit: a longer critical section with the same ordering. `src_pops_exiting_wave_id` reads 0, and **the runtime must put 0 (no collision, bit 31 clear) in the POPS collision SGPR**, so the hardware wait loop is skipped. Needs `VK_EXT_fragment_shader_interlock` (`fragmentShaderPixelInterlock`). |
255| 2D `image_sample_lz` | The T# FORMAT selects the float, UINT or SINT sampled view at LOD zero. With nearest sampling, native gfx1036 returned the original 32-bit integer components. RTX 5080 and gfx1036 Vulkan readbacks matched all four channels on RGBA8 UINT, SINT and UNORM for full-width and D16 results. The R32 UINT/SINT saturation-boundary fixture also matched all 64 sampled sums on both adapters. | 258| 2D `image_sample_lz` | The T# FORMAT selects the float, UINT or SINT sampled view at LOD zero. With nearest sampling, native gfx1036 returned the original 32-bit integer components. RTX 5080 and gfx1036 Vulkan readbacks matched all four channels on RGBA8 UINT, SINT and UNORM for full-width and D16 results. The R32 UINT/SINT saturation-boundary fixture also matched all 64 sampled sums on both adapters. |
@@ -261,7 +264,7 @@ How the generated SPIR-V expects the runtime to work:
261| Mesh shaders | NGG wave64 programs → `VK_EXT_mesh_shader` (`MeshEXT`). **PSV0** (DXBC) gives NumThreads (128×1×1 in the corpus), MaxOutputVertices/Primitives (128/128) and the topology (triangles). System inputs, from Mesa's RADV setup for mesh as NGG on GFX10.3: v5 = first launch vertex ID of the lane (the "vertex_id" slot), `linearGroupIndex * NumThreads + LocalInvocationIndex` with the linear index from WorkgroupId/NumWorkgroups; all 9,282/9,282 corpus mesh shaders read `v5` once with `v_readfirstlane_b32 sX, v5` and use `sX` only via `s_lshr_b32 D, sX, 7` to recover the group index (NumThreads is 128 in the corpus), matching TomBox's mesh ABI (`gid.x * numThreads + gi`) on 1D launches. GPU-checked with `runtime/test/shaders/ms_v5_workgroup.asm` (24/24 groups exact on RTX 4060 Ti and RTX 3080, and on an RTX 4050 Laptop and an AMD Radeon 740M (RADV)); still unverified on Xbox hardware: the low 7 bits of `v5` on lanes 1..127 and whether 3D `DispatchMesh` flattens XYZ or uses X only. The merged-wave-info SGPR (s3 in this ABI) = wave ID << 24, from LocalInvocationIndex >> 6; `v_mbcnt` lanes = LocalInvocationIndex & 63; user data in s16.. as usual. 1,473 of 1,500 sampled mesh shaders read exactly v5, and the rest only add loop-carried registers. Exports: on NGG, thread t exports vertex t (`pos0`, `paramN`) and primitive t (`prim`). They're staged per invocation; an all-`off` export is the dummy a wave with no vertices must issue, and writes nothing. `s_sendmsg GS_ALLOC_REQ` (m0 = prims << 12 \| verts, sent by thread 0) stores the counts in a workgroup variable. At shader end, in uniform control flow: workgroup barrier, `OpSetMeshOutputsEXT(min(verts, max), min(prims, max))`, then each thread writes its staged vertex (Position + Location N) and primitive (`PrimitiveTriangleIndicesEXT` = bits [8:0], [18:10], [28:20]; `CullPrimitiveEXT` = bit 31). `pos1..pos3` clip/cull distances are staged per invocation and emitted in a per-vertex `Block` output struct (`Position` + `ClipDistance`/`CullDistance` arrays, `VK_EXT_mesh_shader`) when used, keeping the standalone `%ms_out_pos` layout unchanged for shaders without `pos1+`. The distances are copied to that struct one float at a time, not as a whole array: SPIRV-Cross 1.4.363.0 turns a whole-array store into a mesh output into a C array assignment that Metal rejects (SHADER-155; `ms_clip` then compiles and draws its 2048/4096 pixels in a native Metal mesh draw on an Apple A18 Pro). GPU-checked with `runtime/test/shaders/ms_tri.asm` (`VKH_MESH=1 vk_harness`), built from the game's own idioms (thread ID from s3 and mbcnt across two waves, thread-0 ALLOC_REQ, per-thread exports): 0 error on every pixel. | 264| Mesh shaders | NGG wave64 programs → `VK_EXT_mesh_shader` (`MeshEXT`). **PSV0** (DXBC) gives NumThreads (128×1×1 in the corpus), MaxOutputVertices/Primitives (128/128) and the topology (triangles). System inputs, from Mesa's RADV setup for mesh as NGG on GFX10.3: v5 = first launch vertex ID of the lane (the "vertex_id" slot), `linearGroupIndex * NumThreads + LocalInvocationIndex` with the linear index from WorkgroupId/NumWorkgroups; all 9,282/9,282 corpus mesh shaders read `v5` once with `v_readfirstlane_b32 sX, v5` and use `sX` only via `s_lshr_b32 D, sX, 7` to recover the group index (NumThreads is 128 in the corpus), matching TomBox's mesh ABI (`gid.x * numThreads + gi`) on 1D launches. GPU-checked with `runtime/test/shaders/ms_v5_workgroup.asm` (24/24 groups exact on RTX 4060 Ti and RTX 3080, and on an RTX 4050 Laptop and an AMD Radeon 740M (RADV)); still unverified on Xbox hardware: the low 7 bits of `v5` on lanes 1..127 and whether 3D `DispatchMesh` flattens XYZ or uses X only. The merged-wave-info SGPR (s3 in this ABI) = wave ID << 24, from LocalInvocationIndex >> 6; `v_mbcnt` lanes = LocalInvocationIndex & 63; user data in s16.. as usual. 1,473 of 1,500 sampled mesh shaders read exactly v5, and the rest only add loop-carried registers. Exports: on NGG, thread t exports vertex t (`pos0`, `paramN`) and primitive t (`prim`). They're staged per invocation; an all-`off` export is the dummy a wave with no vertices must issue, and writes nothing. `s_sendmsg GS_ALLOC_REQ` (m0 = prims << 12 \| verts, sent by thread 0) stores the counts in a workgroup variable. At shader end, in uniform control flow: workgroup barrier, `OpSetMeshOutputsEXT(min(verts, max), min(prims, max))`, then each thread writes its staged vertex (Position + Location N) and primitive (`PrimitiveTriangleIndicesEXT` = bits [8:0], [18:10], [28:20]; `CullPrimitiveEXT` = bit 31). `pos1..pos3` clip/cull distances are staged per invocation and emitted in a per-vertex `Block` output struct (`Position` + `ClipDistance`/`CullDistance` arrays, `VK_EXT_mesh_shader`) when used, keeping the standalone `%ms_out_pos` layout unchanged for shaders without `pos1+`. The distances are copied to that struct one float at a time, not as a whole array: SPIRV-Cross 1.4.363.0 turns a whole-array store into a mesh output into a C array assignment that Metal rejects (SHADER-155; `ms_clip` then compiles and draws its 2048/4096 pixels in a native Metal mesh draw on an Apple A18 Pro). GPU-checked with `runtime/test/shaders/ms_tri.asm` (`VKH_MESH=1 vk_harness`), built from the game's own idioms (thread ID from s3 and mbcnt across two waves, thread-0 ALLOC_REQ, per-thread exports): 0 error on every pixel. |
262| Mesh shaders as compute (`--mesh-compute`) | For devices without `VK_EXT_mesh_shader` (NVIDIA Pascal, for one). Each mesh shader becomes a `GLCompute` module with the same workgroup size and code; only the epilogue changes. Instead of `OpSetMeshOutputsEXT` and the mesh outputs, after the same barrier lane 0 writes the vertex and primitive counts, lane i < vertex count writes its vertex and lane i < primitive count its primitive into this workgroup's **slot** of an output buffer: slot = linear workgroup index (x + y·nx + z·nx·ny) × `slot_bytes`, computed in 64 bits. The buffer's device address is in push-constant dwords 36–37, so these modules declare 152 bytes. Slot layout (`rdna2spirv.mesh_compute_layout`, recorded per shader as `mesh_compute` in the index), all 16-byte aligned: a header (vertex count, primitive count), then `max_vertices` vertices, each holding the position, the clip and then cull distances padded to whole vec4s, and one vec4 per param location; then `max_primitives` primitives of three vertex indices plus 1 if culled. The modules need no mesh capability, extension or `shaderClipDistance`. `tools/mesh_compute_vs.py` writes the vertex shader that draws the slots with a non-indexed `vkCmdDraw(groups × max_primitives × 3)`: vertex v is workgroup v / (3·max_primitives), primitive (v / 3) mod max_primitives, corner v mod 3. A primitive past the count, or one culled, gets one position outside the clip volume at all three corners and is clipped. Otherwise the corner's index, clamped to `max_vertices` − 1, selects the vertex, and its position, distances and params go out at the mesh shader's locations, so the pixel shader is unchanged. One draw rasterizes in vertex order, which is workgroup then primitive order, as with mesh workgroups. Corpus: all 9,282 mesh shaders are 128×1×1 with 128/128 outputs, wave64, 0–18 params, clip distances in 1,906, cull distances and per-primitive attributes in none, no task shaders. On a 32-wide device combine it with `--wave64-emulate`. GPU-checked on an NVIDIA GeForce GTX 1060 6GB (Pascal: no mesh shaders; driver 560.94, Windows 10) with `LEONIDA_MESH_COMPUTE=1 LEONIDA_W64_EMULATE=1`: `ms_tri`, `ms_w64x_ballot` and `ms_wave_info_s3` 4096/4096 pixels exact, `ms_clip` 2048/4096 covered as expected, `ms_v5_workgroup` 24/24 workgroup coordinates, zero Khronos validation messages. Checked in `tests/test_mesh_compute.py`. The runtime side, turning a `DispatchMesh` into that dispatch, a barrier and the draw, is the follow-up (it needs the graphics pipelines of #291). Unused primitives still run the vertex shader; compaction with an indirect draw would avoid that. | 265| Mesh shaders as compute (`--mesh-compute`) | For devices without `VK_EXT_mesh_shader` (NVIDIA Pascal, for one). Each mesh shader becomes a `GLCompute` module with the same workgroup size and code; only the epilogue changes. Instead of `OpSetMeshOutputsEXT` and the mesh outputs, after the same barrier lane 0 writes the vertex and primitive counts, lane i < vertex count writes its vertex and lane i < primitive count its primitive into this workgroup's **slot** of an output buffer: slot = linear workgroup index (x + y·nx + z·nx·ny) × `slot_bytes`, computed in 64 bits. The buffer's device address is in push-constant dwords 36–37, so these modules declare 152 bytes. Slot layout (`rdna2spirv.mesh_compute_layout`, recorded per shader as `mesh_compute` in the index), all 16-byte aligned: a header (vertex count, primitive count), then `max_vertices` vertices, each holding the position, the clip and then cull distances padded to whole vec4s, and one vec4 per param location; then `max_primitives` primitives of three vertex indices plus 1 if culled. The modules need no mesh capability, extension or `shaderClipDistance`. `tools/mesh_compute_vs.py` writes the vertex shader that draws the slots with a non-indexed `vkCmdDraw(groups × max_primitives × 3)`: vertex v is workgroup v / (3·max_primitives), primitive (v / 3) mod max_primitives, corner v mod 3. A primitive past the count, or one culled, gets one position outside the clip volume at all three corners and is clipped. Otherwise the corner's index, clamped to `max_vertices` − 1, selects the vertex, and its position, distances and params go out at the mesh shader's locations, so the pixel shader is unchanged. One draw rasterizes in vertex order, which is workgroup then primitive order, as with mesh workgroups. Corpus: all 9,282 mesh shaders are 128×1×1 with 128/128 outputs, wave64, 0–18 params, clip distances in 1,906, cull distances and per-primitive attributes in none, no task shaders. On a 32-wide device combine it with `--wave64-emulate`. GPU-checked on an NVIDIA GeForce GTX 1060 6GB (Pascal: no mesh shaders; driver 560.94, Windows 10) with `LEONIDA_MESH_COMPUTE=1 LEONIDA_W64_EMULATE=1`: `ms_tri`, `ms_w64x_ballot` and `ms_wave_info_s3` 4096/4096 pixels exact, `ms_clip` 2048/4096 covered as expected, `ms_v5_workgroup` 24/24 workgroup coordinates, zero Khronos validation messages. Checked in `tests/test_mesh_compute.py`. The runtime side, turning a `DispatchMesh` into that dispatch, a barrier and the draw, is the follow-up (it needs the graphics pipelines of #291). Unused primitives still run the vertex shader; compaction with an indirect draw would avoid that. |
263| Geometry shaders | All 195 are `$GS_VoxelizeGeneric` permutations: legacy (merged ES/GS) wave32 programs on LDS rings, with no `exp`. Inputs: vertex i sits at the dword offset in v0 lo / v0 hi / v1 lo; an LDS read at vertex base + 4·(4·reg + comp) is input-signature register reg, component comp (checked: SV_Position xyz in dwords 0–2 and TEXCOORD0.xy in 4–5, as ISG1 declares). Outputs: emitted vertex k is dwords [k·4·nreg, (k+1)·4·nreg) of the lane's GSVS area, dword = 4·reg + comp of the output signature (20 dwords = 5 OSG1 registers; every write matches a declared mask). Translation: synthetic offsets (vertex i at dword 64·i), LDS reads → `gl_in[i]` inputs, LDS writes → staged slots, `MSG_GS EMIT` → copy slot (emit count) to the outputs + `OpEmitVertex`, `CUT` → `OpEndPrimitive`, `GS_DONE` → nothing. The prologue's `s_bfm_b64`/`s_cselect` EXEC setup is fed s3 = 64 << 8. GPU-checked with `runtime/test/shaders/gs_tri.asm` (`VKH_GS=… vk_harness`): 0 error. Without a geometry stage (Apple GPUs: Metal, MoltenVK), `tools/spirv_gs_to_compute.py` lowers the translated module to a compute capture pass, one invocation per input primitive: inputs come from a buffer, each `OpEmitVertex` writes the outputs to a record buffer, and a meta buffer holds each primitive's vertex count and strip ends, for an ordinary draw afterwards (SHADER-159). `gs_tri` lowered this way, converted with SPIRV-Cross and run natively on an Apple A18 Pro: 195/195 records exact for 65 random triangles, and the captured fullscreen triangle drawn from the records matches all 4096 gradient pixels. Not done: wiring it into a draw path, and GS that use cross-lane operations or more than one invocation. | 266| Geometry shaders | All 195 are `$GS_VoxelizeGeneric` permutations: legacy (merged ES/GS) wave32 programs on LDS rings, with no `exp`. Inputs: vertex i sits at the dword offset in v0 lo / v0 hi / v1 lo; an LDS read at vertex base + 4·(4·reg + comp) is input-signature register reg, component comp (checked: SV_Position xyz in dwords 0–2 and TEXCOORD0.xy in 4–5, as ISG1 declares). Outputs: emitted vertex k is dwords [k·4·nreg, (k+1)·4·nreg) of the lane's GSVS area, dword = 4·reg + comp of the output signature (20 dwords = 5 OSG1 registers; every write matches a declared mask). Translation: synthetic offsets (vertex i at dword 64·i), LDS reads → `gl_in[i]` inputs, LDS writes → staged slots, `MSG_GS EMIT` → copy slot (emit count) to the outputs + `OpEmitVertex`, `CUT` → `OpEndPrimitive`, `GS_DONE` → nothing. The prologue's `s_bfm_b64`/`s_cselect` EXEC setup is fed s3 = 64 << 8. GPU-checked with `runtime/test/shaders/gs_tri.asm` (`VKH_GS=… vk_harness`): 0 error. Without a geometry stage (Apple GPUs: Metal, MoltenVK), `tools/spirv_gs_to_compute.py` lowers the translated module to a compute capture pass, one invocation per input primitive: inputs come from a buffer, each `OpEmitVertex` writes the outputs to a record buffer, and a meta buffer holds each primitive's vertex count and strip ends, for an ordinary draw afterwards (SHADER-159). `gs_tri` lowered this way, converted with SPIRV-Cross and run natively on an Apple A18 Pro: 195/195 records exact for 65 random triangles, and the captured fullscreen triangle drawn from the records matches all 4096 gradient pixels. Not done: wiring it into a draw path, and GS that use cross-lane operations or more than one invocation. |
264| Integer clamp | The VOP3 `clamp` bit on `v_add_nc_u32`, `v_sub_nc_u32`, `v_subrev_nc_u32` saturates the result to [0, 0xFFFFFFFF], and on `v_add_nc_i32`/`v_sub_nc_i32` to [0x80000000, 0x7FFFFFFF]; without it they wrap. GFX9+ semantics: LLVM selects `uaddsat`/`usubsat` and `saddsat`/`ssubsat` to exactly these ops with clamp set. **Until this change clamp was silently ignored on the unsigned ops** (and the signed ones were `Unsupported`). Checked on the CPU by `tests/semantic/test_alu_add_nc_clamp.py`, **not yet GPU-verified**. The 16-bit unsigned add/sub (`v_add_nc_u16`, `v_sub_nc_u16`, and the `v_add_u16`/`v_sub_u16`/`v_subrev_u16` `_e64` names) saturate to [0, 0xFFFF] with `clamp` (llvm-mc 21 gfx1030 encodes the bit on them, and LLVM selects i16 `uaddsat`/`usubsat` to them); **until 2026-11-22 the translator wrapped instead**. `clamp` on any other 16-bit integer op raises `Unsupported`. CPU-checked by `tests/semantic/test_alu_u16_clamp.py` (the high half of the destination is kept), **not GPU-verified**. | 267| Integer clamp | The VOP3 `clamp` bit on `v_add_nc_u32`, `v_sub_nc_u32`, `v_subrev_nc_u32` saturates the result to [0, 0xFFFFFFFF], and on `v_add_nc_i32`/`v_sub_nc_i32` to [0x80000000, 0x7FFFFFFF]; without it they wrap. GFX9+ semantics: LLVM selects `uaddsat`/`usubsat` and `saddsat`/`ssubsat` to exactly these ops with clamp set. **Until this change clamp was silently ignored on the unsigned ops** (and the signed ones were `Unsupported`). Checked on the CPU by `tests/semantic/test_alu_add_nc_clamp.py`. The 16-bit unsigned add/sub (`v_add_nc_u16`, `v_sub_nc_u16`, and the `v_add_u16`/`v_sub_u16`/`v_subrev_u16` `_e64` names) saturate to [0, 0xFFFF] with `clamp` (llvm-mc 21 gfx1030 encodes the bit on them, and LLVM selects i16 `uaddsat`/`usubsat` to them); **until 2026-11-22 the translator wrapped instead**. `clamp` on any other 16-bit integer op raises `Unsupported`. CPU-checked by `tests/semantic/test_alu_u16_clamp.py` (the high half of the destination is kept). **Hardware-verified on RDNA2** (AMD Radeon 680M, `gfx1035`, Windows 11, driver `26.5.1`, wave32 and wave64 via `tools/int_hw_probe.py --oracle both`, SHADER-137): all 32-bit and 16-bit `*_nc_*` `clamp` cases (including `op_sel` and kept destination half on u16) match hardware bit-for-bit. **Open divergence measured on the same hardware:** `v_add_co_u32`, `v_sub_co_u32`, `v_subrev_co_u32`, `v_add_co_ci_u32`, `v_sub_co_ci_u32` and `v_subrev_co_ci_u32` with `clamp` saturate D (`0xFFFFFFFF` / `0`) while still reporting the real carry/borrow in `sdst`, whereas the translator currently ignores `clamp` on these carry-out ops. |
265| Gather sampler LOD | Before choosing the mip for the four fetches in `image_gather4_l(_o)`, clamp the requested LOD to S# word 1's MIN_LOD [11:0] and MAX_LOD [23:12] (unsigned 4.8). `ps_gather_sampler_lod.asm` reads the S# from the heap. On RTX 5080 and Radeon Graphics, a maximum of 0.25 selects the base quadrants and a minimum of 0.75 selects the cyan mip across the 64×64 draw. Without these bounds half of each frame reads the wrong level. Radeon also agreed with native `OpImageGather Lod` (`VK_AMD_texture_gather_bias_lod`) for those bounds. At exactly 0.5, with bounds [0,1], that native draw selected mip 1; the emulation now computes the mip as `Floor(LOD + 0.5)`, ties up, and also selects mip 1 (before SHADER-152 it used `RoundEven`, which selected mip 0). | 268| Gather sampler LOD | Before choosing the mip for the four fetches in `image_gather4_l(_o)`, clamp the requested LOD to S# word 1's MIN_LOD [11:0] and MAX_LOD [23:12] (unsigned 4.8). `ps_gather_sampler_lod.asm` reads the S# from the heap. On RTX 5080 and Radeon Graphics, a maximum of 0.25 selects the base quadrants and a minimum of 0.75 selects the cyan mip across the 64×64 draw. Without these bounds half of each frame reads the wrong level. Radeon also agreed with native `OpImageGather Lod` (`VK_AMD_texture_gather_bias_lod`) for those bounds. At exactly 0.5, with bounds [0,1], that native draw selected mip 1; the emulation now computes the mip as `Floor(LOD + 0.5)`, ties up, and also selects mip 1 (before SHADER-152 it used `RoundEven`, which selected mip 0). |
266| `s_absdiff_i32`, `s_mul_hi_i32` | `s_absdiff_i32`: D = \|S0 − S1\| with the 32-bit difference wrapped first (0x7FFFFFFF − 0x80000000 → 1; a difference of −2³¹ stays 0x80000000), SCC = D ≠ 0. `s_mul_hi_i32`: high word of the signed 64-bit product, SCC kept. From the RDNA2 ISA pseudocode; checked on the CPU by `tests/semantic/test_salu_absdiff_mul_hi.py`. **Hardware-verified** on an AMD Radeon RX 7900 XTX (gfx1100, Windows 11, driver 26.10.1) as raw wave32 kernels through `tools/hw_oracle`: `s_absdiff_i32(0x7FFFFFFF, 0x80000000)` = 1 and `s_absdiff_i32(0x80000000, 0)` = 0x80000000, both with SCC = 1, and equal operands give 0 with SCC = 0; `s_mul_hi_i32(0x7FFFFFFF, 0x7FFFFFFF)` = 0x3FFFFFFF and `s_mul_hi_i32(-1, 1)` = 0xFFFFFFFF, with SCC left as it was. | 269| `s_absdiff_i32`, `s_mul_hi_i32` | `s_absdiff_i32`: D = \|S0 − S1\| with the 32-bit difference wrapped first (0x7FFFFFFF − 0x80000000 → 1; a difference of −2³¹ stays 0x80000000), SCC = D ≠ 0. `s_mul_hi_i32`: high word of the signed 64-bit product, SCC kept. From the RDNA2 ISA pseudocode; checked on the CPU by `tests/semantic/test_salu_absdiff_mul_hi.py`. **Hardware-verified** on an AMD Radeon RX 7900 XTX (gfx1100, Windows 11, driver 26.10.1) as raw wave32 kernels through `tools/hw_oracle`: `s_absdiff_i32(0x7FFFFFFF, 0x80000000)` = 1 and `s_absdiff_i32(0x80000000, 0)` = 0x80000000, both with SCC = 1, and equal operands give 0 with SCC = 0; `s_mul_hi_i32(0x7FFFFFFF, 0x7FFFFFFF)` = 0x3FFFFFFF and `s_mul_hi_i32(-1, 1)` = 0xFFFFFFFF, with SCC left as it was. |
267| SCC from scalar ALU | `s_and/or/xor/andn2/orn2/nand/nor/xnor_b32` and `s_lshl/lshr_b32` set SCC = result ≠ 0, `s_add/sub_i32` and `s_addk_i32` set it to signed overflow, `s_min_u32`/`s_max_u32` to S0 < S1 / S0 > S1, and `s_min_i32`/`s_max_i32` to the same compared signed: SCC is 1 when S0 is the one chosen, and a tie chooses S1 (RDNA2 ISA, S_MIN_I32: D = S0 < S1 ? S0 : S1, SCC = 1 if S0 is chosen). **Before this fix these ops left SCC unchanged**, so a following `s_cbranch_scc*` read a stale flag, and until 2026-11-21 `s_min_i32`/`s_max_i32` set SCC on a tie. 32-bit scalar shifts now mask the amount to 5 bits. GPU-checked with `runtime/test/shaders/ps_scc.asm` and `ps_scc_minmax.asm` (NVIDIA GeForce RTX 2060 SUPER, Linux, driver 620.70.06: 4096/4096 pixels exact, and all 4096 differ with the old translator). **On lane masks in a wave32 program** (a source is EXEC, VCC or a mask SGPR, or the result goes to EXEC) the 32-bit bitwise ops' result is the whole wave's mask, so SCC is a subgroup vote (`OpGroupNonUniformAny`), as for the `_b64` forms. Until 2026-11-22 each lane took its own bit: `s_and_b32 s0, vcc_lo, exec_lo; s_cbranch_scc0` skipped the block in lanes whose bit was 0, and a loop closed by `s_andn2_b32 exec_lo, ...; s_cbranch_scc1` let each lane leave early. Found and checked by `tools/cf_diff.py` (FUZZ-8, CPU differential against the ISA model); GPU test `runtime/test/shaders/ps_scc_mask32.asm` passes (s5 == 8 on 2,048 pixels, 192 of them with bit 0, and s5 == 7 on 2,048) on an NVIDIA RTX 4050 Laptop (Linux, driver 620.73.04, natively and under `LEONIDA_W64_EMULATE=1`) and an AMD Radeon 740M (RADV, Mesa 26.3.1), and on an RTX 2060 SUPER per #634. A 32-bit op on one half of a wave64 mask still takes the lane's bit (its SCC would be a vote of that half). | 270| SCC from scalar ALU | `s_and/or/xor/andn2/orn2/nand/nor/xnor_b32` and `s_lshl/lshr_b32` set SCC = result ≠ 0, `s_add/sub_i32` and `s_addk_i32` set it to signed overflow, `s_min_u32`/`s_max_u32` to S0 < S1 / S0 > S1, and `s_min_i32`/`s_max_i32` to the same compared signed: SCC is 1 when S0 is the one chosen, and a tie chooses S1 (RDNA2 ISA, S_MIN_I32: D = S0 < S1 ? S0 : S1, SCC = 1 if S0 is chosen). **Before this fix these ops left SCC unchanged**, so a following `s_cbranch_scc*` read a stale flag, and until 2026-11-21 `s_min_i32`/`s_max_i32` set SCC on a tie. 32-bit scalar shifts now mask the amount to 5 bits. GPU-checked with `runtime/test/shaders/ps_scc.asm` and `ps_scc_minmax.asm` (NVIDIA GeForce RTX 2060 SUPER, Linux, driver 620.70.06: 4096/4096 pixels exact, and all 4096 differ with the old translator). **On lane masks in a wave32 program** (a source is EXEC, VCC or a mask SGPR, or the result goes to EXEC) the 32-bit bitwise ops' result is the whole wave's mask, so SCC is a subgroup vote (`OpGroupNonUniformAny`), as for the `_b64` forms. Until 2026-11-22 each lane took its own bit: `s_and_b32 s0, vcc_lo, exec_lo; s_cbranch_scc0` skipped the block in lanes whose bit was 0, and a loop closed by `s_andn2_b32 exec_lo, ...; s_cbranch_scc1` let each lane leave early. Found and checked by `tools/cf_diff.py` (FUZZ-8, CPU differential against the ISA model); GPU test `runtime/test/shaders/ps_scc_mask32.asm` passes (s5 == 8 on 2,048 pixels, 192 of them with bit 0, and s5 == 7 on 2,048) on an NVIDIA RTX 4050 Laptop (Linux, driver 620.73.04, natively and under `LEONIDA_W64_EMULATE=1`) and an AMD Radeon 740M (RADV, Mesa 26.3.1), and on an RTX 2060 SUPER per #634. A 32-bit op on one half of a wave64 mask still takes the lane's bit (its SCC would be a vote of that half). |
@@ -271,7 +274,7 @@ How the generated SPIR-V expects the runtime to work:
271| Buffer format stores | `buffer_store_format_*` and `_d16_*` encode every format the loads decode (the same FORMATS table: f32/u32, f16, unorm/snorm 8/16/10-10-10-2, uint 8/16). 1–2-byte elements are merged into their dword with atomic and/or so neighbours are kept. The atomics use element 0 of the array at the aligned dword address, which also compiles on MoltenVK 1.4.0 (checked with `cs_store` on an Apple M3 Max and Mesa llvmpipe). d16 data is unpacked first (f16 → float for float kinds, 16-bit integers for integer kinds). Before this, only four f32 formats, rgba16f and rgba8 unorm were stored, and everything else silently stored nothing. GPU-checked with `runtime/test/shaders/cs_store.asm` (rgba8 unorm, R10G10B10A2 (`2_10_10_10`), two r16f halves of one dword, d16 rgba16f: exact, neighbours untouched). `buffer_load_format_d16_*` packs pairs the same way. UNORM/SNORM stores convert NaN to zero before clamping. On native gfx1036, `buffer_store_format_d16_xyzw` into RGBA8_UNORM/SNORM matched clamp, scale by 255/127 and round to nearest even for all 63,488 finite binary16 encodings. Both infinities saturated and all 2,046 NaNs stored zero in both wave32 and wave64. The translated sweep matched all 65,536 bytes per format on RTX 5080 and Radeon Graphics. For normalized stores with format 56 (8/8/8/8) or 50 (10/10/10/2), a Z,Y,X,W descriptor exchanges the red and blue memory fields after filling absent input components with zero. Native gfx1036 confirmed both channel orders at all four instruction widths for packed and ordinary stores in wave32 and wave64. | 274| Buffer format stores | `buffer_store_format_*` and `_d16_*` encode every format the loads decode (the same FORMATS table: f32/u32, f16, unorm/snorm 8/16/10-10-10-2, uint 8/16). 1–2-byte elements are merged into their dword with atomic and/or so neighbours are kept. The atomics use element 0 of the array at the aligned dword address, which also compiles on MoltenVK 1.4.0 (checked with `cs_store` on an Apple M3 Max and Mesa llvmpipe). d16 data is unpacked first (f16 → float for float kinds, 16-bit integers for integer kinds). Before this, only four f32 formats, rgba16f and rgba8 unorm were stored, and everything else silently stored nothing. GPU-checked with `runtime/test/shaders/cs_store.asm` (rgba8 unorm, R10G10B10A2 (`2_10_10_10`), two r16f halves of one dword, d16 rgba16f: exact, neighbours untouched). `buffer_load_format_d16_*` packs pairs the same way. UNORM/SNORM stores convert NaN to zero before clamping. On native gfx1036, `buffer_store_format_d16_xyzw` into RGBA8_UNORM/SNORM matched clamp, scale by 255/127 and round to nearest even for all 63,488 finite binary16 encodings. Both infinities saturated and all 2,046 NaNs stored zero in both wave32 and wave64. The translated sweep matched all 65,536 bytes per format on RTX 5080 and Radeon Graphics. For normalized stores with format 56 (8/8/8/8) or 50 (10/10/10/2), a Z,Y,X,W descriptor exchanges the red and blue memory fields after filling absent input components with zero. Native gfx1036 confirmed both channel orders at all four instruction widths for packed and ordinary stores in wave32 and wave64. |
272| `s_lshl1..4_add_u32` | D = (S0 << N) + S1. SCC = the sum taken in 64 bits is ≥ 2³², so a bit shifted out of S0 sets it as well as a carry out of the add (RDNA ISA pseudocode: `tmp = (64'U(S0) << N) + 64'U(S1)`). Checked on the CPU by `tests/semantic/test_salu_lshl_add.py`. **Hardware-verified** on the same gfx1100 part through `tools/hw_oracle`: `s_lshl1_add_u32(0x80000000, 0)` = 0 with SCC = 1 (the bit shifted out of S0 sets it, with no carry out of the add), `s_lshl2_add_u32(5, 3)` = 0x17 with SCC = 0, `s_lshl4_add_u32(1, 0)` = 0x10. | 275| `s_lshl1..4_add_u32` | D = (S0 << N) + S1. SCC = the sum taken in 64 bits is ≥ 2³², so a bit shifted out of S0 sets it as well as a carry out of the add (RDNA ISA pseudocode: `tmp = (64'U(S0) << N) + 64'U(S1)`). Checked on the CPU by `tests/semantic/test_salu_lshl_add.py`. **Hardware-verified** on the same gfx1100 part through `tools/hw_oracle`: `s_lshl1_add_u32(0x80000000, 0)` = 0 with SCC = 1 (the bit shifted out of S0 sets it, with no carry out of the add), `s_lshl2_add_u32(5, 3)` = 0x17 with SCC = 0, `s_lshl4_add_u32(1, 0)` = 0x10. |
273| Other additions | `image_gather4_l(_o)`: no explicit-LOD gather in core Vulkan, so four `OpImageFetch` at mip `Floor(clamp(LOD, S# MIN_LOD, MAX_LOD) + 0.5)` (ties up, as native) in gather order. With `d16` those four taps round to binary16 and pack low half first into two consecutive VGPRs. The packed words and the first untouched VGPR were checked with `ps_gather_wrap.asm` on RTX 5080 and Radeon Graphics. Each of the four texel coordinates goes through the S#'s own address mode, read from S# word0 (`CLAMP_X` = bits [2:0], `CLAMP_Y` = [5:3]; fields from Mesa `src/amd/registers/gfx10-rsrc.json`, values `SQ_TEX_*` in Mesa `gfx6.json`, matching RADV's `radv_tex_wrap` mapping of Vulkan address modes): 0 wrap (`c mod n`), 1 mirror (`c mod 2n`, reflected), 2 clamp to the last texel, 3 mirror-once (`-1-c` for negative `c`, then clamped), as in Vulkan's address-mode definitions. A literal S# (`s_mov_b32` earlier in the block) is decoded at translation time; otherwise the mode is read from the SGPR at run time. A literal S# with a border mode (4-7: half-border, border colour) or `FORCE_UNNORMALIZED` is `Unsupported`; a run-time S# can't be judged, so modes 4-7 act as clamp-to-edge there and `FORCE_UNNORMALIZED` (word0 bit 15) is not applied (coordinates are still scaled by the image size). Those two are the remaining approximations; the unnormalized rules (texel-unit coordinates, mip 0) weren't confirmed on hardware, so they were not guessed. GPU-checked with `runtime/test/shaders/ps_gather_wrap.asm` (`vk_texture_test`; expected values derived by hand in its header; six border cases, three literal and three run-time S#) on AMD (Radeon 880M, wave64) and NVIDIA RTX 5070. `image_gather4_lz_o`: `OpImageGather … Offset`. `image_store` on 1D (bindings 17–19, `Image1D`) and with a16 coordinates. `ds_swizzle BITMASK_PERM` ("pippi" masks; GPU-checked). `v_add_f64`, `v_cvt_f32_f64` (`Float64`). `v_mul/mad_i32_i24`, `v_alignbyte_b32`, `v_xnor_b32`, `v_ffbh_i32`, `v_swap_b32`, `s_abs_i32`, `s_bfm_b32/b64`, 64-bit ordered and `v_cmpx` compares, 16-bit compares, 8/16-bit global loads, `neg(…)` constant operands (GPU-checked where listed in `runtime/test/shaders`). | 276| Other additions | `image_gather4_l(_o)`: no explicit-LOD gather in core Vulkan, so four `OpImageFetch` at mip `Floor(clamp(LOD, S# MIN_LOD, MAX_LOD) + 0.5)` (ties up, as native) in gather order. With `d16` those four taps round to binary16 and pack low half first into two consecutive VGPRs. The packed words and the first untouched VGPR were checked with `ps_gather_wrap.asm` on RTX 5080 and Radeon Graphics. Each of the four texel coordinates goes through the S#'s own address mode, read from S# word0 (`CLAMP_X` = bits [2:0], `CLAMP_Y` = [5:3]; fields from Mesa `src/amd/registers/gfx10-rsrc.json`, values `SQ_TEX_*` in Mesa `gfx6.json`, matching RADV's `radv_tex_wrap` mapping of Vulkan address modes): 0 wrap (`c mod n`), 1 mirror (`c mod 2n`, reflected), 2 clamp to the last texel, 3 mirror-once (`-1-c` for negative `c`, then clamped), as in Vulkan's address-mode definitions. A literal S# (`s_mov_b32` earlier in the block) is decoded at translation time; otherwise the mode is read from the SGPR at run time. A literal S# with a border mode (4-7: half-border, border colour) or `FORCE_UNNORMALIZED` is `Unsupported`; a run-time S# can't be judged, so modes 4-7 act as clamp-to-edge there and `FORCE_UNNORMALIZED` (word0 bit 15) is not applied (coordinates are still scaled by the image size). Those two are the remaining approximations; the unnormalized rules (texel-unit coordinates, mip 0) weren't confirmed on hardware, so they were not guessed. GPU-checked with `runtime/test/shaders/ps_gather_wrap.asm` (`vk_texture_test`; expected values derived by hand in its header; six border cases, three literal and three run-time S#) on AMD (Radeon 880M, wave64) and NVIDIA RTX 5070. `image_gather4_lz_o`: `OpImageGather … Offset`. `image_store` on 1D (bindings 17–19, `Image1D`) and with a16 coordinates. `ds_swizzle BITMASK_PERM` ("pippi" masks; GPU-checked). `v_add_f64`, `v_cvt_f32_f64` (`Float64`). `v_mul/mad_i32_i24`, `v_alignbyte_b32`, `v_xnor_b32`, `v_ffbh_i32`, `v_swap_b32`, `s_abs_i32`, `s_bfm_b32/b64`, 64-bit ordered and `v_cmpx` compares, 16-bit compares, 8/16-bit global loads, `neg(…)` constant operands (GPU-checked where listed in `runtime/test/shaders`). |
274| `v_mad_u64_u32`, `v_mad_i64_i32` | {sdst, D} = S0 × S1 + S2 as a 65-bit result (RDNA ISA pseudocode), the product unsigned or signed. sdst (a lane mask) gets bit 64 for active lanes and 0 for lanes off in EXEC (`EXEC[lane] ? bit64 : 0`, matching `v_cmp_*` and `*_co_*`): the carry out for u64, and for i64 the sign of the exact sum (bit 64 of a 65-bit two's-complement value), not a signed-overflow flag. `tools/lane_masks.py` tracks sdst as a lane mask (until 2026-11-22 it only matched `*_co_*`, so `s_bcnt1`/`s_ff1`/`v_mbcnt` on sdst read each lane's own mask word as plain data). `clamp` is rejected. Checked on the CPU by `tests/test_lane_masks.py`, `tests/semantic/test_alu_mad64.py` (including 64-lane `s_bcnt1_i32_b64`/`s_ff1_i32_b64` ballot tests), and `tests/semantic/test_carry_exec_mask.py` (EXEC masking on inactive lanes), **not yet GPU-verified**. | 277| `v_mad_u64_u32`, `v_mad_i64_i32` | {sdst, D} = S0 × S1 + S2 as a 65-bit result (RDNA ISA pseudocode), the product unsigned or signed. sdst (a lane mask) gets bit 64 for active lanes and 0 for lanes off in EXEC (`EXEC[lane] ? bit64 : 0`, matching `v_cmp_*` and `*_co_*`): the carry out for u64, and for i64 the sign of the exact sum (bit 64 of a 65-bit two's-complement value), not a signed-overflow flag. `tools/lane_masks.py` tracks sdst as a lane mask (until 2026-11-22 it only matched `*_co_*`, so `s_bcnt1`/`s_ff1`/`v_mbcnt` on sdst read each lane's own mask word as plain data). `clamp` is rejected. Checked on the CPU by `tests/test_lane_masks.py`, `tests/semantic/test_alu_mad64.py` (including 64-lane `s_bcnt1_i32_b64`/`s_ff1_i32_b64` ballot tests), and `tests/semantic/test_carry_exec_mask.py` (EXEC masking on inactive lanes). **Hardware-verified on RDNA2** (AMD Radeon 680M, `gfx1035`, wave32 and wave64 via `tools/int_hw_probe.py --oracle both`, SHADER-137): unsigned carry, signed positive overflow `(-2³¹)² + INT64_MAX` giving `sdst = 0`, negative sum giving `sdst = 1`, and inactive EXEC lane leaving D untouched with `sdst = 0` all match bit-for-bit. |
275| Ray tracing | `image_bvh_intersect_ray` / `image_bvh64_intersect_ray` (64 CS: RT shadows) are one traversal step against AMD's hardware BVH node format. The traversal loop lives in the game's shader. The step is emulated over buffer reads following Mesa RADV's software path (`radv_nir_rt_common.c`, `intersect_ray_amd_software_box/_tri`; node layouts from `bvh_defines.h`). Node id = address >> 3 \| type (0–3 triangle, 4 box16, 5 box32). Box nodes give the four child ids, with misses and NaN boxes = `0xFFFFFFFF`, sorted by entry distance when descriptor bit 63 (box_sort_enable) is set. Triangle nodes read their three vertices from the slots the node type picks: TRI0 (0,1,2), TRI1 (1,3,2), TRI2 (2,3,4), TRI3 (2,4,0), 12 bytes each. They use the watertight test with RADV's shared edge/vertex tie-breaks and give (t/\|det\|, sign(det), b_i/\|det\|, b_j/\|det\|), or (inf, 1, 0, 0) on a miss. The weights i and j are chosen by the node type's byte of the triangle-ID word at +60: bits [1:0] and [3:2], 0/1/2 = vertex 0/1/2; `0x09` gives RADV's (v, w). Vertex slots and remap follow AMD GPURT (`CalcTriangleCompressionVertexIndices`, `SwizzleBarycentrics`) and the public XDXR software path ([bvh.md](bvh.md) §7a). These two references agree; no game BVH is decoded yet to count over. A GPU can't confirm the rule either, because every GPU runs this emulation and none runs the native instruction. `tests/semantic/test_image_bvh_tri.py` runs every node type and remap byte on the interpreter. The game's code divides by `.y` exactly as for the hardware's numerator/denominator. Address = descriptor base + ((node & ~7) << 3), base = descriptor bits [39:0] in 256-byte units (**assumption**: RADV only uses base 0). **The runtime must build the game's acceleration structures in this AMD node format** (RADV's GPU BVH builder produces it) wherever the game's D3D12 calls build them. Far branches with `s_sub_u32`/`s_subb_u32` (backward) are folded too. GPU-checked with `runtime/test/shaders/cs_bvh.asm`: sorted box children and the triangle result are exact. The 32-bit form (11 address dwords: the node id has no high dword) runs the same scene in `cs_bvh32.asm` and gives the same eight words. | 278| Ray tracing | `image_bvh_intersect_ray` / `image_bvh64_intersect_ray` (64 CS: RT shadows) are one traversal step against AMD's hardware BVH node format. The traversal loop lives in the game's shader. The step is emulated over buffer reads following Mesa RADV's software path (`radv_nir_rt_common.c`, `intersect_ray_amd_software_box/_tri`; node layouts from `bvh_defines.h`). Node id = address >> 3 \| type (0–3 triangle, 4 box16, 5 box32). Box nodes give the four child ids, with misses and NaN boxes = `0xFFFFFFFF`, sorted by entry distance when descriptor bit 63 (box_sort_enable) is set. Triangle nodes read their three vertices from the slots the node type picks: TRI0 (0,1,2), TRI1 (1,3,2), TRI2 (2,3,4), TRI3 (2,4,0), 12 bytes each. They use the watertight test with RADV's shared edge/vertex tie-breaks and give (t/\|det\|, sign(det), b_i/\|det\|, b_j/\|det\|), or (inf, 1, 0, 0) on a miss. The weights i and j are chosen by the node type's byte of the triangle-ID word at +60: bits [1:0] and [3:2], 0/1/2 = vertex 0/1/2; `0x09` gives RADV's (v, w). Vertex slots and remap follow AMD GPURT (`CalcTriangleCompressionVertexIndices`, `SwizzleBarycentrics`) and the public XDXR software path ([bvh.md](bvh.md) §7a). These two references agree; no game BVH is decoded yet to count over. A GPU can't confirm the rule either, because every GPU runs this emulation and none runs the native instruction. `tests/semantic/test_image_bvh_tri.py` runs every node type and remap byte on the interpreter. The game's code divides by `.y` exactly as for the hardware's numerator/denominator. Address = descriptor base + ((node & ~7) << 3), base = descriptor bits [39:0] in 256-byte units (**assumption**: RADV only uses base 0). **The runtime must build the game's acceleration structures in this AMD node format** (RADV's GPU BVH builder produces it) wherever the game's D3D12 calls build them. Far branches with `s_sub_u32`/`s_subb_u32` (backward) are folded too. GPU-checked with `runtime/test/shaders/cs_bvh.asm`: sorted box children and the triangle result are exact. The 32-bit form (11 address dwords: the node id has no high dword) runs the same scene in `cs_bvh32.asm` and gives the same eight words. |
276| Coverage | Every shader in the corpus translates. The remaining fidelity gap is wave64 cross-half code on 32-wide subgroups in VS/PS/GS; compute and mesh shaders are exact there with `--wave64-emulate` (see the wave-size and wave64 rows). | 279| Coverage | Every shader in the corpus translates. The remaining fidelity gap is wave64 cross-half code on 32-wide subgroups in VS/PS/GS; compute and mesh shaders are exact there with `--wave64-emulate` (see the wave-size and wave64 rows). |
277| Ray tracing | `image_bvh_intersect_ray` / `image_bvh64_intersect_ray` (64 CS: RT shadows) are one traversal step against AMD's hardware BVH node format. The traversal loop lives in the game's shader. The step is emulated over buffer reads following Mesa RADV's software path (`radv_nir_rt_common.c`, `intersect_ray_amd_software_box/_tri`; node layouts from `bvh_defines.h`). Node id = address >> 3 \| type (0–3 triangle, 4 box16, 5 box32). Box nodes give the four child ids, with misses and NaN boxes = `0xFFFFFFFF`, sorted by entry distance when descriptor bit 63 (box_sort_enable) is set. Triangle nodes use the watertight test with RADV's shared edge/vertex tie-breaks and give (t/\|det\|, sign(det), v/\|det\|, w/\|det\|), or (inf, 1, 0, 0) on a miss. The game's code divides by `.y` exactly as for the hardware's numerator/denominator. Address = descriptor base + ((node & ~7) << 3), base = descriptor bits [39:0] in 256-byte units (**assumption**: RADV only uses base 0). **The runtime must build the game's acceleration structures in this AMD node format** (RADV's GPU BVH builder produces it) wherever the game's D3D12 calls build them. Far branches with `s_sub_u32`/`s_subb_u32` (backward) are folded too. GPU-checked with `runtime/test/shaders/cs_bvh.asm`: sorted box children and the triangle result are exact. | 280| Ray tracing | `image_bvh_intersect_ray` / `image_bvh64_intersect_ray` (64 CS: RT shadows) are one traversal step against AMD's hardware BVH node format. The traversal loop lives in the game's shader. The step is emulated over buffer reads following Mesa RADV's software path (`radv_nir_rt_common.c`, `intersect_ray_amd_software_box/_tri`; node layouts from `bvh_defines.h`). Node id = address >> 3 \| type (0–3 triangle, 4 box16, 5 box32). Box nodes give the four child ids, with misses and NaN boxes = `0xFFFFFFFF`, sorted by entry distance when descriptor bit 63 (box_sort_enable) is set. Triangle nodes use the watertight test with RADV's shared edge/vertex tie-breaks and give (t/\|det\|, sign(det), v/\|det\|, w/\|det\|), or (inf, 1, 0, 0) on a miss. The game's code divides by `.y` exactly as for the hardware's numerator/denominator. Address = descriptor base + ((node & ~7) << 3), base = descriptor bits [39:0] in 256-byte units (**assumption**: RADV only uses base 0). **The runtime must build the game's acceleration structures in this AMD node format** (RADV's GPU BVH builder produces it) wherever the game's D3D12 calls build them. Far branches with `s_sub_u32`/`s_subb_u32` (backward) are folded too. GPU-checked with `runtime/test/shaders/cs_bvh.asm`: sorted box children and the triangle result are exact. |
@@ -290,27 +293,31 @@ How the generated SPIR-V expects the runtime to work:
290| `NoContraction` multiply on MoltenVK (SHADER-182) | On MoltenVK, a multiply with an exact zero result and a negative sign (`+0 × -1.5`, `-0 × 1.0`) returns +0 in f32, f16 and packed f16 (#1203). The f16 multiplies are `OpFMul` on `float`, so all three go through the same path. MoltenVK's SPIRV-Cross turns a `NoContraction` `OpFMul` into its `spvFMul` helper, which returns `fma(l, r, T(0))`. A -0 product plus +0 is +0. SPIRV-Cross [300681bb](https://github.com/KhronosGroup/SPIRV-Cross/commit/300681bbcb8365a8d1eacdacdbdd0249bbf1d6b1) changes the addend to `T(-0.0)`. MoltenVK 1.4.2 and MoltenVK `main` at `5189f8de` (2026-10-13), which pins the parent commit `aa217aeb`, have the old helper. The translator does not change for this. `MVK_CONFIG_FAST_MATH_ENABLED=0` and `SignedZeroInfNanPreserve` (#664) do not help on MoltenVK, because the helper itself adds +0. 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` matches 49/50 programs with `--seed 1 --wave 32`, 98/100 with `--seed 1 --emulate` and 98/100 with `--seed 4 --emulate`. 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). Homebrew MoltenVK 1.4.2 gives the `aa217aeb` counts. | 293| `NoContraction` multiply on MoltenVK (SHADER-182) | On MoltenVK, a multiply with an exact zero result and a negative sign (`+0 × -1.5`, `-0 × 1.0`) returns +0 in f32, f16 and packed f16 (#1203). The f16 multiplies are `OpFMul` on `float`, so all three go through the same path. MoltenVK's SPIRV-Cross turns a `NoContraction` `OpFMul` into its `spvFMul` helper, which returns `fma(l, r, T(0))`. A -0 product plus +0 is +0. SPIRV-Cross [300681bb](https://github.com/KhronosGroup/SPIRV-Cross/commit/300681bbcb8365a8d1eacdacdbdd0249bbf1d6b1) changes the addend to `T(-0.0)`. MoltenVK 1.4.2 and MoltenVK `main` at `5189f8de` (2026-10-13), which pins the parent commit `aa217aeb`, have the old helper. The translator does not change for this. `MVK_CONFIG_FAST_MATH_ENABLED=0` and `SignedZeroInfNanPreserve` (#664) do not help on MoltenVK, because the helper itself adds +0. 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` matches 49/50 programs with `--seed 1 --wave 32`, 98/100 with `--seed 1 --emulate` and 98/100 with `--seed 4 --emulate`. 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). Homebrew MoltenVK 1.4.2 gives the `aa217aeb` counts. |
291| 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. | 294| 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. |
292| Denormal flush and special results in `v_rcp_f32`, `v_rsq_f32`, `v_sqrt_f32`, `v_log_f32`, `v_exp_f32`, `v_rcp_iflag_f32` | Measured on an RX 6800 (gfx1030, not the console's gfx1013) with raw kernels in both wave sizes and all four IEEE/DX10_CLAMP combinations: all six read a denormal input as a zero of its sign and flush a denormal result, even with MODE's denormal field set to keep them. `v_rcp_f32(±0)` = ±inf, `v_rsq_f32(-0)` = -inf, `v_sqrt_f32(-0)` = -0, `v_log_f32(±0)` = -inf, `v_rcp_f32(FLT_MAX)` = +0, `v_exp_f32(-127)` = +0, `v_exp_f32(128)` = +inf, and every invalid result (`v_sqrt_f32`/`v_rsq_f32`/`v_log_f32` of a negative, …) is `0xffc00000`. Each is within 1 ulp of correctly rounded on the values tried, and `v_rcp_iflag_f32` is bit-identical to `v_rcp_f32`. **Not modelled yet:** the translator leaves all six on Vulkan's default denormal handling, and the ±0 and negative inputs above stay undefined in the emitted SPIR-V (`OpFDiv` by zero, `Sqrt`/`Log2` of a negative), as listed in the multiply-add and output modifiers row; the `clamp`/`omod` bits on `v_cvt_f32_*` and `v_rcp_iflag_f32` are modelled there. Source: [@shelbykb2's hardware words](https://github.com/ItsNotRexed/Leonida/issues/634#issuecomment-7074348963), not the ISA text. The corpus only ever writes MODE's FP_ROUND field and carries `mul:2`/`mul:4`/`div:2` on 102,365 float instructions (a compiler does not emit one that is ignored), so the inferred f32 state, IEEE off with denormals flushed, is the one to model. Corpus count (`tools/shader_profile.py`, 26,503 shaders; the shader count of each op deduplicates its `_e32`/`_e64` forms): `v_rcp_f32` 17,393 shaders / 424,863 occurrences, `v_rsq_f32` 17,221 / 269,310, `v_sqrt_f32` 14,511 / 201,422, `v_log_f32` 8,454 / 90,199, `v_exp_f32` 8,603 / 148,846, `v_rcp_iflag_f32` 7,395 / 34,852; 20,193 shaders (76.2%) use at least one, 1,169,492 occurrences (2.6% of the corpus's 44,406,870 instructions). | 295| Denormal flush and special results in `v_rcp_f32`, `v_rsq_f32`, `v_sqrt_f32`, `v_log_f32`, `v_exp_f32`, `v_rcp_iflag_f32` | Measured on an RX 6800 (gfx1030, not the console's gfx1013) with raw kernels in both wave sizes and all four IEEE/DX10_CLAMP combinations: all six read a denormal input as a zero of its sign and flush a denormal result, even with MODE's denormal field set to keep them. `v_rcp_f32(±0)` = ±inf, `v_rsq_f32(-0)` = -inf, `v_sqrt_f32(-0)` = -0, `v_log_f32(±0)` = -inf, `v_rcp_f32(FLT_MAX)` = +0, `v_exp_f32(-127)` = +0, `v_exp_f32(128)` = +inf, and every invalid result (`v_sqrt_f32`/`v_rsq_f32`/`v_log_f32` of a negative, …) is `0xffc00000`. Each is within 1 ulp of correctly rounded on the values tried, and `v_rcp_iflag_f32` is bit-identical to `v_rcp_f32`. **Not modelled yet:** the translator leaves all six on Vulkan's default denormal handling, and the ±0 and negative inputs above stay undefined in the emitted SPIR-V (`OpFDiv` by zero, `Sqrt`/`Log2` of a negative), as listed in the multiply-add and output modifiers row; the `clamp`/`omod` bits on `v_cvt_f32_*` and `v_rcp_iflag_f32` are modelled there. Source: [@shelbykb2's hardware words](https://github.com/ItsNotRexed/Leonida/issues/634#issuecomment-7074348963), not the ISA text. The corpus only ever writes MODE's FP_ROUND field and carries `mul:2`/`mul:4`/`div:2` on 102,365 float instructions (a compiler does not emit one that is ignored), so the inferred f32 state, IEEE off with denormals flushed, is the one to model. Corpus count (`tools/shader_profile.py`, 26,503 shaders; the shader count of each op deduplicates its `_e32`/`_e64` forms): `v_rcp_f32` 17,393 shaders / 424,863 occurrences, `v_rsq_f32` 17,221 / 269,310, `v_sqrt_f32` 14,511 / 201,422, `v_log_f32` 8,454 / 90,199, `v_exp_f32` 8,603 / 148,846, `v_rcp_iflag_f32` 7,395 / 34,852; 20,193 shaders (76.2%) use at least one, 1,169,492 occurrences (2.6% of the corpus's 44,406,870 instructions). |
293| f16 transcendentals (`v_exp_f16`, `v_log_f16`, `v_rcp_f16`, `v_rsq_f16`, `v_sqrt_f16`, `v_sin_f16`, `v_cos_f16`) | Measured on an RX 6700 XT (gfx1031, not the console's gfx1013) with `tools/f16_trans_sweep.py`: all 65,536 inputs of each op, wave32 and wave64 (identical on every input), five MODEs (FUZZ-29). With f16 denormals kept (`denorm_mode_16_64 = 3`, the assembler default and what the translator assumes), `v_exp/log/rcp/rsq/sqrt_f16` are **correctly rounded on every input that is not a NaN** (0 ulp). `v_sin/v_cos_f16` take turns and reduce them exactly over the whole f16 range (no ±256 limit): compared with sin/cos(2πx), every result for |x| > 1 is bit-exact, and for |x| ≤ 1 only 14 (sin) and 4 (cos) of 30,722 are 1 ulp off. So the translator's rule (widen to f32, the GLSL.std.450 function, round to nearest even back to f16) matches the hardware as far as the driver's f32 function is accurate. For sin/cos that holds only once the angle is reduced in turns first (#594): with the f32 product 6.2831855 · x, 16,366 sin and 2,036 cos inputs are more than 1 ulp off, up to 9,944 ulp (sin of 64,640 turns: 0.0267 instead of 0). With `denorm_mode_16_64 = 0`, a denormal operand reads as a zero of its sign, and a denormal result is written as a zero of its sign. That differs from the f32 ops in the row above, which flush in both modes. The f16 field of FP_ROUND is ignored: round toward zero gives the same words as round to nearest on every input. IEEE changes only signalling NaNs. With IEEE off they pass through unchanged; with IEEE on they are quieted (bit 9 set). Payload and sign are kept either way, and quiet NaNs pass unchanged in every mode. Where SPIR-V leaves the result undefined, the hardware gives: log(±0) = -inf, rcp(±0) = ±inf, rsq(+0) = +inf, rsq(-0) = -inf, sqrt(-0) = -0, and `0xfe00` for log/rsq/sqrt of a negative (-inf included) and for sin/cos(±inf). **Not modelled yet:** `Gen.f16_bits` quiets every NaN (the hardware keeps a signalling NaN with IEEE off), and the undefined cases above are left to the driver. | 296| f16 transcendentals (`v_exp_f16`, `v_log_f16`, `v_rcp_f16`, `v_rsq_f16`, `v_sqrt_f16`, `v_sin_f16`, `v_cos_f16`) | Measured on an RX 6700 XT (gfx1031, not the console's gfx1013) with `tools/f16_trans_sweep.py`: all 65,536 inputs of each op, wave32 and wave64 (identical on every input), five MODEs (FUZZ-29). With f16 denormals kept (`denorm_mode_16_64 = 3`, the assembler default and what the translator assumes), `v_exp/log/rcp/rsq/sqrt_f16` are **correctly rounded on every input that is not a NaN** (0 ulp). `v_sin/v_cos_f16` take turns and reduce them exactly over the whole f16 range (no ±256 limit): compared with sin/cos(2πx), every result for |x| > 1 is bit-exact, and for |x| ≤ 1 only 14 (sin) and 4 (cos) of 30,722 are 1 ulp off. So the translator's rule (widen to f32, the GLSL.std.450 function, round to nearest even back to f16) matches the hardware as far as the driver's f32 function is accurate. For sin/cos that holds only once the angle is reduced in turns first (#594): with the f32 product 6.2831855 · x, 16,366 sin and 2,036 cos inputs are more than 1 ulp off, up to 9,944 ulp (sin of 64,640 turns: 0.0267 instead of 0). With `denorm_mode_16_64 = 0`, a denormal operand reads as a zero of its sign, and a denormal result is written as a zero of its sign. That differs from the f32 ops in the row above, which flush in both modes. The f16 field of FP_ROUND is ignored: round toward zero gives the same words as round to nearest on every input. IEEE changes only signalling NaNs. With IEEE off they pass through unchanged; with IEEE on they are quieted (bit 9 set). Payload and sign are kept either way, and quiet NaNs pass unchanged in every mode. Where SPIR-V leaves the result undefined, the hardware gives: log(±0) = -inf, rcp(±0) = ±inf, rsq(+0) = +inf, rsq(-0) = -inf, sqrt(-0) = -0, and `0xfe00` for log/rsq/sqrt of a negative (-inf included) and for sin/cos(±inf). `v_exp_f16`/`v_log_f16` give the same counts on gfx1036 (RDNA2, AMD Windows driver; SHADER-135). **Not modelled yet:** `Gen.f16_bits` quiets every NaN (the hardware keeps a signalling NaN with IEEE off), and the undefined cases above are left to the driver. |
294| `v_cvt_f32_f64` output modifiers | Convert to f32, apply `mul:2`, `mul:4`, or `div:2` if present, then apply `clamp` to [0, 1] if requested. [LLVM GFX10 assembler tests](https://github.com/llvm/llvm-project/blob/main/llvm/test/MC/AMDGPU/gfx10_asm_vop1.s#L3044-L3054) confirm the modifier encodings. `tests/test_f64_conversion.py` checks the resulting SPIR-V data flow. | 297| `v_cvt_f32_f64` output modifiers | Convert to f32, apply `mul:2`, `mul:4`, or `div:2` if present, then apply `clamp` to [0, 1] if requested. [LLVM GFX10 assembler tests](https://github.com/llvm/llvm-project/blob/main/llvm/test/MC/AMDGPU/gfx10_asm_vop1.s#L3044-L3054) confirm the modifier encodings. `tests/test_f64_conversion.py` checks the resulting SPIR-V data flow. |
295| `v_add_f64` output modifiers | The double sum is scaled by `mul:2`, `mul:4` or `div:2` if present, then clamped to [0, 1] if `clamp` is set, as for f32 (`clamp_mods_f64`, GLSL.std.450 `FClamp` on the double, so a NaN result and the sign of a -0 result are left to the driver, also as for f32). **Until 2026-11-22 both were ignored.** Source: LLVM AMDGPU defines it as `VOP3Inst<"v_add_f64", VOP3_Profile<VOP_F64_F64_F64>>` (VOP3Instructions.td), and `VOPProfile` sets `HasClamp` (f64 is a modifier type) and `HasOMod` (floating-point destination) (SIInstrInfo.td). It is the only f64 arithmetic the translator handles; `v_cvt_f32_f64` has the row above. `tests/test_f64_output_modifiers.py` checks the SPIR-V data flow; `runtime/test/shaders/ps_f64_mods.asm` is the GPU test (needs `shaderFloat64`, which `vk_harness` now enables when the fragment shader declares `Float64`), passed on an NVIDIA RTX 6000 Ada (driver 615.71.09, Linux; 4096/4096 pixels exact, and the `main` translator gives the predicted old words). | 298| `v_add_f64` output modifiers | The double sum is scaled by `mul:2`, `mul:4` or `div:2` if present, then clamped to [0, 1] if `clamp` is set, as for f32 (`clamp_mods_f64`, GLSL.std.450 `FClamp` on the double, so a NaN result and the sign of a -0 result are left to the driver, also as for f32). **Until 2026-11-22 both were ignored.** Source: LLVM AMDGPU defines it as `VOP3Inst<"v_add_f64", VOP3_Profile<VOP_F64_F64_F64>>` (VOP3Instructions.td), and `VOPProfile` sets `HasClamp` (f64 is a modifier type) and `HasOMod` (floating-point destination) (SIInstrInfo.td). It is the only f64 arithmetic the translator handles; `v_cvt_f32_f64` has the row above. `tests/test_f64_output_modifiers.py` checks the SPIR-V data flow; `runtime/test/shaders/ps_f64_mods.asm` is the GPU test (needs `shaderFloat64`, which `vk_harness` now enables when the fragment shader declares `Float64`), passed on an NVIDIA RTX 6000 Ada (driver 615.71.09, Linux; 4096/4096 pixels exact, and the `main` translator gives the predicted old words). |
296| Floating-point class compare | `v_cmp_class_f32` writes the selected class to a lane mask. `v_cmpx_class_f32` intersects the existing EXEC with that same predicate and preserves VCC, as specified in [AMD's RDNA2 ISA §12.9](https://www.amd.com/content/dam/amd/en/documents/radeon-tech-docs/instruction-set-architectures/rdna2-shader-instruction-set-architecture.pdf). `cs_cmpx_class_f32` checks both encodings with quiet NaN, positive infinity and signed zero, and verifies that a previously inactive lane stays inactive. GPU-checked on an RTX 4070 SUPER (driver 616.92). | 299| Floating-point class compare | `v_cmp_class_f32` writes the selected class to a lane mask. `v_cmpx_class_f32` intersects the existing EXEC with that same predicate and preserves VCC, as specified in [AMD's RDNA2 ISA §12.9](https://www.amd.com/content/dam/amd/en/documents/radeon-tech-docs/instruction-set-architectures/rdna2-shader-instruction-set-architecture.pdf). `cs_cmpx_class_f32` checks both encodings with quiet NaN, positive infinity and signed zero, and verifies that a previously inactive lane stays inactive. GPU-checked on an RTX 4070 SUPER (driver 616.92). |
297| 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. | 300| 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. |
298| 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`); **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)` (`FClamp`). | 301| 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`); **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)` (`FClamp`). |
299| 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; 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; 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"). | 302| 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 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"). |
303| 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; 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. Details in docs/shader_validation.md ("32-bit float VALU on the GPU"). |
300| 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. 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 `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`); 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. | 304| 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. 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 `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`); 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. |
301| 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). 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). 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. | 305| 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). 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). 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. |
302| Lane select (`v_readlane_b32` / `v_writelane_b32`) | The lane is **S1[4:0] in wave32** and S1[5:0] in wave64, from an SGPR or a constant, and EXEC is ignored (RDNA 3 ISA guide pseudocode for both opcodes; RDNA 2 has the same encoding and gives no pseudocode). **Until #488 (SHADER-52) a wave32 shader masked with 63 as well**: a lane select of 32 or more wrote no lane, and a read shuffled from a lane past the end of a 32-wide subgroup, which SPIR-V leaves undefined (NVIDIA wraps it, so reads happened to come out right there). Found by the FUZZ-7 cross-lane fuzzer: 23 of 100 random wave32 programs, each minimized to `s_mov_b32 s28, K; v_writelane_b32 vD, x, s28` with K ≥ 32. GPU-checked with `runtime/test/shaders/cs_w32_lane_wrap.asm` (25 16 777 777) on NVIDIA GeForce RTX 5060 (#488) and RTX 4090 (subgroup 32, driver 621.14); `tests/test_translate.py` checks the masks in the SPIR-V, and `tests/semantic/test_wave32_lane_select.py` runs the shader across 32 lanes, where a mask of 63 is an out-of-range shuffle. | 306| Lane select (`v_readlane_b32` / `v_writelane_b32`) | The lane is **S1[4:0] in wave32** and S1[5:0] in wave64, from an SGPR or a constant, and EXEC is ignored (RDNA 3 ISA guide pseudocode for both opcodes; RDNA 2 has the same encoding and gives no pseudocode). **Until #488 (SHADER-52) a wave32 shader masked with 63 as well**: a lane select of 32 or more wrote no lane, and a read shuffled from a lane past the end of a 32-wide subgroup, which SPIR-V leaves undefined (NVIDIA wraps it, so reads happened to come out right there). Found by the FUZZ-7 cross-lane fuzzer: 23 of 100 random wave32 programs, each minimized to `s_mov_b32 s28, K; v_writelane_b32 vD, x, s28` with K ≥ 32. GPU-checked with `runtime/test/shaders/cs_w32_lane_wrap.asm` (25 16 777 777) on NVIDIA GeForce RTX 5060 (#488) and RTX 4090 (subgroup 32, driver 621.14); `tests/test_translate.py` checks the masks in the SPIR-V, and `tests/semantic/test_wave32_lane_select.py` runs the shader across 32 lanes, where a mask of 63 is an out-of-range shuffle. |
303| Wave64 emulation (`--wave64-emulate`) | Wave64 compute and mesh shaders exact on **any** subgroup size (32-wide NVIDIA, Intel, AMD in wave32 mode), with no subgroup operation at all. One invocation is still one lane. Everything a lane needs from the rest of its wave goes through a Workgroup buffer `%x_buf`: votes (`s_cbranch_vccz/vccnz/execz/execnz`, SCC of mask ops, `s_cmp` of masks), whole-mask words (`s_bcnt1`, `s_ff1`, `v_mbcnt`), `v_readlane`, `v_readfirstlane`, `ds_bpermute`, `ds_swizzle`, `v_permlane16/x16`. The program runs in rounds: in each round every wave that is neither done nor waiting at `s_barrier` runs one segment of its program (a basic block, cut at each cross-lane op), then the whole workgroup meets at one `OpControlBarrier` (Workgroup, AcquireRelease, workgroup + uniform + image memory) that sits in uniform control flow, because every invocation runs every round. A cross-lane op ends its segment after the lane has stored its value (per-lane data, double-buffered by round parity) or ORed its bit (two mask words per wave, three slots by round mod 3, each slot cleared two rounds after it was read); the code after it runs one round later, when all 64 lanes have written. SSA values live across a cut go through Function variables. `s_barrier` is a scheduler state: the wave stops running segments until every wave that isn't done is waiting, which is also how hardware counts finished waves. A memory access that conflicts with an earlier one in the same segment (read after write, write after read, write after write; LDS and buffer/image memory separately) starts a new round, so two halves of a wave in different subgroups access memory in instruction order, as the lanes of one hardware wave do; not ordered: scalar loads of memory the wave wrote, and sampling an image it wrote. The missing lanes of a partial last wave read as 0. Without the flag the output is unchanged, apart from two fixes that apply to every wave64 compute/mesh shader: `v_writelane_b32` selects the lane by the wave lane (on a 32-wide subgroup writes to lanes 32–63 were lost; `cs_w64x_writelane`), and `ds_bpermute_b32` (see the LDS row). Fewer rounds, same results: a whole-mask read (`s_bcnt1`, `v_mbcnt_lo/hi`, ...) of the value of the same register (or EXEC) that an earlier read in the block already exchanged reuses that exchange (the value's identity is the SSA id last stored to the register, forgotten at block start and at any label); and a block that ends in a voted branch (`s_cbranch_vccz/vccnz/execz/execnz`) runs its successor in the round that reads the vote, since that segment only reads the vote and picks the next block (an inner loop in the scheduler, flag `%x_chain`). Both rules are pinned by `cs_w64x_mask_reuse` (a mask register and EXEC rewritten between reads), `cs_w64x_mask_reuse2` (EXEC read twice, a read after a buffer store, one half of a mask pair rewritten while the other is kept, a voted branch whose successor starts with a load of the other half's earlier store) and `cs_w64x_chain_barrier` (a voted branch whose successor starts with `s_barrier`, two waves): expected values from the ISA, first run on the AMD 880M with its native 64-wide subgroup, then emulated on both GPUs; `tests/test_translate.py` counts the exchanges in the SPIR-V (one per value, a new one after a rewrite of the register or EXEC), and the translator refuses (`Unsupported`) a voted branch whose segment was not started by the vote's own round. `scripts/bench_wave64.py` times `cs_bench_mix` native and emulated and checks the emulated output bytes against the native AMD run. Cost: one workgroup barrier per segment, and `%x_buf` = (2·L + 6·W + 7) dwords for L invocations in W waves, counted in `lds_bytes`. GPU-checked on NVIDIA GeForce RTX 5070 Laptop (subgroup 32, driver 617.42) and AMD Radeon 880M (subgroup 64, AMD driver 26.11.2 LLPC): `check.py` 38/39 (the mesh test runs in the other script) and `scripts/run_gpu_tests.py` 40/40 on both with `LEONIDA_W64_EMULATE=1`, including every wave64 test (`cs_wavemask`, `cs_wave64_ballot`, `cs_wm_*`) and the cross-half suite `cs_w64x_*` / `ms_w64x_ballot`: readlane and writelane at lanes ≥ 32, readfirstlane with only upper lanes active, branches voted by one lane of either half, ballot + `v_mbcnt_lo/hi` compaction over 64 lanes (also in a mesh shader, 4096/4096 pixels), a 128-thread workgroup whose two waves take different branches, `s_barrier` between waves with different loop counts, LDS read-after-write and write-after-read across the halves without a barrier, a load, ballot and load in one block, and a partial wave (group 40). Without the flag the same RTX 5070 passes 19/37 (the wave64 tests skip there). Not covered: VS/PS/GS (no workgroup memory or barrier there). | 307| Wave64 emulation (`--wave64-emulate`) | Wave64 compute and mesh shaders exact on **any** subgroup size (32-wide NVIDIA, Intel, AMD in wave32 mode), with no subgroup operation at all. One invocation is still one lane. Everything a lane needs from the rest of its wave goes through a Workgroup buffer `%x_buf`: votes (`s_cbranch_vccz/vccnz/execz/execnz`, SCC of mask ops, `s_cmp` of masks), whole-mask words (`s_bcnt1`, `s_ff1`, `v_mbcnt`), `v_readlane`, `v_readfirstlane`, `ds_bpermute`, `ds_swizzle`, `v_permlane16/x16`. The program runs in rounds: in each round every wave that is neither done nor waiting at `s_barrier` runs one segment of its program (a basic block, cut at each cross-lane op), then the whole workgroup meets at one `OpControlBarrier` (Workgroup, AcquireRelease, workgroup + uniform + image memory) that sits in uniform control flow, because every invocation runs every round. A cross-lane op ends its segment after the lane has stored its value (per-lane data, double-buffered by round parity) or ORed its bit (two mask words per wave, three slots by round mod 3, each slot cleared two rounds after it was read); the code after it runs one round later, when all 64 lanes have written. SSA values live across a cut go through Function variables. `s_barrier` is a scheduler state: the wave stops running segments until every wave that isn't done is waiting, which is also how hardware counts finished waves. A memory access that conflicts with an earlier one in the same segment (read after write, write after read, write after write; LDS and buffer/image memory separately) starts a new round, so two halves of a wave in different subgroups access memory in instruction order, as the lanes of one hardware wave do; not ordered: scalar loads of memory the wave wrote, and sampling an image it wrote. The missing lanes of a partial last wave read as 0. Without the flag the output is unchanged, apart from two fixes that apply to every wave64 compute/mesh shader: `v_writelane_b32` selects the lane by the wave lane (on a 32-wide subgroup writes to lanes 32–63 were lost; `cs_w64x_writelane`), and `ds_bpermute_b32` (see the LDS row). Fewer rounds, same results: a whole-mask read (`s_bcnt1`, `v_mbcnt_lo/hi`, ...) of the value of the same register (or EXEC) that an earlier read in the block already exchanged reuses that exchange (the value's identity is the SSA id last stored to the register, forgotten at block start and at any label); and a block that ends in a voted branch (`s_cbranch_vccz/vccnz/execz/execnz`) runs its successor in the round that reads the vote, since that segment only reads the vote and picks the next block (an inner loop in the scheduler, flag `%x_chain`). Both rules are pinned by `cs_w64x_mask_reuse` (a mask register and EXEC rewritten between reads), `cs_w64x_mask_reuse2` (EXEC read twice, a read after a buffer store, one half of a mask pair rewritten while the other is kept, a voted branch whose successor starts with a load of the other half's earlier store) and `cs_w64x_chain_barrier` (a voted branch whose successor starts with `s_barrier`, two waves): expected values from the ISA, first run on the AMD 880M with its native 64-wide subgroup, then emulated on both GPUs; `tests/test_translate.py` counts the exchanges in the SPIR-V (one per value, a new one after a rewrite of the register or EXEC), and the translator refuses (`Unsupported`) a voted branch whose segment was not started by the vote's own round. `scripts/bench_wave64.py` times `cs_bench_mix` native and emulated and checks the emulated output bytes against the native AMD run. Cost: one workgroup barrier per segment, and `%x_buf` = (2·L + 6·W + 7) dwords for L invocations in W waves, counted in `lds_bytes`. GPU-checked on NVIDIA GeForce RTX 5070 Laptop (subgroup 32, driver 617.42) and AMD Radeon 880M (subgroup 64, AMD driver 26.11.2 LLPC): `check.py` 38/39 (the mesh test runs in the other script) and `scripts/run_gpu_tests.py` 40/40 on both with `LEONIDA_W64_EMULATE=1`, including every wave64 test (`cs_wavemask`, `cs_wave64_ballot`, `cs_wm_*`) and the cross-half suite `cs_w64x_*` / `ms_w64x_ballot`: readlane and writelane at lanes ≥ 32, readfirstlane with only upper lanes active, branches voted by one lane of either half, ballot + `v_mbcnt_lo/hi` compaction over 64 lanes (also in a mesh shader, 4096/4096 pixels), a 128-thread workgroup whose two waves take different branches, `s_barrier` between waves with different loop counts, LDS read-after-write and write-after-read across the halves without a barrier, a load, ballot and load in one block, and a partial wave (group 40). Without the flag the same RTX 5070 passes 19/37 (the wave64 tests skip there). Not covered: VS/PS/GS (no workgroup memory or barrier there). Known driver bug: AMD's Windows shader compiler for RDNA2 crashes (access violation in `vkCreateComputePipelines`) on many emulated compute shaders with LDS (#857: drivers 32.0.21030 to 32.0.21045.29003, iGPUs and RX 6000; 23.20.44, RDNA3, RDNA4, RADV and NVIDIA are fine), so `make_game.py --wave64-emulate auto` leaves emulation off when the runtime's GPU is such a device and runs wave64 natively (`rdna2_amd_windows` in `tools/vk_subgroup_info.py`, by PCI device ID and driver ID). |
308| Wave64 emulation (`--wave64-emulate`) | Wave64 compute and mesh shaders exact on **any** subgroup size (32-wide NVIDIA, Intel, AMD in wave32 mode), with no subgroup operation at all. One invocation is still one lane. Everything a lane needs from the rest of its wave goes through a Workgroup buffer `%x_buf`: votes (`s_cbranch_vccz/vccnz/execz/execnz`, SCC of mask ops, `s_cmp` of masks), whole-mask words (`s_bcnt1`, `s_ff1`, `v_mbcnt`), `v_readlane`, `v_readfirstlane`, `ds_bpermute`, `ds_swizzle`, `v_permlane16/x16`. The program runs in rounds: in each round every wave that is neither done nor waiting at `s_barrier` runs one segment of its program (a basic block, cut at each cross-lane op), then the whole workgroup meets at one `OpControlBarrier` (Workgroup, AcquireRelease, workgroup + uniform + image memory) that sits in uniform control flow, because every invocation runs every round. A cross-lane op ends its segment after the lane has stored its value (per-lane data, double-buffered by round parity) or ORed its bit (two mask words per wave, three slots by round mod 3, each slot cleared two rounds after it was read); the code after it runs one round later, when all 64 lanes have written. SSA values live across a cut go through Function variables. `s_barrier` is a scheduler state: the wave stops running segments until every wave that isn't done is waiting, which is also how hardware counts finished waves. A memory access that conflicts with an earlier one in the same segment (read after write, write after read, write after write; LDS and buffer/image memory separately) starts a new round, so two halves of a wave in different subgroups access memory in instruction order, as the lanes of one hardware wave do. A scalar load (`s_load*`, `s_buffer_load*`) counts as a buffer read: until #1587 it was left out, so a store and a later scalar load of the same address shared a segment and the half in the other subgroup could load before this half had stored (`valu_fuzz.py --family mem --emulate`: lanes 32-63 read the fill pattern after an `s_buffer_load`/`s_load` of the slot lane 0 had written, on RDNA1 RADV and an RTX 5060; `v_readfirstlane_b32`, which gives that slot, already reads the whole wave). Pinned by `tests/semantic/test_w64x_scalar_load_order.py` (no segment of the emitted rounds accesses buffer memory after a write or writes after a read; three of its five cases fail without the rule). Confirmed by that CPU test and the ordering argument above; the race does not show on an RX 7900 XTX (AMD 26.10.1 LLPC, Windows 11): `valu_fuzz.py --family mem --seed 5 --programs 21 --wave 64 --emulate` matches 21/21 before and after the rule (3 runs each), so a GPU reproduction on RDNA1/RADV (where #1587 was found) is still pending. Not ordered: sampling an image the wave wrote. The missing lanes of a partial last wave read as 0. Without the flag the output is unchanged, apart from two fixes that apply to every wave64 compute/mesh shader: `v_writelane_b32` selects the lane by the wave lane (on a 32-wide subgroup writes to lanes 32–63 were lost; `cs_w64x_writelane`), and `ds_bpermute_b32` (see the LDS row). Fewer rounds, same results: a whole-mask read (`s_bcnt1`, `v_mbcnt_lo/hi`, ...) of the value of the same register (or EXEC) that an earlier read in the block already exchanged reuses that exchange (the value's identity is the SSA id last stored to the register, forgotten at block start and at any label); and a block that ends in a voted branch (`s_cbranch_vccz/vccnz/execz/execnz`) runs its successor in the round that reads the vote, since that segment only reads the vote and picks the next block (an inner loop in the scheduler, flag `%x_chain`). Both rules are pinned by `cs_w64x_mask_reuse` (a mask register and EXEC rewritten between reads), `cs_w64x_mask_reuse2` (EXEC read twice, a read after a buffer store, one half of a mask pair rewritten while the other is kept, a voted branch whose successor starts with a load of the other half's earlier store) and `cs_w64x_chain_barrier` (a voted branch whose successor starts with `s_barrier`, two waves): expected values from the ISA, first run on the AMD 880M with its native 64-wide subgroup, then emulated on both GPUs; `tests/test_translate.py` counts the exchanges in the SPIR-V (one per value, a new one after a rewrite of the register or EXEC), and the translator refuses (`Unsupported`) a voted branch whose segment was not started by the vote's own round. `scripts/bench_wave64.py` times `cs_bench_mix` native and emulated and checks the emulated output bytes against the native AMD run. Cost: one workgroup barrier per segment, and `%x_buf` = (2·L + 6·W + 7) dwords for L invocations in W waves, counted in `lds_bytes`. GPU-checked on NVIDIA GeForce RTX 5070 Laptop (subgroup 32, driver 617.42) and AMD Radeon 880M (subgroup 64, AMD driver 26.11.2 LLPC): `check.py` 38/39 (the mesh test runs in the other script) and `scripts/run_gpu_tests.py` 40/40 on both with `LEONIDA_W64_EMULATE=1`, including every wave64 test (`cs_wavemask`, `cs_wave64_ballot`, `cs_wm_*`) and the cross-half suite `cs_w64x_*` / `ms_w64x_ballot`: readlane and writelane at lanes ≥ 32, readfirstlane with only upper lanes active, branches voted by one lane of either half, ballot + `v_mbcnt_lo/hi` compaction over 64 lanes (also in a mesh shader, 4096/4096 pixels), a 128-thread workgroup whose two waves take different branches, `s_barrier` between waves with different loop counts, LDS read-after-write and write-after-read across the halves without a barrier, a load, ballot and load in one block, and a partial wave (group 40). Without the flag the same RTX 5070 passes 19/37 (the wave64 tests skip there). Not covered: VS/PS/GS (no workgroup memory or barrier there). |
304| Barycentric fallback (`--bary-fallback`) | For devices without `VK_KHR_fragment_shader_barycentric` (NVIDIA Pascal, for one). The raw pair a PS reads ("PS system inputs": 321 PS) comes from an ordinary vec3 input, `%bary`, at the lowest location none of the shader's attributes uses, instead of `BuiltIn BaryCoordKHR`. The module then needs neither the `FragmentBarycentricKHR` capability nor the extension, and the index records the location as `bary_fallback_input`. The stage before the PS writes (1,0,0), (0,1,0), (0,0,1) at the triangle's three vertices: `tools/bary_fallback_gs.py` writes that pass-through geometry shader from the index (Position and the PS's input locations copied unchanged). Default (perspective) interpolation of those weights is the perspective-correct barycentric, the value `BaryCoordKHR` has, so `.y`/`.z` stay AMD's i/j; shaders that don't read the pair translate to the same module either way. GPU-checked on an NVIDIA GeForce GTX 1060 6GB (Pascal, no barycentric extension; driver 560.94, Windows 10) with `LEONIDA_BARY_FALLBACK=1`: `ps_bary` 4096/4096 pixels exact, and `ps_uniform_branch` and `ps_scc_mask32` pass, through `run_gpu_tests.py` and `build.py` + `check.py`, with zero Khronos validation messages. Checked in `tests/semantic/test_bary_fallback.py`. For a known VS/PS pair, `python -I tools/bary_fallback_gs.py DIR --pair VS PS` builds `PS.bary_gs.clipN.spv`. It copies the producer’s `ClipDistance[N]` at each emitted vertex, using the VS index field `clip_distance_count`. On RTX 5080 and Radeon integrated graphics, two independently shifted clip planes yielded 512, 1024, 2048 or 4096 covered pixels, matching the native barycentric path. For a cull-only VS the pair writes `PS.bary_gs.cullN.spv` from `cull_distance_count`. A two-plane synthetic draw on the same GPUs covered 0 pixels when every vertex was negative for either plane and all 4096 when each plane had a nonnegative vertex. The helper rejects mixed clip/cull arrays. The runtime building that GS per pipeline is the follow-up (it needs the graphics pipelines of #291). | 309| Barycentric fallback (`--bary-fallback`) | For devices without `VK_KHR_fragment_shader_barycentric` (NVIDIA Pascal, for one). The raw pair a PS reads ("PS system inputs": 321 PS) comes from an ordinary vec3 input, `%bary`, at the lowest location none of the shader's attributes uses, instead of `BuiltIn BaryCoordKHR`. The module then needs neither the `FragmentBarycentricKHR` capability nor the extension, and the index records the location as `bary_fallback_input`. The stage before the PS writes (1,0,0), (0,1,0), (0,0,1) at the triangle's three vertices: `tools/bary_fallback_gs.py` writes that pass-through geometry shader from the index (Position and the PS's input locations copied unchanged). Default (perspective) interpolation of those weights is the perspective-correct barycentric, the value `BaryCoordKHR` has, so `.y`/`.z` stay AMD's i/j; shaders that don't read the pair translate to the same module either way. GPU-checked on an NVIDIA GeForce GTX 1060 6GB (Pascal, no barycentric extension; driver 560.94, Windows 10) with `LEONIDA_BARY_FALLBACK=1`: `ps_bary` 4096/4096 pixels exact, and `ps_uniform_branch` and `ps_scc_mask32` pass, through `run_gpu_tests.py` and `build.py` + `check.py`, with zero Khronos validation messages. Checked in `tests/semantic/test_bary_fallback.py`. For a known VS/PS pair, `python -I tools/bary_fallback_gs.py DIR --pair VS PS` builds `PS.bary_gs.clipN.spv`. It copies the producer’s `ClipDistance[N]` at each emitted vertex, using the VS index field `clip_distance_count`. On RTX 5080 and Radeon integrated graphics, two independently shifted clip planes yielded 512, 1024, 2048 or 4096 covered pixels, matching the native barycentric path. For a cull-only VS the pair writes `PS.bary_gs.cullN.spv` from `cull_distance_count`. A two-plane synthetic draw on the same GPUs covered 0 pixels when every vertex was negative for either plane and all 4096 when each plane had a nonnegative vertex. The helper rejects mixed clip/cull arrays. The runtime building that GS per pipeline is the follow-up (it needs the graphics pipelines of #291). |
305| Metadata index | `spirv/index.json`: one entry per translated shader with its stage, `wave64` / `subgroup_size`, SPIR-V capabilities and extensions, the Vulkan **features** to enable (barycentrics, interlock, mesh, geometry, Float64, Int64, buffer device address, write-without-format, `shaderFmaFloat32` for `--fma khr`, …), `needs_maintenance8`, the descriptor bindings it uses (set 0), push-constant size, `local_size`, `user_sgprs` (CS), `lds_bytes`, mesh `max_vertices`/`max_primitives`/`params`, geometry inputs/outputs, vertex-input locations and types, full `vertex_input_signature` (ISG1 register/mask/system-value/component-type, for PSO lookup), `wave64_emulated` (true for VS/PS/GS wave64: 64-wide subgroups can only be requested for compute/mesh, so graphics wave64 stays emulated 2x32 until cross-half ops go through LDS; also true for compute/mesh translated with `--wave64-emulate`, which then carry `wave64_exchange: "workgroup"` and `subgroup_size: null`: any subgroup size is exact, request none), `dynamic_format` (runtime V# FORMAT: codes outside FORMATS decode to 0) / `fixed_format_codes`, `src_sha256` and optional `fssm_sha256` (via `--fssm-dir`), PS system inputs, `bary_fallback_input` (`--bary-fallback`: the location of the barycentric input), `mesh_compute` (`--mesh-compute`: the slot layout and push-constant size), and input/output locations. A runtime can create every pipeline at load time from it without parsing SPIR-V. | 310| Metadata index | `spirv/index.json`: one entry per translated shader with its stage, `wave64` / `subgroup_size`, SPIR-V capabilities and extensions, the Vulkan **features** to enable (barycentrics, interlock, mesh, geometry, Float64, Int64, buffer device address, write-without-format, `shaderFmaFloat32` for `--fma khr`, …), `needs_maintenance8`, the descriptor bindings it uses (set 0), push-constant size, `local_size`, `user_sgprs` (CS), `lds_bytes`, mesh `max_vertices`/`max_primitives`/`params`, geometry inputs/outputs, vertex-input locations and types, full `vertex_input_signature` (ISG1 register/mask/system-value/component-type, for PSO lookup), `wave64_emulated` (true for VS/PS/GS wave64, which the translator emits as per-subgroup code with no cross-half exchange, and for compute/mesh translated with `--wave64-emulate`; the runtime does not use it: it reads `wave64`, `subgroup_size` and `wave64_exchange`), `dynamic_format` (runtime V# FORMAT: codes outside FORMATS decode to 0) / `fixed_format_codes`, `src_sha256` and optional `fssm_sha256` (via `--fssm-dir`), PS system inputs, `bary_fallback_input` (`--bary-fallback`: the location of the barycentric input), `mesh_compute` (`--mesh-compute`: the slot layout and push-constant size), and input/output locations. A shader translated with `--wave64-emulate` carries `wave64_exchange: "workgroup"` and `subgroup_size: null`: any subgroup size is exact, request none. Otherwise `subgroup_size` (64 for wave64, 32) is what the PSO asks for through `VkPipelineShaderStageRequiredSubgroupSizeCreateInfo` where the device lists the stage in `requiredSubgroupSizeStages` (docs/d3d12_vulkan.md section 3.2): that list is the driver's, not "compute/mesh only". The AMD Windows driver reports FRAGMENT, COMPUTE, TASK and MESH (measured on a Radeon 880M, driver 26.11.2, sizes 32..64), and current Mesa RADV on GFX10+ reports COMPUTE, FRAGMENT and task/mesh (`src/amd/vulkan/radv_physical_device.c`, `requiredSubgroupSizeStages`, Mesa main at 152b9cde; older Mesa: compute only), so wave64 pixel shaders can run exact there. NVIDIA lists every stage but only size 32, so there a native wave64 shader cannot get 64 and wave64 PS/VS/GS stay 2x32. A runtime can create every pipeline at load time from it without parsing SPIR-V. |
306| Full-corpus pipeline build | `vk_pipeline_check <spirv dir> pipeline_cache.bin --jobs 4` on an RTX 4060 Ti (NVIDIA 595 driver): **all 26,503 shaders become real pipelines, 0 failures** (cs 2,689, ps 12,101, ms 9,282, vs 2,236, gs 195; graphics stages with generated stub partners). Compile time 40,784 s of CPU (2.84 h wall on 4 threads): cs 23,633 s (mean 8.8 s; the ray-tracing ScreenProbes/RTShadowTrace shaders take 2-19 min each), ps 11,481 s, ms 5,395 s, vs 275 s. The resulting `VkPipelineCache` is 3.81 GB; seeding a run with it makes those pipelines instant, which is what a fast first boot needs. The cache is per driver and GPU, and a shader whose SPIR-V changes compiles again (the checker resumes from the file). Neither register storage (one variable per register) nor smaller SPIR-V cut NVIDIA compile time: the big ray-tracing shaders are expensive as such, so the runtime should compile them in the background rather than block on them. | 311| Full-corpus pipeline build | `vk_pipeline_check <spirv dir> pipeline_cache.bin --jobs 4` on an RTX 4060 Ti (NVIDIA 595 driver): **all 26,503 shaders become real pipelines, 0 failures** (cs 2,689, ps 12,101, ms 9,282, vs 2,236, gs 195; graphics stages with generated stub partners). Compile time 40,784 s of CPU (2.84 h wall on 4 threads): cs 23,633 s (mean 8.8 s; the ray-tracing ScreenProbes/RTShadowTrace shaders take 2-19 min each), ps 11,481 s, ms 5,395 s, vs 275 s. The resulting `VkPipelineCache` is 3.81 GB; seeding a run with it makes those pipelines instant, which is what a fast first boot needs. The cache is per driver and GPU, and a shader whose SPIR-V changes compiles again (the checker resumes from the file). Neither register storage (one variable per register) nor smaller SPIR-V cut NVIDIA compile time: the big ray-tracing shaders are expensive as such, so the runtime should compile them in the background rather than block on them. |
307| Wave-uniform branches | VCC and EXEC are wave-wide registers, but one invocation holds only its own lane's bit. `s_cbranch_vccz/vccnz/execz/execnz` therefore reduce the condition across the subgroup (`OpGroupNonUniformAny`), so the whole wave takes the branch together, as on hardware. Before this, each lane decided alone. A lane could skip scalar instructions that the hardware wave executes (its SGPRs went stale for later code), and cross-lane ops or barriers inside the block saw a split wave. `v_cmp`/`v_cmp_class`/64-bit compares now write 0 for inactive lanes (hardware VOPC behaviour), so the reduction sees the true mask. GPU-checked with `runtime/test/shaders/ps_uniform_branch.asm`: lanes whose own VCC bit is 0 run the block's scalar add when their wave has any set bit. `s_cbranch_scc0/1` stay per lane; SCC is uniform as long as the SGPRs feeding it are. | 312| Wave-uniform branches | VCC and EXEC are wave-wide registers, but one invocation holds only its own lane's bit. `s_cbranch_vccz/vccnz/execz/execnz` therefore reduce the condition across the subgroup (`OpGroupNonUniformAny`), so the whole wave takes the branch together, as on hardware. Before this, each lane decided alone. A lane could skip scalar instructions that the hardware wave executes (its SGPRs went stale for later code), and cross-lane ops or barriers inside the block saw a split wave. `v_cmp`/`v_cmp_class`/64-bit compares now write 0 for inactive lanes (hardware VOPC behaviour), so the reduction sees the true mask. GPU-checked with `runtime/test/shaders/ps_uniform_branch.asm`: lanes whose own VCC bit is 0 run the block's scalar add when their wave has any set bit. `s_cbranch_scc0/1` stay per lane; SCC is uniform as long as the SGPRs feeding it are. |
308| Compute shaders | FSSM header word **0x138 = `COMPUTE_PGM_RSRC2`**: USER_SGPR [5:1], TGID_X/Y/Z_EN [9:7], TG_SIZE_EN [10], TIDIG_COMP_CNT [12:11], LDS_SIZE [23:15] in 512-byte units. Words **0x13C/0x140/0x144 = thread-group size**. This was checked against what all 2,689 CS read before writing: 2,281 match exactly, and the rest overshoot only through loop-carried registers in the straight-line check. 0x110, which looked similar, doesn't match. Layout: s0..user−1 = user data (push constants), then the enabled workgroup IDs (`WorkgroupId`), and v0/v1/v2 = thread ID x/y/z (`LocalInvocationId`, separate VGPRs on GFX10). Example: the 1,013 shaders with RSRC2 `0x998` have 12 user SGPRs, group ID x/y in s12/s13, and compute x = s12·32 + v0. Shaders with TG_SIZE_EN are rejected for now. GPU-checked with `runtime/test/shaders/cs_lds.asm` through `runtime/test/vk_compute_test.cpp`: 4 groups × 64 threads, LDS exchange between the two waves of a group behind `s_barrier`, store through a V# into the device-address heap, 0 mismatches. | 313| Compute shaders | FSSM header word **0x138 = `COMPUTE_PGM_RSRC2`**: USER_SGPR [5:1], TGID_X/Y/Z_EN [9:7], TG_SIZE_EN [10], TIDIG_COMP_CNT [12:11], LDS_SIZE [23:15] in 512-byte units. Words **0x13C/0x140/0x144 = thread-group size**. This was checked against what all 2,689 CS read before writing: 2,281 match exactly, and the rest overshoot only through loop-carried registers in the straight-line check. 0x110, which looked similar, doesn't match. Layout: s0..user−1 = user data (push constants), then the enabled workgroup IDs (`WorkgroupId`), and v0/v1/v2 = thread ID x/y/z (`LocalInvocationId`, separate VGPRs on GFX10). Example: the 1,013 shaders with RSRC2 `0x998` have 12 user SGPRs, group ID x/y in s12/s13, and compute x = s12·32 + v0. Shaders with TG_SIZE_EN are rejected for now. GPU-checked with `runtime/test/shaders/cs_lds.asm` through `runtime/test/vk_compute_test.cpp`: 4 groups × 64 threads, LDS exchange between the two waves of a group behind `s_barrier`, store through a V# into the device-address heap, 0 mismatches. |
314| Signed-byte dot products | `v_dot4_i32_i8 D, S0, S1, S2` (VOP3P) is S2 plus the sum of the four products of the sign-extended bytes of S0 and S1, modulo 2^32; `v_dot4c_i32_i8 D, S0, S1` (VOP2) adds the same sum to D. Emitted as four pairs of `OpBitFieldSExtract`, `OpIMul` and `OpIAdd`. **Confirmed on RDNA2 hardware** (gfx1036, raw kernels through `tools/hw_oracle`): 10 operand sets, both instructions and both source orders of the accumulating one, with sign-mixed bytes and sums that wrap; the measured words are the table in `tests/semantic/test_alu_dot4_i8.py`. Two modifiers were measured too and are Unsupported: `clamp` saturates `v_dot4_i32_i8` to a signed 32-bit value (the two overflowing sets), and `op_sel` 2 with `op_sel_hi` 5 exchanges the 16-bit halves of S1 before the products (5 sets; the form of the 89 words `llvm-mc` does not decode, [fspx.md](fspx.md)). Counts: the 29 FSPX programs use the pair 27,271 times (`v_dot4c_i32_i8` 25,813, `v_dot4_i32_i8` 1,458), all in 13 programs; none of the game's own 26,503 shaders has either encoding (0 of the 12,791 words `llvm-mc` cannot decode there with gfx1013). With the rule 17 of the 29 programs translate and pass `spirv-val` (13 before). |
309| Workgroup barriers | `s_barrier` (cs/ms) is one `OpControlBarrier` (workgroup scope, workgroup memory). On RDNA every `s_barrier` counts against the same workgroup barrier and a wave that has ended no longer counts, while Vulkan requires a barrier to be reached by every invocation in uniform control flow. Under `--wave64-emulate` the round loop keeps a single barrier at the top level, so this holds. **Native wave32 compute shaders run in barrier rounds** when an `s_barrier` sits anywhere but a top-level block of the structured tree (one every invocation runs): under a guard, in a loop, or in the dispatch loop (`needs_barrier_rounds`, `bar_scheduler`). That is the emulated loop without its cross-lane part: `s_barrier` ends a segment, each invocation runs its blocks until its next `s_barrier` or the end, then the whole workgroup meets at one `OpControlBarrier` (the same workgroup/acquire-release/workgroup-memory semantics) at the end of the round. A wave that is done no longer holds the others, and a per-round count of the invocations not done (three `Workgroup` words, by round mod 3) ends the loop. Cross-lane operations stay subgroup operations, as in the dispatch loop, since a wave's lanes run the same segment. A barrier in a top-level block keeps the single `OpControlBarrier` in place. In the 1.0.2.1 corpus 43 of the 55 wave32 cs shaders with `s_barrier` have one nested (SHADER-91's count), so those 43 now run in rounds. Why: an Intel GPU does not survive the nested form. `cs_barrier_divergent.asm` (two barrier sites in different branches), `cs_barrier_early_end.asm` (the other waves end without a barrier) and `cs_barrier_loop.asm` (a barrier in a loop whose trip count differs per wave) each lose the device (`vkQueueWaitIdle` → `VK_ERROR_DEVICE_LOST`) on an Intel Arrow Lake Xe-LPG iGPU (Windows 32.0.101.8132), and `cs_barrier_divergent` hangs or writes nothing on a UHD 770 (101.6129, #634). With barrier rounds all three pass there and on an RTX 5070 Ti Laptop (617.42). NVIDIA passed them before too (RTX 4070 Ti on 610.88 and 621.24, RTX 5090 on Linux 595.99, RTX 5070 Ti). **Still not proven on the native wave64 path** (wave64 cs and every ms, run natively only on AMD's 64-wide subgroups): there the barrier stays where `s_barrier` is, inside a selection or loop construct in every ms and most wave64 cs shaders of the corpus. Branches are scalar, so whole waves take the same path, and RDNA's own barrier counts the way the shader expects. | 315| Workgroup barriers | `s_barrier` (cs/ms) is one `OpControlBarrier` (workgroup scope, workgroup memory). On RDNA every `s_barrier` counts against the same workgroup barrier and a wave that has ended no longer counts, while Vulkan requires a barrier to be reached by every invocation in uniform control flow. Under `--wave64-emulate` the round loop keeps a single barrier at the top level, so this holds. **Native wave32 compute shaders run in barrier rounds** when an `s_barrier` sits anywhere but a top-level block of the structured tree (one every invocation runs): under a guard, in a loop, or in the dispatch loop (`needs_barrier_rounds`, `bar_scheduler`). That is the emulated loop without its cross-lane part: `s_barrier` ends a segment, each invocation runs its blocks until its next `s_barrier` or the end, then the whole workgroup meets at one `OpControlBarrier` (the same workgroup/acquire-release/workgroup-memory semantics) at the end of the round. A wave that is done no longer holds the others, and a per-round count of the invocations not done (three `Workgroup` words, by round mod 3) ends the loop. Cross-lane operations stay subgroup operations, as in the dispatch loop, since a wave's lanes run the same segment. A barrier in a top-level block keeps the single `OpControlBarrier` in place. In the 1.0.2.1 corpus 43 of the 55 wave32 cs shaders with `s_barrier` have one nested (SHADER-91's count), so those 43 now run in rounds. Why: an Intel GPU does not survive the nested form. `cs_barrier_divergent.asm` (two barrier sites in different branches), `cs_barrier_early_end.asm` (the other waves end without a barrier) and `cs_barrier_loop.asm` (a barrier in a loop whose trip count differs per wave) each lose the device (`vkQueueWaitIdle` → `VK_ERROR_DEVICE_LOST`) on an Intel Arrow Lake Xe-LPG iGPU (Windows 32.0.101.8132), and `cs_barrier_divergent` hangs or writes nothing on a UHD 770 (101.6129, #634). With barrier rounds all three pass there and on an RTX 5070 Ti Laptop (617.42). NVIDIA passed them before too (RTX 4070 Ti on 610.88 and 621.24, RTX 5090 on Linux 595.99, RTX 5070 Ti). **Still not proven on the native wave64 path** (wave64 cs and every ms, run natively only on AMD's 64-wide subgroups): there the barrier stays where `s_barrier` is, inside a selection or loop construct in every ms and most wave64 cs shaders of the corpus. Branches are scalar, so whole waves take the same path, and RDNA's own barrier counts the way the shader expects. |
310| LDS | A `Workgroup` uint array sized from LDS_SIZE, rounded up to a power of two that also covers every constant offset (15 of 486 shaders index past LDS_SIZE). Covers `ds_read/write_b32..b128`, `read2/write2` (+`st64`), `u16`/`i16`/`u8`/`i8` reads (also `ds_read_u16_d16`/`_d16_hi` and, since SHADER-85, `ds_read_u8_d16`/`_d16_hi` and `ds_read_i8_d16`/`_d16_hi`: the byte is zero- or sign-extended 8→16 into one half of the destination VGPR and the other half is kept, per the RDNA2 ISA DS opcode descriptions (opcodes 162–165) and as for the u16 d16 reads; GPU-checked with `cs_w32_lds_u8_d16.asm`, byte values 0x80/0xFF/0x7F with a non-zero `offset:`), `b16`/`b8` writes (atomic and/or, so neighbouring lanes don't race), the add/sub/min/max/and/or/xor atomics with and without return, `wrxchg`, `cmpst` (`OpAtomicCompareExchange` with DATA as comparator and DATA2 as value), and `ds_bpermute_b32` as a subgroup shuffle. `ds_permute_b32`, its forward (scatter) form, has no Vulkan equivalent: each source lane that is on in EXEC publishes `((vAddr + offset) >> 2) mod 32` and each destination lane scans the 32 sources of its half and keeps the last one that targets it (a shuffle of target and data per source lane; under `--wave64-emulate` two buffer rounds and a Function variable instead). Per the ISA pseudocode (`tmp[0..63] = 0`; `next if !EXEC[i]` on the source; `VGPR[VDST][i] = tmp[i]` only `if EXEC[i]`): a destination lane nobody targets gets 0, an off source sends nothing, an off destination keeps its VDST, and the half rule above applies as for `ds_bpermute_b32`. When several sources target one lane the ISA leaves the winner unpredictable ("the value from one of the writers"; its pseudocode says the highest-numbered); the translator takes the highest, and nothing may depend on it. Confirmed by the GPU tests `cs_w32_permute.asm` and, per half of a wave64, `cs_w64x_permute.asm` (SHADER-90: rotation, offset, unwritten lane = 0, off destination keeps its value, off source does not win) and `tests/semantic/test_ds_permute.py`. A source lane that is off in EXEC reads 0 and an off destination lane keeps its value (RDNA ISA §10.4.4), in wave32 as in wave64. In wave64 the permute also runs as two wave32s: each half reads lanes of its own half. Until 2026-11-21 lanes 32–63 of a 64-wide subgroup read the low half and inactive sources kept their value (`cs_w64x_bpermute`, AMD Radeon 880M); the wave32 path shuffled the raw value until the same day (`cs_bpermute32`: wave32, EXEC without lanes 8–15, so lane 6 reads 0; GPU-checked on RTX 5070 and Radeon 880M). A source lane that doesn't exist, in the missing lanes of a partial wave, also reads 0: the shuffle result is kept only where a ballot of the running invocations has the source lane, since SPIR-V leaves a shuffle from an invocation that isn't running undefined. Before this, RADV returned stale register values that changed between runs (`cs_w64x_partial`, a 40-thread group, native wave64 on AMD RX 6700 XT, RADV Mesa 26.3.1). Writes and atomics run only in active lanes. Indices wrap at the array size, where hardware would return 0 for out-of-range reads. `s_barrier` = `OpControlBarrier` Workgroup/Workgroup, AcquireRelease + WorkgroupMemory. | 316| LDS | A `Workgroup` uint array sized from LDS_SIZE, rounded up to a power of two that also covers every constant offset (15 of 486 shaders index past LDS_SIZE). Covers `ds_read/write_b32..b128`, `read2/write2` (+`st64`), `u16`/`i16`/`u8`/`i8` reads (also `ds_read_u16_d16`/`_d16_hi` and, since SHADER-85, `ds_read_u8_d16`/`_d16_hi` and `ds_read_i8_d16`/`_d16_hi`: the byte is zero- or sign-extended 8→16 into one half of the destination VGPR and the other half is kept, per the RDNA2 ISA DS opcode descriptions (opcodes 162–165) and as for the u16 d16 reads; GPU-checked with `cs_w32_lds_u8_d16.asm`, byte values 0x80/0xFF/0x7F with a non-zero `offset:`), `b16`/`b8` writes (atomic and/or, so neighbouring lanes don't race), the add/sub/min/max/and/or/xor atomics with and without return, `wrxchg`, `cmpst` (`OpAtomicCompareExchange` with DATA as comparator and DATA2 as value), and `ds_bpermute_b32` as a subgroup shuffle. `ds_permute_b32`, its forward (scatter) form, has no Vulkan equivalent: each source lane that is on in EXEC publishes `((vAddr + offset) >> 2) mod 32` and each destination lane scans the 32 sources of its half and keeps the last one that targets it (a shuffle of target and data per source lane; under `--wave64-emulate` two buffer rounds and a Function variable instead). Per the ISA pseudocode (`tmp[0..63] = 0`; `next if !EXEC[i]` on the source; `VGPR[VDST][i] = tmp[i]` only `if EXEC[i]`): a destination lane nobody targets gets 0, an off source sends nothing, an off destination keeps its VDST, and the half rule above applies as for `ds_bpermute_b32`. When several sources target one lane the ISA leaves the winner unpredictable ("the value from one of the writers"; its pseudocode says the highest-numbered); the translator takes the highest, and nothing may depend on it. Confirmed by the GPU tests `cs_w32_permute.asm` and, per half of a wave64, `cs_w64x_permute.asm` (SHADER-90: rotation, offset, unwritten lane = 0, off destination keeps its value, off source does not win) and `tests/semantic/test_ds_permute.py`. A source lane that is off in EXEC reads 0 and an off destination lane keeps its value (RDNA ISA §10.4.4), in wave32 as in wave64. In wave64 the permute also runs as two wave32s: each half reads lanes of its own half. Until 2026-11-21 lanes 32–63 of a 64-wide subgroup read the low half and inactive sources kept their value (`cs_w64x_bpermute`, AMD Radeon 880M); the wave32 path shuffled the raw value until the same day (`cs_bpermute32`: wave32, EXEC without lanes 8–15, so lane 6 reads 0; GPU-checked on RTX 5070 and Radeon 880M). A source lane that doesn't exist, in the missing lanes of a partial wave, also reads 0: the shuffle result is kept only where a ballot of the running invocations has the source lane, since SPIR-V leaves a shuffle from an invocation that isn't running undefined. Before this, RADV returned stale register values that changed between runs (`cs_w64x_partial`, a 40-thread group, native wave64 on AMD RX 6700 XT, RADV Mesa 26.3.1). Writes and atomics run only in active lanes. Indices wrap at the array size, where hardware would return 0 for out-of-range reads. `s_barrier` = `OpControlBarrier` Workgroup/Workgroup, AcquireRelease + WorkgroupMemory. |
311| `ds_cmpst_b32` | The non-returning compare-and-store: `M = (M == data0) ? data1 : M`, the same `OpAtomicCompareExchange` as `ds_cmpst_rtn_b32` with the old value dropped (operands vaddr, data0, data1). Source: RDNA2 ISA DS_CMPST_B32. CPU-checked by `tests/semantic/test_lds_atomics_values.py`. **Not GPU-verified.** | 317| `ds_cmpst_b32` | The non-returning compare-and-store: `M = (M == data0) ? data1 : M`, the same `OpAtomicCompareExchange` as `ds_cmpst_rtn_b32` with the old value dropped (operands vaddr, data0, data1). Source: RDNA2 ISA DS_CMPST_B32. CPU-checked by `tests/semantic/test_lds_atomics_values.py`. **Not GPU-verified.** |
312| `ds_wrxchg2_rtn_b32`, `ds_wrxchg2st64_rtn_b32` | Two atomic exchanges, addressed as `ds_write2_b32` addresses its dwords: `vaddr + offset0 * 4` and `vaddr + offset1 * 4` (times 64 for st64). `M[A0] = data0` and `M[A1] = data1`, and `vdst` (a VGPR pair) gets the two old words. Both exchanges run before either result is written, so `vdst` may alias the address or data VGPRs. When both offsets name one dword, the second exchange returns `data0`. Each exchange is atomic on its own, not the pair together, as on hardware (two DS operations). Until 2026-11-22 both ops raised `Unsupported`. CPU-checked by `tests/semantic/test_lds_wrxchg2.py` (offsets, st64 = 256-byte steps, the same dword twice, aliasing, a single-VGPR `vdst` rejected). **Not GPU-verified.** | 318| `ds_wrxchg2_rtn_b32`, `ds_wrxchg2st64_rtn_b32` | Two atomic exchanges, addressed as `ds_write2_b32` addresses its dwords: `vaddr + offset0 * 4` and `vaddr + offset1 * 4` (times 64 for st64). `M[A0] = data0` and `M[A1] = data1`, and `vdst` (a VGPR pair) gets the two old words. Both exchanges run before either result is written, so `vdst` may alias the address or data VGPRs. When both offsets name one dword, the second exchange returns `data0`. Each exchange is atomic on its own, not the pair together, as on hardware (two DS operations). Until 2026-11-22 both ops raised `Unsupported`. CPU-checked by `tests/semantic/test_lds_wrxchg2.py` (offsets, st64 = 256-byte steps, the same dword twice, aliasing, a single-VGPR `vdst` rejected). **Not GPU-verified.** |
313| `ds_wrxchg_rtn_b64`, `ds_wrxchg2_rtn_b64`, `ds_wrxchg2st64_rtn_b64` | 64-bit LDS exchanges (two dwords, low first): `M[A] = DATA`, and `vdst` gets the old 64 bits. `wrxchg_rtn_b64` has one element at `vaddr + offset`. The `2` forms have two, at `vaddr + offset0/offset1 * 8` (times 64 for st64), as `ds_write2_b64` addresses them, and `vdst` is four VGPRs. Each dword is its own 32-bit `OpAtomicExchange`, so the memory ends as a 64-bit exchange leaves it, without Int64 atomics on Workgroup memory. All exchanges run before `vdst` is written. **Approximation:** the returned pair comes from two reads, so another lane's 64-bit op on the same element between them can show up half done (as for `ds_and/or/xor_b64`). Until 2026-11-22 these three raised `Unsupported`. CPU-checked by `tests/semantic/test_lds_wrxchg_b64.py` (values, `offset:`, `vdst` aliasing the data, both 2 forms, st64 = 512-byte steps, bad operands rejected). **Not GPU-verified.** | 319| `ds_wrxchg_rtn_b64`, `ds_wrxchg2_rtn_b64`, `ds_wrxchg2st64_rtn_b64` | 64-bit LDS exchanges (two dwords, low first): `M[A] = DATA`, and `vdst` gets the old 64 bits. `wrxchg_rtn_b64` has one element at `vaddr + offset`. The `2` forms have two, at `vaddr + offset0/offset1 * 8` (times 64 for st64), as `ds_write2_b64` addresses them, and `vdst` is four VGPRs. Each dword is its own 32-bit `OpAtomicExchange`, so the memory ends as a 64-bit exchange leaves it, without Int64 atomics on Workgroup memory. All exchanges run before `vdst` is written. **Approximation:** the returned pair comes from two reads, so another lane's 64-bit op on the same element between them can show up half done (as for `ds_and/or/xor_b64`). Until 2026-11-22 these three raised `Unsupported`. CPU-checked by `tests/semantic/test_lds_wrxchg_b64.py` (values, `offset:`, `vdst` aliasing the data, both 2 forms, st64 = 512-byte steps, bad operands rejected). **Not GPU-verified.** |
320| `ds_and_b64`, `ds_or_b64`, `ds_xor_b64` (and `_rtn_`) | `M = M op DATA` on the 64-bit LDS element at `vaddr + offset` (two dwords, low first); the `_rtn_` form returns the old 64 bits in a VGPR pair. A bitwise op works on each bit alone, so it is emitted as one 32-bit `OpAtomicAnd/Or/Xor` per dword. That leaves exactly the memory a 64-bit atomic would, without Int64 atomics on Workgroup memory (optional in Vulkan). **Approximation:** the returned pair comes from two reads, so another lane's 64-bit op on the same element between them can show up half done; the memory result is exact. The other 64-bit LDS atomics (`add/sub/min/max_u64`, `wrxchg_b64`, `cmpst_b64`) carry between dwords or need the pair to move together, and still raise `Unsupported`. Until 2026-11-22 these three were rejected as well. CPU-checked by `tests/semantic/test_lds_bitwise_b64.py` (all six forms, offsets, `vdst` aliasing the data, seeded values). **Not GPU-verified.** |
314| `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. | 321| `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. |
315| 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). **Not GPU-verified.** | 322| 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). **Not GPU-verified.** |
316| 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. | 323| 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. |
@@ -330,31 +337,51 @@ How the generated SPIR-V expects the runtime to work:
330| `v_mqsad_u32_u8` | Four masked byte-SADs with full 32-bit accumulators: D[k] = S2[k] + `v_msad_u8` of the 32-bit window S0[8k+31:8k] of the 64-bit S0 against S1, wrapping at 32 bits (S2 and D are four VGPRs). Every source is read before the first write; `clamp` raises `Unsupported`. Source: RDNA ISA pseudocode. CPU-checked by `tests/semantic/test_alu_mqsad_u32.py`. **Not GPU-verified.** | 337| `v_mqsad_u32_u8` | Four masked byte-SADs with full 32-bit accumulators: D[k] = S2[k] + `v_msad_u8` of the 32-bit window S0[8k+31:8k] of the 64-bit S0 against S1, wrapping at 32 bits (S2 and D are four VGPRs). Every source is read before the first write; `clamp` raises `Unsupported`. Source: RDNA ISA pseudocode. CPU-checked by `tests/semantic/test_alu_mqsad_u32.py`. **Not GPU-verified.** |
331| `s_sext_i32_i8`, `s_sext_i32_i16`, `s_flbit_i32` | The first two sign-extend the low byte or the low half of S0 to 32 bits (`OpBitFieldSExtract`). `s_flbit_i32` counts how many bits in a row from the MSB equal the sign bit, and gives −1 when all bits are the same (0 and −1); it is the scalar form of `v_ffbh_i32` and goes through the same code. None of the three writes SCC. Source: RDNA2 ISA SOP1 opcodes 23, 25 and 26. CPU-checked by `tests/semantic/test_salu_sext_flbit.py` (#549): edge words with SCC starting at 0 and at 1, and 30 seeded values with long runs of sign bits. Not in the translated corpus, not GPU-checked. | 338| `s_sext_i32_i8`, `s_sext_i32_i16`, `s_flbit_i32` | The first two sign-extend the low byte or the low half of S0 to 32 bits (`OpBitFieldSExtract`). `s_flbit_i32` counts how many bits in a row from the MSB equal the sign bit, and gives −1 when all bits are the same (0 and −1); it is the scalar form of `v_ffbh_i32` and goes through the same code. None of the three writes SCC. Source: RDNA2 ISA SOP1 opcodes 23, 25 and 26. CPU-checked by `tests/semantic/test_salu_sext_flbit.py` (#549): edge words with SCC starting at 0 and at 1, and 30 seeded values with long runs of sign bits. Not in the translated corpus, not GPU-checked. |
332| `v_lerp_u8` | Per byte i: `D.b[i] = (S0.b[i] + S1.b[i] + (S2.b[i] & 1)) >> 1`, an unsigned average where bit 0 of S2's byte decides whether 0.5 rounds up. The 9-bit sum shifted right by 1 fits back in its byte, so nothing carries between bytes. `clamp` raises `Unsupported` (the ISA doesn't define it for this op). Source: RDNA2 ISA VOP3 opcode 333. CPU-checked by `tests/semantic/test_alu_lerp_u8.py` (#577): a 9×9×5 grid of edge and rounding words, 40 seeded cases, an SGPR source with an inline S2, `clamp` rejected. Not in the translated corpus, not GPU-checked. | 339| `v_lerp_u8` | Per byte i: `D.b[i] = (S0.b[i] + S1.b[i] + (S2.b[i] & 1)) >> 1`, an unsigned average where bit 0 of S2's byte decides whether 0.5 rounds up. The 9-bit sum shifted right by 1 fits back in its byte, so nothing carries between bytes. `clamp` raises `Unsupported` (the ISA doesn't define it for this op). Source: RDNA2 ISA VOP3 opcode 333. CPU-checked by `tests/semantic/test_alu_lerp_u8.py` (#577): a 9×9×5 grid of edge and rounding words, 40 seeded cases, an SGPR source with an inline S2, `clamp` rejected. Not in the translated corpus, not GPU-checked. |
333| Scalar select and pack (`s_cmov_b32`, `s_cmovk_i32`, `s_pack_ll/lh/hh_b32_b16`) | `s_cmov_b32` / `s_cmovk_i32`: D = SCC ? S0 : D (`s_cmovk_i32`'s S0 is the 16-bit immediate, sign-extended); SCC is read, not written; the destination must be an SGPR (a lane-mask destination, and `s_cmov_b64`, stay `Unsupported`, #210). `s_pack_*`: the low half of D from S0, the high half from S1, the letters naming the half of each (l = 15:0, h = 31:16), S0 first; GFX10 has no `s_pack_hl`; SCC not written. Source: RDNA2 ISA SOP1/SOP2/SOPK. CPU-checked by `tests/semantic/test_salu_cmov.py` and `test_salu_pack.py`; the translated shaders were run on NVIDIA by reviewers (`s_cmov*`: RTX 5090, RTX 4050 and Radeon 740M in #613; `s_pack_*`: RTX 5090 in #449). **Not measured on RDNA2.** | 340| Scalar select and pack (`s_cmov_b32`, `s_cmovk_i32`, `s_cmov_b64`, `s_pack_ll/lh/hh_b32_b16`) | `s_cmov_b32` / `s_cmovk_i32`: D = SCC ? S0 : D (`s_cmovk_i32`'s S0 is the 16-bit immediate, sign-extended); SCC is read, not written; the destination must be an SGPR (a lane-mask destination stays `Unsupported`, #210). `s_cmov_b64`: D[63:0] = SCC ? S0[63:0] : D[63:0], SCC read and not written, on plain 64-bit data pairs (SGPR pair, immediate or `null`); any dword that is or has been a lane mask (EXEC, VCC or a mask SGPR) makes the pair `Unsupported` — conservatively, because a CFG join can drop a register that is a mask on only one path — while 0/-1 EITHER constants are data; selecting a per-lane bit as data would silently return a bool instead of the wave's mask (#210). `s_pack_*`: the low half of D from S0, the high half from S1, the letters naming the half of each (l = 15:0, h = 31:16), S0 first; GFX10 has no `s_pack_hl`; SCC not written. Source: RDNA2 ISA SOP1/SOP2/SOPK and LLVM AMDGPU [SOPInstructions.td](https://github.com/llvm/llvm-project/blob/2bfedf3338162e2c841a73cd7cd9e98d00add608/llvm/lib/Target/AMDGPU/SOPInstructions.td) (`S_CMOV_B64 : SOP1_64` under `Uses = [SCC]`). CPU-checked by `tests/semantic/test_salu_cmov.py`, `tests/semantic/test_salu_cmov_b64.py` and `test_salu_pack.py`; **not GPU-verified, no corpus count**; the translated shaders were run on NVIDIA by reviewers (`s_cmov_b32/k_i32`: RTX 5090, RTX 4050 and Radeon 740M in #613; `s_pack_*`: RTX 5090 in #449). **Not measured on RDNA2.** |
334| `s_bfe_u32` / `s_bfe_i32` past bit 31 | offset = S1[4:0], width = S1[22:16] (7 bits; S1 bits 23 to 31 are ignored). When offset + width > 32 the field stops at bit 31: width = min(width, 32 - offset), and `s_bfe_i32` sign-extends from the top bit that exists. Example: `s_bfe_i32 s4, 0xd2f90159, 0x7f001c` gives `0xfffffffd` (4-bit field `0xd`), not `0xd`. SCC = D ≠ 0. Source: measured on gfx1150 (Radeon 880M) with `tools/salu_diff.py --oracle hw`, 4000 random control words, all bit-exact, and on gfx1201 (Radeon RX 9070, RDNA4) with 10,000 `salu_diff --oracle hw` programs, 0 mismatches (seed 500 with `--bfe-any`); the translator (`bfe_width`) already did this. LLVM's v_bfe fold (`constantFoldBFE`) is analogous but has a 5-bit width. **RDNA2 is not measured**; the ISA pseudocode does not say. | 341| `s_bfe_u32` / `s_bfe_i32` past bit 31 | offset = S1[4:0], width = S1[22:16] (7 bits; S1 bits 23 to 31 are ignored). When offset + width > 32 the field stops at bit 31: width = min(width, 32 - offset), and `s_bfe_i32` sign-extends from the top bit that exists. Example: `s_bfe_i32 s4, 0xd2f90159, 0x7f001c` gives `0xfffffffd` (4-bit field `0xd`), not `0xd`. SCC = D ≠ 0. Source: measured on gfx1150 (Radeon 880M) with `tools/salu_diff.py --oracle hw`, 4000 random control words, all bit-exact, and on gfx1201 (Radeon RX 9070, RDNA4) with 10,000 `salu_diff --oracle hw` programs, 0 mismatches (seed 500 with `--bfe-any`); the translator (`bfe_width`) already did this. LLVM's v_bfe fold (`constantFoldBFE`) is analogous but has a 5-bit width. **RDNA2 is not measured**; the ISA pseudocode does not say. |
335| 64-bit scalar data ops (`s_brev_b64`, `s_bfe_u64`/`s_bfe_i64`, `s_bitset0_b64`/`s_bitset1_b64`, `s_flbit_i32_b64`/`s_flbit_i32_i64`) | The SGPR pair is 64-bit data, as for `s_lshl_b64`; a pair that `lane_masks.py` marks as a lane mask (or EXEC) stays `Unsupported` (#210). `s_brev_b64`: D.lo = reverse(S0.hi), D.hi = reverse(S0.lo). `s_bfe_*64`: offset = S1[5:0], width = S1[22:16]; width 0 gives 0; a field past bit 63 stops there (the 64-bit form of the `s_bfe_u32` rule, LLVM `constantFoldBFE`); SCC = D ≠ 0. `s_bitset*_b64`: bit S0 & 63 of the pair cleared / set. `s_flbit_i32_b64`: zeros above the top 1 from bit 63, −1 for 0; `s_flbit_i32_i64`: the same of ~S0 when S0 < 0, −1 for 0 and −1. None but `s_bfe` writes SCC. Source: RDNA2 ISA SOP1/SOP2. CPU-checked by `tests/semantic/test_salu_brev_b64.py`, `test_salu_bfe_64.py`, `test_salu_bitset_b64.py`, `test_salu_flbit_64.py` (#723, #726, #729, #733). **Hardware-verified** on an AMD Radeon RX 7900 XTX (gfx1100, Windows 11, driver 26.10.1), one raw wave32 kernel per op through `tools/hw_oracle`: `s_brev_b64` of 0x12345678_0000000F has low word 0x1E6A2C48, `s_bfe_u64(0x00000123_45678000, w16 o28)` = 0x1234, `s_bfe_i64(0x00000001_80000000, w2 o31)` has 0xFFFFFFFF in both words, `s_bitset1_b64(0, 40)` has high word 0x100, `s_flbit_i32_b64(0x00010000)` = 47 and `s_flbit_i32_i64(0xFFFFFFFF_FFFF0000)` = 48. These are the words `runtime/test/shaders/cs_w32_salu64.asm` expects. | 342| 64-bit scalar data ops (`s_brev_b64`, `s_bfe_u64`/`s_bfe_i64`, `s_bitset0_b64`/`s_bitset1_b64`, `s_flbit_i32_b64`/`s_flbit_i32_i64`) | The SGPR pair is 64-bit data, as for `s_lshl_b64`; a pair that `lane_masks.py` marks as a lane mask (or EXEC) stays `Unsupported` (#210). `s_brev_b64`: D.lo = reverse(S0.hi), D.hi = reverse(S0.lo). `s_bfe_*64`: offset = S1[5:0], width = S1[22:16]; width 0 gives 0; a field past bit 63 stops there (the 64-bit form of the `s_bfe_u32` rule, LLVM `constantFoldBFE`); SCC = D ≠ 0. `s_bitset*_b64`: bit S0 & 63 of the pair cleared / set. `s_flbit_i32_b64`: zeros above the top 1 from bit 63, −1 for 0; `s_flbit_i32_i64`: the same of ~S0 when S0 < 0, −1 for 0 and −1. None but `s_bfe` writes SCC. Source: RDNA2 ISA SOP1/SOP2. CPU-checked by `tests/semantic/test_salu_brev_b64.py`, `test_salu_bfe_64.py`, `test_salu_bitset_b64.py`, `test_salu_flbit_64.py` (#723, #726, #729, #733). **Hardware-verified** on an AMD Radeon RX 7900 XTX (gfx1100, Windows 11, driver 26.10.1), one raw wave32 kernel per op through `tools/hw_oracle`: `s_brev_b64` of 0x12345678_0000000F has low word 0x1E6A2C48, `s_bfe_u64(0x00000123_45678000, w16 o28)` = 0x1234, `s_bfe_i64(0x00000001_80000000, w2 o31)` has 0xFFFFFFFF in both words, `s_bitset1_b64(0, 40)` has high word 0x100, `s_flbit_i32_b64(0x00010000)` = 47 and `s_flbit_i32_i64(0xFFFFFFFF_FFFF0000)` = 48. These are the words `runtime/test/shaders/cs_w32_salu64.asm` expects. |
343| 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. **Hardware-verified on RDNA2** (`gfx1035`, wave32 and wave64 via `tools/int_hw_probe.py --oracle both`, SHADER-137). |
344| `v_mqsad_u32_u8` | Four masked byte-SADs with full 32-bit accumulators: D[k] = S2[k] + `v_msad_u8` of the 32-bit window S0[8k+31:8k] of the 64-bit S0 against S1, wrapping at 32 bits (S2 and D are four VGPRs). Every source is read before the first write; `clamp` raises `Unsupported`. Source: RDNA ISA pseudocode. CPU-checked by `tests/semantic/test_alu_mqsad_u32.py`. **Hardware-verified on RDNA2** (`gfx1035`, wave32 and wave64 via `tools/int_hw_probe.py --oracle both`, SHADER-137). |
345| `s_sext_i32_i8`, `s_sext_i32_i16`, `s_flbit_i32` | The first two sign-extend the low byte or the low half of S0 to 32 bits (`OpBitFieldSExtract`). `s_flbit_i32` counts how many bits in a row from the MSB equal the sign bit, and gives −1 when all bits are the same (0 and −1); it is the scalar form of `v_ffbh_i32` and goes through the same code. None of the three writes SCC. Source: RDNA2 ISA SOP1 opcodes 23, 25 and 26. CPU-checked by `tests/semantic/test_salu_sext_flbit.py` (#549): edge words with SCC starting at 0 and at 1, and 30 seeded values with long runs of sign bits. Not in the translated corpus. **Hardware-verified on RDNA2** (`gfx1035`, wave32 and wave64 via `tools/int_hw_probe.py --oracle both`, SHADER-137, SCC kept). |
346| `v_lerp_u8` | Per byte i: `D.b[i] = (S0.b[i] + S1.b[i] + (S2.b[i] & 1)) >> 1`, an unsigned average where bit 0 of S2's byte decides whether 0.5 rounds up. The 9-bit sum shifted right by 1 fits back in its byte, so nothing carries between bytes. `clamp` raises `Unsupported` (the ISA doesn't define it for this op). Source: RDNA2 ISA VOP3 opcode 333. CPU-checked by `tests/semantic/test_alu_lerp_u8.py` (#577): a 9×9×5 grid of edge and rounding words, 40 seeded cases, an SGPR source with an inline S2, `clamp` rejected. Not in the translated corpus. **Hardware-verified on RDNA2** (`gfx1035`, wave32 and wave64 via `tools/int_hw_probe.py --oracle both`, SHADER-137). |
347| Scalar select and pack (`s_cmov_b32`, `s_cmovk_i32`, `s_pack_ll/lh/hh_b32_b16`) | `s_cmov_b32` / `s_cmovk_i32`: D = SCC ? S0 : D (`s_cmovk_i32`'s S0 is the 16-bit immediate, sign-extended); SCC is read, not written; the destination must be an SGPR (a lane-mask destination, and `s_cmov_b64`, stay `Unsupported`, #210). `s_pack_*`: the low half of D from S0, the high half from S1, the letters naming the half of each (l = 15:0, h = 31:16), S0 first; GFX10 has no `s_pack_hl`; SCC not written. Source: RDNA2 ISA SOP1/SOP2/SOPK. CPU-checked by `tests/semantic/test_salu_cmov.py` and `test_salu_pack.py`; the translated shaders were run on NVIDIA by reviewers (`s_cmov*`: RTX 5090, RTX 4050 and Radeon 740M in #613; `s_pack_*`: RTX 5090 in #449). **Hardware-verified on RDNA2** (`gfx1035`, wave32 and wave64 via `tools/int_hw_probe.py --oracle both`, SHADER-137, SCC kept). |
348| `s_bfe_u32` / `s_bfe_i32` past bit 31 | offset = S1[4:0], width = S1[22:16] (7 bits; S1 bits 23 to 31 are ignored). When offset + width > 32 the field stops at bit 31: width = min(width, 32 - offset), and `s_bfe_i32` sign-extends from the top bit that exists. Example: `s_bfe_i32 s4, 0xd2f90159, 0x7f001c` gives `0xfffffffd` (4-bit field `0xd`), not `0xd`. SCC = D ≠ 0. Source: measured on gfx1150 (Radeon 880M) with `tools/salu_diff.py --oracle hw`, 4000 random control words, all bit-exact, on gfx1201 (Radeon RX 9070, RDNA4) with 10,000 `salu_diff --oracle hw` programs, 0 mismatches (seed 500 with `--bfe-any`), and **on RDNA2** (AMD Radeon 680M, `gfx1035`: `tools/salu_diff.py --oracle hw,translator --bfe-any --programs 500 --seed 1`, 500/500 match, plus `tools/int_hw_probe.py --oracle both` wave32 and wave64, SHADER-137); the translator (`bfe_width`) already did this. LLVM's v_bfe fold (`constantFoldBFE`) is analogous but has a 5-bit width. |
349| 64-bit scalar data ops (`s_brev_b64`, `s_bfe_u64`/`s_bfe_i64`, `s_bitset0_b64`/`s_bitset1_b64`, `s_flbit_i32_b64`/`s_flbit_i32_i64`) | The SGPR pair is 64-bit data, as for `s_lshl_b64`; a pair that `lane_masks.py` marks as a lane mask (or EXEC) stays `Unsupported` (#210). `s_brev_b64`: D.lo = reverse(S0.hi), D.hi = reverse(S0.lo). `s_bfe_*64`: offset = S1[5:0], width = S1[22:16]; width 0 gives 0; a field past bit 63 stops there (the 64-bit form of the `s_bfe_u32` rule, LLVM `constantFoldBFE`); SCC = D ≠ 0. `s_bitset*_b64`: bit S0 & 63 of the pair cleared / set. `s_flbit_i32_b64`: zeros above the top 1 from bit 63, −1 for 0; `s_flbit_i32_i64`: the same of ~S0 when S0 < 0, −1 for 0 and −1. None but `s_bfe` writes SCC. Source: RDNA2 ISA SOP1/SOP2. CPU-checked by `tests/semantic/test_salu_brev_b64.py`, `test_salu_bfe_64.py`, `test_salu_bitset_b64.py`, `test_salu_flbit_64.py` (#723, #726, #729, #733). **Hardware-verified** on an AMD Radeon RX 7900 XTX (gfx1100, Windows 11, driver 26.10.1), one raw wave32 kernel per op through `tools/hw_oracle`: `s_brev_b64` of 0x12345678_0000000F has low word 0x1E6A2C48, `s_bfe_u64(0x00000123_45678000, w16 o28)` = 0x1234, `s_bfe_i64(0x00000001_80000000, w2 o31)` has 0xFFFFFFFF in both words, `s_bitset1_b64(0, 40)` has high word 0x100, `s_flbit_i32_b64(0x00010000)` = 47 and `s_flbit_i32_i64(0xFFFFFFFF_FFFF0000)` = 48. These are the words `runtime/test/shaders/cs_w32_salu64.asm` expects. Also **hardware-verified on RDNA2** (`gfx1035`, wave32 and wave64 via `tools/int_hw_probe.py --oracle both`, SHADER-137). |
336| `s_quadmask_b32`/`_b64`, `s_bitreplicate_b64_b32` | On scalar data (RDNA2 ISA SOP1): `s_quadmask_b32` sets D[i] to the OR of S0[4i+3:4i] for the 8 quads, `s_quadmask_b64` does the same for the 16 quads of the 64-bit S0 (D[63:16] = 0), and both set SCC = D != 0. `s_bitreplicate_b64_b32` copies each bit S0[i] to D[2i] and D[2i+1] and leaves SCC. Built from fixed shift/mask steps, with no loop. A lane-mask source (EXEC, VCC or an SGPR that `holds_lane_mask`) or an EXEC/VCC destination raises `Unsupported`: each invocation holds only its own lane's bit, and these ops read the other lanes of a quad or move bits between lanes. Until 2026-11-22 all three were rejected. CPU-checked by `tests/semantic/test_salu_quadmask_bitreplicate.py` (fixed and seeded values, SCC written or kept, immediates, aliasing, lane masks rejected). **Not GPU-verified.** | 350| `s_quadmask_b32`/`_b64`, `s_bitreplicate_b64_b32` | On scalar data (RDNA2 ISA SOP1): `s_quadmask_b32` sets D[i] to the OR of S0[4i+3:4i] for the 8 quads, `s_quadmask_b64` does the same for the 16 quads of the 64-bit S0 (D[63:16] = 0), and both set SCC = D != 0. `s_bitreplicate_b64_b32` copies each bit S0[i] to D[2i] and D[2i+1] and leaves SCC. Built from fixed shift/mask steps, with no loop. A lane-mask source (EXEC, VCC or an SGPR that `holds_lane_mask`) or an EXEC/VCC destination raises `Unsupported`: each invocation holds only its own lane's bit, and these ops read the other lanes of a quad or move bits between lanes. Until 2026-11-22 all three were rejected. CPU-checked by `tests/semantic/test_salu_quadmask_bitreplicate.py` (fixed and seeded values, SCC written or kept, immediates, aliasing, lane masks rejected). **Not GPU-verified.** |
337| 64-bit scalar bitwise ops (`s_and_b64`, `s_or_b64`, `s_xor_b64`, `s_andn2_b64`, `s_orn2_b64`, `s_nand_b64`, `s_nor_b64`, `s_xnor_b64`, `s_not_b64`) | Dispatched like `s_cselect_b64`: when destination is `exec`/`vcc` or any source is a lane mask (`holds_lane_mask` or `exec`/`vcc`), uses the per-lane mask path (`mask_src`/`mask_dst` including `null` dst) and votes SCC across the wave (`scc_from_mask`). Otherwise operates on both 32-bit dwords of non-mask 64-bit scalar data (SGPR pairs, sign-extended inline/literal immediates, `null` = 0), reads all source dwords before storing (preserving destination aliasing), accepts `null` destination, and sets `SCC = ((D.lo \| D.hi) != 0)`. Until 2026-11-22 these ops always took the lane-mask path, duplicating D.lo into D.hi and voting SCC on D.lo alone. `s_nand/nor/xnor_b64` compute `~(S0 op S1)` on both paths (a lane's mask value is 0 or ~0, so the NOT is per lane); until 2026-11-22 they were rejected as unsupported. Source: RDNA2 ISA SOP1/SOP2. CPU-checked by `tests/semantic/test_salu64_bitwise_data.py` (all 9 ops, 4-corner SCC, immediates, aliasing, stale mask overwrite, wave32/wave64 lane-mask regression, and `--wave64-emulate`). **Not GPU-verified.** | 351| 64-bit scalar bitwise ops (`s_and_b64`, `s_or_b64`, `s_xor_b64`, `s_andn2_b64`, `s_orn2_b64`, `s_nand_b64`, `s_nor_b64`, `s_xnor_b64`, `s_not_b64`) | Dispatched like `s_cselect_b64`: when destination is `exec`/`vcc` or any source is a lane mask (`holds_lane_mask` or `exec`/`vcc`), uses the per-lane mask path (`mask_src`/`mask_dst` including `null` dst) and votes SCC across the wave (`scc_from_mask`). Otherwise operates on both 32-bit dwords of non-mask 64-bit scalar data (SGPR pairs, sign-extended inline/literal immediates, `null` = 0), reads all source dwords before storing (preserving destination aliasing), accepts `null` destination, and sets `SCC = ((D.lo \| D.hi) != 0)`. Until 2026-11-22 these ops always took the lane-mask path, duplicating D.lo into D.hi and voting SCC on D.lo alone. `s_nand/nor/xnor_b64` compute `~(S0 op S1)` on both paths (a lane's mask value is 0 or ~0, so the NOT is per lane); until 2026-11-22 they were rejected as unsupported. Source: RDNA2 ISA SOP1/SOP2. CPU-checked by `tests/semantic/test_salu64_bitwise_data.py` (all 9 ops, 4-corner SCC, immediates, aliasing, stale mask overwrite, wave32/wave64 lane-mask regression, and `--wave64-emulate`). **Not GPU-verified.** |
352| 64-bit scalar data ops (`s_brev_b64`, `s_bfe_u64`/`s_bfe_i64`, `s_bitset0_b64`/`s_bitset1_b64`, `s_flbit_i32_b64`/`s_flbit_i32_i64`) | The SGPR pair is 64-bit data, as for `s_lshl_b64`; a pair that `lane_masks.py` marks as a lane mask (or EXEC) stays `Unsupported` (#210). `s_brev_b64`: D.lo = reverse(S0.hi), D.hi = reverse(S0.lo). `s_bfe_*64`: offset = S1[5:0], width = S1[22:16]; width 0 gives 0; a field past bit 63 stops there (the 64-bit form of the `s_bfe_u32` rule, LLVM `constantFoldBFE`); SCC = D ≠ 0. `s_bitset*_b64`: bit S0 & 63 of the pair cleared / set. `s_flbit_i32_b64`: zeros above the top 1 from bit 63, −1 for 0; `s_flbit_i32_i64`: the same of ~S0 when S0 < 0, −1 for 0 and −1. None but `s_bfe` writes SCC. Source: RDNA2 ISA SOP1/SOP2. CPU-checked by `tests/semantic/test_salu_brev_b64.py`, `test_salu_bfe_64.py`, `test_salu_bitset_b64.py`, `test_salu_flbit_64.py` (#723, #726, #729, #733). **Not GPU-verified.** |
353| `s_quadmask_b32`/`_b64`, `s_bitreplicate_b64_b32` | On scalar data (RDNA2 ISA SOP1): `s_quadmask_b32` sets D[i] to the OR of S0[4i+3:4i] for the 8 quads, `s_quadmask_b64` does the same for the 16 quads of the 64-bit S0 (D[63:16] = 0), and both set SCC = D != 0. `s_bitreplicate_b64_b32` copies each bit S0[i] to D[2i] and D[2i+1] and leaves SCC. Built from fixed shift/mask steps, with no loop. A lane-mask source (EXEC, VCC or an SGPR that `holds_lane_mask`) or an EXEC/VCC destination raises `Unsupported`: each invocation holds only its own lane's bit, and these ops read the other lanes of a quad or move bits between lanes. Until 2026-11-22 all three were rejected. CPU-checked by `tests/semantic/test_salu_quadmask_bitreplicate.py` (fixed and seeded values, SCC written or kept, immediates, aliasing, lane masks rejected). **Hardware-verified** on an AMD Radeon RX 7900 XTX (gfx1100, Windows 11, driver 26.10.1) through `tools/hw_oracle`, one raw wave32 kernel per op: `s_quadmask_b32(0xF)` = 1 with SCC 1, `(0xF0000000)` = 0x80, `(0x0F0F0F0F)` = 0x55 (the set quads are 0, 2, 4 and 6), `(0)` = 0 with SCC 0; `s_quadmask_b64` of 0xF = 1 and of 0xF0000000_00000000 (quad 15, bits 60..63) = 0x8000 in the low word with D[63:16] = 0; `s_bitreplicate_b64_b32` of 5 = 0x33 and of 0x80000000 = 0xC0000000_00000000, with SCC left as it was. |
354| 64-bit scalar bitwise ops (`s_and_b64`, `s_or_b64`, `s_xor_b64`, `s_andn2_b64`, `s_orn2_b64`, `s_nand_b64`, `s_nor_b64`, `s_xnor_b64`, `s_not_b64`) | Dispatched like `s_cselect_b64`: when destination is `exec`/`vcc` or any source is a lane mask (`holds_lane_mask` or `exec`/`vcc`), uses the per-lane mask path (`mask_src`/`mask_dst` including `null` dst) and votes SCC across the wave (`scc_from_mask`). Otherwise operates on both 32-bit dwords of non-mask 64-bit scalar data (SGPR pairs, sign-extended inline/literal immediates, `null` = 0), reads all source dwords before storing (preserving destination aliasing), accepts `null` destination, and sets `SCC = ((D.lo \| D.hi) != 0)`. Until 2026-11-22 these ops always took the lane-mask path, duplicating D.lo into D.hi and voting SCC on D.lo alone. `s_nand/nor/xnor_b64` compute `~(S0 op S1)` on both paths (a lane's mask value is 0 or ~0, so the NOT is per lane); until 2026-11-22 they were rejected as unsupported. Source: RDNA2 ISA SOP1/SOP2. CPU-checked by `tests/semantic/test_salu64_bitwise_data.py` (all 9 ops, 4-corner SCC, immediates, aliasing, stale mask overwrite, wave32/wave64 lane-mask regression, and `--wave64-emulate`). **Hardware-verified** on the same part through `tools/hw_oracle` for the plain-data path: `s_and_b64(0xFFFFFFFF_00000000, 0x0F0F0F0F_0F0F0F0F)` = 0x0F0F0000_00000000, `s_xnor_b64(0xFFFF0000_00000000, 0_FFFFFFFF)` = 0x0000FFFF_00000000, `s_nand_b64(0xFFFF0000_0, 0)` = 0xFFFFFFFF_FFFFFFFF, `s_not_b64(0x0000FFFF_0)` = 0xFFFF0000_FFFFFFFF and `s_andn2_b64(0xFFFF0000_0, 0)` = 0xFFFF0000_0, all with SCC 1, while `s_or_b64(0, 0)` = 0 with SCC 0: SCC = ((D.lo ≠ 0) or (D.hi ≠ 0)). The lane-mask path (EXEC/VCC sources, or a mask destination) is a translator model and cannot be measured this way. |
338| Constant lane masks (`Gen.mask_src` immediates) | A constant read as a lane mask is one bit per lane: lane L takes bit L. The 64-bit forms (`s_and/or/andn2_saveexec_b64`, `s_andn2_wrexec_b64`, `s_mov_b64`/`s_not_b64` into EXEC or VCC, `s_and/or/xor/andn2/orn2_b64` and `s_cselect_b64` on the lane-mask path) read the 64-bit value, an inline constant sign-extended (`-16` = lanes 4-63) and a literal with a zero high word, as `src64_data` reads 64-bit constants; the b32 forms (`s_*_saveexec_b32`, `s_andn2_wrexec_b32`) read the 32-bit value at bit L mod 32. 0 and -1 still give no lane and every lane, with no per-lane code. `s_bcnt0/1_i32_b64` of a constant counts the constant's 64 bits (scalar data, like `s_ff0/1_i32_b64`). **Before this fix every lane took bit 0 of the constant**: `s_and_saveexec_b32 s7, 0xff00` with all 32 lanes on left none on, `5` left all 32 on, and `s_bcnt1_i32_b64 s0, 0xff00ff` gave 32. llvm-mc rejects a constant as the mask operand of `v_cndmask_b32_e64` / `v_add_co_ci_u32_e64` and decodes one as "Invalid immediate", so those VALU callers never see a constant. Not covered here: SGPRs read as masks (#293) and a literal with bit 31 set in a 64-bit position (zero- vs sign-extension not measured). GPU-checked with `runtime/test/shaders/cs_w32_mask_imm.asm` and `cs_w64_mask_imm.asm` on an NVIDIA GeForce RTX 5080 (driver 616.92; wave64 with `LEONIDA_W64_EMULATE=1`) and an AMD Radeon RDNA2 iGPU (driver 26.10.1, native 64-wide subgroup): both failed before on both GPUs. Run across every lane in `tests/semantic/test_value_semantics.py` (`LaneMaskConstants`). | 355| Constant lane masks (`Gen.mask_src` immediates) | A constant read as a lane mask is one bit per lane: lane L takes bit L. The 64-bit forms (`s_and/or/andn2_saveexec_b64`, `s_andn2_wrexec_b64`, `s_mov_b64`/`s_not_b64` into EXEC or VCC, `s_and/or/xor/andn2/orn2_b64` and `s_cselect_b64` on the lane-mask path) read the 64-bit value, an inline constant sign-extended (`-16` = lanes 4-63) and a literal with a zero high word, as `src64_data` reads 64-bit constants; the b32 forms (`s_*_saveexec_b32`, `s_andn2_wrexec_b32`) read the 32-bit value at bit L mod 32. 0 and -1 still give no lane and every lane, with no per-lane code. `s_bcnt0/1_i32_b64` of a constant counts the constant's 64 bits (scalar data, like `s_ff0/1_i32_b64`). **Before this fix every lane took bit 0 of the constant**: `s_and_saveexec_b32 s7, 0xff00` with all 32 lanes on left none on, `5` left all 32 on, and `s_bcnt1_i32_b64 s0, 0xff00ff` gave 32. llvm-mc rejects a constant as the mask operand of `v_cndmask_b32_e64` / `v_add_co_ci_u32_e64` and decodes one as "Invalid immediate", so those VALU callers never see a constant. Not covered here: SGPRs read as masks (#293) and a literal with bit 31 set in a 64-bit position (zero- vs sign-extension not measured). GPU-checked with `runtime/test/shaders/cs_w32_mask_imm.asm` and `cs_w64_mask_imm.asm` on an NVIDIA GeForce RTX 5080 (driver 616.92; wave64 with `LEONIDA_W64_EMULATE=1`) and an AMD Radeon RDNA2 iGPU (driver 26.10.1, native 64-wide subgroup): both failed before on both GPUs. Run across every lane in `tests/semantic/test_value_semantics.py` (`LaneMaskConstants`). |
339| Vector integer additions (`v_mul_hi_u32_u24`/`v_mul_hi_i32_i24`, `v_lshrrev_b64`/`v_ashrrev_i64`, `v_qsad_pk_u16_u8`/`v_mqsad_pk_u16_u8`) | `v_mul_hi_*24`: the high 32 bits of the 48-bit product of the low 24 bits, zero-extended (u24) or sign-extended from bit 23 (i24); the high halves of `v_mul_u32_u24` / `v_mul_i32_i24`. `v_lshrrev_b64` / `v_ashrrev_i64`: the pair (or a 64-bit constant) shifted right by S0 & 63, logically or arithmetically, through the `v_lshlrev_b64` code. `v_qsad_pk_u16_u8` / `v_mqsad_pk_u16_u8`: D.u16[k] = (S2.u16[k] + byte SAD of the 32-bit window S0[8k+31:8k] against S1) & 0xFFFF; the m form skips bytes where S1's byte is 0; `clamp` raises `Unsupported`. Source: RDNA ISA pseudocode. CPU-checked by `tests/semantic/test_alu_mul_hi_24.py`, `test_alu_shift_b64.py`, `test_alu_qsad.py`; run on NVIDIA by reviewers (`v_mul_hi_*24`: RTX 5090 and RTX 5070 in #440; `v_qsad`/`v_mqsad`: 24 cases bit-exact on an RTX 3060 in #623). **Not measured on RDNA2.** | 356| Vector integer additions (`v_mul_hi_u32_u24`/`v_mul_hi_i32_i24`, `v_lshrrev_b64`/`v_ashrrev_i64`, `v_qsad_pk_u16_u8`/`v_mqsad_pk_u16_u8`) | `v_mul_hi_*24`: the high 32 bits of the 48-bit product of the low 24 bits, zero-extended (u24) or sign-extended from bit 23 (i24); the high halves of `v_mul_u32_u24` / `v_mul_i32_i24`. `v_lshrrev_b64` / `v_ashrrev_i64`: the pair (or a 64-bit constant) shifted right by S0 & 63, logically or arithmetically, through the `v_lshlrev_b64` code. `v_qsad_pk_u16_u8` / `v_mqsad_pk_u16_u8`: D.u16[k] = (S2.u16[k] + byte SAD of the 32-bit window S0[8k+31:8k] against S1) & 0xFFFF; the m form skips bytes where S1's byte is 0; `clamp` raises `Unsupported`. Source: RDNA ISA pseudocode. CPU-checked by `tests/semantic/test_alu_mul_hi_24.py`, `test_alu_shift_b64.py`, `test_alu_qsad.py`; run on NVIDIA by reviewers (`v_mul_hi_*24`: RTX 5090 and RTX 5070 in #440; `v_qsad`/`v_mqsad`: 24 cases bit-exact on an RTX 3060 in #623). **Hardware-verified on RDNA2** (`gfx1035`, wave32 and wave64 via `tools/int_hw_probe.py --oracle both`, SHADER-137). |
340| Constant and ordered VOPC, `v_cmp(x)_nlg_*`, `v_cvt_off_f32_i4`, `v_pipeflush` | `v_cmp(x)_f_*` is always false, `v_cmp(x)_t_*` (integers) and `v_cmp(x)_tru_*` (floats) always true; `v_cmp(x)_o_{f32,f16}` is true when neither source is NaN, `_u_` when either is (`OpIsNan`), and `_nlg_` when `x == y` or either source is NaN (`OpFUnordEqual`, completing all 16 IEEE-754 RDNA2 float VOPC predicates; LLVM `gfx10_asm_vopc.s`); the result goes through the usual VOPC path (VCC, an SGPR mask, or EXEC for `v_cmpx`; off lanes give 0). `v_cvt_off_f32_i4`: D = sext(S0[3:0]) / 16 (the ISA's CVT_OFF_TABLE, -0.5 .. 0.4375), exact, output modifiers apply. `v_pipeflush` only flushes the VALU pipeline and is translated as nothing, like `v_nop`. Source: RDNA2 ISA VOPC and VOP1. CPU-checked by `tests/semantic/test_vopc_const_ordered.py`, `tests/semantic/test_float_compares.py` (`nlg`; GPU-checked by `ps_cmp_nlg.asm`: f32 and f16 with ±0, quiet and signalling NaN, ±inf and ignored f16 high halves, the e64 form with `abs`/`neg`, and `v_cmpx_nlg` on equal and NaN operands, Tesla V100 (NVIDIA 580.95.05, Linux)), `test_alu_cvt_off.py` (GPU-checked by `ps_cvt_off.asm`, upper bits ignored and `mul:4` with and without `clamp`), `test_valu_pipeflush.py`; the constant/ordered float compares were run on an RTX 5090 (16 draws, quiet and signalling NaNs) and the suite on RTX 4050 / Radeon 740M in #620; `v_pipeflush` on RTX 5090 / RTX 3060 in #735. | 357| Constant and ordered VOPC, `v_cmp(x)_nlg_*`, `v_cvt_off_f32_i4`, `v_pipeflush` | `v_cmp(x)_f_*` is always false, `v_cmp(x)_t_*` (integers) and `v_cmp(x)_tru_*` (floats) always true; `v_cmp(x)_o_{f32,f16}` is true when neither source is NaN, `_u_` when either is (`OpIsNan`), and `_nlg_` when `x == y` or either source is NaN (`OpFUnordEqual`, completing all 16 IEEE-754 RDNA2 float VOPC predicates; LLVM `gfx10_asm_vopc.s`); the result goes through the usual VOPC path (VCC, an SGPR mask, or EXEC for `v_cmpx`; off lanes give 0). `v_cvt_off_f32_i4`: D = sext(S0[3:0]) / 16 (the ISA's CVT_OFF_TABLE, -0.5 .. 0.4375), exact, output modifiers apply. `v_pipeflush` only flushes the VALU pipeline and is translated as nothing, like `v_nop`. Source: RDNA2 ISA VOPC and VOP1. CPU-checked by `tests/semantic/test_vopc_const_ordered.py`, `tests/semantic/test_float_compares.py` (`nlg`; GPU-checked by `ps_cmp_nlg.asm`: f32 and f16 with ±0, quiet and signalling NaN, ±inf and ignored f16 high halves, the e64 form with `abs`/`neg`, and `v_cmpx_nlg` on equal and NaN operands, Tesla V100 (NVIDIA 580.95.05, Linux)), `test_alu_cvt_off.py` (GPU-checked by `ps_cvt_off.asm`, upper bits ignored and `mul:4` with and without `clamp`), `test_valu_pipeflush.py`; the constant/ordered float compares were run on an RTX 5090 (16 draws, quiet and signalling NaNs) and the suite on RTX 4050 / Radeon 740M in #620; `v_pipeflush` on RTX 5090 / RTX 3060 in #735. |
341| Relative VGPR moves (`v_movrel*`) | The VGPR file is a Function-scope uint array, so `v_movrels_b32`/`v_movreld_b32`/`v_movrelsd_b32` become dynamic array accesses at `reg + M0` (the whole of M0, as the RDNA2 ISA's opcode descriptions say). `v_movrelsd_2_b32` (VOP1 opcode 72) offsets each side by its own field: VGPR[D + M0[25:16]] = VGPR[S0 + M0[9:0]], other M0 bits ignored (RDNA2 ISA §12.8 opcode description and the RDNA3 ISA; the RDNA2 §6.6 summary table prints M0[7:0] for the source). The write keeps inactive lanes. Not modelled: the hardware's range check against the wave's VGPR allocation (an out-of-range source reads VGPR0, an out-of-range write is dropped). CPU-checked by `tests/semantic/test_alu_movrelsd_2.py` (including set ignored M0 bits); GPU-checked with `runtime/test/shaders/cs_movrelsd_2.asm` (the ISA's own example, v25 ← v17 with M0 = (20 << 16) \| 10) on NVIDIA RTX 4050 Laptop (Ada) and AMD Radeon 740M (RADV). | 358| Relative VGPR moves (`v_movrel*`) | The VGPR file is a Function-scope uint array, so `v_movrels_b32`/`v_movreld_b32`/`v_movrelsd_b32` become dynamic array accesses at `reg + M0` (the whole of M0, as the RDNA2 ISA's opcode descriptions say). `v_movrelsd_2_b32` (VOP1 opcode 72) offsets each side by its own field: VGPR[D + M0[25:16]] = VGPR[S0 + M0[9:0]], other M0 bits ignored (RDNA2 ISA §12.8 opcode description and the RDNA3 ISA; the RDNA2 §6.6 summary table prints M0[7:0] for the source). The write keeps inactive lanes. Not modelled: the hardware's range check against the wave's VGPR allocation (an out-of-range source reads VGPR0, an out-of-range write is dropped). CPU-checked by `tests/semantic/test_alu_movrelsd_2.py` (including set ignored M0 bits); GPU-checked with `runtime/test/shaders/cs_movrelsd_2.asm` (the ISA's own example, v25 ← v17 with M0 = (20 << 16) \| 10) on NVIDIA RTX 4050 Laptop (Ada) and AMD Radeon 740M (RADV). |
342| Relative SGPR reads (`s_movrels_b32`, `s_movrels_b64`) | `D = SGPR[S0 + M0]`; the b64 form reads the pair at `S0 + M0` and `S0 + M0 + 1` (RDNA2 ISA SOP1). The SGPR file is a Function-scope uint array, so this is a dynamic load, as for `v_movrels`. Every SGPR write stores into that array (`store_reg`), so the load sees the current value. All reads happen before the destination is written, so D may overlap the source. SCC is not written. The index wraps to the 128 array slots, so it cannot reach the lane-mask parking slots past them. **Not modelled:** the hardware's range check, and reads past s105 landing on VCC and the other special registers. `s_movreld_b32/b64`, the relative writes, stay `Unsupported`, because the translator keeps translate-time knowledge of SGPR values (literal S# words, descriptor caches) that a dynamic write would invalidate. Until 2026-11-22 both reads raised `Unsupported`. CPU-checked by `tests/semantic/test_salu_movrels.py` (M0 from 0 to 5 and from a register, the b64 pair, an overlapping destination, SCC kept, `s_movreld` rejected). **Not GPU-verified.** | 359| Relative SGPR reads (`s_movrels_b32`, `s_movrels_b64`) | `D = SGPR[S0 + M0]`; the b64 form reads the pair at `S0 + M0` and `S0 + M0 + 1` (RDNA2 ISA SOP1). The SGPR file is a Function-scope uint array, so this is a dynamic load, as for `v_movrels`. Every SGPR write stores into that array (`store_reg`), so the load sees the current value. All reads happen before the destination is written, so D may overlap the source. SCC is not written. The index wraps to the 128 array slots, so it cannot reach the lane-mask parking slots past them. **Not modelled:** the hardware's range check, and reads past s105 landing on VCC and the other special registers. `s_movreld_b32/b64`, the relative writes, stay `Unsupported`, because the translator keeps translate-time knowledge of SGPR values (literal S# words, descriptor caches) that a dynamic write would invalidate. Until 2026-11-22 both reads raised `Unsupported`. CPU-checked by `tests/semantic/test_salu_movrels.py` (M0 from 0 to 5 and from a register, the b64 pair, an overlapping destination, SCC kept, `s_movreld` rejected). **Not GPU-verified.** |
360| `v_swaprel_b32` | GFX10 VOP1 opcode 104: swap `VGPR[D + M0[25:16]]` and `VGPR[S0 + M0[9:0]]`, the two M0 fields `v_movrelsd_2_b32` uses; the other M0 bits are ignored (RDNA2 ISA opcode description). Both registers are read before either is written. When both name one register it keeps its value. Inactive lanes keep both registers (`OpSelect` on `active`). As for `v_movrel*`, the hardware's range check against the VGPR allocation is not modelled. A non-VGPR operand raises `Unsupported`. Until 2026-11-22 the op raised `Unsupported`. CPU-checked by `tests/semantic/test_alu_swaprel.py` (both fields, ignored M0 bits, a self-swap, a register-file model). **Not GPU-verified.** |
361| Relative SGPR reads (`s_movrels_b32`, `s_movrels_b64`) | `D = SGPR[S0 + M0]`; the b64 form reads the pair at `S0 + M0` and `S0 + M0 + 1` (RDNA2 ISA SOP1). The SGPR file is a Function-scope uint array, so this is a dynamic load, as for `v_movrels`. Every SGPR write stores into that array (`store_reg`), so the load sees the current value. All reads happen before the destination is written, so D may overlap the source. SCC is not written. The index wraps to the 128 array slots, so it cannot reach the lane-mask parking slots past them. An SGPR that `lane_masks.py` marks as a lane mask (a saved EXEC, a `v_cmp` result) holds only this lane's bit, so the whole wave's mask word is collected for each such SGPR (as for `s_bcnt1`) and read instead when the index lands on it; D then holds the mask as data (SHADER-284, CPU-checked by `tests/semantic/test_salu_movrels_lane_mask.py`, wave32 and wave64). **Not modelled:** the hardware's range check, and reads past s105 landing on VCC and the other special registers. `s_movreld_b32/b64`, the relative writes, stay `Unsupported`, because the translator keeps translate-time knowledge of SGPR values (literal S# words, descriptor caches) that a dynamic write would invalidate. Until 2026-11-22 both reads raised `Unsupported`. CPU-checked by `tests/semantic/test_salu_movrels.py` (M0 from 0 to 5 and from a register, the b64 pair, an overlapping destination, SCC kept, `s_movreld` rejected). **Not GPU-verified.** |
362| Relative SGPR reads (`s_movrels_b32`, `s_movrels_b64`) | `D = SGPR[S0 + M0]`; the b64 form reads the pair at `S0 + M0` and `S0 + M0 + 1` (RDNA2 ISA SOP1). The SGPR file is a Function-scope uint array, so this is a dynamic load, as for `v_movrels`. Every SGPR write stores into that array (`store_reg`), so the load sees the current value. All reads happen before the destination is written, so D may overlap the source. SCC is not written. The index wraps to the 128 array slots, so it cannot reach the lane-mask parking slots past them. **Not modelled:** the hardware's range check, and reads past s105 landing on VCC and the other special registers. `s_movreld_b32/b64`, the relative writes, stay `Unsupported`, because the translator keeps translate-time knowledge of SGPR values (literal S# words, descriptor caches) that a dynamic write would invalidate. Until 2026-11-22 both reads raised `Unsupported`. CPU-checked by `tests/semantic/test_salu_movrels.py` (M0 from 0 to 5 and from a register, the b64 pair, an overlapping destination, SCC kept, `s_movreld` rejected). **Hardware-verified on RDNA2** (`gfx1035`, wave32 and wave64 via `tools/int_hw_probe.py --oracle both`, SHADER-137, SCC kept). |
343| d16 and f16 format narrowing | The f16 of every d16 result (image samples and gathers, the `image_sample_c_lz` compare result, typed buffer loads) and of the f16 formats a typed buffer store writes is narrowed with integer round to nearest even (`Gen.f16_bits`; #489, #711), not with `PackHalf2x16`. AMD drivers lower `PackHalf2x16` to `v_cvt_pkrtz_f16_f32`, which rounds toward zero (#489), and there about half of all unorm8, unorm16 and snorm8 values loaded with d16 came out 1 ulp low (123 of 256, 31,742 of 65,536 and 110 of 256). Packed MUBUF and MTBUF loads clamp unsigned 32-bit channels to 65535 before writing each half. On native gfx1036, values 65534 and 65535 survived, while 65536, 65537 and 0xffffffff all produced 0xffff, across all four load widths in wave32 and wave64. Packed `buffer_load_format_d16_x` and `_xyz` write only the low 16 bits of the final VGPR. Its upper half survives even when the load is out of bounds. Native gfx1036 wave32 and wave64 confirmed this with RGBA8_UINT and RGBA8_UNORM, two destination seeds, and both even-component loads as full-write controls. Full pairs are packed by `pack_f16_pair_int` and an odd final buffer component is narrowed with `f16_bits` for float/normalized formats. These memory conversions do not use `f16_pack2`: they come from the texture and buffer units, not the VALU whose rounding `MODE.FP_ROUND` sets (#753). Round to nearest even for these conversions is inferred, as in #489, not measured. #489's own narrower, `f32_to_f16_int`, was folded into `f16_bits` on 2026-11-22: the two gave the same bits on 30,648 inputs (every f32 exponent, ties, the subnormal and overflow edges, NaN), and `f16_bits` lost its one GLSL.std.450 instruction (`UMin`) so the packer stays free of them. Checked by `tests/test_translate.py` (`test_depth_compare_sample_result_width`, `test_buffer_format_f16_narrowing_avoids_packhalf2x16`), `tests/test_d16_pack.py` and `tests/semantic/test_buffer_load_format.py` (`D16NormalizedRounding`). | 363| d16 and f16 format narrowing | The f16 of every d16 result (image samples and gathers, the `image_sample_c_lz` compare result, typed buffer loads) and of the f16 formats a typed buffer store writes is narrowed with integer round to nearest even (`Gen.f16_bits`; #489, #711), not with `PackHalf2x16`. AMD drivers lower `PackHalf2x16` to `v_cvt_pkrtz_f16_f32`, which rounds toward zero (#489), and there about half of all unorm8, unorm16 and snorm8 values loaded with d16 came out 1 ulp low (123 of 256, 31,742 of 65,536 and 110 of 256). Packed MUBUF and MTBUF loads clamp unsigned 32-bit channels to 65535 before writing each half. On native gfx1036, values 65534 and 65535 survived, while 65536, 65537 and 0xffffffff all produced 0xffff, across all four load widths in wave32 and wave64. Packed `buffer_load_format_d16_x` and `_xyz` write only the low 16 bits of the final VGPR. Its upper half survives even when the load is out of bounds. Native gfx1036 wave32 and wave64 confirmed this with RGBA8_UINT and RGBA8_UNORM, two destination seeds, and both even-component loads as full-write controls. Full pairs are packed by `pack_f16_pair_int` and an odd final buffer component is narrowed with `f16_bits` for float/normalized formats. These memory conversions do not use `f16_pack2`: they come from the texture and buffer units, not the VALU whose rounding `MODE.FP_ROUND` sets (#753). Round to nearest even for these conversions is inferred, as in #489, not measured. #489's own narrower, `f32_to_f16_int`, was folded into `f16_bits` on 2026-11-22: the two gave the same bits on 30,648 inputs (every f32 exponent, ties, the subnormal and overflow edges, NaN), and `f16_bits` lost its one GLSL.std.450 instruction (`UMin`) so the packer stays free of them. Checked by `tests/test_translate.py` (`test_depth_compare_sample_result_width`, `test_buffer_format_f16_narrowing_avoids_packhalf2x16`), `tests/test_d16_pack.py` and `tests/semantic/test_buffer_load_format.py` (`D16NormalizedRounding`). |
344| Float-to-int saturation | `v_cvt_u32_f32` and `v_cvt_i32_f32` truncate toward zero, saturate out-of-range values (including infinities) to the destination bounds, and return zero for NaN. The conversion operand is kept in range before emitting SPIR-V `OpConvertFToU`/`OpConvertFToS`. 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), §12.8, VOP1 opcodes 7 and 8. The synthetic `cs_cvt_f32_sat.asm` fixture is checked bit-for-bit by `tests/semantic/test_float_to_int.py`. | 364| Float-to-int saturation | `v_cvt_u32_f32` and `v_cvt_i32_f32` truncate toward zero, saturate out-of-range values (including infinities) to the destination bounds, and return zero for NaN. The conversion operand is kept in range before emitting SPIR-V `OpConvertFToU`/`OpConvertFToS`. 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), §12.8, VOP1 opcodes 7 and 8. The synthetic `cs_cvt_f32_sat.asm` fixture is checked bit-for-bit by `tests/semantic/test_float_to_int.py`. |
345| `v_cvt_f16_u16`, `v_cvt_f16_i16`, `v_cvt_u16_f16`, `v_cvt_i16_f16` | Conversions of the low 16-bit half (`op_sel:[src,dst]` picks the high half of the source / of the destination in the VOP3 form); the other half of the destination is kept, like the other 16-bit-result ops (see *16-bit results*). `v_cvt_f16_u16` / `v_cvt_f16_i16` convert the unsigned / sign-extended half and narrow with the usual f16 rounding (65520 and above give +infinity for the unsigned form). `v_cvt_u16_f16` / `v_cvt_i16_f16` truncate toward zero, saturate to [0, 65535] / [-32768, 32767] (an f16 infinity too) and give 0 for NaN, as the 32-bit conversions do (*Float-to-int saturation*). `clamp` and the output multipliers are rejected as `Unsupported` rather than guessed. Source: the 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) pseudocode. **Not measured on hardware**: the kept half of the destination for the integer-result forms and the NaN result. Checked on the CPU by `tests/semantic/test_alu_cvt_16.py`; not run on the shader corpus. | 365| `v_cvt_f16_u16`, `v_cvt_f16_i16`, `v_cvt_u16_f16`, `v_cvt_i16_f16` | Conversions of the low 16-bit half (`op_sel:[src,dst]` picks the high half of the source / of the destination in the VOP3 form where supported; GFX10 does not accept `op_sel` on these opcodes); the other half of the destination is kept, like the other 16-bit-result ops (see *16-bit results*). `v_cvt_f16_u16` / `v_cvt_f16_i16` convert the unsigned / sign-extended half and narrow with the usual f16 rounding (65520 and above give +infinity for the unsigned form). `v_cvt_u16_f16` / `v_cvt_i16_f16` truncate toward zero, saturate to [0, 65535] / [-32768, 32767] (an f16 infinity too) and give 0 for NaN, as the 32-bit conversions do (*Float-to-int saturation*). `clamp` and the output multipliers are rejected as `Unsupported` rather than guessed. Source: the 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) pseudocode. Checked on the CPU by `tests/semantic/test_alu_cvt_16.py`; **hardware-verified on RDNA2** (`gfx1035`, wave32 and wave64 via `tools/int_hw_probe.py --oracle both`, SHADER-137): all four `_e64` forms keep the high half of the destination, `v_cvt_u16/i16_f16` give 0 for ±qNaN and saturate ±inf, and `v_cvt_f16_u16(65520)` gives +inf (`0x7c00`). Not run on the shader corpus. |
346| `v_frexp_mant_f32`, `v_frexp_exp_i32_f32`, `v_ldexp_f32` | Computed on the binary32 word, with no float arithmetic. A normal input has a biased exponent of 1..254. `v_frexp_mant_f32` returns the input with its exponent set to 126 (a mantissa in [0.5, 1), sign kept); `v_frexp_exp_i32_f32` returns the biased exponent minus 126, so mantissa × 2^exponent is the input. Zero and denormals (read as zero) give a signed zero and exponent 0; infinities and NaNs give the input unchanged and exponent 0. `v_ldexp_f32` is S0 × 2^S1 with S1 a signed integer: S1 is clamped to [-512, 512] and added to the exponent field; a new field above 254 gives ±infinity, one of 0 or below gives ±0 (no denormal results), and zero, infinities and NaNs ignore S1. Neg/abs, `clamp` and the output multipliers apply as for other float ops (not to the integer exponent result). Source: the 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) pseudocode for these three opcodes. **Not measured on hardware**: the denormal input and result handling (the f32 denormal mode is not modelled) and the NaN payload are the translator's choice. Checked on the CPU by `tests/semantic/test_alu_frexp_ldexp.py`; not run on the shader corpus. | 366| `v_frexp_mant_f32`, `v_frexp_exp_i32_f32`, `v_ldexp_f32` | Computed on the binary32 word, with no float arithmetic. A normal input has a biased exponent of 1..254. `v_frexp_mant_f32` returns the input with its exponent set to 126 (a mantissa in [0.5, 1), sign kept); `v_frexp_exp_i32_f32` returns the biased exponent minus 126, so mantissa × 2^exponent is the input. Zero and denormals (read as zero) give a signed zero and exponent 0; infinities and NaNs give the input unchanged and exponent 0. `v_ldexp_f32` is S0 × 2^S1 with S1 a signed integer: S1 is clamped to [-512, 512] and added to the exponent field; a new field above 254 gives ±infinity, one of 0 or below gives ±0 (no denormal results), and zero, infinities and NaNs ignore S1. Neg/abs, `clamp` and the output multipliers apply as for other float ops (not to the integer exponent result). Source: the 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) pseudocode for these three opcodes. **Not measured on hardware**: the denormal input and result handling (the f32 denormal mode is not modelled) and the NaN payload are the translator's choice. Checked on the CPU by `tests/semantic/test_alu_frexp_ldexp.py`; not run on the shader corpus. |
347| `v_mad_u16`, `v_mad_i16` | `D = S0 * S1 + S2` on the low 16-bit halves (VOP3 only). The product and sum are formed in 32 bits, so nothing overflows, and the low 16 bits are the result. `op_sel` bits 0..2 read the high half of a source and bit 3 writes the high half of the destination; like the other opsel-capable 16-bit VOP3 ops the other half of the destination is kept (see *16-bit results*). `clamp` saturates the full-width result to [0, 65535] (`v_mad_u16`) or [-32768, 32767] (`v_mad_i16`). Source: the 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) pseudocode and Mesa ACO's `can_use_opsel`. **Not measured on hardware**: `clamp` on the multiply-add (the translator saturates after the full-width sum) and the kept half. Checked on the CPU by `tests/semantic/test_alu_mad_u16_i16.py`; not run on the shader corpus. | 367| `v_mad_u16`, `v_mad_i16` | `D = S0 * S1 + S2` on the low 16-bit halves (VOP3 only). The product and sum are formed in 32 bits, so nothing overflows, and the low 16 bits are the result. `op_sel` bits 0..2 read the high half of a source and bit 3 writes the high half of the destination; like the other opsel-capable 16-bit VOP3 ops the other half of the destination is kept (see *16-bit results*). `clamp` saturates the full-width result to [0, 65535] (`v_mad_u16`) or [-32768, 32767] (`v_mad_i16`). Source: the 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) pseudocode and Mesa ACO's `can_use_opsel`. Checked on the CPU by `tests/semantic/test_alu_mad_u16_i16.py`; **hardware-verified on RDNA2** (`gfx1035`, wave32 and wave64 via `tools/int_hw_probe.py --oracle both`, SHADER-137): full-width `clamp`, `op_sel` and the untouched destination half match bit-for-bit. Not run on the shader corpus. |
348| `v_frexp_mant_f16`, `v_frexp_exp_i16_f16`, `v_ldexp_f16` | The binary16 versions of `v_frexp_mant_f32`, `v_frexp_exp_i32_f32` and `v_ldexp_f32`, computed on the f16 word of the low half with no float arithmetic (`op_sel` picks the high half of a source; the last `op_sel` bit sends the result to the high half of the destination; the other half of the destination is kept). A normal input has a biased exponent of 1..30. `v_frexp_mant_f16` returns the input with its exponent set to 14 (a mantissa in [0.5, 1), sign kept); `v_frexp_exp_i16_f16` returns the biased exponent minus 14 as a 16-bit integer, so mantissa × 2^exponent is the input. Zero and denormals (read as zero) give a signed zero and exponent 0; infinities and NaNs give the input unchanged and exponent 0. `v_ldexp_f16` is S0 × 2^S1 with S1 the low 16 bits of the source read as a signed integer: S1 is clamped to [-64, 64] and added to the exponent field; a new field above 30 gives ±infinity, one of 0 or below gives ±0 (no denormal results), and zero, infinities and NaNs ignore S1. Source neg/abs apply to the float operand. `clamp` and the output multipliers are rejected as unsupported rather than guessed. Source: the 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) pseudocode for these three opcodes. **Not measured on hardware**: the denormal input and result handling, the NaN payload, and whether `v_frexp_exp_i16_f16` keeps the high half of its destination (it is modelled like the other 16-bit ops here, which keep it) are the translator's choice. Checked on the CPU by `tests/semantic/test_alu_frexp_ldexp_f16.py`; not run on the shader corpus. | 368| `v_frexp_mant_f16`, `v_frexp_exp_i16_f16`, `v_ldexp_f16` | The binary16 versions of `v_frexp_mant_f32`, `v_frexp_exp_i32_f32` and `v_ldexp_f32`, computed on the f16 word of the low half with no float arithmetic (`op_sel` picks the high half of a source; the last `op_sel` bit sends the result to the high half of the destination; the other half of the destination is kept). A normal input has a biased exponent of 1..30. `v_frexp_mant_f16` returns the input with its exponent set to 14 (a mantissa in [0.5, 1), sign kept); `v_frexp_exp_i16_f16` returns the biased exponent minus 14 as a 16-bit integer, so mantissa × 2^exponent is the input. Zero and denormals (read as zero) give a signed zero and exponent 0; infinities and NaNs give the input unchanged and exponent 0. `v_ldexp_f16` is S0 × 2^S1 with S1 the low 16 bits of the source read as a signed integer: S1 is clamped to [-64, 64] and added to the exponent field; a new field above 30 gives ±infinity, one of 0 or below gives ±0 (no denormal results), and zero, infinities and NaNs ignore S1. Source neg/abs apply to the float operand. `clamp` and the output multipliers are rejected as unsupported rather than guessed. Source: the 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) pseudocode for these three opcodes. **Not measured on hardware**: the denormal input and result handling, the NaN payload, and whether `v_frexp_exp_i16_f16` keeps the high half of its destination (it is modelled like the other 16-bit ops here, which keep it) are the translator's choice. Checked on the CPU by `tests/semantic/test_alu_frexp_ldexp_f16.py`; not run on the shader corpus. |
369| `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` 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`. **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`. |
349| `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. Source neg/abs apply first. Checked on the CPU by `tests/semantic/test_alu_cvt_flr_rpi.py`, **not yet GPU-verified**. | 370| `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. Source neg/abs apply first. Checked on the CPU by `tests/semantic/test_alu_cvt_flr_rpi.py`, **not yet GPU-verified**. |
350| `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. 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. NaN gives 0, as `v_cvt_i32_f32` does; that is **not measured on hardware**. Source modifiers apply. `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). **Not GPU-verified.** | 371| `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. 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. NaN gives 0, as `v_cvt_i32_f32` does; that is **not measured on hardware**. Source modifiers apply. `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). **Not GPU-verified.** |
372| 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. `v_fma_mix*` with f32 sources uses `Fma` then narrows (two roundings) in nearest-even mode, while the hardware rounds once: 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). |
373| `v_cvt_flr_i32_f32`, `v_cvt_rpi_i32_f32` | Currently translated as `f32_to_i32(floor(S0))` and `f32_to_i32(floor(S0 + 0.5))` with the `+ 0.5` rounded in binary32, saturating at ±2³¹ and ±inf and returning 0 for NaN (source neg/abs apply first); checked on the CPU by `tests/semantic/test_alu_cvt_flr_rpi.py`. **Measured on RDNA2 (`gfx1035`, wave32 and wave64 via `tools/int_hw_probe.py --oracle both`, SHADER-137) — two open divergences from the current translation:** (1) `v_cvt_rpi_i32_f32` computes exact `floor(S0 + 0.5)` with no f32 rounding of the add (`0x3effffff` → `0`, `0x4b000001` → `0x00800001`, `0x4b7fffff` → `0x00ffffff`, whereas the translator gives `1`, `0x00800002`, `0x01000000`); (2) both `v_cvt_flr_i32_f32` and `v_cvt_rpi_i32_f32` saturate NaN by its sign bit (`0x7fc00000` → `0x7fffffff`, `0xffc00000` → `0x80000000`), whereas `v_cvt_i32_f32` in the same probe returns `0` for every NaN. |
374| `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. 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. NaN gives 0, as `v_cvt_i32_f32` does. Source modifiers apply. `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). **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. |
351| 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. `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). | 375| 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. `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). |
376| 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. `v_fma_mix*` rounds once straight to f16 via round-to-odd in both nearest and toward-zero modes (see Known approximations). |
352| `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. | 377| `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. |
353| 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. **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. | 378| 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. **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. |
354| 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 29 − 2N and high halves at 30 − 2N, below MoltenVK's 31 locations (124 components); 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..(29 − P) / 2), and a PS whose decoded-half location is also an attribute it reads is rejected (`Unsupported`), not mislinked. 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. Not combined with `--bary-fallback`'s geometry shader. | 379| 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 29 − 2N and high halves at 30 − 2N, below MoltenVK's 31 locations (124 components); 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..(29 − P) / 2), and a PS whose decoded-half location is also an attribute it reads is rejected (`Unsupported`), not mislinked. 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. Not combined with `--bary-fallback`'s geometry shader. |
380| `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. |
381| 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 a PS whose decoded-half location is also an attribute it reads is rejected (`Unsupported`), not mislinked. 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. 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. **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 124 vertex output components. Not combined with `--bary-fallback`'s geometry shader. |
355| `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)). | 382| `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)). |
356| 16-bit vector compare `op_sel` (`v_cmp(x)_*_{f16,u16,i16}`) | VOP3 `op_sel:[s0,s1]` selects bit `[15:0]` (`0`) or `[31:16]` (`1`) of each source before f16 input modifiers (`neg`/`abs`, via `Gen.f16_in`) or `u16`/`i16` zero-/sign-extension (`OpBitFieldUExtract`/`OpBitFieldSExtract` at bit offset 16 when set, 0 otherwise); VOPC writes a scalar lane mask (VCC/SGPR or EXEC for `v_cmpx`), so there is no destination `op_sel` bit. Until 2026-11-22 `Gen.compare` hardcoded the low half and ignored `mods`. Source: AMD RDNA2 ISA VOP3 `op_sel` and Mesa ACO `can_use_opsel`. Checked on the CPU by `tests/semantic/test_vcmp16_opsel.py` (all four `op_sel` combinations across `f16` relations/ordered/unordered/NaN/`neg`/`abs`, `u16`, signed `i16`, and `v_cmpx` wave32/wave64 EXEC updates via `spirv_mini_interp` and `spirv_wave_interp`); **not GPU-verified**. | 383| 16-bit vector compare `op_sel` (`v_cmp(x)_*_{f16,u16,i16}`) | VOP3 `op_sel:[s0,s1]` selects bit `[15:0]` (`0`) or `[31:16]` (`1`) of each source before f16 input modifiers (`neg`/`abs`, via `Gen.f16_in`) or `u16`/`i16` zero-/sign-extension (`OpBitFieldUExtract`/`OpBitFieldSExtract` at bit offset 16 when set, 0 otherwise); VOPC writes a scalar lane mask (VCC/SGPR or EXEC for `v_cmpx`), so there is no destination `op_sel` bit. Until 2026-11-22 `Gen.compare` hardcoded the low half and ignored `mods`. Source: AMD RDNA2 ISA VOP3 `op_sel` and Mesa ACO `can_use_opsel`. Checked on the CPU by `tests/semantic/test_vcmp16_opsel.py` (all four `op_sel` combinations across `f16` relations/ordered/unordered/NaN/`neg`/`abs`, `u16`, signed `i16`, and `v_cmpx` wave32/wave64 EXEC updates via `spirv_mini_interp` and `spirv_wave_interp`); **not GPU-verified**. |
357| Known approximations | `v_cvt_pkrtz_f16_f32` is now **exact round-toward-zero** (finite overflow gives ±65504, not inf). The GPU smoke test caught the old round-to-nearest version producing inf in `PS_ImposterShadow`. The other f16 packs (`v_cvt_f16_f32`, d16 results, mix ops) round to nearest, which matches the default mode; the ALU ones follow a MODE toward-zero write (below; ALU sites: see the f16 rounding row). MODE: `s_setreg_imm32_b32 hwreg(HW_REG_MODE, 2, 2)` (f16/f64 rounding) is tracked in a per-invocation variable, the only MODE field the corpus writes (9,417 writes in 6,333 shaders: 6,694 toward zero, 2,723 back to nearest even). While it is toward zero, every VALU f16 result except the transcendentals listed below (`v_cvt_f16_f32`, f16 arithmetic, `v_pk_*_f16`, `v_fma_mix{lo,hi}_f16`, `v_interp_p2_f16`) rounds toward zero exactly, with the integer conversion `v_cvt_pkrtz_f16_f32` uses (`f16_bits(rtz=True)`, see the f16 rounding row), and `v_add_f64` steps back one ulp when the TwoSum error shows it rounded away from zero; finite overflow gives the largest finite value. The `v_add_f64` output modifiers apply after that step and round to nearest, so an omod that overflows or lands on a subnormal is not toward zero. **omod versus denormal mode is unmodelled:** the translator applies `mul:2`/`mul:4`/`div:2` regardless of the MODE denormal fields (as before this change), whereas hardware ignores omod when denormals are kept (denorm fields = 3) and applies it when they are flushed (both measured on an RX 6800: `v_add_f64 (1 - 2^-60) mul:2` with denormals kept gave 3ff00000:00000000 nearest and 3fefffff:ffffffff toward zero, unscaled; mul:2 was applied with denormals flushed); the tests therefore claim no omod order. CPU-checked by `tests/test_mode_round.py` (the RX 6800 words for f16 add/sub, `v_fma_mix`, the transcendentals, f64 overflow). f16 add and sub (f16 operands) and `v_pk_add_f16` take the exact TwoSum error of the f32 result into account, so they are exact toward zero too (f32 then f16 rounding alone would be wrong: 2 - 2^-24 is an f32 tie that rounds up to 2.0); f16 FMAs need nothing extra, since their round-to-odd f32 value (SHADER-55) narrows exactly in either mode. `v_fma_mix{lo,hi}_f16` rounds the exact fma once, straight to f16, toward zero (an RX 6800 gave 0x3fff for 1 * 2 - 2^-30, where rounding to f32 first and then narrowing gives 0x4000): `Gen.fma_mix_odd` corrects the f32 `Fma` to round-to-odd by the sign of its exact residual (product error by `Fma(x, y, -x*y)`, TwoSum of the sum), which narrows exactly in either direction; the nearest-even path is unchanged (f32 `Fma`, then narrow). `fma_mix_odd` also handles a tiny product (|x*y| < 2^-64: its error underflows or is flushed, so the residual sign is sign(x) xor sign(y), independent of the driver's denormal mode) and an f32 overflow with finite operands (toward zero gives ±FLT_MAX, so f16 ±65504). `v_rcp_f16`, `v_rsq_f16`, `v_sqrt_f16` and `v_sin_f16` ignore the rounding mode on hardware (RX 6800: the same words in every mode), so they always narrow to nearest even; `v_cos_f16`, `v_exp_f16` and `v_log_f16` are unmeasured, assumed like those four and treated the same. The "every VALU f16 result rounds toward zero" sentence above therefore excludes these seven; the f16 results of `v_floor/ceil/trunc/rndne/fract_f16` are exact and need no rounding. Nearest-mode `v_fma_mix*` still rounds twice (f32 `Fma`, then narrow): main's behaviour, unmeasured. `tools/fma_mix_probe.py --oracle hw` measures it on an AMD GPU, with seven inputs where the two rules differ by one f16 ulp (docs/shader_validation.md). The `v_add_f64` step needs f64 denormals preserved (not flushed) by the driver for subnormal sums. Shaders that never write MODE emit the same code as without this. Writes to other MODE bits (f32 rounding, denormals), directed rounding (+inf/-inf) and register-valued writes are refused, so nothing changes silently; none occur in the corpus. Denormal behaviour is still Vulkan's default. Format conversions in memory and texture units don't follow MODE. `v_mul_legacy_f32` now keeps the `0 × anything = 0` rule like `v_mad_legacy_f32` (GPU-checked with `runtime/test/shaders/ps_legacy_mul.asm` on AMD Radeon RX 9070 XT). | 384| Known approximations | `v_cvt_pkrtz_f16_f32` is now **exact round-toward-zero** (finite overflow gives ±65504, not inf). The GPU smoke test caught the old round-to-nearest version producing inf in `PS_ImposterShadow`. The other f16 packs (`v_cvt_f16_f32`, d16 results, mix ops) round to nearest, which matches the default mode; the ALU ones follow a MODE toward-zero write (below; ALU sites: see the f16 rounding row). MODE: `s_setreg_imm32_b32 hwreg(HW_REG_MODE, 2, 2)` (f16/f64 rounding) is tracked in a per-invocation variable, the only MODE field the corpus writes (9,417 writes in 6,333 shaders: 6,694 toward zero, 2,723 back to nearest even). While it is toward zero, every VALU f16 result except the transcendentals listed below (`v_cvt_f16_f32`, f16 arithmetic, `v_pk_*_f16`, `v_fma_mix{lo,hi}_f16`, `v_interp_p2_f16`) rounds toward zero exactly, with the integer conversion `v_cvt_pkrtz_f16_f32` uses (`f16_bits(rtz=True)`, see the f16 rounding row), and `v_add_f64` steps back one ulp when the TwoSum error shows it rounded away from zero; finite overflow gives the largest finite value. The `v_add_f64` output modifiers apply after that step and round to nearest, so an omod that overflows or lands on a subnormal is not toward zero. **omod versus denormal mode is unmodelled:** the translator applies `mul:2`/`mul:4`/`div:2` regardless of the MODE denormal fields (as before this change), whereas hardware ignores omod when denormals are kept (denorm fields = 3) and applies it when they are flushed (both measured on an RX 6800: `v_add_f64 (1 - 2^-60) mul:2` with denormals kept gave 3ff00000:00000000 nearest and 3fefffff:ffffffff toward zero, unscaled; mul:2 was applied with denormals flushed); the tests therefore claim no omod order. CPU-checked by `tests/test_mode_round.py` (the RX 6800 words for f16 add/sub, `v_fma_mix`, the transcendentals, f64 overflow). f16 add and sub (f16 operands) and `v_pk_add_f16` take the exact TwoSum error of the f32 result into account, so they are exact toward zero too (f32 then f16 rounding alone would be wrong: 2 - 2^-24 is an f32 tie that rounds up to 2.0); f16 FMAs need nothing extra, since their round-to-odd f32 value (SHADER-55) narrows exactly in either mode. `v_fma_mix{lo,hi}_f16` rounds the exact fma once, straight to f16, in both nearest-even and toward-zero modes (measured on AMD RDNA2 gfx1036 and verified by `tools/fma_mix_probe.py`; finding 7079901079): `Gen.fma_mix_odd` corrects the f32 `Fma` to round-to-odd by the sign of its exact residual (product error by `Fma(x, y, -x*y)`, TwoSum of the sum), which narrows exactly in either direction. `fma_mix_odd` also handles a tiny product (|x*y| < 2^-64: its error underflows or is flushed, so the residual sign is sign(x) xor sign(y), independent of the driver's denormal mode) and an f32 overflow with finite operands (toward zero gives ±FLT_MAX, so f16 ±65504). `v_rcp_f16`, `v_rsq_f16`, `v_sqrt_f16` and `v_sin_f16` ignore the rounding mode on hardware (RX 6800: the same words in every mode), so they always narrow to nearest even; `v_cos_f16`, `v_exp_f16` and `v_log_f16` are unmeasured, assumed like those four and treated the same. The "every VALU f16 result rounds toward zero" sentence above therefore excludes these seven; the f16 results of `v_floor/ceil/trunc/rndne/fract_f16` are exact and need no rounding. The `v_add_f64` step needs f64 denormals preserved (not flushed) by the driver for subnormal sums. Shaders that never write MODE emit the same code as without this. Writes to other MODE bits (f32 rounding, denormals), directed rounding (+inf/-inf) and register-valued writes are refused, so nothing changes silently; none occur in the corpus. Denormal behaviour is still Vulkan's default. Format conversions in memory and texture units don't follow MODE. `v_mul_legacy_f32` now keeps the `0 × anything = 0` rule like `v_mad_legacy_f32` (GPU-checked with `runtime/test/shaders/ps_legacy_mul.asm` on AMD Radeon RX 9070 XT). |
358| Denormal flush in `v_mad_f32`, `v_mac_f32`, `v_mad_legacy_f32` (SHADER-118) | The three have no f32 denormal support: a subnormal operand, the rounded product or the result reads as signed zero, whatever the MODE register says. `Gen.flush_f32` emits `|x| < FLT_MIN → copysign(0, x)` on the three operands, after the product rounding and after `omod`/`clamp`; inf and NaN compare false and pass through, and 0 keeps its sign. Source: LLVM AMDGPU `SIISelLowering.cpp`, `SITargetLowering::isFMADLegal` (llvm-project `1922c0c`), which forms `v_mad_f32`/`v_mac_f32` only when f32 denormals are flushed. Corpus count with `tools/shader_profile.py` over the 26,503 gfx1013 shaders: `v_mad_f32` in 7,298 shaders (139,287 occurrences), `v_mac_f32` in 5,889 (276,806: 265,901 `_e32`, 10,811 `_e64`, 94 `_dpp`), `v_mad_legacy_f32` in 6,059 (24,765); 9,297 shaders (35.1%) use at least one, 440,858 occurrences (0.99% of the corpus's 44,406,870 instructions). Checked on the CPU by `tests/semantic/test_valu_f32_min3_max3_mad.py` (`DenormalFlushTests`: the flush column, NaN/inf/zero pass-through, and a sabotaged pass-through that fails); **not GPU-verified** — a native measurement still needs an RDNA1/RDNA2 part that has these opcodes. The `omod` order is an assumption: the flush runs after `div:2`/`mul:2`/`mul:4`, so `FLT_MIN div:2` is flushed, as pinned by that test. | 385| Denormal flush in `v_mad_f32`, `v_mac_f32`, `v_mad_legacy_f32` (SHADER-118) | The three have no f32 denormal support: a subnormal operand, the rounded product or the result reads as signed zero, whatever the MODE register says. `Gen.flush_f32` emits `|x| < FLT_MIN → copysign(0, x)` on the three operands, after the product rounding and after `omod`/`clamp`; inf and NaN compare false and pass through, and 0 keeps its sign. Source: LLVM AMDGPU `SIISelLowering.cpp`, `SITargetLowering::isFMADLegal` (llvm-project `1922c0c`), which forms `v_mad_f32`/`v_mac_f32` only when f32 denormals are flushed. Corpus count with `tools/shader_profile.py` over the 26,503 gfx1013 shaders: `v_mad_f32` in 7,298 shaders (139,287 occurrences), `v_mac_f32` in 5,889 (276,806: 265,901 `_e32`, 10,811 `_e64`, 94 `_dpp`), `v_mad_legacy_f32` in 6,059 (24,765); 9,297 shaders (35.1%) use at least one, 440,858 occurrences (0.99% of the corpus's 44,406,870 instructions). Checked on the CPU by `tests/semantic/test_valu_f32_min3_max3_mad.py` (`DenormalFlushTests`: the flush column, NaN/inf/zero pass-through, and a sabotaged pass-through that fails); **not GPU-verified** — a native measurement still needs an RDNA1/RDNA2 part that has these opcodes. The `omod` order is an assumption: the flush runs after `div:2`/`mul:2`/`mul:4`, so `FLT_MIN div:2` is flushed, as pinned by that test. |
359| `v_mac_legacy_f32` | The GFX10.1 VOP2 form of `v_mad_legacy_f32` with D as the addend: D = legacy(S0 * S1) + D, where 0 times anything (inf and NaN included) is +0, with the same denormal flush and VOP3 modifiers. D is read before it is written, as for `v_mac_f32` (LLVM `VOP2Instructions.td`: `V_MAC_LEGACY_F32` has `$src2` tied to `$vdst`). Until 2026-11-22 it raised `Unsupported`. CPU-checked by `MacLegacyF32Tests` in `tests/semantic/test_valu_f32_min3_max3_mad.py` (a 15x8x6 grid against the `v_mad_legacy_f32` reference, the zero rule, clamp/neg, D aliased as a source). **Not GPU-verified**: like the other mad opcodes it exists on gfx1010-1013 only, so no RDNA2 desktop part runs it. | 386| `v_mac_legacy_f32` | The GFX10.1 VOP2 form of `v_mad_legacy_f32` with D as the addend: D = legacy(S0 * S1) + D, where 0 times anything (inf and NaN included) is +0, with the same denormal flush and VOP3 modifiers. D is read before it is written, as for `v_mac_f32` (LLVM `VOP2Instructions.td`: `V_MAC_LEGACY_F32` has `$src2` tied to `$vdst`). Until 2026-11-22 it raised `Unsupported`. CPU-checked by `MacLegacyF32Tests` in `tests/semantic/test_valu_f32_min3_max3_mad.py` (a 15x8x6 grid against the `v_mad_legacy_f32` reference, the zero rule, clamp/neg, D aliased as a source). **Not GPU-verified**: like the other mad opcodes it exists on gfx1010-1013 only, so no RDNA2 desktop part runs it. |
360| Whole-quad mode (`s_wqm_b64` / `s_wqm_b32`) | A lane mask register holds only this lane's bit, so WQM on one (EXEC, VCC, an SGPR the mask analysis found) ORs the bit of the lane's quad, lanes 4n..4n+3 of the wave: two `OpGroupNonUniformQuadSwap` (horizontal, then vertical; capability `GroupNonUniformQuad`) in the default mode in fragment and compute shaders (quad operations are only guaranteed there; vertex, geometry and mesh shaders shuffle from the quad's four lanes), or the four lanes' values read through `%x_buf` under `--wave64-emulate` (no subgroup operation there). A quad never crosses lane 31/32, so the mask bits are exact per half on a 32-wide subgroup; SCC is a wave vote, so on wave64 it needs a 64-wide subgroup or `--wave64-emulate` (as every wave-wide mask op). The result goes to EXEC, VCC or an SGPR pair as a mask, SCC = the wave-wide any of it (same vote as the other mask ops). A 32-bit form in wave64 (`exec_lo`/`exec_hi`, `vcc_lo`/`vcc_hi`, a half-mask SGPR) writes only its own half (`exec_half_write`) and votes SCC over that half only (`cs_wqm_w64_half`). A source that is not a lane mask (a value loaded from memory, a literal) is data: `((x | x>>1 | x>>2 | x>>3) & 0x11111111) * 15` per 32-bit word and SCC = result != 0, no subgroup operation. Assumptions: in compute and mesh shaders the subgroup lane is `LocalInvocationIndex` mod the subgroup size (as for every cross-lane op); a hardware quad is four consecutive lanes of a wave, and in a pixel shader Vulkan's quad (the 2x2 pixels, helper invocations included) is the same four lanes; GPU-checked on both AMD and NVIDIA with `ps_wqm.asm` (every 2x2 block of a 64x64 target, fully covered). Not covered: helper-invocation behaviour at triangle edges is untested, and in native mode an absent invocation in a partial quad (a compute group whose size is not a multiple of 4) gives an undefined value (emulated, the missing lanes of a partial wave read as 0). Before this the instruction was the identity, so helper lanes stayed off (#156 SHADER-34: `s_wqm_b64` appears in 4,285 pixel shaders). GPU-checked with `runtime/test/shaders/cs_wqm_w64.asm`, `cs_wqm_w64_half.asm`, `cs_wqm_w32.asm` and `ps_wqm.asm` on AMD Radeon 880M (subgroup 64) and NVIDIA GeForce RTX 5070 Laptop (subgroup 32; `cs_wqm_w64` there needs `LEONIDA_W64_EMULATE=1`), with and without `--wave64-emulate`. | 387| Whole-quad mode (`s_wqm_b64` / `s_wqm_b32`) | A lane mask register holds only this lane's bit, so WQM on one (EXEC, VCC, an SGPR the mask analysis found) ORs the bit of the lane's quad, lanes 4n..4n+3 of the wave: two `OpGroupNonUniformQuadSwap` (horizontal, then vertical; capability `GroupNonUniformQuad`) in the default mode in fragment and compute shaders (quad operations are only guaranteed there; vertex, geometry and mesh shaders shuffle from the quad's four lanes), or the four lanes' values read through `%x_buf` under `--wave64-emulate` (no subgroup operation there). A quad never crosses lane 31/32, so the mask bits are exact per half on a 32-wide subgroup; SCC is a wave vote, so on wave64 it needs a 64-wide subgroup or `--wave64-emulate` (as every wave-wide mask op). The result goes to EXEC, VCC or an SGPR pair as a mask, SCC = the wave-wide any of it (same vote as the other mask ops). A 32-bit form in wave64 (`exec_lo`/`exec_hi`, `vcc_lo`/`vcc_hi`, a half-mask SGPR) writes only its own half (`exec_half_write`) and votes SCC over that half only (`cs_wqm_w64_half`). A source that is not a lane mask (a value loaded from memory, a literal) is data: `((x | x>>1 | x>>2 | x>>3) & 0x11111111) * 15` per 32-bit word and SCC = result != 0, no subgroup operation. Assumptions: in compute and mesh shaders the subgroup lane is `LocalInvocationIndex` mod the subgroup size (as for every cross-lane op); a hardware quad is four consecutive lanes of a wave, and in a pixel shader Vulkan's quad (the 2x2 pixels, helper invocations included) is the same four lanes; GPU-checked on both AMD and NVIDIA with `ps_wqm.asm` (every 2x2 block of a 64x64 target, fully covered). Not covered: helper-invocation behaviour at triangle edges is untested, and in native mode an absent invocation in a partial quad (a compute group whose size is not a multiple of 4) gives an undefined value (emulated, the missing lanes of a partial wave read as 0). Before this the instruction was the identity, so helper lanes stayed off (#156 SHADER-34: `s_wqm_b64` appears in 4,285 pixel shaders). GPU-checked with `runtime/test/shaders/cs_wqm_w64.asm`, `cs_wqm_w64_half.asm`, `cs_wqm_w32.asm` and `ps_wqm.asm` on AMD Radeon 880M (subgroup 64) and NVIDIA GeForce RTX 5070 Laptop (subgroup 32; `cs_wqm_w64` there needs `LEONIDA_W64_EMULATE=1`), with and without `--wave64-emulate`. |
diff --git a/docs/fspx.md b/docs/fspx.md
index 7c9770f84..6d6c2f4eb 100644
--- a/docs/fspx.md
+++ b/docs/fspx.md
@@ -88,8 +88,11 @@ compute shader.
88 - `fspx_unpack.py --disasm` defaults to `gfx1030`. 88 - `fspx_unpack.py --disasm` defaults to `gfx1030`.
89- **What llvm-mc still rejects.** With `gfx1030`, 21 of the 29 decode with no invalid word. The other 89 words, in 8 89- **What llvm-mc still rejects.** With `gfx1030`, 21 of the 29 decode with no invalid word. The other 89 words, in 8
90 programs, are all VOP3P opcode 0x16 with `op_sel` 2 and `op_sel_hi` 5. That is the opcode of the 1,458 90 programs, are all VOP3P opcode 0x16 with `op_sel` 2 and `op_sel_hi` 5. That is the opcode of the 1,458
91 `v_dot4_i32_i8` that `llvm-mc` does decode, all of which have `op_sel` 0. What the hardware does with that `op_sel` 91 `v_dot4_i32_i8` that `llvm-mc` does decode, all of which have `op_sel` 0.
92 was not checked. 92 - Measured on RDNA2 hardware (gfx1036, through `tools/hw_oracle`, the instruction given as two raw words): with
93 `op_sel` 2 and `op_sel_hi` 5 the result is the dot product with the two 16-bit halves of the second source
94 exchanged, in all 5 operand sets (4 of them give another word under the plain rule). So `op_sel` selects halves
95 here as it does for the packed 16-bit ops. The words are in `tests/semantic/test_alu_dot4_i8.py`.
93 96
94## Kind 7: records 97## Kind 7: records
95 98
@@ -108,12 +111,13 @@ compute shader.
108 111
109With `tools/fspx_unpack.py --disasm` and `tools/rdna2spirv.py` on the 29 programs: 112With `tools/fspx_unpack.py --disasm` and `tools/rdna2spirv.py` on the 29 programs:
110 113
111- **13 translate and pass `spirv-val`.** They are the 16 programs that use no dot4 instruction, minus 3 that stop at 114- **17 translate and pass `spirv-val`.** 13 of them are the 16 programs that use no dot4 instruction, minus 3 that
112 `v_pk_add_u16`, `image_atomic_add` (2D) and `v_pk_fmac_f16`. 115 stop at `v_pk_add_u16`, `image_atomic_add` (2D) and `v_pk_fmac_f16`. The other 4 use dot4 (design.md, "Signed-byte
113- **The 13 programs that use dot4 do not translate yet.** The translator has neither dot4 form: 116 dot products").
114 - 10 stop at `v_dot4_i32_i8`; 117- **9 more programs that use dot4 do not translate yet.** The first thing each stops at:
115 - 2 stop earlier, at a reachable word `llvm-mc` does not decode (the VOP3P words above); 118 - 6 at an `s_buffer_load_dwordx8` or `_dwordx16` whose destination range ends in `vcc_lo, vcc_hi`;
116 - 1 stops earlier, at an `src_scc` operand. 119 - 2 at a reachable word `llvm-mc` does not decode (the VOP3P words above);
120 - 1 at an `src_scc` operand.
117 121
118## Unknown 122## Unknown
119 123
diff --git a/docs/gameinput.md b/docs/gameinput.md
index 055cec655..f848ab0d2 100644
--- a/docs/gameinput.md
+++ b/docs/gameinput.md
@@ -136,6 +136,29 @@ uses:
136 136
137An effect is sent only when its bytes change, so a steady level costs one report. 137An effect is sent only when its bytes change, so a steady level costs one report.
138 138
139## Motion
140
141Pads whose SDL gamepad reports both a gyroscope and an accelerometer (a DualSense, a Switch Pro, Steam Input pads) get
142`GameInputKindMotion` in `supportedInput` and a `motionInfo` (`GameInputMotionInfo`, Microsoft's v0 layout); `IGameInputReading::GetMotionState`
143returns a `GameInputMotionState` on their readings, and `GetCurrentReading`/`GetNextReading` answer a
144`GameInputKindMotion` query for such a pad and return `GAMEINPUT_E_READING_NOT_FOUND` for a pad without sensors. The
145sensors are enabled when the pad is opened, at SDL's requested rate, and every poll reads the latest sample.
146
147- The state carries **signed fractions of the maxima `motionInfo` reports** (1.0 = full magnitude), which is the
148 convention Microsoft documents for `GameInputMotionState`. SDL delivers accel in m/s² (gravity included) and gyro
149 in rad/s, so the shim divides by the maxima. The maxima are this shim's choice — SDL does not expose a sensor
150 range — and are 2 g (19.6133 m/s²) and 2000 deg/s (34.9066 rad/s), a DualSense's accelerometer and gyro ranges
151 (VERIFY against the game and a real pad).
152- A pad at rest sits at about 0.5 on the gravity axis and 0.0 on all gyro axes. SDL answers sensor reads with zeros
153 before the device's first sample arrives; since a real accelerometer never reads exactly zero (gravity), all-zero
154 accel means "no sample yet" and the reading carries no motion at all — `GetMotionState` returns false.
155- SDL's gamepad API has no compass and the shim synthesises no orientation quaternion, so the magnetic-field and
156 orientation members are zero with `GameInputMotionAccuracyUnknown`.
157- A pad with sensors streams a reading every ~8 ms (~125 Hz) even when nothing else changes, so motion is not stuck
158 at the last button event; pads without sensors keep the old change-driven behaviour. The 8 ms window and the 512-
159 reading history cap bound the cost.
160- `gameinput_probe` prints the accel and gyro fractions when the pad has sensors (a resting pad shows ~0.5 g).
161
139## Environment variables 162## Environment variables
140 163
141| variable | default | effect | 164| variable | default | effect |
@@ -165,7 +188,7 @@ The API surface:
165| interface | implemented | not implemented | 188| interface | implemented | not implemented |
166|---|---|---| 189|---|---|---|
167| `IGameInput` | `GetCurrentTimestamp` (µs), `GetCurrentReading`, `GetNextReading`, `GetPreviousReading`, `RegisterReadingCallback`, `RegisterDeviceCallback` (blocking and async enumeration), `RegisterGuideButtonCallback`, `RegisterKeyboardLayoutCallback` (never fires), `StopCallback`, `UnregisterCallback`, `CreateDispatcher`, `FindDeviceFromId`, `EnableOemDeviceSupport` (no-op), `SetFocusPolicy` (no-op) | `GetTemporalReading`, `CreateAggregateDevice`, `FindDeviceFromObject/PlatformHandle/PlatformString` | 190| `IGameInput` | `GetCurrentTimestamp` (µs), `GetCurrentReading`, `GetNextReading`, `GetPreviousReading`, `RegisterReadingCallback`, `RegisterDeviceCallback` (blocking and async enumeration), `RegisterGuideButtonCallback`, `RegisterKeyboardLayoutCallback` (never fires), `StopCallback`, `UnregisterCallback`, `CreateDispatcher`, `FindDeviceFromId`, `EnableOemDeviceSupport` (no-op), `SetFocusPolicy` (no-op) | `GetTemporalReading`, `CreateAggregateDevice`, `FindDeviceFromObject/PlatformHandle/PlatformString` |
168| `IGameInputReading` | kind, sequence number, timestamp, device, gamepad state, UI navigation state, controller axes and buttons | raw report, keyboard, mouse, touch, motion, arcade/flight stick, racing wheel (all return nothing) | 191| `IGameInputReading` | kind, sequence number, timestamp, device, gamepad state, UI navigation state, controller axes and buttons, motion state | raw report, keyboard, mouse, touch, arcade/flight stick, racing wheel (all return nothing) |
169| `IGameInputDevice` | device info, status, battery, `SetRumbleState` | force feedback and haptic motors (none reported), raw device I/O, power off, input synchronization (no-ops) | 192| `IGameInputDevice` | device info, status, battery, `SetRumbleState` | force feedback and haptic motors (none reported), raw device I/O, power off, input synchronization (no-ops) |
170| `IGameInputDispatcher` | `Dispatch`, `OpenWaitHandle` | the quota (the queue is short) | 193| `IGameInputDispatcher` | `Dispatch`, `OpenWaitHandle` | the quota (the queue is short) |
171 194
@@ -235,7 +258,11 @@ shim fills (`GameInputDeviceInfo` 320 bytes with `deviceFamily` at 96 and the in
235 rumble as SDL receives them, the DualSense effect bytes in each `LEONIDA_DS_TRIGGERS` mode, the lightbar, a 258 rumble as SDL receives them, the DualSense effect bytes in each `LEONIDA_DS_TRIGGERS` mode, the lightbar, a
236 dispatcher, async and blocking enumeration, unregistering, unplugging and replugging, and three identical pads 259 dispatcher, async and blocking enumeration, unregistering, unplugging and replugging, and three identical pads
237 (an id each, `FindDeviceFromId` and device-filtered readings per pad, replugging one, two and all three, and the 260 (an id each, `FindDeviceFromId` and device-filtered readings per pad, replugging one, two and all three, and the
238 first twin's id equal to the single-pad id). The keyboard pad is 261 first twin's id equal to the single-pad id). Motion runs on a virtual pad with sensors (`nsensors` in the
262 virtual-joystick description, fed with `SDL_SendJoystickVirtualSensorData`): the kind and `motionInfo` on a sensor
263 pad and not on a plain one, no motion before the first sample, normalisation against the `motionInfo` maxima, the
264 accuracy values, the ±1 clamp, the ~8 ms cadence, and that a motion query on a pad without sensors is
265 `GAMEINPUT_E_READING_NOT_FOUND`. The keyboard pad is
239 driven through `rt::gameinput::set_keyboard_source` and `set_cursor_source` with fake keys, focus and cursor: every 266 driven through `rt::gameinput::set_keyboard_source` and `set_cursor_source` with fake keys, focus and cursor: every
240 binding, two keys at once, each WASD direction, opposite keys cancelling, diagonals, the mouse moving the right 267 binding, two keys at once, each WASD direction, opposite keys cancelling, diagonals, the mouse moving the right
241 stick, clamping and decaying to 0, the mouse-button triggers, no input out of focus, release of buttons, sticks and 268 stick, clamping and decaying to 0, the mouse-button triggers, no input out of focus, release of buttons, sticks and
@@ -258,6 +285,11 @@ These need the game executable or a test on hardware:
258 not measured from a console. 285 not measured from a console.
259- **Battery capacity** is reported as a fraction (remaining 0..1 of full 1), not in device units. 286- **Battery capacity** is reported as a fraction (remaining 0..1 of full 1), not in device units.
260- **`UnregisterCallback` timeout** is not honoured; it waits for a callback that is running. 287- **`UnregisterCallback` timeout** is not honoured; it waits for a callback that is running.
288- **Motion normalisation maxima** (2 g accel, 2000 deg/s gyro) are this shim's choice; SDL exposes no sensor range,
289 and whether the game reads motion, and against what scale, is unknown until it runs. The accelerometer range a
290 DualSense exposes can also be wider than 2 g, so hard shakes may clamp at 1.0.
291- **Motion members the shim does not provide** (magnetic field, orientation) are zero with
292 `GameInputMotionAccuracyUnknown`; whether a title wants a synthesised quaternion there is unknown.
261- **Device family**: every pad is reported as `GameInputFamilyXboxOne`; a title that filters on family sees only 293- **Device family**: every pad is reported as `GameInputFamilyXboxOne`; a title that filters on family sees only
262 that. 294 that.
263- **Identical pads at start**: twins are numbered in the order the shim opens them. For pads already connected when 295- **Identical pads at start**: twins are numbered in the order the shim opens them. For pads already connected when
diff --git a/docs/pipeline_check.md b/docs/pipeline_check.md
index 01e9d01f3..51ae4281f 100644
--- a/docs/pipeline_check.md
+++ b/docs/pipeline_check.md
@@ -10,6 +10,49 @@ The checker exits nonzero if a module fails to load, a pipeline fails to compile
10cache save fails. It still finishes checking the other entries and attempts the final save so the next run 10cache save fails. It still finishes checking the other entries and attempts the final save so the next run
11can reuse successful pipelines. Entries reported as skipped do not count as failures. 11can reuse successful pipelines. Entries reported as skipped do not count as failures.
12 12
13## Check user-defined interfaces between stages
14
15`tools/shader_link_check.py` compares the binary SPIR-V declarations of the shaders you plan to put in the
16same pipeline. Use it before driver compilation to locate missing varyings, overlapping components, type
17mismatches and per-primitive mesh declarations. It reads local modules and needs only Python.
18
19```powershell
20python -I tools/shader_link_check.py check --vs <vertex.spv> --ps <pixel.spv>
21python -I tools/shader_link_check.py check --vs <vertex.spv> --gs <geometry.spv> --ps <pixel.spv>
22python -I tools/shader_link_check.py check --ms <mesh.spv> --ps <pixel.spv>
23python -I tools/shader_link_check.py inspect <shader.spv>
24```
25
26To audit a batch, give it the shader names from your local translation directory in a JSON file. A stage can
27use a string or a `shader` and `entry` object. Names refer to `<name>.spv` in `--shader-dir`.
28
29```json
30{
31 "version": 1,
32 "pipelines": [
33 {"name": "two-stage", "vs": "vs_example", "ps": "ps_example"},
34 {"name": "with-geometry", "vs": "vs_example", "gs": "gs_example",
35 "ps": {"shader": "ps_other", "entry": "main"}}
36 ]
37}
38```
39
40```powershell
41python -I tools/shader_link_check.py batch pairs.json --shader-dir <spirv> --quiet --report link-report.json
42```
43
44The report records per-pipeline results. It uses the Vulkan Location and Component model, including one
45outer array level for geometry inputs, mesh outputs and fragment `PerVertexKHR` inputs. Add `--maintenance4`
46when the actual device enables that feature and the pipeline relies on matching a wider output vector to a
47narrower input vector. See [Vulkan interface matching][interfaces].
48
49Exit codes are `0` for compatible interfaces, `1` for a mismatch and `2` for a bad input or an interface
50the reader cannot interpret. Continue with the driver checker for shader instruction validation, resource
51bindings, device limits and pipeline state. Shader pairs must come from the caller. Share aggregate counts
52and error classes, keeping the local shader files and reports that identify them on your PC.
53
54[interfaces]: https://docs.vulkan.org/spec/latest/chapters/interfaces.html#interfaces-iointerfaces-matching
55
13## Corpus 56## Corpus
14 57
15The translated corpus is 26,503 entries: 2,236 vertex, 12,101 pixel, 2,689 compute, 9,282 mesh and 58The translated corpus is 26,503 entries: 2,236 vertex, 12,101 pixel, 2,689 compute, 9,282 mesh and
diff --git a/docs/rbf0.md b/docs/rbf0.md
index 5ccdb5a8a..3e6779cb3 100644
--- a/docs/rbf0.md
+++ b/docs/rbf0.md
@@ -468,8 +468,16 @@ python -I tools/rbf0_tree.py <work>\data-carve <work>\subtitle.json --root CMovi
468# Unit tests: synthetic headers and trees only 468# Unit tests: synthetic headers and trees only
469python -I tests/test_rbf0_index.py 469python -I tests/test_rbf0_index.py
470python -I tests/test_rbf0_tree.py 470python -I tests/test_rbf0_tree.py
471python -I tests/test_imhex_patterns.py
471``` 472```
472 473
474To look at one resource in a hex editor, open the inflated and joined resource (not the archive) in
475[ImHex](https://imhex.werwolv.net/) with [tools/imhex/rbf0.hexpat](../tools/imhex/rbf0.hexpat). The pattern follows
476the grammar in section 3, picks the 8- or 4-byte value width from the prologue, and stops where the root element
477closes. `tests/test_imhex_patterns.py` builds wide and narrow streams with every record type, checks them with
478`rbf0_index.parse_rbf0`, and when ImHex is installed (on `PATH`, in its default Windows folder, or named by
479`LEONIDA_IMHEX`) compares the pattern's output with the parser's.
480
473`--start` must be 0 or more and `--limit` at least 1 (decimal or `0x` hex); an out-of-range value stops with a 481`--start` must be 0 or more and `--limit` at least 1 (decimal or `0x` hex); an out-of-range value stops with a
474one-line error and exit code 2 before an index is written. 482one-line error and exit code 2 before an index is written.
475 483
diff --git a/docs/related_projects.md b/docs/related_projects.md
index 2ba45392e..d6a0ef39f 100644
--- a/docs/related_projects.md
+++ b/docs/related_projects.md
@@ -96,6 +96,7 @@ GPL-3.0-or-later.
96**What we use it for:** `tools/isa_coverage.py` reads `amdgpu_isa_rdna2.xml` from a path the user supplies and counts 96**What we use it for:** `tools/isa_coverage.py` reads `amdgpu_isa_rdna2.xml` from a path the user supplies and counts
97which instructions the translator has a rule for ([isa_coverage.md](isa_coverage.md)). The XML is not vendored (11 MB); 97which instructions the translator has a rule for ([isa_coverage.md](isa_coverage.md)). The XML is not vendored (11 MB);
98tests use a small fixture of our own in the same schema. 98tests use a small fixture of our own in the same schema.
99
99## Mesa (AMD register database and format tables) and LLVM's AMDGPU backend 100## Mesa (AMD register database and format tables) and LLVM's AMDGPU backend
100 101
101<https://gitlab.freedesktop.org/mesa/mesa> (`src/amd/registers/*.json`, `src/amd/common/ac_descriptors.c`), 102<https://gitlab.freedesktop.org/mesa/mesa> (`src/amd/registers/*.json`, `src/amd/common/ac_descriptors.c`),
diff --git a/docs/rpf.md b/docs/rpf.md
index 3f0865ab9..ffc6d34e2 100644
--- a/docs/rpf.md
+++ b/docs/rpf.md
@@ -69,6 +69,13 @@ both paths. It is used to check exported assets without keeping a second copy.
69of each zlib stream and indexes the measured `name.#dr`/`#ft`/`#dd` spellings with their archive offsets. It 69of each zlib stream and indexes the measured `name.#dr`/`#ft`/`#dd` spellings with their archive offsets. It
70does not decode a resource or need the TOC; see [resource_names.md](resource_names.md). 70does not decode a resource or need the TOC; see [resource_names.md](resource_names.md).
71 71
72### Viewing a header in ImHex
73
74[tools/imhex/rpf9.hexpat](../tools/imhex/rpf9.hexpat) is a pattern for the [ImHex](https://imhex.werwolv.net/) hex
75editor. It names the magic and the data offset at `+4`, shows the u32s at `+8` and `+12` unnamed, and shows the range
76from `+0x10` to the data offset (the rest of the header and the TOC) as one opaque byte array. It decodes nothing in
77that range. `python -I tests/test_imhex_patterns.py` runs it on a synthetic header when ImHex is installed.
78
72## Limits 79## Limits
73 80
74- The TOC is the hard boundary. File names, original paths and the exact file boundaries come from the TOC, 81- The TOC is the hard boundary. File names, original paths and the exact file boundaries come from the TOC,
diff --git a/docs/runtime_imports.md b/docs/runtime_imports.md
index 6761ff227..c3860caf1 100644
--- a/docs/runtime_imports.md
+++ b/docs/runtime_imports.md
@@ -41,21 +41,23 @@ All 16 DLLs in the package map at their preferred base `0x180000000` with no rel
41| `XboxBvhBuilder.dll` | 909,312 | `0x227cc` | 3 | 54 | 0 | 0 | 41| `XboxBvhBuilder.dll` | 909,312 | `0x227cc` | 3 | 54 | 0 | 0 |
42| `amd_fidelityfx_upscaler_xbox.dll` | 802,816 | `0x26780` | 5 | 81 | 0 | 0 | 42| `amd_fidelityfx_upscaler_xbox.dll` | 802,816 | `0x26780` | 5 | 81 | 0 | 0 |
43| `amd_fidelityfx_loader_xbox.dll` | 32,768 | `0x18d0` | 4 | 18 | 0 | 0 | 43| `amd_fidelityfx_loader_xbox.dll` | 32,768 | `0x18d0` | 4 | 18 | 0 | 0 |
44| `libHttpClient.GDK.dll` | 999,424 | `0x11f0` | 7 | 191 | 0 | 0 | 44| `libHttpClient.GDK.dll` | 999,424 | `0x11f0` | 10 | 188 | 0 | 0 |
45| `XCurl.dll` | 188,416 | `0x17b0` | 7 | 133 | 0 | 0 | 45| `XCurl.dll` | 188,416 | `0x17b0` | 8 | 132 | 0 | 0 |
46| `concrt140.dll` | 303,104 | `0x29160` | 1 | 102 | 0 | 0 | 46| `concrt140.dll` | 303,104 | `0x29160` | 1 | 102 | 0 | 0 |
47| `msvcp140.dll` | 577,536 | `0x525a0` | 5 | 182 | 0 | 0 | 47| `msvcp140.dll` | 577,536 | `0x525a0` | 9 | 178 | 0 | 0 |
48| `msvcp140_1.dll` | 36,864 | `0x15c0` | 1 | 32 | 0 | 0 | 48| `msvcp140_1.dll` | 36,864 | `0x15c0` | 1 | 32 | 0 | 0 |
49| `msvcp140_2.dll` | 192,512 | `0x1efa0` | 1 | 95 | 0 | 0 | 49| `msvcp140_2.dll` | 192,512 | `0x1efa0` | 1 | 95 | 0 | 0 |
50| `msvcp140_atomic_wait.dll` | 81,920 | `0x3c80` | 3 | 61 | 0 | 0 | 50| `msvcp140_atomic_wait.dll` | 81,920 | `0x3c80` | 3 | 61 | 0 | 0 |
51| `msvcp140_codecvt_ids.dll` | 28,672 | `0x1340` | 1 | 23 | 0 | 0 | 51| `msvcp140_codecvt_ids.dll` | 28,672 | `0x1340` | 1 | 23 | 0 | 0 |
52| `vccorlib140.dll` | 344,064 | `0x27e50` | 6 | 108 | 0 | 0 | 52| `vccorlib140.dll` | 344,064 | `0x27e50` | 6 | 108 | 0 | 0 |
53| `vcomp140.dll` | 86,016 | `0x6580` | 3 | 75 | 0 | 0 | 53| `vcomp140.dll` | 86,016 | `0x6580` | 7 | 71 | 0 | 0 |
54| `vcruntime140.dll` | 110,592 | `0xf890` | 3 | 38 | 0 | 0 | 54| `vcruntime140.dll` | 110,592 | `0xf890` | 3 | 38 | 0 | 0 |
55| `vcruntime140_1.dll` | 49,152 | `0x3e90` | 1 | 33 | 0 | 0 | 55| `vcruntime140_1.dll` | 49,152 | `0x3e90` | 1 | 33 | 0 | 0 |
56 56
57Since the library-loader shims (`runtime/shims/library_loader.cpp`), a module's `LoadLibrary*`, `GetModuleHandle*`, `GetProcAddress` and `FreeLibrary` imports count as shim, through `kernel32`, `kernelbase` or the `api-ms-win-core-libraryloader-*` set it names. That is why every image above has a few more shim and fewer host imports than before; the Xbox-specific imports below are unchanged. 57Since the library-loader shims (`runtime/shims/library_loader.cpp`), a module's `LoadLibrary*`, `GetModuleHandle*`, `GetProcAddress` and `FreeLibrary` imports count as shim, through `kernel32`, `kernelbase` or the `api-ms-win-core-libraryloader-*` set it names. That is why every image above has a few more shim and fewer host imports than before; the Xbox-specific imports below are unchanged.
58 58
59The process shim (`runtime/shims/process.cpp`) serves `ExitProcess` and `GetCommandLineA/W` the same way: through `kernel32`, `kernelbase`, and `api-ms-win-core-processthreads-l1-1-0` and `api-ms-win-core-processenvironment-l1-1-0`, the sets the API-set umbrella libraries (`OneCore_apiset.lib`, `mincore.lib`) bind them to. `vcomp140.dll` imports `ExitProcess` from the first of these. The UCRT's `_get_narrow_winmain_command_line` and `_get_wide_winmain_command_line` are served too, so a `WinMain` executable gets the game's command line as `lpCmdLine`. The table above is `gta6rt --dry-run` on each DLL at the commit that added this paragraph.
60
59The six unique Xbox-specific imports (eight consumer/import pairs) are exactly the set recorded in 61The six unique Xbox-specific imports (eight consumer/import pairs) are exactly the set recorded in
60[`d3d12_vulkan.md` §7](d3d12_vulkan.md#7-prior-art-and-measured-xbox-abi): 62[`d3d12_vulkan.md` §7](d3d12_vulkan.md#7-prior-art-and-measured-xbox-abi):
61 63
diff --git a/docs/shader_validation.md b/docs/shader_validation.md
index d6399d74f..ddaafe738 100644
--- a/docs/shader_validation.md
+++ b/docs/shader_validation.md
@@ -13,9 +13,11 @@ harness itself). The GPU-side runners are described below: `tools/valu_fuzz.py`
13check that the module computes what the RDNA2 program computes. Those are different questions, and 13check that the module computes what the RDNA2 program computes. Those are different questions, and
14this repository already has cases where only the second question had a useful answer: 14this repository already has cases where only the second question had a useful answer:
15 15
16- All 26,503 shaders translate and pass `spirv-val` (Vulkan 1.2), yet the SDWA source/destination 16- All 26,503 shaders translate and pass `spirv-val` (Vulkan 1.2) at `43d4703`, after `dcd8ecf` fixed
17 selects were silently ignored until 2026-11-20. That passed validation for 3,826 of the 13,926 17 the ID-bound regression (#881); the intervening `dedd75c` run was 26,501, and `793b06f` before
18 translated shaders and produced wrong values (`docs/design.md`, "SDWA"). 18 #223's LLVM 23 source-field fix was 25,032. Yet the SDWA source/destination selects were silently
19 ignored until 2026-11-20: validation passed for 3,826 of the 13,926 shaders translated at the time
20 and produced wrong values (`docs/design.md`, "SDWA").
19- The compressed-export bug was found by a GPU test, not by validation: LLVM prints `v4, v4, v5, v5` 21- The compressed-export bug was found by a GPU test, not by validation: LLVM prints `v4, v4, v5, v5`
20 for a compressed pair, and the translated shader exported `(r, g, r, g)`. 22 for a compressed pair, and the translated shader exported `(r, g, r, g)`.
21- `v_cvt_pkrtz_f16_f32` with round-to-nearest overflowed a finite value to infinity; the GPU smoke 23- `v_cvt_pkrtz_f16_f32` with round-to-nearest overflowed a finite value to infinity; the GPU smoke
@@ -255,6 +257,40 @@ RDNA4 (Radeon RX 9070, gfx1201, driver 26.11.2, `rocm-sdk-core` 10.0.0 clang): 1
255500, 2000 each, and seed 500 with `--bfe-any`) gave 0 mismatches, so gfx1201 follows the same `s_bfe` rule. With 257500, 2000 each, and seed 500 with `--bfe-any`) gave 0 mismatches, so gfx1201 follows the same `s_bfe` rule. With
256`--oracle translator,hw`, 200 of 200 programs matched (seed 1). 258`--oracle translator,hw`, 200 of 200 programs matched (seed 1).
257 259
260#### RDNA2 integer rows (`tools/int_hw_probe.py`, SHADER-137)
261
262`tools/int_hw_probe.py` runs 87 hand-written cases across 19 integer groups (both wave32 and wave64) natively on
263an AMD GPU through `tools/hw_oracle` and compares every output word against `tools/rdna2spirv.py` +
264`tests/semantic/spirv_mini_interp.py` (with scalar ops run twice, SCC preset to 0 and 1, so SCC written vs kept is
265observed directly).
266
267Measured on an **AMD Radeon 680M (gfx1035, RDNA2)**, Windows 11 (`10.0.26300`), AMD driver `26.5.1`
268(`32.0.21043.7012`, `amdhip64_6.dll`), conda-forge `clang 22.1.8` + `lld 23.1.6` (`--oracle both --wave both`):
269**87 cases: 82 bit-exact matches, 5 known live translator divergences, 0 unexpected mismatches, 0 wave32/wave64
270differences** (plus `tools/salu_diff.py --oracle hw,translator --bfe-any --programs 500 --seed 1`: 500/500 match).
271
272- **Matched RDNA2 silicon in both wave32 and wave64 (82/87):** `s_absdiff_i32`, `s_mul_hi_i32/u32`, `s_lshl1..4_add_u32`
273 (64-bit shift-out and add carry into SCC), `s_sext_i32_i8/i16`, `s_flbit_i32`, `s_cmov_b32`, `s_cmovk_i32`,
274 `s_pack_ll/lh/hh_b32_b16`, `s_bfe_u32/i32` past bit 31, `s_brev_b64`, `s_bfe_u64/i64`, `s_bitset0/1_b64`,
275 `s_flbit_i32_b64/i64`, `s_quadmask_b32/b64`, `s_bitreplicate_b64_b32`, all nine 64-bit scalar bitwise ops on scalar
276 data, `s_movrels_b32/b64`, `v_add/sub/subrev_nc_u32` / `v_add/sub_nc_i32` / `v_add/sub_nc_u16` with `clamp` and
277 `op_sel`, `v_mad_u64_u32` / `v_mad_i64_i32` (`sdst` bit 64 sign of exact 65-bit sum and inactive-EXEC masking),
278 `v_sad_u8`/`hi_u8`/`u16`/`u32`, `v_msad_u8`, `v_lerp_u8`, `v_qsad_pk_u16_u8`, `v_mqsad_pk_u16_u8`, `v_mqsad_u32_u8`,
279 `v_mul_hi_u32_u24`/`i32_i24`, `v_lshrrev_b64`/`v_ashrrev_i64`, `v_mad_u16`/`i16` (`clamp`, `op_sel`, untouched half
280 kept), `v_cvt_f16_u16/i16` and `v_cvt_u16/i16_f16` (`_e64` keeps high half; NaN → 0, ±inf saturates; note GFX10
281 does not accept `op_sel` on these opcodes), `v_cvt_i32_f32` (control: all ±qNaN/±sNaN → 0), and
282 `v_cvt_pknorm_i16/u16_f32` (±qNaN → 0, ±inf saturation, RNE ties at ±0.5).
283- **Live translator divergences confirmed on gfx1035 (5/87, pinned in `KNOWN_DIVERGENCES`):**
284 1. **`v_add_co_u32`, `v_sub_co_u32`, `v_subrev_co_u32`, `v_add_co_ci_u32`, `v_sub_co_ci_u32`, `v_subrev_co_ci_u32`
285 with `clamp`:** hardware saturates `D` (`0xffffffff` on carry, `0x00000000` on borrow) while still reporting the
286 real carry/borrow (`1`) in `sdst`; the translator currently ignores `clamp` on these ops.
287 2. **`v_cvt_rpi_i32_f32` precision:** hardware computes exact `floor(x + 0.5)` without binary32 rounding of `x + 0.5`
288 (`0x3effffff` → `0`, `0x4b000001` → `0x00800001`, `0x4b7fffff` → `0x00ffffff`), whereas the translator rounds
289 `x + 0.5` in f32 first (`1`, `0x00800002`, `0x01000000`).
290 3. **`v_cvt_flr_i32_f32` / `v_cvt_rpi_i32_f32` on NaN:** hardware saturates by the NaN's sign bit (`0x7fc00000` →
291 `0x7fffffff`, `0xffc00000` → `0x80000000`), whereas `v_cvt_i32_f32` gives `0` for every NaN; the translator gives
292 `0` for both `flr` and `rpi`.
293
258Two assembler facts matter when writing edge cases: 294Two assembler facts matter when writing edge cases:
259 295
260- An integer token in a float-operand position uses AMD's inline-constant encoding for values 0..64 296- An integer token in a float-operand position uses AMD's inline-constant encoding for values 0..64
@@ -826,6 +862,22 @@ denormal, 2,810 other not judged. The four MODE settings read back in the kernel
826`0x3c0`, so the float mode of the kernel descriptor reaches the hardware through that launcher as well. 862`0x3c0`, so the float mode of the kernel descriptor reaches the hardware through that launcher as well.
827`--negative-control` catches all six wrong models there (3 to 25 mismatches each). 863`--negative-control` catches all six wrong models there (3 to 25 mismatches each).
828 864
865The same seeds through the Windows HIP launcher (`hw_oracle.c`) on the integrated GPU of a Ryzen 7 9800X3D (gfx1036;
866Windows 10 22H2, AMD driver 32.0.13036.4, `amdhip64_6.dll`, AMD clang 23.0.0git from rocm-sdk-core 10.0.0, main at
86741f44826) give the same counts in every column: 38,858 programs, **28,671 match, 0 mismatch, 56 known deviation**
868(all `omod_neg_zero`), 4,224 skipped, 3,097 denormal, 2,810 other. `--negative-control` again catches all six (3 to
86925 mismatches). Two launchers on two machines and two operating systems agree on the hardware words.
870
871`v_rcp_iflag_f32` (SHADER-136; added to the rcp / rsq / sqrt / exp / log family after the run above, so it is not in
872its counts) on the same gfx1036 through the Windows launcher, `--ops v_rcp_iflag_f32 --programs 1000 --probes 24`,
873seeds 1 to 6: 6,552 programs, **5,971 match, 0 mismatch, 35 known deviation** (`omod_neg_zero`), 279 denormal, 267
874other. It shares `v_rcp_f32`'s model, and the clamp and omod bits behave as on the other ops (summed over the six
875seeds, per MODE setting flush / keep / no_dx10 / ieee): clamp makes a -0 result +0 in every mode (98 each) and a NaN
876result +0 except with DX10_CLAMP off, where the NaN passes (169); omod is applied with IEEE off, including with f32
877denormals kept (461 each; like the other transcendental ops), and ignored with IEEE on (461); a -0 result becomes +0
878under omod (35 each, none with IEEE on); a signalling NaN passes unchanged with IEEE off and is quieted with IEEE on
879(59); denormal operands read as zero and denormal results flush in every mode.
880
829What the hardware answered where the model does not judge (gfx1150; the RDNA2 run above agrees where it is cited): 881What the hardware answered where the model does not judge (gfx1150; the RDNA2 run above agrees where it is cited):
830 882
831- **No model error found.** The model was right wherever it had an answer, in 30,577 programs; the min/max/med3 883- **No model error found.** The model was right wherever it had an answer, in 30,577 programs; the min/max/med3
@@ -962,18 +1014,90 @@ side follows the same rule. Exit 1 means they differ, or a side follows neither
962is unavailable. 1014is unavailable.
963 1015
964`tests/test_fma_mix_probe.py` checks the expected words against a derivation written out by hand. It also checks that 1016`tests/test_fma_mix_probe.py` checks the expected words against a derivation written out by hand. It also checks that
965the translator follows the double rule today, and that the compute shader gives the pixel shader's words on the 1017the translator follows the single rounding rule, and that the compute shader gives the pixel shader's words on the
966interpreter. If the hardware rounds once, the fix is to use `Gen.fma_mix_odd` in nearest mode as well. Round-to-odd at 1018interpreter. Hardware measurement on AMD RDNA2 confirmed that the hardware rounds once, straight to f16, so the translator
967f32 then narrows exactly. With that change the translator gives the single-rounded word on all seven inputs. 1019uses `Gen.fma_mix_odd` in nearest mode as well. Round-to-odd at f32 then narrows exactly, giving the single-rounded word on
1020all seven discriminating inputs.
968 1021
969Results: 1022Results:
970 1023
971| GPU | Driver | `translator` | `vulkan` | `hw` | 1024| GPU | Driver | `translator` | `vulkan` | `hw` |
972|---|---|---|---|---| 1025|---|---|---|---|---|
973| NVIDIA GeForce RTX 5060 (Blackwell), Windows 11 | 621.24 | double | double, 8 of 8 words | not AMD | 1026| NVIDIA GeForce RTX 5060 (Blackwell), Windows 11 | 621.24 | double | double, 8 of 8 words | not AMD |
1027| AMD Radeon iGPU (RDNA2, gfx1036), Windows 11, HIP backend | 32.0.21044.64 | double | not run | **single**, 7 of 7 ties; control `0x4100` |
974 1028
975The `hw` column is still empty: the question needs an RDNA GPU. On the RTX 5060, a translator copy changed to use 1029RDNA2 rounds once. Every tie input gives the single-rounded word (A `0x3c01`, B `0x3c01`, C `0xbc01`, D `0x0001`,
1030E `0x7bff`, F `0x3c01`, G `0x3c01`), so the translator is one f16 ulp off on exactly these inputs (SHADER-135; the
1031translator is not changed here). On the RTX 5060, a translator copy changed to use
976`fma_mix_odd` in nearest mode gave the single-rounded word for all seven inputs on the `vulkan` side as well. 1032`fma_mix_odd` in nearest mode gave the single-rounded word for all seven inputs on the `vulkan` side as well.
1033| NVIDIA GeForce RTX 5060 (Blackwell), Windows 11 | 621.24 | single | single, 8 of 8 words | not AMD |
1034| AMD Radeon gfx1036 (RDNA2), Linux / Windows | | single | single, 8 of 8 words | single, 8 of 8 words |
1035
1036Measurement on AMD RDNA2 (gfx1036) confirmed single rounding across all 7 discriminating cases (finding 7079901079).
1037Using `fma_mix_odd` produces the exact hardware single-rounded words in both nearest-even and toward-zero modes.
1038
1039### f16 output modifiers, clamp and `v_fma_mix*` operands on RDNA2 (SHADER-135)
1040
1041*Measured on an RDNA2 iGPU (gfx1036), AMD Windows driver 32.0.21044.64, HIP backend, AMD clang 23.0.0git, `main`
1042a0acd33d.* Raw kernels written by hand, one lane each. The MODE comes from the kernel descriptor (`ieee`,
1043`dx10_clamp`, `denorm_mode_32`, `denorm_mode_16_64`). Every program writes one word, starting from a destination of
1044`0x5a5a5a5a`, so a half the op must not write shows up. 1,385 programs assembled, each run in wave32 and wave64, and
1045the two wave sizes agree on every word. `tools/fma_mix_probe.py --oracle hw` (the section above) and
1046`tools/f16_trans_sweep.py --ops v_exp_f16,v_log_f16` ran on the same GPU.
1047
1048- **An omod on an f16 result acts only with IEEE 0 and f16 denormals flushed (`denorm_mode_16_64 = 0`).** In that
1049 MODE `mul:2`, `mul:4` and `div:2` scale the results of `v_add_f16`, `v_mul_f16`, `v_fma_f16`, `v_fmac_f16_e64`,
1050 `v_cvt_f16_f32_e64`, `v_exp_f16_e64` and `v_rcp_f16_e64` (`v_fmac_f16_e64` 0.75 · 1 + -0 `mul:4` gives `0x4200`).
1051 With `denorm_mode_16_64 = 3` or IEEE 1 they leave the result as it is (`0x3a00`), and `denorm_mode_32` makes no
1052 difference. The f32 control (`v_add_f32_e64 mul:2`) follows `denorm_mode_32` instead, as on gfx1150 above. Unlike
1053 the f32 transcendentals there, `v_exp_f16` and `v_rcp_f16` obey the same rule as the ALU ops. When the omod acts, a
1054 -0 result becomes +0 (`v_fmac_f16` -0 · 1 + -0 `mul:2` gives `0x0000`), and it comes before the clamp
1055 (`v_cvt_f16_f32_e64` 0.75 `clamp mul:2` gives `0x3c00`, not `0x3e00`).
1056- **clamp** on `v_cvt_f16_f32_e64`, `v_fmac_f16_e64`, `v_fma_mixlo_f16` and `v_fma_mix_f32` clamps to [0, 1] in every
1057 MODE: -0.5 and -0 give +0, 3.0 and an overflow (1e5, 65504 · 2) give 1.0. A NaN gives +0 with DX10_CLAMP 1. With
1058 DX10_CLAMP 0 it stays the NaN the op gives without clamp. This is SHADER-186's f32 rule, here for the f16 results and
1059 the mix ops.
1060- **Constants in `v_fma_mix*` operands.** A float inline constant is the f32 constant where `op_sel_hi` makes the
1061 operand f32, and the f16 constant with a zero high half where it makes it f16. `1.0`, `-1.0`, `0.5`, `2.0` and
1062 `-4.0` give their value either way. `0.15915494` gives `0x3e22f983` as f32 and `0x3118` as f16 (`0x3e230000` once
1063 widened). With `op_sel_hi = 1` and `op_sel = 1`, every float constant reads +0.0. An integer inline constant is its
1064 32-bit integer. As an f32 operand, `1` and `64` are f32 denormals (+0 with `denorm_mode_32 = 0`) and `-1` is the NaN
1065 `0xffffffff`. As an f16 operand, `op_sel` picks a half: `1` gives `0x0001` low and +0 high, and `-1` gives `0xffff`
1066 in both. `op_sel` is ignored for an f32 operand. For gfx10, llvm-mc rejects a 32-bit literal in these ops ("invalid
1067 operand"). It encodes a literal equal to an f16 inline constant, such as `0x3c00`, as that constant (`0xf2`).
1068- **Mix-op denormals follow the mode of their own width.** An f16 operand (`op_sel_hi = 1`) and an f16 result
1069 (`mixlo`/`mixhi`) become a zero of their sign with `denorm_mode_16_64 = 0`, and are kept with 3, whatever
1070 `denorm_mode_32` says. An f32 denormal is flushed with `denorm_mode_32 = 0` and kept with 3.
1071- **Mix-op NaNs.** An f16 NaN operand widens with its payload (`0x7c01` → `0x7f802000`, `0xfe01` → `0xffc02000`).
1072 `v_fma_mix_f32` keeps a signalling NaN, f16 or f32, with IEEE 0, and quiets it with IEEE 1, payload kept
1073 (`0x7f800001` → `0x7fc00001`). `v_fma_mixlo_f16` quiets every NaN in every MODE and keeps the top payload bits
1074 (`0x7c01` → `0x7e01`, `0x7d55` → `0x7f55`, f32 `0x7fa00000` → `0x7f00`, f32 `0x7f800001` → `0x7e00`).
1075- **`v_exp_f16` and `v_log_f16` give gfx1031's counts exactly**, on all 65,536 inputs in the five MODEs of the f16
1076 transcendentals section: 0 ulp on every input that is not a NaN, with f16 denormals kept. With them flushed, 831
1077 `v_exp_f16` results and 1,023 `v_log_f16` operands become zero. Signalling NaNs are quieted only with IEEE 1, and
1078 wave32 = wave64.
1079
1080**The translator against these words.** Each program was translated as a pixel shader and run on
1081`tests/semantic/spirv_mini_interp.py`, then compared with the hardware under the MODE the translator assumes for the
1082game (IEEE 0, DX10_CLAMP 1, f32 denormals flushed, f16 denormals kept). It gives the same word for the float
1083constants in every `op_sel`/`op_sel_hi` combination, for the integer constants as f16 halves, for clamp on values that
1084are not NaN, and for the f16 denormals. It differs in five ways, none fixed here:
1085
10861. **f16 omod.** The translator applies `mul:2`/`mul:4`/`div:2` to every f16 result. The hardware ignores them in this
1087 MODE (24 words: `v_add/mul/fma/fmac/exp/rcp_f16`). `v_cvt_f16_f32` drops its omod and clamp today, so its omod
1088 matches by accident; #718 would make it apply. The two assumptions can't both hold for the game. Either its shaders
1089 run with f16 denormals flushed, and keeping them is wrong, or every f16 omod in them does nothing. A corpus count
1090 of omod on f16 instructions would decide, since a compiler that emits one expects it to act (LLVM folds an omod only
1091 when "output denormals" are off, the `SIFoldOperands.cpp` comment quoted above). That count needs the game files.
10922. **clamp of a NaN.** The interpreter refuses `FClamp` with a NaN operand, which GLSL.std.450 leaves undefined. The
1093 hardware gives +0 with DX10_CLAMP 1, for `v_fmac_f16`, `v_fma_mixlo_f16` and `v_fma_mix_f32` alike (SHADER-186).
10943. **Mix-op rounding.** The hardware rounds once (the section above).
10954. **f32 denormal operands of the mix ops.** They are not flushed with `denorm_mode_32 = 0`: `0x00000001`, `0x807fffff`
1096 and the integer constants `1` and `64` used as f32 give the denormal, where the hardware gives a zero of its sign
1097 (compare SHADER-118 for the mad ops).
10985. **NaN payloads.** Where the hardware keeps the payload and, with IEEE 0, the signalling bit, the translator writes
1099 the canonical quiet NaN (`0x7fc00000`, `0x7e00`). For example, `v_fmac_f16` keeps `0x7c01`. This is the "not
1100 modelled yet" note of the f16 transcendentals row in `docs/design.md`, here for these ops too.
977 1101
978## Coverage plan and cost 1102## Coverage plan and cost
979 1103
diff --git a/docs/testing.md b/docs/testing.md
index 1035d7080..ddf6b642c 100644
--- a/docs/testing.md
+++ b/docs/testing.md
@@ -114,7 +114,7 @@ python -I runtime/test/shaders/build.py <out dir>
114python -I runtime/test/shaders/check.py <out dir> <folder with the test programs> 114python -I runtime/test/shaders/check.py <out dir> <folder with the test programs>
115``` 115```
116 116
117For 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 ignore `VK_LOADER_LAYERS_DISABLE=~implicit~` and can inject unsupported swapchain flags. 117For 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").
118 118
119## The Windows runtime on Linux, under Wine or Proton 119## The Windows runtime on Linux, under Wine or Proton
120 120
@@ -261,6 +261,9 @@ The GPU tools of `runtime/test/shaders` (`vk_compute_test`, `vk_harness`, ...) r
261| Validation errors that only your machine shows (e.g. `xbox_present`'s sRGB swapchain `STORAGE` message), with MSI Afterburner/RivaTuner or OBS installed | An overlay layer that hooks the swapchain: RivaTuner's `VK_LAYER_RTSS` adds `STORAGE` usage to it. On some setups it stays loaded even with `VK_LOADER_LAYERS_DISABLE=~implicit~` | Also set the layer's own switch: `DISABLE_RTSS_LAYER=1`, `DISABLE_VULKAN_OBS_CAPTURE=1` (OBS). Any other layer's switch is the `disable_environment` entry in its manifest (the JSON listed under `HKLM\SOFTWARE\Khronos\Vulkan\ImplicitLayers` or `HKCU\...`). `VK_LOADER_DEBUG=layer` prints the layers that were actually inserted | 261| Validation errors that only your machine shows (e.g. `xbox_present`'s sRGB swapchain `STORAGE` message), with MSI Afterburner/RivaTuner or OBS installed | An overlay layer that hooks the swapchain: RivaTuner's `VK_LAYER_RTSS` adds `STORAGE` usage to it. On some setups it stays loaded even with `VK_LOADER_LAYERS_DISABLE=~implicit~` | Also set the layer's own switch: `DISABLE_RTSS_LAYER=1`, `DISABLE_VULKAN_OBS_CAPTURE=1` (OBS). Any other layer's switch is the `disable_environment` entry in its manifest (the JSON listed under `HKLM\SOFTWARE\Khronos\Vulkan\ImplicitLayers` or `HKCU\...`). `VK_LOADER_DEBUG=layer` prints the layers that were actually inserted |
262| Validation errors without a VUID, or messages from a layer you didn't ask for | An implicit Vulkan layer from other software (Rockstar Social Club, ReShade, MangoHud, an overlay) | Set `VK_LOADER_LAYERS_DISABLE=~implicit~`. Note that third-party overlays (RivaTuner `VK_LAYER_RTSS` from MSI Afterburner, OBS `VK_LAYER_OBS_HOOK`) stay loaded under `~implicit~` and can add `VK_IMAGE_USAGE_STORAGE_BIT` to swapchains; set `DISABLE_RTSS_LAYER=1` and `DISABLE_VULKAN_OBS_CAPTURE=1` to disable them | 262| Validation errors without a VUID, or messages from a layer you didn't ask for | An implicit Vulkan layer from other software (Rockstar Social Club, ReShade, MangoHud, an overlay) | Set `VK_LOADER_LAYERS_DISABLE=~implicit~`. Note that third-party overlays (RivaTuner `VK_LAYER_RTSS` from MSI Afterburner, OBS `VK_LAYER_OBS_HOOK`) stay loaded under `~implicit~` and can add `VK_IMAGE_USAGE_STORAGE_BIT` to swapchains; set `DISABLE_RTSS_LAYER=1` and `DISABLE_VULKAN_OBS_CAPTURE=1` to disable them |
263| False validation failures in `xbox_present` or present tests (e.g. sRGB swapchain `STORAGE` messages) with MSI Afterburner or OBS running | Overlay Vulkan layers (RivaTuner `VK_LAYER_RTSS`, OBS `VK_LAYER_OBS_HOOK`) remain active under `VK_LOADER_LAYERS_DISABLE=~implicit~` and inject `VK_IMAGE_USAGE_STORAGE_BIT` into swapchains | Set `DISABLE_RTSS_LAYER=1` and `DISABLE_VULKAN_OBS_CAPTURE=1` for validation runs | 263| False validation failures in `xbox_present` or present tests (e.g. sRGB swapchain `STORAGE` messages) with MSI Afterburner or OBS running | Overlay Vulkan layers (RivaTuner `VK_LAYER_RTSS`, OBS `VK_LAYER_OBS_HOOK`) remain active under `VK_LOADER_LAYERS_DISABLE=~implicit~` and inject `VK_IMAGE_USAGE_STORAGE_BIT` into swapchains | Set `DISABLE_RTSS_LAYER=1` and `DISABLE_VULKAN_OBS_CAPTURE=1` for validation runs |
264| Validation errors that only your machine shows (e.g. `xbox_present`'s sRGB swapchain `STORAGE` message), with MSI Afterburner/RivaTuner or OBS installed | An overlay layer that hooks the swapchain: while RivaTuner Statistics Server is running, its `VK_LAYER_RTSS` adds `STORAGE` usage to it. In an elevated (administrator) terminal the loader ignores `VK_LOADER_LAYERS_DISABLE` (`VK_LOADER_DEBUG=all` says so), so `~implicit~` leaves the layer in | Run the tests from a normal terminal, close the overlay application, or set the layer's own switch, which works elevated too: `DISABLE_RTSS_LAYER=1`, `DISABLE_VULKAN_OBS_CAPTURE=1` (OBS). Any other layer's switch is the `disable_environment` entry in its manifest (the JSON listed under `HKLM\SOFTWARE\Khronos\Vulkan\ImplicitLayers` or `HKCU\...`). `VK_LOADER_DEBUG=layer` prints the layers that were actually inserted |
265| `vk_sync_validation` fails with `LEONIDA_VK_VALIDATION=1` ("the write-after-write hazard was not reported") | Synchronization validation is off although the tests ask for it: an older layer, or a layer setting such as `VK_KHRONOS_VALIDATION_VALIDATE_SYNC=false` or a `vk_layer_settings.txt` that overrides it. Every other GPU test then reports "0 validation errors" without having been checked | Remove the override or update the Vulkan SDK, then rerun `ctest -R vk_sync_validation` until it passes |
266| Validation errors that only your machine shows (e.g. `xbox_present`'s sRGB swapchain `STORAGE` message), with MSI Afterburner/RivaTuner or OBS installed | An overlay layer that hooks the swapchain: while RivaTuner Statistics Server is running, its `VK_LAYER_RTSS` adds `STORAGE` usage to it. In an elevated (administrator) terminal the loader ignores `VK_LOADER_LAYERS_DISABLE` (`VK_LOADER_DEBUG=all` says so), so `~implicit~` leaves the layer in | Run the tests from a normal terminal, close the overlay application, or set the layer's own switch, which works elevated too: `DISABLE_RTSS_LAYER=1`, `DISABLE_VULKAN_OBS_CAPTURE=1` (OBS). Any other layer's switch is the `disable_environment` entry in its manifest (the JSON listed under `HKLM\SOFTWARE\Khronos\Vulkan\ImplicitLayers` or `HKCU\...`). `VK_LOADER_DEBUG=layer` prints the layers that were actually inserted |
264| Every test crashes inside `libnvidia-eglcore.so` | NVIDIA's 535 server driver (Ubuntu 24.04's default) | Use driver 615 or newer | 267| Every test crashes inside `libnvidia-eglcore.so` | NVIDIA's 535 server driver (Ubuntu 24.04's default) | Use driver 615 or newer |
265| `build.py`: 0 translated, reason `.text` | An old `build.py` with LLVM 19 | Update to current `main` | 268| `build.py`: 0 translated, reason `.text` | An old `build.py` with LLVM 19 | Update to current `main` |
266| `vk_harness` doesn't compile: `VK_KHR_maintenance8` names unknown | Vulkan headers older than the SDK the code was written against | Update to current `main` (the code now builds without it), or use current Khronos Vulkan-Headers; conda-forge's package is too old | 269| `vk_harness` doesn't compile: `VK_KHR_maintenance8` names unknown | Vulkan headers older than the SDK the code was written against | Update to current `main` (the code now builds without it), or use current Khronos Vulkan-Headers; conda-forge's package is too old |
diff --git a/make_game.py b/make_game.py
index ab548f293..cff1068e1 100644
--- a/make_game.py
+++ b/make_game.py
@@ -334,7 +334,19 @@ def choose_game() -> str:
334 print(" That folder isn't a supported version of the game. Try again.") 334 print(" That folder isn't a supported version of the game. Try again.")
335 335
336 336
337def icloud_documents() -> bool:
338 """macOS: whether iCloud Drive holds Desktop & Documents. With that sync on, ~/Documents lives in iCloud Drive,
339 which uploads what goes in it and may evict files from the disk ("Optimize Mac Storage"). The folder can stay in
340 iCloud Drive after the sync is turned off; leaving Documents alone then costs nothing."""
341 return sys.platform == "darwin" and os.path.isdir(
342 os.path.join(os.path.expanduser("~"), "Library", "Mobile Documents", "com~apple~CloudDocs", "Documents"))
343
344
337def default_out() -> str: 345def default_out() -> str:
346 """Documents/Leonida, except on a Mac whose Documents iCloud syncs: the port and its work folder (hundreds of
347 GB made from the game) must stay on this computer, so they go to ~/Leonida there."""
348 if icloud_documents():
349 return os.path.join(os.path.expanduser("~"), "Leonida")
338 return os.path.join(os.path.expanduser("~"), "Documents", "Leonida") 350 return os.path.join(os.path.expanduser("~"), "Documents", "Leonida")
339 351
340 352
@@ -752,7 +764,11 @@ def fallback_flags(a) -> tuple[str, ...]:
752def smallest_max_subgroup(vulkaninfo_text: str): 764def smallest_max_subgroup(vulkaninfo_text: str):
753 """The smallest maxSubgroupSize vulkaninfo reports over all devices (text or --json output), or None.""" 765 """The smallest maxSubgroupSize vulkaninfo reports over all devices (text or --json output), or None."""
754 size = r'maxSubgroupSize"?\s*[=:]\s*(\d+)' 766 size = r'maxSubgroupSize"?\s*[=:]\s*(\d+)'
755 starts = [m.start() for m in re.finditer(r'deviceName"?\s*[=:]', vulkaninfo_text)] 767 # A device's own name is the least indented one; deeper ones (VK_KHR_maintenance7's layered APIs, e.g.
768 # MoltenVK's Metal device, in both the text and the --json output) belong to the device above them.
769 names = list(re.finditer(r'(?m)^([ \t]*)"?deviceName"?\s*[=:]', vulkaninfo_text))
770 depth = min((len(m.group(1)) for m in names), default=0)
771 starts = [m.start() for m in names if len(m.group(1)) == depth]
756 if not starts: 772 if not starts:
757 sizes = [int(n) for n in re.findall(size, vulkaninfo_text)] 773 sizes = [int(n) for n in re.findall(size, vulkaninfo_text)]
758 return min(sizes) if sizes else None 774 return min(sizes) if sizes else None
@@ -790,6 +806,16 @@ def wave64_emulate(mode: str) -> bool:
790 "(exact on every GPU; --wave64-emulate off to skip it on a GPU with 64-wide subgroups)") 806 "(exact on every GPU; --wave64-emulate off to skip it on a GPU with 64-wide subgroups)")
791 return True 807 return True
792 on = size < 64 808 on = size < 64
809 if on:
810 gpu = runtime_gpu_info()
811 if gpu.get("rdna2_amd_windows") and gpu.get("native64"):
812 # #857: AMD's Windows compiler for RDNA2 crashes creating many emulated LDS compute pipelines. The
813 # runtime runs on this GPU, which takes wave64 natively, so the 32-wide device (an Intel iGPU next to
814 # an RX 6000 card, say) gets native wave64 modules it isn't used for.
815 log(f"shaders: smallest maximum subgroup size is {size}, but the runtime's GPU ({gpu.get('device', '?')}) "
816 "is RDNA2 on the AMD Windows driver, whose shader compiler crashes on emulated wave64 code (#857), "
817 "and runs wave64 natively: wave64 emulation off (--wave64-emulate on to force it)")
818 return False
793 if not on and runtime_gpu_native64() is False: 819 if not on and runtime_gpu_native64() is False:
794 log(f"shaders: smallest maximum subgroup size is {size}, but the Vulkan query found no 64-wide path for both " 820 log(f"shaders: smallest maximum subgroup size is {size}, but the Vulkan query found no 64-wide path for both "
795 "compute and mesh (fixed default size or required-size control): wave64 emulation on") 821 "compute and mesh (fixed default size or required-size control): wave64 emulation on")
@@ -810,6 +836,17 @@ def runtime_gpu_native64():
810 return None 836 return None
811 837
812 838
839def runtime_gpu_info() -> dict:
840 """tools/vk_subgroup_info.py's answer for the GPU the runtime would use; {} when it can't tell."""
841 try:
842 r = subprocess.run([sys.executable, "-I", os.path.join(TOOLS, "vk_subgroup_info.py")],
843 capture_output=True, text=True, timeout=60)
844 info = json.loads(r.stdout.strip().splitlines()[-1])
845 return info if isinstance(info, dict) and "error" not in info else {}
846 except (OSError, ValueError, IndexError, subprocess.SubprocessError):
847 return {}
848
849
813def runtime_gpu_per_vertex(): 850def runtime_gpu_per_vertex():
814 """per_vertex_inputs as tools/vk_subgroup_info.py answers for the GPU the runtime would use: False where the 851 """per_vertex_inputs as tools/vk_subgroup_info.py answers for the GPU the runtime would use: False where the
815 driver can't compile PerVertexKHR (MoltenVK) or lacks fragmentShaderBarycentric, None when it can't tell.""" 852 driver can't compile PerVertexKHR (MoltenVK) or lacks fragmentShaderBarycentric, None when it can't tell."""
@@ -1210,7 +1247,8 @@ def main() -> int:
1210 ap = argparse.ArgumentParser(description="Build the PC port from your own copy of the game.") 1247 ap = argparse.ArgumentParser(description="Build the PC port from your own copy of the game.")
1211 ap.add_argument("--game", help="your package folder (found automatically if left out)") 1248 ap.add_argument("--game", help="your package folder (found automatically if left out)")
1212 ap.add_argument("--pick", action="store_true", help="choose your package folder in a folder dialog") 1249 ap.add_argument("--pick", action="store_true", help="choose your package folder in a folder dialog")
1213 ap.add_argument("--out", help="folder for the finished port (default Documents/Leonida)") 1250 ap.add_argument("--out", help="folder for the finished port (default Documents/Leonida; ~/Leonida on a Mac "
1251 "whose Documents iCloud syncs)")
1214 ap.add_argument("--work", help="folder for intermediate files (hundreds of GB; default <out>/work)") 1252 ap.add_argument("--work", help="folder for intermediate files (hundreds of GB; default <out>/work)")
1215 ap.add_argument("--stages", help="comma list from: " + ",".join(STAGES)) 1253 ap.add_argument("--stages", help="comma list from: " + ",".join(STAGES))
1216 ap.add_argument("--check", action="store_true", help="only check the game files") 1254 ap.add_argument("--check", action="store_true", help="only check the game files")
@@ -1311,6 +1349,8 @@ def main() -> int:
1311 fallbacks = fallback_flags(a) if "shaders" in stages else () 1349 fallbacks = fallback_flags(a) if "shaders" in stages else ()
1312 preflight(stages, work, a.wav, runtime_build, emulate=emulate, keep_emulated=keep_emulated, 1350 preflight(stages, work, a.wav, runtime_build, emulate=emulate, keep_emulated=keep_emulated,
1313 fallbacks=fallbacks, jobs=a.jobs) 1351 fallbacks=fallbacks, jobs=a.jobs)
1352 if not a.out and icloud_documents():
1353 log("iCloud syncs Documents on this Mac: building into ~/Leonida instead, so the game's files stay off iCloud")
1314 log(f"building into {out} (work files in {work})") 1354 log(f"building into {out} (work files in {work})")
1315 t0 = time.time() 1355 t0 = time.time()
1316 if "shaders" in stages: 1356 if "shaders" in stages:
diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt
index 6ea698f38..2fb2c2fd4 100644
--- a/runtime/CMakeLists.txt
+++ b/runtime/CMakeLists.txt
@@ -394,10 +394,20 @@ if(BUILD_TESTING)
394 set_target_properties(tiny_game PROPERTIES 394 set_target_properties(tiny_game PROPERTIES
395 RUNTIME_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/fixtures/game/$<CONFIG>" 395 RUNTIME_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/fixtures/game/$<CONFIG>"
396 ) 396 )
397 # The same game with no .reloc, at the default EXE base, as RT-22 asks about the real one: it can only run at
398 # 0x140000000, which arm64 Wine on macOS uses for itself (src/base_reservation.h).
399 add_executable(tiny_game_fixed test/fixtures/tiny_game.cpp)
400 target_link_libraries(tiny_game_fixed PRIVATE xgameruntime_stub)
401 target_compile_definitions(tiny_game_fixed PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX _CRT_SECURE_NO_WARNINGS)
402 target_compile_options(tiny_game_fixed PRIVATE /W4 /permissive- /utf-8 /EHsc)
403 target_link_options(tiny_game_fixed PRIVATE /FIXED /DYNAMICBASE:NO /BASE:0x140000000)
404 set_target_properties(tiny_game_fixed PROPERTIES
405 RUNTIME_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/fixtures/game/$<CONFIG>"
406 )
397 add_executable(tiny_game_exit_code_test test/tiny_game_exit_code_test.cpp) 407 add_executable(tiny_game_exit_code_test test/tiny_game_exit_code_test.cpp)
398 target_compile_definitions(tiny_game_exit_code_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) 408 target_compile_definitions(tiny_game_exit_code_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX)
399 target_compile_options(tiny_game_exit_code_test PRIVATE /W4 /permissive- /utf-8) 409 target_compile_options(tiny_game_exit_code_test PRIVATE /W4 /permissive- /utf-8)
400 add_dependencies(tiny_game_exit_code_test gta6rt tiny_game) 410 add_dependencies(tiny_game_exit_code_test gta6rt tiny_game tiny_game_fixed)
401 add_test(NAME pe_loader COMMAND pe_loader_test "$<TARGET_FILE:tiny_dll>" "$<TARGET_FILE:tiny_exe>") 411 add_test(NAME pe_loader COMMAND pe_loader_test "$<TARGET_FILE:tiny_dll>" "$<TARGET_FILE:tiny_exe>")
402 412
403 # Synthetic, hand-built images through Loader::load: range checks, wrapping RVAs, import-table termination and 413 # Synthetic, hand-built images through Loader::load: range checks, wrapping RVAs, import-table termination and
@@ -499,6 +509,11 @@ if(BUILD_TESTING)
499 add_test(NAME descriptor_table COMMAND descriptor_table_test) 509 add_test(NAME descriptor_table COMMAND descriptor_table_test)
500 add_executable(shader_library_test test/shader_library_test.cpp) 510 add_executable(shader_library_test test/shader_library_test.cpp)
501 add_test(NAME shader_library COMMAND shader_library_test) 511 add_test(NAME shader_library COMMAND shader_library_test)
512 # Optional: skips unless LEONIDA_SHADERS names a translated work folder (<work>/shaders/spirv).
513 add_executable(shader_library_corpus_test test/shader_library_corpus_test.cpp)
514 add_test(NAME shader_library_corpus COMMAND shader_library_corpus_test)
515 # Reads all 26,503 containers and modules: about 9 minutes from a hard disk.
516 set_tests_properties(shader_library_corpus PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 3600)
502 if(WIN32) 517 if(WIN32)
503 # Optional: skips unless LEONIDA_GAME_DIR and LEONIDA_MOVIE are set. 518 # Optional: skips unless LEONIDA_GAME_DIR and LEONIDA_MOVIE are set.
504 add_executable(bink_decode_test 519 add_executable(bink_decode_test
@@ -595,6 +610,11 @@ if(BUILD_TESTING)
595 add_test(NAME run_tiny_game COMMAND gta6rt --run $<TARGET_FILE:tiny_game> -- hello 42) 610 add_test(NAME run_tiny_game COMMAND gta6rt --run $<TARGET_FILE:tiny_game> -- hello 42)
596 add_test(NAME run_tiny_game_exit_code COMMAND tiny_game_exit_code_test 611 add_test(NAME run_tiny_game_exit_code COMMAND tiny_game_exit_code_test
597 "$<TARGET_FILE:gta6rt>" "$<TARGET_FILE:tiny_game>") 612 "$<TARGET_FILE:gta6rt>" "$<TARGET_FILE:tiny_game>")
613 # Without relocations it can only run at 0x140000000 (base_reservation.h), so passing means it got there; the
614 # game's exact exit code comes back through the relaunch.
615 add_test(NAME run_tiny_game_fixed COMMAND gta6rt --run $<TARGET_FILE:tiny_game_fixed> -- hello 42)
616 add_test(NAME run_tiny_game_fixed_exit_code COMMAND tiny_game_exit_code_test
617 "$<TARGET_FILE:gta6rt>" "$<TARGET_FILE:tiny_game_fixed>")
598 # Two modes at once are refused before anything is mapped (#886). The stand-in game's own arguments are passed, 618 # Two modes at once are refused before anything is mapped (#886). The stand-in game's own arguments are passed,
599 # so a gta6rt that ignored the conflict would run it, print "running" and exit 0. 619 # so a gta6rt that ignored the conflict would run it, print "running" and exit 0.
600 foreach(modes "dry-run;run" "dry-run;init" "init;run") 620 foreach(modes "dry-run;run" "dry-run;init" "init;run")
@@ -677,6 +697,11 @@ if(TARGET Vulkan::Headers)
677 endif() 697 endif()
678 endforeach() 698 endforeach()
679 if(BUILD_TESTING) 699 if(BUILD_TESTING)
700 add_test(NAME vk_pipeline_check_cli COMMAND "${CMAKE_COMMAND}"
701 "-DTOOL=$<TARGET_FILE:vk_pipeline_check>"
702 "-DTEST_DIR=${CMAKE_CURRENT_BINARY_DIR}/vk_pipeline_check_cli_input"
703 "-DRUNNER=${CMAKE_CROSSCOMPILING_EMULATOR}"
704 -P "${CMAKE_CURRENT_SOURCE_DIR}/test/check_vk_pipeline_cli.cmake")
680 add_test(NAME depth24_convert COMMAND depth24_convert_test) 705 add_test(NAME depth24_convert COMMAND depth24_convert_test)
681 set_tests_properties(depth24_convert PROPERTIES SKIP_RETURN_CODE 77) 706 set_tests_properties(depth24_convert PROPERTIES SKIP_RETURN_CODE 77)
682 # The XDXR BVH builder: the GPU writes every case, then tools/xdxr_bvh.py validates and traces them. 707 # The XDXR BVH builder: the GPU writes every case, then tools/xdxr_bvh.py validates and traces them.
@@ -691,6 +716,37 @@ if(TARGET Vulkan::Headers)
691 set_tests_properties(xdxr_build_check PROPERTIES FIXTURES_REQUIRED xdxr_build_cases SKIP_RETURN_CODE 77) 716 set_tests_properties(xdxr_build_check PROPERTIES FIXTURES_REQUIRED xdxr_build_cases SKIP_RETURN_CODE 77)
692 endif() 717 endif()
693 endif() 718 endif()
719 # VulkanQueue/VulkanContext query-state synchronization (remove_query_pool vs commit, cross-queue plan/commit)
720 # and pending Wait() preservation across transient vkQueueSubmit failures.
721 add_executable(vk_queue_query_sync_test test/vk_queue_query_sync_test.cpp)
722 target_link_libraries(vk_queue_query_sync_test PRIVATE Vulkan::Headers ${CMAKE_DL_LIBS})
723 if(WIN32)
724 target_compile_definitions(vk_queue_query_sync_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX)
725 else()
726 find_package(Threads REQUIRED)
727 target_link_libraries(vk_queue_query_sync_test PRIVATE Threads::Threads)
728 endif()
729 if(MSVC)
730 target_compile_options(vk_queue_query_sync_test PRIVATE /W4 /permissive- /utf-8)
731 endif()
732 if(BUILD_TESTING)
733 add_test(NAME vk_queue_query_sync COMMAND vk_queue_query_sync_test)
734 set_tests_properties(vk_queue_query_sync PROPERTIES SKIP_RETURN_CODE 77)
735 endif()
736 # With LEONIDA_VK_VALIDATION=1: synchronization validation reports a missing barrier (and not a present one), so
737 # the other GPU tests' "0 validation errors" was checked by an active layer. 77 without validation or a device.
738 add_executable(vk_sync_validation_selftest test/vk_sync_validation_selftest.cpp)
739 target_link_libraries(vk_sync_validation_selftest PRIVATE Vulkan::Headers ${CMAKE_DL_LIBS})
740 if(WIN32)
741 target_compile_definitions(vk_sync_validation_selftest PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX)
742 endif()
743 if(MSVC)
744 target_compile_options(vk_sync_validation_selftest PRIVATE /W4 /permissive- /utf-8)
745 endif()
746 if(BUILD_TESTING)
747 add_test(NAME vk_sync_validation COMMAND vk_sync_validation_selftest)
748 set_tests_properties(vk_sync_validation PROPERTIES SKIP_RETURN_CODE 77)
749 endif()
694 if(NOT Vulkan_GLSLANG_VALIDATOR_EXECUTABLE) 750 if(NOT Vulkan_GLSLANG_VALIDATOR_EXECUTABLE)
695 find_program(Vulkan_GLSLANG_VALIDATOR_EXECUTABLE glslangValidator HINTS "$ENV{VULKAN_SDK}/Bin" "$ENV{VULKAN_SDK}/bin") 751 find_program(Vulkan_GLSLANG_VALIDATOR_EXECUTABLE glslangValidator HINTS "$ENV{VULKAN_SDK}/Bin" "$ENV{VULKAN_SDK}/bin")
696 endif() 752 endif()
@@ -722,6 +778,19 @@ if(TARGET Vulkan::Headers)
722 if(BUILD_TESTING) 778 if(BUILD_TESTING)
723 add_test(NAME vk_device_pick COMMAND vk_device_pick_test) 779 add_test(NAME vk_device_pick COMMAND vk_device_pick_test)
724 endif() 780 endif()
781 # Committed BC* texture zero-initialization via vk.zero_buffer or vk.copy_scratch (D3D-220).
782 add_executable(vk_bc_zero_init_test test/vk_bc_zero_init_test.cpp)
783 target_link_libraries(vk_bc_zero_init_test PRIVATE Vulkan::Headers ${CMAKE_DL_LIBS})
784 if(WIN32)
785 target_compile_definitions(vk_bc_zero_init_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX)
786 endif()
787 if(MSVC)
788 target_compile_options(vk_bc_zero_init_test PRIVATE /W4 /permissive- /utf-8)
789 endif()
790 if(BUILD_TESTING)
791 add_test(NAME vk_bc_zero_init COMMAND vk_bc_zero_init_test)
792 set_tests_properties(vk_bc_zero_init PROPERTIES SKIP_RETURN_CODE 77)
793 endif()
725 # CPU-only: the bindless set's array sizes from synthetic device limits. 794 # CPU-only: the bindless set's array sizes from synthetic device limits.
726 add_executable(bindless_sizing_test test/bindless_sizing_test.cpp) 795 add_executable(bindless_sizing_test test/bindless_sizing_test.cpp)
727 target_link_libraries(bindless_sizing_test PRIVATE Vulkan::Headers) 796 target_link_libraries(bindless_sizing_test PRIVATE Vulkan::Headers)
@@ -820,6 +889,8 @@ if(TARGET Vulkan::Headers)
820 target_compile_options(d3d12_queue_wait_test PRIVATE /W4 /permissive- /utf-8) 889 target_compile_options(d3d12_queue_wait_test PRIVATE /W4 /permissive- /utf-8)
821 add_test(NAME d3d12_queue_wait COMMAND d3d12_queue_wait_test) 890 add_test(NAME d3d12_queue_wait COMMAND d3d12_queue_wait_test)
822 set_tests_properties(d3d12_queue_wait PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 20) 891 set_tests_properties(d3d12_queue_wait PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 20)
892 add_test(NAME d3d12_queue_wait_timeout COMMAND d3d12_queue_wait_test --timeout-control)
893 set_tests_properties(d3d12_queue_wait_timeout PROPERTIES SKIP_RETURN_CODE 77 WILL_FAIL TRUE TIMEOUT 10)
823 894
824 # XDXR acceleration structures through BuildRaytracingAccelerationStructure (docs/d3d12_vulkan.md 4.8): the 895 # XDXR acceleration structures through BuildRaytracingAccelerationStructure (docs/d3d12_vulkan.md 4.8): the
825 # device builds them, tools/xdxr_bvh.py checks them. 896 # device builds them, tools/xdxr_bvh.py checks them.
@@ -928,6 +999,14 @@ if(TARGET Vulkan::Headers)
928 target_compile_options(queue_proxy_test PRIVATE /W4 /permissive- /utf-8) 999 target_compile_options(queue_proxy_test PRIVATE /W4 /permissive- /utf-8)
929 add_test(NAME queue_proxy COMMAND queue_proxy_test) 1000 add_test(NAME queue_proxy COMMAND queue_proxy_test)
930 set_tests_properties(queue_proxy PROPERTIES SKIP_RETURN_CODE 77) 1001 set_tests_properties(queue_proxy PROPERTIES SKIP_RETURN_CODE 77)
1002 # Xbox-ABI command allocator proxies (device slot 9) on the Vulkan device, and the unwrapped PC allocator on the
1003 # host runtime: forwarding, refused tail, guard region, lists and GPU copies on the proxy. 77: no device at all.
1004 add_executable(allocator_proxy_test test/allocator_proxy_test.cpp)
1005 target_link_libraries(allocator_proxy_test PRIVATE gta6rt_d3d12_com d3d12 dxgi)
1006 target_compile_definitions(allocator_proxy_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX)
1007 target_compile_options(allocator_proxy_test PRIVATE /W4 /permissive- /utf-8)
1008 add_test(NAME allocator_proxy COMMAND allocator_proxy_test)
1009 set_tests_properties(allocator_proxy PROPERTIES SKIP_RETURN_CODE 77)
931 # The countdown behind those event-backed waits, with no GPU: the full unsigned count, no wrap past zero. 1010 # The countdown behind those event-backed waits, with no GPU: the full unsigned count, no wrap past zero.
932 add_executable(d3d12_fence_waiter_test test/d3d12_fence_waiter_test.cpp) 1011 add_executable(d3d12_fence_waiter_test test/d3d12_fence_waiter_test.cpp)
933 target_compile_definitions(d3d12_fence_waiter_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) 1012 target_compile_definitions(d3d12_fence_waiter_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX)
@@ -1066,7 +1145,7 @@ if(TARGET Vulkan::Headers)
1066 add_custom_command( 1145 add_custom_command(
1067 OUTPUT ${LEONIDA_M15_FILES} 1146 OUTPUT ${LEONIDA_M15_FILES}
1068 COMMAND ${CMAKE_COMMAND} -E remove_directory ${LEONIDA_M15_DIR} 1147 COMMAND ${CMAKE_COMMAND} -E remove_directory ${LEONIDA_M15_DIR}
1069 COMMAND ${CMAKE_COMMAND} -E env "LLVM_MC=${LEONIDA_LLVM_MC}" "PATH=${LEONIDA_SPIRV_TOOLS_NATIVE};$ENV{PATH}" 1148 COMMAND ${CMAKE_COMMAND} -E env "LLVM_MC=${LEONIDA_LLVM_MC}" "LEONIDA_SPIRV_TOOLS=${LEONIDA_SPIRV_TOOLS_NATIVE}"
1070 $<TARGET_FILE:Python3::Interpreter> -I ${CMAKE_CURRENT_SOURCE_DIR}/test/shaders/build.py 1149 $<TARGET_FILE:Python3::Interpreter> -I ${CMAKE_CURRENT_SOURCE_DIR}/test/shaders/build.py
1071 ${LEONIDA_M15_DIR} vs_m15 ps_m15 1150 ${LEONIDA_M15_DIR} vs_m15 ps_m15
1072 DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/test/shaders/build.py 1151 DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/test/shaders/build.py
@@ -1094,7 +1173,7 @@ if(TARGET Vulkan::Headers)
1094 add_custom_command( 1173 add_custom_command(
1095 OUTPUT ${LEONIDA_M2_FILES} 1174 OUTPUT ${LEONIDA_M2_FILES}
1096 COMMAND ${CMAKE_COMMAND} -E remove_directory ${LEONIDA_M2_DIR} 1175 COMMAND ${CMAKE_COMMAND} -E remove_directory ${LEONIDA_M2_DIR}
1097 COMMAND ${CMAKE_COMMAND} -E env "LLVM_MC=${LEONIDA_LLVM_MC}" "PATH=${LEONIDA_SPIRV_TOOLS_NATIVE};$ENV{PATH}" 1176 COMMAND ${CMAKE_COMMAND} -E env "LLVM_MC=${LEONIDA_LLVM_MC}" "LEONIDA_SPIRV_TOOLS=${LEONIDA_SPIRV_TOOLS_NATIVE}"
1098 $<TARGET_FILE:Python3::Interpreter> -I ${CMAKE_CURRENT_SOURCE_DIR}/test/shaders/build.py 1177 $<TARGET_FILE:Python3::Interpreter> -I ${CMAKE_CURRENT_SOURCE_DIR}/test/shaders/build.py
1099 ${LEONIDA_M2_DIR} vs_m2 ps_m2 ps_m2_uoff 1178 ${LEONIDA_M2_DIR} vs_m2 ps_m2 ps_m2_uoff
1100 DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/test/shaders/build.py 1179 DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/test/shaders/build.py
@@ -1124,7 +1203,7 @@ if(TARGET Vulkan::Headers)
1124 add_custom_command( 1203 add_custom_command(
1125 OUTPUT ${LEONIDA_M3_FILES} 1204 OUTPUT ${LEONIDA_M3_FILES}
1126 COMMAND ${CMAKE_COMMAND} -E remove_directory ${LEONIDA_M3_DIR} 1205 COMMAND ${CMAKE_COMMAND} -E remove_directory ${LEONIDA_M3_DIR}
1127 COMMAND ${CMAKE_COMMAND} -E env "LLVM_MC=${LEONIDA_LLVM_MC}" "PATH=${LEONIDA_SPIRV_TOOLS_NATIVE};$ENV{PATH}" 1206 COMMAND ${CMAKE_COMMAND} -E env "LLVM_MC=${LEONIDA_LLVM_MC}" "LEONIDA_SPIRV_TOOLS=${LEONIDA_SPIRV_TOOLS_NATIVE}"
1128 $<TARGET_FILE:Python3::Interpreter> -I ${CMAKE_CURRENT_SOURCE_DIR}/test/shaders/build.py 1207 $<TARGET_FILE:Python3::Interpreter> -I ${CMAKE_CURRENT_SOURCE_DIR}/test/shaders/build.py
1129 ${LEONIDA_M3_DIR} vs_m3 ps_m3 vs_m2 ps_m3_post 1208 ${LEONIDA_M3_DIR} vs_m3 ps_m3 vs_m2 ps_m3_post
1130 DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/test/shaders/build.py 1209 DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/test/shaders/build.py
@@ -1158,7 +1237,9 @@ if(TARGET Vulkan::Headers)
1158 target_compile_definitions(d3d12_indirect_zero_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) 1237 target_compile_definitions(d3d12_indirect_zero_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX)
1159 target_compile_options(d3d12_indirect_zero_test PRIVATE /W4 /permissive- /utf-8) 1238 target_compile_options(d3d12_indirect_zero_test PRIVATE /W4 /permissive- /utf-8)
1160 add_test(NAME d3d12_indirect_zero COMMAND d3d12_indirect_zero_test) 1239 add_test(NAME d3d12_indirect_zero COMMAND d3d12_indirect_zero_test)
1240 set_tests_properties(d3d12_indirect_zero PROPERTIES SKIP_RETURN_CODE 77)
1161 set_tests_properties(d3d12_node_mask PROPERTIES SKIP_RETURN_CODE 77) 1241 set_tests_properties(d3d12_node_mask PROPERTIES SKIP_RETURN_CODE 77)
1242 set_tests_properties(d3d12_indirect_zero PROPERTIES SKIP_RETURN_CODE 77)
1162 1243
1163 # CopyResource / CopyTextureRegion between BC and its uncompressed equivalent (and depth <-> colour) against the 1244 # CopyResource / CopyTextureRegion between BC and its uncompressed equivalent (and depth <-> colour) against the
1164 # host runtime and WARP; run explicitly on a Vulkan GPU. 1245 # host runtime and WARP; run explicitly on a Vulkan GPU.
@@ -1280,9 +1361,82 @@ if(TARGET Vulkan::Headers)
1280 target_compile_options(d3d12_draw_test PRIVATE /W4 /permissive- /utf-8) 1361 target_compile_options(d3d12_draw_test PRIVATE /W4 /permissive- /utf-8)
1281 add_test(NAME d3d12_draw COMMAND d3d12_draw_test) 1362 add_test(NAME d3d12_draw COMMAND d3d12_draw_test)
1282 set_tests_properties(d3d12_draw PROPERTIES SKIP_RETURN_CODE 77) 1363 set_tests_properties(d3d12_draw PROPERTIES SKIP_RETURN_CODE 77)
1364 # Set 0 from the compute bind point: a compute PSO whose shader declares set-0 bindings samples through the
1365 # device's bindless set, which nothing but the layer binds.
1366 set(LEONIDA_TEST_CS_SET0_SAMPLE ${CMAKE_CURRENT_BINARY_DIR}/generated/cs_set0_sample.spv)
1367 add_custom_command(
1368 OUTPUT ${LEONIDA_TEST_CS_SET0_SAMPLE}
1369 COMMAND ${Vulkan_GLSLANG_VALIDATOR_EXECUTABLE} -V --target-env vulkan1.3 -o ${LEONIDA_TEST_CS_SET0_SAMPLE}
1370 ${CMAKE_CURRENT_SOURCE_DIR}/test/glsl/cs_set0_sample.comp
1371 DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/test/glsl/cs_set0_sample.comp
1372 COMMENT "Compiling the set-0 compute test shader"
1373 VERBATIM)
1374 add_executable(d3d12_set0_compute_test test/d3d12_set0_compute_test.cpp shims/d3d12_xs_device.cpp
1375 ${LEONIDA_TEST_CS_SET0_SAMPLE})
1376 target_link_libraries(d3d12_set0_compute_test PRIVATE gta6rt_d3d12_com)
1377 target_compile_definitions(d3d12_set0_compute_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX
1378 LEONIDA_TEST_CS_SET0_SAMPLE_SPV="${LEONIDA_TEST_CS_SET0_SAMPLE}")
1379 target_compile_options(d3d12_set0_compute_test PRIVATE /W4 /permissive- /utf-8)
1380 add_test(NAME d3d12_set0_compute COMMAND d3d12_set0_compute_test)
1381 set_tests_properties(d3d12_set0_compute PROPERTIES SKIP_RETURN_CODE 77)
1382 else()
1383 message(STATUS "glslangValidator not found: d3d12_compute_test, d3d12_draw_test and d3d12_set0_compute_test are not built")
1384 endif()
1385
1386 # Subgroup size control in PSOs, end to end: runtime/test/shaders/cs_w64x_readlane.asm translated natively and with
1387 # --wave64-emulate, and cs_wqm_w32.asm, built here with tools/rdna2spirv.py through test/shaders/build.py. Needs
1388 # llvm-mc with the AMDGPU target (LLVM_MC in the environment, as for the other shader tests, or llvm-mc on PATH)
1389 # and the Vulkan SDK's spirv tools; without them the test is not built.
1390 if(DEFINED ENV{LLVM_MC})
1391 set(LEONIDA_LLVM_MC "$ENV{LLVM_MC}")
1392 else()
1393 find_program(LEONIDA_LLVM_MC llvm-mc HINTS "C:/msys64/ucrt64/bin")
1394 endif()
1395 if(LEONIDA_LLVM_MC AND Vulkan_GLSLANG_VALIDATOR_EXECUTABLE)
1396 set(LEONIDA_SG_DIR ${CMAKE_CURRENT_BINARY_DIR}/generated/subgroup_shaders)
1397 set(LEONIDA_SG_INDEXES "")
1398 foreach(case "w64_native;cs_w64x_readlane;0" "w64_emulated;cs_w64x_readlane;1" "w32_native;cs_wqm_w32;0"
1399 "ps_w64_native;ps_w64x_readlane;0")
1400 list(GET case 0 folder)
1401 list(GET case 1 shader)
1402 list(GET case 2 emulate)
1403 set(index ${LEONIDA_SG_DIR}/${folder}/spirv/index.json)
1404 add_custom_command(
1405 OUTPUT ${index}
1406 COMMAND ${CMAKE_COMMAND} -E env LLVM_MC=${LEONIDA_LLVM_MC} LEONIDA_W64_EMULATE=${emulate}
1407 $<TARGET_FILE:Python3::Interpreter> -I ${CMAKE_CURRENT_SOURCE_DIR}/test/shaders/build.py
1408 ${LEONIDA_SG_DIR}/${folder} ${shader}
1409 DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/test/shaders/build.py
1410 ${CMAKE_CURRENT_SOURCE_DIR}/test/shaders/${shader}.asm
1411 ${CMAKE_CURRENT_SOURCE_DIR}/../tools/rdna2spirv.py
1412 COMMENT "Translating ${shader} for the subgroup size test (${folder})"
1413 VERBATIM)
1414 list(APPEND LEONIDA_SG_INDEXES ${index})
1415 endforeach()
1416 # The probe shaders that store the subgroup size the driver ran them with, and a one-triangle vertex shader.
1417 foreach(source cs_sg_probe.comp ps_sg_probe.frag vs_sg_fullscreen.vert)
1418 set(output ${LEONIDA_SG_DIR}/glsl/${source}.spv)
1419 add_custom_command(
1420 OUTPUT ${output}
1421 COMMAND ${CMAKE_COMMAND} -E make_directory ${LEONIDA_SG_DIR}/glsl
1422 COMMAND ${Vulkan_GLSLANG_VALIDATOR_EXECUTABLE} -V --target-env vulkan1.3 -o ${output}
1423 ${CMAKE_CURRENT_SOURCE_DIR}/test/glsl/${source}
1424 DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/test/glsl/${source}
1425 COMMENT "Compiling ${source}"
1426 VERBATIM)
1427 list(APPEND LEONIDA_SG_INDEXES ${output})
1428 endforeach()
1429 add_executable(d3d12_subgroup_test test/d3d12_subgroup_test.cpp shims/d3d12_xs_device.cpp ${LEONIDA_SG_INDEXES})
1430 target_link_libraries(d3d12_subgroup_test PRIVATE gta6rt_d3d12_com)
1431 target_compile_definitions(d3d12_subgroup_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX
1432 LEONIDA_TEST_SUBGROUP_SHADERS="${LEONIDA_SG_DIR}")
1433 target_compile_options(d3d12_subgroup_test PRIVATE /W4 /permissive- /utf-8)
1434 add_test(NAME d3d12_subgroup COMMAND d3d12_subgroup_test)
1435 set_tests_properties(d3d12_subgroup PROPERTIES SKIP_RETURN_CODE 77)
1283 else() 1436 else()
1284 message(STATUS "glslangValidator not found: d3d12_compute_test and d3d12_draw_test are not built") 1437 message(STATUS "llvm-mc (set LLVM_MC) or glslangValidator not found: d3d12_subgroup_test is not built")
1285 endif() 1438 endif()
1439
1286 # The loader can create this device instead of the host's (D3D12XboxCreateDevice, LEONIDA_D3D12=vulkan). 1440 # The loader can create this device instead of the host's (D3D12XboxCreateDevice, LEONIDA_D3D12=vulkan).
1287 if(TARGET gta6rt) 1441 if(TARGET gta6rt)
1288 target_link_libraries(gta6rt PRIVATE gta6rt_d3d12_com) 1442 target_link_libraries(gta6rt PRIVATE gta6rt_d3d12_com)
@@ -1392,6 +1546,10 @@ if(TARGET Vulkan::Headers)
1392 endif() 1546 endif()
1393 add_test(NAME replay_cpu_bench_selftest COMMAND replay_cpu_bench --self-test) 1547 add_test(NAME replay_cpu_bench_selftest COMMAND replay_cpu_bench --self-test)
1394 add_test(NAME vk_descriptor_bench_selftest COMMAND vk_descriptor_bench --self-test) 1548 add_test(NAME vk_descriptor_bench_selftest COMMAND vk_descriptor_bench --self-test)
1549 # The subgroup size a pipeline stage asks for, from synthetic index entries and device properties.
1550 add_executable(subgroup_size_test test/subgroup_size_test.cpp)
1551 target_link_libraries(subgroup_size_test PRIVATE Vulkan::Headers)
1552 add_test(NAME subgroup_size COMMAND subgroup_size_test)
1395 endif() 1553 endif()
1396else() 1554else()
1397 message(STATUS "Vulkan headers not found: GPU test tools, vk_pipeline_check, d3d12_state_map_test and " 1555 message(STATUS "Vulkan headers not found: GPU test tools, vk_pipeline_check, d3d12_state_map_test and "
diff --git a/runtime/README.md b/runtime/README.md
index 85907e335..7060f4368 100644
--- a/runtime/README.md
+++ b/runtime/README.md
@@ -204,6 +204,9 @@ SDK, or `-DLEONIDA_VULKAN_HEADERS_FETCH=ON` to download the pinned Khronos Vulka
204 Vulkan SDK's `spirv-as` and `spirv-val` at build time. 204 Vulkan SDK's `spirv-as` and `spirv-val` at build time.
205- `d3d12_compute_test` — the compute path: root signature, a compute PSO found by its FSSM hash in a 205- `d3d12_compute_test` — the compute path: root signature, a compute PSO found by its FSSM hash in a
206 translator-style index, root arguments through the GPU address arena, and two dispatches. 206 translator-style index, root arguments through the GPU address arena, and two dispatches.
207- `d3d12_set0_compute_test` — set 0 from the compute bind point: a compute PSO whose index entry lists set-0
208 bindings, and four dispatches that sample two SRVs, bytes no view was made for and a clamping sampler through
209 the bindless set the layer binds.
207- `d3d12_present_test` — milestone M0: opens a window and presents 60 cleared frames through the proxy on 210- `d3d12_present_test` — milestone M0: opens a window and presents 60 cleared frames through the proxy on
208 Vulkan, resizes it and presents 10 more, and checks the colour on screen. A driver double then injects an 211 Vulkan, resizes it and presents 10 more, and checks the colour on screen. A driver double then injects an
209 out-of-date and a suboptimal present, a failed semaphore during a swapchain recreation and a failed blit 212 out-of-date and a suboptimal present, a failed semaphore during a swapchain recreation and a failed blit
@@ -232,6 +235,14 @@ The PE-loader and Bink-decode tests that need the retail package are optional: w
232`LEONIDA_GAME_DIR` (and, for Bink, `LEONIDA_MOVIE`) is unset they print `SKIP` and exit 0. They read 235`LEONIDA_GAME_DIR` (and, for Bink, `LEONIDA_MOVIE`) is unset they print `SKIP` and exit 0. They read
233the files in place and never copy or commit game data. 236the files in place and never copy or commit game data.
234 237
238`shader_library_corpus_test` runs the D3D12 layer's shader lookup (`src/shader_library.h`) over a work folder
239that `make_game.py --stages shaders` built from your copy. With `LEONIDA_SHADERS=<work>/shaders/spirv` it takes
240every container in `<work>/shaders/dxbc` (or `LEONIDA_SHADER_DXBC`), inflates its FSSM program and looks it up
241under the stage its DXIL program header names. Each container has to find its own `index.json` entry and a
242readable `.spv`, every entry has to be reached, and in containers with more than one 0x0D payload no earlier
243payload may be the indexed program. Without `LEONIDA_SHADERS` it prints `SKIP` (CTest reports it as skipped).
244It prints counts only; on the 1.0.2.1 corpus all 26,503 containers resolve.
245
235## Current limits 246## Current limits
236 247
237`gta6rt --run <exe> [-- args]` runs an executable's entry point inside the runtime (`shims/process.cpp` gives it its 248`gta6rt --run <exe> [-- args]` runs an executable's entry point inside the runtime (`shims/process.cpp` gives it its
diff --git a/runtime/shims/d3d12_com.cpp b/runtime/shims/d3d12_com.cpp
index 6fc3e2c51..581bc0fa9 100644
--- a/runtime/shims/d3d12_com.cpp
+++ b/runtime/shims/d3d12_com.cpp
@@ -113,8 +113,9 @@ class CommandAllocator final
113 : public Child<CommandAllocator, ID3D12CommandAllocatorStubs, ID3D12Object, ID3D12DeviceChild, ID3D12Pageable, 113 : public Child<CommandAllocator, ID3D12CommandAllocatorStubs, ID3D12Object, ID3D12DeviceChild, ID3D12Pageable,
114 ID3D12CommandAllocator> { 114 ID3D12CommandAllocator> {
115public: 115public:
116 // {7d0e6b51-34a2-4f0c-9a61-0c5b2e8f4a10} 116 // {7d0e6b51-34a2-4f0c-9a61-0c5b2e8f4a10}, public in d3d12_xs_device.h: the device proxy's slot 9 wraps an allocator
117 static constexpr GUID kTag{0x7d0e6b51, 0x34a2, 0x4f0c, {0x9a, 0x61, 0x0c, 0x5b, 0x2e, 0x8f, 0x4a, 0x10}}; 117 // in an Xbox-ABI allocator proxy only when it answers this tag, because from() below resolves such a proxy.
118 static constexpr GUID kTag = d3d12_xs::kLeonidaCommandAllocatorTag;
118 explicit CommandAllocator(D3D12_COMMAND_LIST_TYPE type) : type_(type) {} 119 explicit CommandAllocator(D3D12_COMMAND_LIST_TYPE type) : type_(type) {}
119 // Lists own their recorded commands, so there is nothing to free. As on the PC runtime (D3D-51, measured by 120 // Lists own their recorded commands, so there is nothing to free. As on the PC runtime (D3D-51, measured by
120 // d3d12_vulkan_device_test): E_FAIL while a list is recording into this allocator, and S_OK while its lists are 121 // d3d12_vulkan_device_test): E_FAIL while a list is recording into this allocator, and S_OK while its lists are
@@ -124,7 +125,12 @@ public:
124 // The one list that is recording into this allocator, or null. D3D12 allows one at a time. 125 // The one list that is recording into this allocator, or null. D3D12 allows one at a time.
125 const void* recording() const { return recording_; } 126 const void* recording() const { return recording_; }
126 void set_recording(const void* list) { recording_ = list; } 127 void set_recording(const void* list) { recording_ = list; }
127 static CommandAllocator* from(IUnknown* object) { return Child::from<CommandAllocator>(object); } 128 // An allocator proxy (the title's allocator from device slot 9) stands for the allocator behind it, so every
129 // list method that takes an allocator (CreateCommandList, Reset) resolves it here.
130 static CommandAllocator* from(IUnknown* object) {
131 if (ID3D12CommandAllocator* real = d3d12_xs::allocator_proxy_real_allocator(object)) object = real;
132 return Child::from<CommandAllocator>(object);
133 }
128 134
129private: 135private:
130 D3D12_COMMAND_LIST_TYPE type_; 136 D3D12_COMMAND_LIST_TYPE type_;
@@ -214,10 +220,14 @@ public:
214 bind_root(compute_, signature); 220 bind_root(compute_, signature);
215 } 221 }
216 void STDMETHODCALLTYPE SetGraphicsRootSignature(ID3D12RootSignature* signature) override { 222 void STDMETHODCALLTYPE SetGraphicsRootSignature(ID3D12RootSignature* signature) override {
223 d3d12_trace::record("ID3D12GraphicsCommandList::SetGraphicsRootSignature");
217 bind_root(graphics_, signature); 224 bind_root(graphics_, signature);
218 } 225 }
219 226
220 void STDMETHODCALLTYPE SetPipelineState(ID3D12PipelineState* state) override { set_pipeline(state); } 227 void STDMETHODCALLTYPE SetPipelineState(ID3D12PipelineState* state) override {
228 d3d12_trace::record("ID3D12GraphicsCommandList::SetPipelineState");
229 set_pipeline(state);
230 }
221 231
222 // The bound heaps matter to direct heap indexing, which is still open (section 3.4); tables carry their VAs. 232 // The bound heaps matter to direct heap indexing, which is still open (section 3.4); tables carry their VAs.
223 void STDMETHODCALLTYPE SetDescriptorHeaps(UINT, ID3D12DescriptorHeap* const*) override {} 233 void STDMETHODCALLTYPE SetDescriptorHeaps(UINT, ID3D12DescriptorHeap* const*) override {}
@@ -327,11 +337,13 @@ public:
327 } 337 }
328 338
329 void STDMETHODCALLTYPE DrawInstanced(UINT vertices, UINT instances, UINT first_vertex, UINT first_instance) override { 339 void STDMETHODCALLTYPE DrawInstanced(UINT vertices, UINT instances, UINT first_vertex, UINT first_instance) override {
340 d3d12_trace::record("ID3D12GraphicsCommandList::DrawInstanced");
330 record_draw(false, vertices, instances, first_vertex, 0, first_instance); 341 record_draw(false, vertices, instances, first_vertex, 0, first_instance);
331 } 342 }
332 343
333 void STDMETHODCALLTYPE DrawIndexedInstanced(UINT indices, UINT instances, UINT first_index, INT base_vertex, 344 void STDMETHODCALLTYPE DrawIndexedInstanced(UINT indices, UINT instances, UINT first_index, INT base_vertex,
334 UINT first_instance) override { 345 UINT first_instance) override {
346 d3d12_trace::record("ID3D12GraphicsCommandList::DrawIndexedInstanced");
335 record_draw(true, indices, instances, first_index, base_vertex, first_instance); 347 record_draw(true, indices, instances, first_index, base_vertex, first_instance);
336 } 348 }
337 349
diff --git a/runtime/shims/d3d12_com.h b/runtime/shims/d3d12_com.h
index 51b4d3136..2e1f2d3c5 100644
--- a/runtime/shims/d3d12_com.h
+++ b/runtime/shims/d3d12_com.h
@@ -25,6 +25,7 @@
25#include <vector> 25#include <vector>
26 26
27#include "../src/root_signature.h" 27#include "../src/root_signature.h"
28#include "../src/subgroup_size.h"
28 29
29namespace leonida { 30namespace leonida {
30class VulkanPresenter; 31class VulkanPresenter;
@@ -77,6 +78,9 @@ struct VulkanDeviceInfo {
77 bool separate_depth_stencil_layouts = true; 78 bool separate_depth_stencil_layouts = true;
78 std::uint32_t max_push_constants_size = 0; 79 std::uint32_t max_push_constants_size = 0;
79 bool push_constants_need_fallback = false; 80 bool push_constants_need_fallback = false;
81 // The subgroup sizes the device offers and whether subgroupSizeControl / computeFullSubgroups are enabled on it
82 // (src/subgroup_size.h). Default: nothing, so pipelines request no size.
83 leonida::SubgroupSizeCaps subgroup;
80 // Enabled: runtimeDescriptorArray, the dynamic indexing of sampled- and storage-image arrays, and update after 84 // Enabled: runtimeDescriptorArray, the dynamic indexing of sampled- and storage-image arrays, and update after
81 // bind for sampled images, storage images and storage buffers. The device then keeps the bindless set 0 of 85 // bind for sampled images, storage images and storage buffers. The device then keeps the bindless set 0 of
82 // the translated shaders (docs section 3.4), and texture views and samplers are put in it as they are 86 // the translated shaders (docs section 3.4), and texture views and samplers are put in it as they are
@@ -260,6 +264,8 @@ struct RootArgumentLayout {
260const RootArgumentLayout* root_signature_layout(ID3D12RootSignature* signature); 264const RootArgumentLayout* root_signature_layout(ID3D12RootSignature* signature);
261std::uintptr_t compute_pipeline_id(ID3D12PipelineState* pipeline); 265std::uintptr_t compute_pipeline_id(ID3D12PipelineState* pipeline);
262std::uintptr_t graphics_pipeline_id(ID3D12PipelineState* pipeline); 266std::uintptr_t graphics_pipeline_id(ID3D12PipelineState* pipeline);
267// What each stage of a Vulkan device's PSO asked for (src/subgroup_size.h), in creation order; null for another PSO.
268const std::vector<leonida::SubgroupRequest>* pipeline_subgroup_requests(ID3D12PipelineState* pipeline);
263 269
264// The size of every descriptor slot (GetDescriptorHandleIncrementSize), for handle ranges. 270// The size of every descriptor slot (GetDescriptorHandleIncrementSize), for handle ranges.
265inline constexpr UINT descriptor_size = 32; 271inline constexpr UINT descriptor_size = 32;
diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp
index 54662bacb..a8a14a316 100644
--- a/runtime/shims/d3d12_vulkan_device.cpp
+++ b/runtime/shims/d3d12_vulkan_device.cpp
@@ -33,7 +33,6 @@
33#include <iterator> 33#include <iterator>
34#include <map> 34#include <map>
35#include <cstring> 35#include <cstring>
36#include <map>
37#include <memory> 36#include <memory>
38#include <mutex> 37#include <mutex>
39#include <set> 38#include <set>
@@ -67,6 +66,37 @@ void log_once(const char* what, int value) {
67 if (seen.insert({what, value}).second) std::fprintf(stderr, "[rt] d3d12: %s %d\n", what, value); 66 if (seen.insert({what, value}).second) std::fprintf(stderr, "[rt] d3d12: %s %d\n", what, value);
68} 67}
69 68
69// A shader whose subgroup size cannot be had runs at the device's: inexact if it crosses the halves of a wave64 (or,
70// for a wave32 shader on a 64-wide default, reads lanes that are not its own). Logged once per stage with the first
71// shader's name, then again at 10, 100, 1000... of that stage so a whole corpus stays readable.
72void report_subgroup_unavailable(const leonida::ShaderEntry& entry, const leonida::SubgroupRequest& request,
73 const leonida::SubgroupSizeCaps& caps) {
74 static std::mutex mutex;
75 static std::map<std::string, std::pair<std::set<std::string>, unsigned>> seen; // stage -> names, next report
76 std::lock_guard lock(mutex);
77 auto& [names, next_report] = seen[entry.stage];
78 if (!names.insert(entry.name).second) return;
79 if (names.size() == 1) next_report = 10;
80 else if (names.size() != next_report) return;
81 else next_report *= 10;
82 const bool emulable = entry.stage == "cs" || entry.stage == "ms";
83 const std::string so_far =
84 names.size() > 1 ? " (shaders of this stage so far: " + std::to_string(names.size()) + ")" : "";
85 std::fprintf(stderr,
86 "[rt] d3d12: %s (%s) is a %u-wide shader but this device cannot require that subgroup size for the "
87 "stage (device sizes %u..%u, default %u, subgroupSizeControl %s); it runs at the device's size and "
88 "is inexact where lanes of the other half matter%s\n",
89 entry.name.c_str(), entry.stage.c_str(), request.wanted, caps.min_size, caps.max_size,
90 caps.default_size, caps.subgroup_size_control ? "on" : "off",
91 so_far.c_str());
92 if (emulable && request.wanted == 64)
93 std::fprintf(stderr, "[rt] d3d12: translate wave64 %s shaders with --wave64-emulate for this GPU "
94 "(make_game.py --wave64-emulate auto does)\n", entry.stage.c_str());
95 else if (request.wanted == 64)
96 std::fprintf(stderr, "[rt] d3d12: no emulation exists for wave64 %s shaders yet (docs/d3d12_vulkan.md, "
97 "subgroup size)\n", entry.stage.c_str());
98}
99
70struct Format { 100struct Format {
71 VkFormat format = VK_FORMAT_UNDEFINED; 101 VkFormat format = VK_FORMAT_UNDEFINED;
72 VkImageAspectFlags aspects = 0; 102 VkImageAspectFlags aspects = 0;
@@ -131,6 +161,10 @@ Format vulkan_format(DXGI_FORMAT format, bool depth) {
131 // Vulkan 1.3 requires sampling it (formerly VK_EXT_4444_formats). 161 // Vulkan 1.3 requires sampling it (formerly VK_EXT_4444_formats).
132 case DXGI_FORMAT_B4G4R4A4_UNORM: return {VK_FORMAT_A4R4G4B4_UNORM_PACK16, color}; 162 case DXGI_FORMAT_B4G4R4A4_UNORM: return {VK_FORMAT_A4R4G4B4_UNORM_PACK16, color};
133 case DXGI_FORMAT_B8G8R8A8_UNORM_SRGB: return {VK_FORMAT_B8G8R8A8_SRGB, color}; 163 case DXGI_FORMAT_B8G8R8A8_UNORM_SRGB: return {VK_FORMAT_B8G8R8A8_SRGB, color};
164 // The X byte has no channel of its own: the BGRA8 images hold it, and shader views read alpha as 1.
165 case DXGI_FORMAT_B8G8R8X8_TYPELESS: return {VK_FORMAT_B8G8R8A8_UNORM, color, true};
166 case DXGI_FORMAT_B8G8R8X8_UNORM: return {VK_FORMAT_B8G8R8A8_UNORM, color};
167 case DXGI_FORMAT_B8G8R8X8_UNORM_SRGB: return {VK_FORMAT_B8G8R8A8_SRGB, color};
134 case DXGI_FORMAT_R16G16_TYPELESS: return {VK_FORMAT_R16G16_SFLOAT, color, true}; 168 case DXGI_FORMAT_R16G16_TYPELESS: return {VK_FORMAT_R16G16_SFLOAT, color, true};
135 case DXGI_FORMAT_R16G16_FLOAT: return {VK_FORMAT_R16G16_SFLOAT, color}; 169 case DXGI_FORMAT_R16G16_FLOAT: return {VK_FORMAT_R16G16_SFLOAT, color};
136 case DXGI_FORMAT_R16G16_UINT: return {VK_FORMAT_R16G16_UINT, color}; 170 case DXGI_FORMAT_R16G16_UINT: return {VK_FORMAT_R16G16_UINT, color};
@@ -225,6 +259,13 @@ bool rgb96_refused(const D3D12_RESOURCE_DESC& desc) {
225 D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL)); 259 D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL));
226} 260}
227 261
262// B8G8R8X8: the BGRA8 Vulkan formats with the alpha byte unused. Its typeless family is a family of its own, so
263// views never cross between it and B8G8R8A8, although both land on the same VkFormat.
264bool alpha_unused(DXGI_FORMAT format) {
265 return format == DXGI_FORMAT_B8G8R8X8_TYPELESS || format == DXGI_FORMAT_B8G8R8X8_UNORM ||
266 format == DXGI_FORMAT_B8G8R8X8_UNORM_SRGB;
267}
268
228// The full mip chain's length for a texture this size. 269// The full mip chain's length for a texture this size.
229UINT16 full_mips(UINT64 width, UINT height, UINT depth) { 270UINT16 full_mips(UINT64 width, UINT height, UINT depth) {
230 UINT16 mips = 0; 271 UINT16 mips = 0;
@@ -241,6 +282,14 @@ bool xr_bias_compatible(const D3D12_RESOURCE_DESC& desc) {
241 return mips == 1; 282 return mips == 1;
242} 283}
243 284
285// The Xbox tiled layout word (slot 76, docs/d3d12_vulkan.md section 4.2) is outside D3D12_TEXTURE_LAYOUT's
286// enumerators, so compare as an integer.
287constexpr UINT kXboxTiledLayout = 0x101;
288
289bool is_tiled_layout(D3D12_TEXTURE_LAYOUT layout) {
290 return layout == D3D12_TEXTURE_LAYOUT_64KB_UNDEFINED_SWIZZLE || static_cast<UINT>(layout) == kXboxTiledLayout;
291}
292
244// A volume RTV covers W slices of one mip. UINT_MAX extends through the last slice of that mip. 293// A volume RTV covers W slices of one mip. UINT_MAX extends through the last slice of that mip.
245leonida::TargetView volume_rtv(leonida::ResourceId id, const D3D12_RESOURCE_DESC& resource, 294leonida::TargetView volume_rtv(leonida::ResourceId id, const D3D12_RESOURCE_DESC& resource,
246 const D3D12_RENDER_TARGET_VIEW_DESC* view) { 295 const D3D12_RENDER_TARGET_VIEW_DESC* view) {
@@ -284,7 +333,8 @@ struct TextureCreateInfo {
284 info.usage = VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT; 333 info.usage = VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT;
285 if (desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET) info.usage |= VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT; 334 if (desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET) info.usage |= VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT;
286 if (desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL) info.usage |= VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT; 335 if (desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL) info.usage |= VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT;
287 if (desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS) { 336 // No B8G8R8X8 view is ever a UAV, so its typeless family needs no storage usage (not every GPU has it for BGRA8).
337 if ((desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS) && !alpha_unused(desc.Format)) {
288 info.usage |= VK_IMAGE_USAGE_STORAGE_BIT; 338 info.usage |= VK_IMAGE_USAGE_STORAGE_BIT;
289 if (!volume && info.samples == VK_SAMPLE_COUNT_1_BIT && attachment_usable) 339 if (!volume && info.samples == VK_SAMPLE_COUNT_1_BIT && attachment_usable)
290 info.usage |= VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT; 340 info.usage |= VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT;
@@ -331,6 +381,12 @@ struct DeviceState {
331 // True when VK_FORMAT_E5B9G9R9_UFLOAT_PACK32 lacks native STORAGE_IMAGE but mutable R32_UINT+{R32_UINT,E5B9G9R9} 381 // True when VK_FORMAT_E5B9G9R9_UFLOAT_PACK32 lacks native STORAGE_IMAGE but mutable R32_UINT+{R32_UINT,E5B9G9R9}
332 // is supported, so R9G9B9E5_SHAREDEXP UAV textures are backed by R32_UINT with separate storage/sampled views. 382 // is supported, so R9G9B9E5_SHAREDEXP UAV textures are backed by R32_UINT with separate storage/sampled views.
333 bool r9g9b9e5_uav_emulated = false; 383 bool r9g9b9e5_uav_emulated = false;
384 // D3D-219: VK_EXT_image_view_min_lod may select levels with minLodInteger = floor(minLod), the spec's
385 // "alternative", while D3D12's ResourceMinLODClamp is fractional. Intel's integrated GPUs on Windows do: a 0.75
386 // clamp sampled at LOD 0 with point mip filtering reads mip 0 (UHD 770 101.7092, Arrow Lake Xe-LPG; #1015).
387 // bind_image gives such a driver the clamp rounded to the nearest level, which point mip filtering selects
388 // exactly. LEONIDA_MIN_LOD_INTEGER=1 or 0 forces it either way.
389 bool min_lod_integer = false;
334 390
335 // Cached physical-device no-attachment sample counts for D3D12_OPTIONS19. 391 // Cached physical-device no-attachment sample counts for D3D12_OPTIONS19.
336 UINT no_output_sample_counts = 0; 392 UINT no_output_sample_counts = 0;
@@ -575,6 +631,13 @@ struct DeviceState {
575 log_once("96-bit (R32G32B32) render targets not supported; format", desc.Format); 631 log_once("96-bit (R32G32B32) render targets not supported; format", desc.Format);
576 return {}; 632 return {};
577 } 633 }
634 // The host runtime refuses typed B8G8R8X8 with unordered access (its typeless family is accepted): the
635 // BGRA8 image could take storage writes, but D3D12 has no typed UAV for these formats.
636 if (alpha_unused(desc.Format) && desc.Format != DXGI_FORMAT_B8G8R8X8_TYPELESS &&
637 (desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS)) {
638 log_once("B8G8R8X8 textures cannot allow unordered access; format", desc.Format);
639 return {};
640 }
578 Format format = texture_storage_format(desc.Format, desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL); 641 Format format = texture_storage_format(desc.Format, desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL);
579 format.d24 = format.format == VK_FORMAT_D24_UNORM_S8_UINT; // native or not: clears are quantised 642 format.d24 = format.format == VK_FORMAT_D24_UNORM_S8_UINT; // native or not: clears are quantised
580 if (format.format == VK_FORMAT_D24_UNORM_S8_UINT && !depth_usable(format.format)) { 643 if (format.format == VK_FORMAT_D24_UNORM_S8_UINT && !depth_usable(format.format)) {
@@ -733,6 +796,9 @@ struct DeviceState {
733 log_once("SRV requires VK_EXT_image_view_min_lod; first mip", int(image.first_mip)); 796 log_once("SRV requires VK_EXT_image_view_min_lod; first mip", int(image.first_mip));
734 return false; 797 return false;
735 } 798 }
799 // A driver that floors the clamp (min_lod_integer) gets the level point mip filtering picks:
800 // nearest(d') = ceil(d' + 0.5) - 1, the spec's preferred rounding. It stays within the mip range.
801 if (min_lod_integer) clamp.minLod = std::ceil(clamp.minLod + 0.5f) - 1.0f;
736 clamp.pNext = view_info.pNext; 802 clamp.pNext = view_info.pNext;
737 view_info.pNext = &clamp; 803 view_info.pNext = &clamp;
738 } 804 }
@@ -1298,6 +1364,10 @@ public:
1298 binding.size = desc_.Width; 1364 binding.size = desc_.Width;
1299 binding.buffer = device_.arena.buffer; 1365 binding.buffer = device_.arena.buffer;
1300 binding.buffer_offset = va_; 1366 binding.buffer_offset = va_;
1367 binding.va = va_;
1368 binding.host_readable = (heap_.Type == D3D12_HEAP_TYPE_READBACK ||
1369 (heap_.Type == D3D12_HEAP_TYPE_CUSTOM &&
1370 heap_.CPUPageProperty == D3D12_CPU_PAGE_PROPERTY_WRITE_BACK));
1301 device_.context->add_resource(id(), binding); 1371 device_.context->add_resource(id(), binding);
1302 return S_OK; 1372 return S_OK;
1303 } 1373 }
@@ -1403,8 +1473,9 @@ public:
1403 D3D12_RESOURCE_DESC STDMETHODCALLTYPE GetDesc() override { 1473 D3D12_RESOURCE_DESC STDMETHODCALLTYPE GetDesc() override {
1404 D3D12_RESOURCE_DESC desc = desc_; 1474 D3D12_RESOURCE_DESC desc = desc_;
1405 if (!desc.Alignment) { 1475 if (!desc.Alignment) {
1406 desc.Alignment = desc.SampleDesc.Count > 1 ? D3D12_DEFAULT_MSAA_RESOURCE_PLACEMENT_ALIGNMENT 1476 desc.Alignment = (desc.SampleDesc.Count > 1 && !is_tiled_layout(desc.Layout))
1407 : D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT; 1477 ? D3D12_DEFAULT_MSAA_RESOURCE_PLACEMENT_ALIGNMENT
1478 : D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT;
1408 } 1479 }
1409 return desc; 1480 return desc;
1410 } 1481 }
@@ -1880,6 +1951,7 @@ public:
1880 bool reserved() const { return reserved_; } 1951 bool reserved() const { return reserved_; }
1881 VkDeviceSize offset() const { return offset_; } 1952 VkDeviceSize offset() const { return offset_; }
1882 UINT64 bytes() const { return desc_.SizeInBytes; } 1953 UINT64 bytes() const { return desc_.SizeInBytes; }
1954 UINT64 alignment() const { return desc_.Alignment ? desc_.Alignment : D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT; }
1883 const D3D12_HEAP_PROPERTIES& properties() const { return desc_.Properties; } 1955 const D3D12_HEAP_PROPERTIES& properties() const { return desc_.Properties; }
1884 D3D12_HEAP_FLAGS flags() const { return desc_.Flags; } 1956 D3D12_HEAP_FLAGS flags() const { return desc_.Flags; }
1885 1957
@@ -1970,9 +2042,22 @@ public:
1970 return false; 2042 return false;
1971 } 2043 }
1972 2044
2045 // Asks for the subgroup size the shader was translated for, where the device allows (src/subgroup_size.h): the
2046 // stage gets VkPipelineShaderStageRequiredSubgroupSizeCreateInfo in `storage` (which must outlive pipeline
2047 // creation) and, for compute, REQUIRE_FULL_SUBGROUPS. A size the device cannot give is reported, not hidden.
2048 void subgroup_size_for(const leonida::ShaderEntry& entry, VkPipelineShaderStageRequiredSubgroupSizeCreateInfo& storage,
2049 VkPipelineShaderStageCreateInfo& stage) {
2050 const leonida::SubgroupRequest request = leonida::decide_subgroup_size(entry, device_.info.subgroup);
2051 if (request.outcome == leonida::SubgroupOutcome::unavailable)
2052 report_subgroup_unavailable(entry, request, device_.info.subgroup);
2053 leonida::apply_subgroup_request(request, storage, stage);
2054 subgroup_requests_.push_back(request);
2055 }
2056
1973 std::uintptr_t id() const { return reinterpret_cast<std::uintptr_t>(static_cast<const ID3D12PipelineState*>(this)); } 2057 std::uintptr_t id() const { return reinterpret_cast<std::uintptr_t>(static_cast<const ID3D12PipelineState*>(this)); }
1974 bool compute() const { return registered_ && !is_graphics_; } 2058 bool compute() const { return registered_ && !is_graphics_; }
1975 bool graphics() const { return registered_ && is_graphics_; } 2059 bool graphics() const { return registered_ && is_graphics_; }
2060 const std::vector<leonida::SubgroupRequest>& subgroup_requests() const { return subgroup_requests_; }
1976 2061
1977 // A VS (+ PS) pipeline for dynamic rendering. Vertex input comes from the input layout matched to the VS's 2062 // A VS (+ PS) pipeline for dynamic rendering. Vertex input comes from the input layout matched to the VS's
1978 // input signature by semantic name and index: location = the element's register, the translator's rule 2063 // input signature by semantic name and index: location = the element's register, the translator's rule
@@ -1997,9 +2082,14 @@ public:
1997 log_once("graphics pipeline stage not supported yet (hull/domain/geometry/stream output):", 0); 2082 log_once("graphics pipeline stage not supported yet (hull/domain/geometry/stream output):", 0);
1998 return E_NOTIMPL; 2083 return E_NOTIMPL;
1999 } 2084 }
2000 if (desc.SampleDesc.Count > 1) { 2085 const UINT samples = desc.SampleDesc.Count;
2001 log_once("multisampled graphics pipelines not supported yet; samples", int(desc.SampleDesc.Count)); 2086 if (!samples || samples > D3D12_MAX_MULTISAMPLE_SAMPLE_COUNT || (samples & (samples - 1))) {
2002 return E_NOTIMPL; 2087 log_once("invalid graphics pipeline sample count:", int(samples));
2088 return E_INVALIDARG;
2089 }
2090 if (desc.SampleDesc.Quality != 0) {
2091 log_once("invalid graphics pipeline sample quality:", int(desc.SampleDesc.Quality));
2092 return E_INVALIDARG;
2003 } 2093 }
2004 const leonida::ShaderLibrary* library = device_.library(); 2094 const leonida::ShaderLibrary* library = device_.library();
2005 if (!library) return E_FAIL; 2095 if (!library) return E_FAIL;
@@ -2014,6 +2104,8 @@ public:
2014 Stage stages[2] = {{"vs", VK_SHADER_STAGE_VERTEX_BIT, desc.VS}, {"ps", VK_SHADER_STAGE_FRAGMENT_BIT, desc.PS}}; 2104 Stage stages[2] = {{"vs", VK_SHADER_STAGE_VERTEX_BIT, desc.VS}, {"ps", VK_SHADER_STAGE_FRAGMENT_BIT, desc.PS}};
2015 bool uses_bindless = false; // a stage declares set-0 bindings: the layout holds the device's set 0 2105 bool uses_bindless = false; // a stage declares set-0 bindings: the layout holds the device's set 0
2016 std::vector<VkPipelineShaderStageCreateInfo> stage_infos; 2106 std::vector<VkPipelineShaderStageCreateInfo> stage_infos;
2107 // Chained from stage_infos, which the recipe keeps for variants built at draw time: so they live in the recipe.
2108 auto& required_sizes = recipe_.required_sizes;
2017 const Stage* code_stage = nullptr; 2109 const Stage* code_stage = nullptr;
2018 for (Stage& stage : stages) { 2110 for (Stage& stage : stages) {
2019 if (!stage.code.pShaderBytecode || !stage.code.BytecodeLength) continue; // no PS: depth only 2111 if (!stage.code.pShaderBytecode || !stage.code.BytecodeLength) continue; // no PS: depth only
@@ -2061,6 +2153,7 @@ public:
2061 info.stage = stage.bit; 2153 info.stage = stage.bit;
2062 info.module = module; 2154 info.module = module;
2063 info.pName = "main"; 2155 info.pName = "main";
2156 subgroup_size_for(*stage.entry, required_sizes[stage_infos.size()], info);
2064 stage_infos.push_back(info); 2157 stage_infos.push_back(info);
2065 } 2158 }
2066 2159
@@ -2145,7 +2238,7 @@ public:
2145 raster.depthClampEnable = r.DepthClipEnable ? VK_FALSE : VK_TRUE; 2238 raster.depthClampEnable = r.DepthClipEnable ? VK_FALSE : VK_TRUE;
2146 2239
2147 VkPipelineMultisampleStateCreateInfo multisample{VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO}; 2240 VkPipelineMultisampleStateCreateInfo multisample{VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO};
2148 multisample.rasterizationSamples = VK_SAMPLE_COUNT_1_BIT; 2241 multisample.rasterizationSamples = VkSampleCountFlagBits(samples);
2149 const VkSampleMask sample_mask = desc.SampleMask; 2242 const VkSampleMask sample_mask = desc.SampleMask;
2150 multisample.pSampleMask = &sample_mask; 2243 multisample.pSampleMask = &sample_mask;
2151 multisample.alphaToCoverageEnable = desc.BlendState.AlphaToCoverageEnable; 2244 multisample.alphaToCoverageEnable = desc.BlendState.AlphaToCoverageEnable;
@@ -2231,6 +2324,55 @@ public:
2231 graphics_.depth_format = f.format; 2324 graphics_.depth_format = f.format;
2232 graphics_.depth_aspects = f.aspects; 2325 graphics_.depth_aspects = f.aspects;
2233 } 2326 }
2327 if (samples > 1) {
2328 const auto& dinfo = device_.info;
2329 const bool has_color = std::any_of(graphics_.color_formats.begin(), graphics_.color_formats.end(),
2330 [](VkFormat f) { return f != VK_FORMAT_UNDEFINED; });
2331 const bool has_depth = graphics_.depth_format != VK_FORMAT_UNDEFINED;
2332 if (const auto get_props = reinterpret_cast<PFN_vkGetPhysicalDeviceProperties>(
2333 dinfo.get_instance_proc ? dinfo.get_instance_proc(dinfo.instance, "vkGetPhysicalDeviceProperties")
2334 : nullptr)) {
2335 VkPhysicalDeviceProperties props{};
2336 get_props(dinfo.physical, &props);
2337 VkSampleCountFlags supported = ~VkSampleCountFlags(0);
2338 if (has_color) supported &= props.limits.framebufferColorSampleCounts;
2339 if (has_depth && (graphics_.depth_aspects & VK_IMAGE_ASPECT_DEPTH_BIT))
2340 supported &= props.limits.framebufferDepthSampleCounts;
2341 if (has_depth && (graphics_.depth_aspects & VK_IMAGE_ASPECT_STENCIL_BIT))
2342 supported &= props.limits.framebufferStencilSampleCounts;
2343 if (!has_color && !has_depth) supported &= props.limits.framebufferNoAttachmentsSampleCounts;
2344 if (!(supported & samples)) {
2345 log_once("multisample count not supported by framebuffer limits; samples", int(samples));
2346 return E_INVALIDARG;
2347 }
2348 }
2349 if ((has_color || has_depth) && !device_.image_format_properties) {
2350 log_once("cannot query per-format multisample support; samples", int(samples));
2351 return E_INVALIDARG;
2352 }
2353 for (const VkFormat fmt : graphics_.color_formats) {
2354 if (fmt == VK_FORMAT_UNDEFINED) continue;
2355 VkImageFormatProperties img_props{};
2356 if (device_.image_format_properties(dinfo.physical, fmt, VK_IMAGE_TYPE_2D, VK_IMAGE_TILING_OPTIMAL,
2357 VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT, 0, &img_props) != VK_SUCCESS ||
2358 !(img_props.sampleCounts & samples)) {
2359 log_once("multisample count not supported by color attachment format; samples", int(samples));
2360 return E_INVALIDARG;
2361 }
2362 }
2363 if (has_depth) {
2364 VkImageFormatProperties img_props{};
2365 if (device_.image_format_properties(dinfo.physical, graphics_.depth_format, VK_IMAGE_TYPE_2D,
2366 VK_IMAGE_TILING_OPTIMAL,
2367 VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT, 0,
2368 &img_props) != VK_SUCCESS ||
2369 !(img_props.sampleCounts & samples)) {
2370 log_once("multisample count not supported by depth/stencil attachment format; samples",
2371 int(samples));
2372 return E_INVALIDARG;
2373 }
2374 }
2375 }
2234 // Every stage this path accepts reads the user SGPRs, so the range covers the whole stage table, not only the 2376 // Every stage this path accepts reads the user SGPRs, so the range covers the whole stage table, not only the
2235 // stages present. A stage added to the table (geometry, mesh) is covered without touching this. 2377 // stages present. A stage added to the table (geometry, mesh) is covered without touching this.
2236 for (const Stage& stage : stages) graphics_.push_stages |= stage.bit; 2378 for (const Stage& stage : stages) graphics_.push_stages |= stage.bit;
@@ -2308,7 +2450,6 @@ public:
2308 entry->name.c_str()); 2450 entry->name.c_str());
2309 return E_NOTIMPL; 2451 return E_NOTIMPL;
2310 } 2452 }
2311 if (entry->wave64) log_once("wave64 compute shader runs 32-wide (subgroup size control not requested yet)", 0);
2312 const std::vector<std::uint32_t> words = library->spirv(*entry); 2453 const std::vector<std::uint32_t> words = library->spirv(*entry);
2313 if (words.empty()) { 2454 if (words.empty()) {
2314 std::fprintf(stderr, "[rt] d3d12: %s.spv is missing or not SPIR-V\n", entry->name.c_str()); 2455 std::fprintf(stderr, "[rt] d3d12: %s.spv is missing or not SPIR-V\n", entry->name.c_str());
@@ -2336,6 +2477,8 @@ public:
2336 pipeline_info.stage.stage = VK_SHADER_STAGE_COMPUTE_BIT; 2477 pipeline_info.stage.stage = VK_SHADER_STAGE_COMPUTE_BIT;
2337 pipeline_info.stage.module = module_; 2478 pipeline_info.stage.module = module_;
2338 pipeline_info.stage.pName = "main"; 2479 pipeline_info.stage.pName = "main";
2480 VkPipelineShaderStageRequiredSubgroupSizeCreateInfo required_size{};
2481 subgroup_size_for(*entry, required_size, pipeline_info.stage);
2339 pipeline_info.layout = pipeline_.layout; 2482 pipeline_info.layout = pipeline_.layout;
2340 if (vk.vkCreateComputePipelines(dev, VK_NULL_HANDLE, 1, &pipeline_info, nullptr, &pipeline_.pipeline) != 2483 if (vk.vkCreateComputePipelines(dev, VK_NULL_HANDLE, 1, &pipeline_info, nullptr, &pipeline_.pipeline) !=
2341 VK_SUCCESS) 2484 VK_SUCCESS)
@@ -2357,6 +2500,7 @@ private:
2357 // What a graphics pipeline is made from, so variants can be built at draw time. 2500 // What a graphics pipeline is made from, so variants can be built at draw time.
2358 struct Recipe { 2501 struct Recipe {
2359 std::vector<VkPipelineShaderStageCreateInfo> stages; 2502 std::vector<VkPipelineShaderStageCreateInfo> stages;
2503 VkPipelineShaderStageRequiredSubgroupSizeCreateInfo required_sizes[2]{}; // what `stages` chain
2360 std::vector<VkVertexInputAttributeDescription> attributes; 2504 std::vector<VkVertexInputAttributeDescription> attributes;
2361 std::vector<VkVertexInputBindingDescription> bindings; 2505 std::vector<VkVertexInputBindingDescription> bindings;
2362 VkPipelineInputAssemblyStateCreateInfo assembly{}; 2506 VkPipelineInputAssemblyStateCreateInfo assembly{};
@@ -2452,6 +2596,7 @@ private:
2452 VkDeviceSize code_bytes_ = 0; 2596 VkDeviceSize code_bytes_ = 0;
2453 bool registered_ = false; 2597 bool registered_ = false;
2454 bool is_graphics_ = false; 2598 bool is_graphics_ = false;
2599 std::vector<leonida::SubgroupRequest> subgroup_requests_; // one per stage, in creation order
2455}; 2600};
2456 2601
2457// A view of a texture as Create*View describes it, before the resource's own shape is applied. 2602// A view of a texture as Create*View describes it, before the resource's own shape is applied.
@@ -2544,6 +2689,10 @@ bool image_descriptor(const Resource& resource, const TextureView& view, leonida
2544 log_once("incompatible typed A8 view format:", int(view.format)); 2689 log_once("incompatible typed A8 view format:", int(view.format));
2545 return false; 2690 return false;
2546 } 2691 }
2692 if (alpha_unused(view.format) != alpha_unused(desc.Format)) {
2693 log_once("view format from another typeless family (B8G8R8X8 and B8G8R8A8):", int(view.format));
2694 return false;
2695 }
2547 if ((view.format == DXGI_FORMAT_R9G9B9E5_SHAREDEXP) != (desc.Format == DXGI_FORMAT_R9G9B9E5_SHAREDEXP)) { 2696 if ((view.format == DXGI_FORMAT_R9G9B9E5_SHAREDEXP) != (desc.Format == DXGI_FORMAT_R9G9B9E5_SHAREDEXP)) {
2548 log_once("incompatible R9G9B9E5 view format:", int(view.format)); 2697 log_once("incompatible R9G9B9E5 view format:", int(view.format));
2549 return false; 2698 return false;
@@ -2611,9 +2760,11 @@ bool image_descriptor(const Resource& resource, const TextureView& view, leonida
2611 // D3D12's component mapping picks, for each of R, G, B, A, a channel of the format or a constant; the T# 2760 // D3D12's component mapping picks, for each of R, G, B, A, a channel of the format or a constant; the T#
2612 // says the same about the hardware's channels, which the format places. 2761 // says the same about the hardware's channels, which the format places.
2613 // A stencil view's format has its eight bits in G and no R, B or A of its own (0, 0, 1 when read). 2762 // A stencil view's format has its eight bits in G and no R, B or A of its own (0, 0, 1 when read).
2763 // B8G8R8X8 has no alpha: it reads 1.
2614 g::Swizzle channels = g::format_swizzle(view_format); 2764 g::Swizzle channels = g::format_swizzle(view_format);
2615 if (stencil) channels = {g::select_zero, g::select_x, g::select_zero, g::select_one}; 2765 if (stencil) channels = {g::select_zero, g::select_x, g::select_zero, g::select_one};
2616 else if (desc.Format == DXGI_FORMAT_A8_UNORM) channels = {g::select_zero, g::select_zero, g::select_zero, g::select_x}; 2766 else if (desc.Format == DXGI_FORMAT_A8_UNORM) channels = {g::select_zero, g::select_zero, g::select_zero, g::select_x};
2767 else if (alpha_unused(desc.Format)) channels[3] = g::select_one;
2617 for (UINT i = 0; i < 4; ++i) { 2768 for (UINT i = 0; i < 4; ++i) {
2618 const UINT from = D3D12_DECODE_SHADER_4_COMPONENT_MAPPING(i, view.mapping); 2769 const UINT from = D3D12_DECODE_SHADER_4_COMPONENT_MAPPING(i, view.mapping);
2619 if (msaa && from > D3D12_SHADER_COMPONENT_MAPPING_FORCE_VALUE_1) { 2770 if (msaa && from > D3D12_SHADER_COMPONENT_MAPPING_FORCE_VALUE_1) {
@@ -2895,6 +3046,15 @@ public:
2895 VkPhysicalDeviceProperties properties{}; 3046 VkPhysicalDeviceProperties properties{};
2896 device_properties(info.physical, &properties); 3047 device_properties(info.physical, &properties);
2897 state_.max_sampler_lod_bias = properties.limits.maxSamplerLodBias; 3048 state_.max_sampler_lod_bias = properties.limits.maxSamplerLodBias;
3049 {
3050 constexpr std::uint32_t kIntelVendorId = 0x8086;
3051 state_.min_lod_integer = properties.vendorID == kIntelVendorId &&
3052 properties.deviceType == VK_PHYSICAL_DEVICE_TYPE_INTEGRATED_GPU;
3053 char text[4] = {};
3054 size_t length = 0;
3055 if (getenv_s(&length, text, "LEONIDA_MIN_LOD_INTEGER") == 0 && length > 1)
3056 state_.min_lod_integer = text[0] != '0';
3057 }
2898 std::uint32_t family_count = 0; 3058 std::uint32_t family_count = 0;
2899 queue_families(info.physical, &family_count, nullptr); 3059 queue_families(info.physical, &family_count, nullptr);
2900 std::vector<VkQueueFamilyProperties> families(family_count); 3060 std::vector<VkQueueFamilyProperties> families(family_count);
@@ -2939,7 +3099,19 @@ public:
2939 get_properties(state_.info.physical, &properties); 3099 get_properties(state_.info.physical, &properties);
2940 features.ms_samples = {VK_SAMPLE_COUNT_4_BIT, state_.ms_fallback_samples(VK_FORMAT_R32_UINT), 3100 features.ms_samples = {VK_SAMPLE_COUNT_4_BIT, state_.ms_fallback_samples(VK_FORMAT_R32_UINT),
2941 state_.ms_fallback_samples(VK_FORMAT_R32_SINT)}; 3101 state_.ms_fallback_samples(VK_FORMAT_R32_SINT)};
2942 if (!leonida::bindless::size_bindings(features, properties.properties.limits, v11, indexed)) 3102 // Past maxPerSetDescriptors, ask the driver about the grown layout (D3D-219: Intel's Xe-LP reports 6159).
3103 const auto layout_support = reinterpret_cast<PFN_vkGetDescriptorSetLayoutSupport>(
3104 get_device(state_.info.device, "vkGetDescriptorSetLayoutSupport"));
3105 std::function<bool(const leonida::BindlessFeatures&)> layout_supported;
3106 if (layout_support)
3107 layout_supported = [&](const leonida::BindlessFeatures& candidate) {
3108 const leonida::bindless::SetLayout layout(candidate);
3109 VkDescriptorSetLayoutSupport support{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_SUPPORT};
3110 layout_support(state_.info.device, &layout.info, &support);
3111 return support.supported == VK_TRUE;
3112 };
3113 if (!leonida::bindless::size_bindings(features, properties.properties.limits, v11, indexed,
3114 layout_supported))
2943 std::fprintf(stderr, "[rt] d3d12: the device's descriptor limits are below the bindless set's default " 3115 std::fprintf(stderr, "[rt] d3d12: the device's descriptor limits are below the bindless set's default "
2944 "sizes; it holds less\n"); 3116 "sizes; it holds less\n");
2945 } 3117 }
@@ -3358,7 +3530,7 @@ public:
3358 auto& vk = state_.context->vk; 3530 auto& vk = state_.context->vk;
3359 if (desc && state_.context->xdxr_acceleration_structures()) { 3531 if (desc && state_.context->xdxr_acceleration_structures()) {
3360 // XDXR records: the layout depends only on the triangle or instance count (xdxr_build.h), so the sizes 3532 // XDXR records: the layout depends only on the triangle or instance count (xdxr_build.h), so the sizes
3361 // are exact. An update rebuilds the structure, so it needs the same scratch. 3533 // are exact. An update refits (no sort); the build's scratch size covers it.
3362 leonida::BuildAccelerationStructure build{}; 3534 leonida::BuildAccelerationStructure build{};
3363 build.is_tlas = desc->Type == D3D12_RAYTRACING_ACCELERATION_STRUCTURE_TYPE_TOP_LEVEL; 3535 build.is_tlas = desc->Type == D3D12_RAYTRACING_ACCELERATION_STRUCTURE_TYPE_TOP_LEVEL;
3364 if (build.is_tlas) { 3536 if (build.is_tlas) {
@@ -3521,7 +3693,7 @@ public:
3521 return hand_out(signature, riid, out); 3693 return hand_out(signature, riid, out);
3522 } 3694 }
3523 3695
3524 // PC slot 11; the Xbox ABI reaches it through device slot 62 (the proxy forwards). 3696 // PC slot 11; the Xbox ABI reaches it through device slots 62 and 67 (the proxy forwards).
3525 HRESULT STDMETHODCALLTYPE CreateComputePipelineState(const D3D12_COMPUTE_PIPELINE_STATE_DESC* desc, REFIID riid, 3697 HRESULT STDMETHODCALLTYPE CreateComputePipelineState(const D3D12_COMPUTE_PIPELINE_STATE_DESC* desc, REFIID riid,
3526 void** out) override { 3698 void** out) override {
3527 if (!out) return E_POINTER; 3699 if (!out) return E_POINTER;
@@ -3707,6 +3879,24 @@ public:
3707 std::size_t(count) * kDescriptorSize); 3879 std::size_t(count) * kDescriptorSize);
3708 } 3880 }
3709 3881
3882 // A constant-buffer view is a 16-byte GFX10 raw buffer V# in the first half of the slot (zeros in the rest).
3883 // A null description, zero address, or zero size leaves the whole slot zeroed (null V#: reads return 0).
3884 void STDMETHODCALLTYPE CreateConstantBufferView(const D3D12_CONSTANT_BUFFER_VIEW_DESC* desc,
3885 D3D12_CPU_DESCRIPTOR_HANDLE destination) override {
3886 d3d12_trace::record("ID3D12Device::CreateConstantBufferView");
3887 if (!destination.ptr) return;
3888 std::memset(reinterpret_cast<void*>(destination.ptr), 0, kDescriptorSize);
3889 if (!desc || !desc->BufferLocation || !desc->SizeInBytes) return;
3890 leonida::gfx10::Buffer buffer{};
3891 buffer.address = desc->BufferLocation;
3892 buffer.stride = 0;
3893 buffer.num_records = desc->SizeInBytes;
3894 buffer.format = leonida::gfx10::format_from_vulkan(VK_FORMAT_R32_UINT);
3895 buffer.oob_select = leonida::gfx10::OobSelect::raw;
3896 const leonida::gfx10::BufferWords words = leonida::gfx10::encode(buffer);
3897 std::memcpy(reinterpret_cast<void*>(destination.ptr), words.data(), sizeof(words));
3898 }
3899
3710 // A shader-resource view of a texture is a T# in the slot (docs section 3.4): the shader loads those eight 3900 // A shader-resource view of a texture is a T# in the slot (docs section 3.4): the shader loads those eight
3711 // dwords through its descriptor table and finds the image by them. A slot left as zeros is a null descriptor: 3901 // dwords through its descriptor table and finds the image by them. A slot left as zeros is a null descriptor:
3712 // nothing is registered for it, so the shader gets the fallback image. Buffer views are not implemented. 3902 // nothing is registered for it, so the shader gets the fallback image. Buffer views are not implemented.
@@ -3844,6 +4034,11 @@ public:
3844 return; 4034 return;
3845 } 4035 }
3846 } 4036 }
4037 // B8G8R8X8 has no typed UAV, so no format of its family gives an unordered-access view.
4038 if (alpha_unused(r->desc().Format) || alpha_unused(view.format)) {
4039 log_once("unordered-access view of a B8G8R8X8 format; format", int(view.format));
4040 return;
4041 }
3847 write_image_descriptor(*r, view, destination, true); 4042 write_image_descriptor(*r, view, destination, true);
3848 } 4043 }
3849 4044
@@ -3984,14 +4179,15 @@ public:
3984 return CreateReservedResource1(desc, D3D12_RESOURCE_STATE_COMMON, nullptr, session, riid, out); 4179 return CreateReservedResource1(desc, D3D12_RESOURCE_STATE_COMMON, nullptr, session, riid, out);
3985 } 4180 }
3986 4181
3987 // Tiling of a reserved resource (src/resource_tiling.h). Anything else, as on the PC runtime, has no tiles: 4182 // Tiling of a reserved resource or a tiled (64KB_UNDEFINED_SWIZZLE) texture (src/resource_tiling.h). Anything
3988 // every output is zero and no subresource tiling is written. 4183 // else, as on the PC runtime, has no tiles: every output is zero and no subresource tiling is written.
3989 void STDMETHODCALLTYPE GetResourceTiling(ID3D12Resource* resource, UINT* total, D3D12_PACKED_MIP_INFO* packed, 4184 void STDMETHODCALLTYPE GetResourceTiling(ID3D12Resource* resource, UINT* total, D3D12_PACKED_MIP_INFO* packed,
3990 D3D12_TILE_SHAPE* shape, UINT* count, UINT first, 4185 D3D12_TILE_SHAPE* shape, UINT* count, UINT first,
3991 D3D12_SUBRESOURCE_TILING* tilings) override { 4186 D3D12_SUBRESOURCE_TILING* tilings) override {
3992 leonida::ResourceTiling tiling; 4187 leonida::ResourceTiling tiling;
3993 Resource* r = Resource::from<Resource>(resource); 4188 Resource* r = Resource::from<Resource>(resource);
3994 const bool ok = r && r->reserved() && resource_tiling(r->GetDesc(), tiling); 4189 const bool ok = r && (r->reserved() || is_tiled_layout(r->GetDesc().Layout)) &&
4190 resource_tiling(r->GetDesc(), tiling);
3995 if (total) *total = ok ? tiling.total_tiles : 0; 4191 if (total) *total = ok ? tiling.total_tiles : 0;
3996 if (packed) 4192 if (packed)
3997 *packed = ok ? D3D12_PACKED_MIP_INFO{UINT8(tiling.standard_mips), UINT8(tiling.packed_mips), 4193 *packed = ok ? D3D12_PACKED_MIP_INFO{UINT8(tiling.standard_mips), UINT8(tiling.packed_mips),
@@ -4148,14 +4344,33 @@ public:
4148 log_once("placed resource offset not 64 KiB aligned:", int(heap_offset)); 4344 log_once("placed resource offset not 64 KiB aligned:", int(heap_offset));
4149 return E_INVALIDARG; 4345 return E_INVALIDARG;
4150 } 4346 }
4347 const bool tiled = is_tiled_layout(desc->Layout);
4348 const bool msaa = desc->SampleDesc.Count > 1;
4151 if (desc->Dimension == D3D12_RESOURCE_DIMENSION_BUFFER) { 4349 if (desc->Dimension == D3D12_RESOURCE_DIMENSION_BUFFER) {
4152 if (heap_offset + desc->Width > heap->bytes()) return E_INVALIDARG; 4350 if (desc->Layout != D3D12_TEXTURE_LAYOUT_ROW_MAJOR) return E_INVALIDARG;
4153 } else if (heap_offset >= heap->bytes()) { 4351 if (desc->Width > heap->bytes() || heap_offset > heap->bytes() - desc->Width) return E_INVALIDARG;
4154 return E_INVALIDARG; 4352 } else {
4155 } 4353 if (heap->properties().Type == D3D12_HEAP_TYPE_UPLOAD ||
4156 if (desc->Layout == D3D12_TEXTURE_LAYOUT_64KB_UNDEFINED_SWIZZLE) { 4354 heap->properties().Type == D3D12_HEAP_TYPE_READBACK)
4157 log_once("tiled placed resource not supported yet; dimension", int(desc->Dimension)); 4355 return E_INVALIDARG;
4158 return E_NOTIMPL; 4356 if (tiled || msaa) {
4357 if (tiled && desc->Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE2D &&
4358 desc->Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE3D)
4359 return E_INVALIDARG;
4360 if (msaa && desc->Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE2D) return E_INVALIDARG;
4361 if (msaa && (heap->flags() & D3D12_HEAP_FLAG_DENY_RT_DS_TEXTURES)) return E_INVALIDARG;
4362 const D3D12_RESOURCE_ALLOCATION_INFO alloc = allocation(*desc);
4363 if (alloc.SizeInBytes == UINT64_MAX || heap->alignment() < alloc.Alignment ||
4364 heap_offset % alloc.Alignment || alloc.SizeInBytes > heap->bytes() ||
4365 heap_offset > heap->bytes() - alloc.SizeInBytes)
4366 return E_INVALIDARG;
4367 if (tiled && static_cast<UINT>(desc->Layout) == kXboxTiledLayout) {
4368 log_once("placed resource with the Xbox tiled layout, as 64KB_UNDEFINED_SWIZZLE; dimension",
4369 int(desc->Dimension));
4370 }
4371 } else if (heap_offset >= heap->bytes()) {
4372 return E_INVALIDARG;
4373 }
4159 } 4374 }
4160 // Only buffers are addressable, as in D3D12: a placed texture keeps a null VA and its own Vulkan image. 4375 // Only buffers are addressable, as in D3D12: a placed texture keeps a null VA and its own Vulkan image.
4161 const VkDeviceSize placed_va = desc->Dimension == D3D12_RESOURCE_DIMENSION_BUFFER ? heap->offset() + heap_offset : 0; 4376 const VkDeviceSize placed_va = desc->Dimension == D3D12_RESOURCE_DIMENSION_BUFFER ? heap->offset() + heap_offset : 0;
@@ -4164,10 +4379,8 @@ public:
4164 HRESULT hr = E_NOTIMPL; 4379 HRESULT hr = E_NOTIMPL;
4165 if (desc->Dimension == D3D12_RESOURCE_DIMENSION_BUFFER) { 4380 if (desc->Dimension == D3D12_RESOURCE_DIMENSION_BUFFER) {
4166 hr = resource->create_placed_buffer(); 4381 hr = resource->create_placed_buffer();
4167 } else if (desc->Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE2D) { 4382 } else if (!tiled && desc->Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE2D) {
4168 log_once("placed resource dimension not supported:", int(desc->Dimension)); 4383 log_once("placed resource dimension not supported:", int(desc->Dimension));
4169 } else if (desc->SampleDesc.Count > 1) {
4170 log_once("multisampled placed resource not supported; samples", int(desc->SampleDesc.Count));
4171 } else { 4384 } else {
4172 hr = S_OK; 4385 hr = S_OK;
4173 const Format format = state_.texture_format(*desc); 4386 const Format format = state_.texture_format(*desc);
@@ -4693,8 +4906,9 @@ public:
4693 if (optimal & VK_FORMAT_FEATURE_DEPTH_STENCIL_ATTACHMENT_BIT) { 4906 if (optimal & VK_FORMAT_FEATURE_DEPTH_STENCIL_ATTACHMENT_BIT) {
4694 s1 |= D3D12_FORMAT_SUPPORT1_DEPTH_STENCIL; 4907 s1 |= D3D12_FORMAT_SUPPORT1_DEPTH_STENCIL;
4695 } 4908 }
4696 if ((optimal & VK_FORMAT_FEATURE_STORAGE_IMAGE_BIT) || 4909 // B8G8R8X8 has no typed UAV in D3D12 (texture_format refuses it), whatever the BGRA8 image could do.
4697 (buffer & VK_FORMAT_FEATURE_STORAGE_TEXEL_BUFFER_BIT)) { 4910 if (!alpha_unused(fs->Format) && ((optimal & VK_FORMAT_FEATURE_STORAGE_IMAGE_BIT) ||
4911 (buffer & VK_FORMAT_FEATURE_STORAGE_TEXEL_BUFFER_BIT))) {
4698 s1 |= D3D12_FORMAT_SUPPORT1_TYPED_UNORDERED_ACCESS_VIEW; 4912 s1 |= D3D12_FORMAT_SUPPORT1_TYPED_UNORDERED_ACCESS_VIEW;
4699 // A typed UAV texture read is not a storage-image read: the translator reads it through the 4913 // A typed UAV texture read is not a storage-image read: the translator reads it through the
4700 // texture's sampled binding with the T#'s numeric type (rdna2spirv.py image_read_typed), so a 4914 // texture's sampled binding with the T#'s numeric type (rdna2spirv.py image_read_typed), so a
@@ -4933,16 +5147,22 @@ private:
4933 D3D12_RESOURCE_DESC resolved = desc; 5147 D3D12_RESOURCE_DESC resolved = desc;
4934 if (!resolved.MipLevels) resolved.MipLevels = full; 5148 if (!resolved.MipLevels) resolved.MipLevels = full;
4935 if (resolved.MipLevels > full) return kInvalidAllocation; 5149 if (resolved.MipLevels > full) return kInvalidAllocation;
4936 if (samples > 1 && (volume || one_d || resolved.MipLevels != 1 || 5150 const bool depth_stencil = desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL;
5151 if (samples > 1 && (volume || one_d || resolved.MipLevels != 1 || !(desc.Flags & attachment) ||
5152 (desc.Flags & attachment) == attachment ||
4937 (desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS))) 5153 (desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS)))
4938 return kInvalidAllocation; 5154 return kInvalidAllocation;
4939 // The PC runtime: simultaneous access only single-sampled and without depth-stencil, and no volume depth. 5155 // The PC runtime: simultaneous access only single-sampled and without depth-stencil, and no volume depth.
4940 const bool depth_stencil = desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL;
4941 if (((desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_SIMULTANEOUS_ACCESS) && (depth_stencil || samples > 1)) || 5156 if (((desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_SIMULTANEOUS_ACCESS) && (depth_stencil || samples > 1)) ||
4942 (volume && depth_stencil)) 5157 (volume && depth_stencil))
4943 return kInvalidAllocation; 5158 return kInvalidAllocation;
4944 if (desc.Layout != D3D12_TEXTURE_LAYOUT_UNKNOWN) 5159 const bool tiled = is_tiled_layout(desc.Layout);
5160 if (tiled) {
5161 if (one_d || (samples > 1 && samples != 4)) return kInvalidAllocation;
5162 if (desc.Alignment && desc.Alignment != align_64k) return kInvalidAllocation;
5163 } else if (desc.Layout != D3D12_TEXTURE_LAYOUT_UNKNOWN) {
4945 log_once("GetResourceAllocationInfo layout as UNKNOWN:", desc.Layout); 5164 log_once("GetResourceAllocationInfo layout as UNKNOWN:", desc.Layout);
5165 }
4946 5166
4947 const Format format = state_.texture_format(desc); 5167 const Format format = state_.texture_format(desc);
4948 if (!format.format) { 5168 if (!format.format) {
@@ -4952,6 +5172,11 @@ private:
4952 VkMemoryRequirements need{}; 5172 VkMemoryRequirements need{};
4953 const TextureCreateInfo create(resolved, format, state_.color_attachment_usable(format.format)); 5173 const TextureCreateInfo create(resolved, format, state_.color_attachment_usable(format.format));
4954 if (!state_.memory_requirements(create.info, need)) return kInvalidAllocation; 5174 if (!state_.memory_requirements(create.info, need)) return kInvalidAllocation;
5175 if (tiled) {
5176 leonida::ResourceTiling tiling;
5177 if (!resource_tiling(resolved, tiling)) return kInvalidAllocation;
5178 return {UINT64(tiling.total_tiles) * leonida::tile_size_in_bytes, align_64k};
5179 }
4955 5180
4956 // D3D12's alignment: 64 KiB, or 4 MiB with MSAA, unless the description asks for a small one (4 KiB, 64 KiB 5181 // D3D12's alignment: 64 KiB, or 4 MiB with MSAA, unless the description asks for a small one (4 KiB, 64 KiB
4957 // with MSAA). 4 KiB needs the top mip of one array slice to fit in 16 tiles of 4 KiB and the resource not to 5182 // with MSAA). 4 KiB needs the top mip of one array slice to fit in 16 tiles of 4 KiB and the resource not to
@@ -4997,12 +5222,10 @@ private:
4997 if (!image_descriptor(resource, view, image)) return; 5222 if (!image_descriptor(resource, view, image)) return;
4998 const leonida::gfx10::ImageWords words = leonida::gfx10::encode(image); 5223 const leonida::gfx10::ImageWords words = leonida::gfx10::encode(image);
4999 const bool registered = state_.bind_image(words, image, resource.image(), resource.format(), 5224 const bool registered = state_.bind_image(words, image, resource.image(), resource.format(),
5000 resource.aspects(), storage, false, 5225 resource.aspects(), storage, resource.has_view_format_list(),
5001 resource.r9g9b9e5_as_r32_uint()); 5226 resource.r9g9b9e5_as_r32_uint());
5002 if (leonida::gfx10::multisampled(image.type) && !registered) return; 5227 if (leonida::gfx10::multisampled(image.type) && !registered) return;
5003 std::memcpy(reinterpret_cast<void*>(destination.ptr), words.data(), sizeof(words)); 5228 std::memcpy(reinterpret_cast<void*>(destination.ptr), words.data(), sizeof(words));
5004 state_.bind_image(words, image, resource.image(), resource.format(), resource.aspects(), storage,
5005 resource.has_view_format_list(), resource.r9g9b9e5_as_r32_uint());
5006 } 5229 }
5007 5230
5008 // Shared by CreateCommittedResource and CreateCommittedResource3. A castable-format list is only meaningful on 5231 // Shared by CreateCommittedResource and CreateCommittedResource3. A castable-format list is only meaningful on
@@ -5131,14 +5354,11 @@ private:
5131 HRESULT create_reserved(const D3D12_RESOURCE_DESC* desc, REFIID riid, void** out) { 5354 HRESULT create_reserved(const D3D12_RESOURCE_DESC* desc, REFIID riid, void** out) {
5132 if (out) *out = nullptr; 5355 if (out) *out = nullptr;
5133 if (!desc) return E_INVALIDARG; 5356 if (!desc) return E_INVALIDARG;
5134 // The Xbox tiled layout word. 0x101 is outside D3D12_TEXTURE_LAYOUT's enumerators, so it can't be a
5135 // constexpr enum value (clang rejects the cast in a constant expression); compare it as an integer.
5136 constexpr UINT xbox_tiled = 0x101;
5137 D3D12_RESOURCE_DESC backing = *desc; 5357 D3D12_RESOURCE_DESC backing = *desc;
5138 if (desc->Dimension == D3D12_RESOURCE_DIMENSION_BUFFER) { 5358 if (desc->Dimension == D3D12_RESOURCE_DIMENSION_BUFFER) {
5139 if (desc->Layout != D3D12_TEXTURE_LAYOUT_ROW_MAJOR) return E_INVALIDARG; 5359 if (desc->Layout != D3D12_TEXTURE_LAYOUT_ROW_MAJOR) return E_INVALIDARG;
5140 } else { 5360 } else {
5141 if (static_cast<UINT>(desc->Layout) == xbox_tiled) { 5361 if (static_cast<UINT>(desc->Layout) == kXboxTiledLayout) {
5142 log_once("reserved resource with the Xbox tiled layout, as 64KB_UNDEFINED_SWIZZLE; dimension", 5362 log_once("reserved resource with the Xbox tiled layout, as 64KB_UNDEFINED_SWIZZLE; dimension",
5143 desc->Dimension); 5363 desc->Dimension);
5144 } else if (desc->Layout != D3D12_TEXTURE_LAYOUT_64KB_UNDEFINED_SWIZZLE) { 5364 } else if (desc->Layout != D3D12_TEXTURE_LAYOUT_64KB_UNDEFINED_SWIZZLE) {
@@ -5190,6 +5410,7 @@ private:
5190 const leonida::BlockFormat block = leonida::block_format(format.format, format.aspects); 5410 const leonida::BlockFormat block = leonida::block_format(format.format, format.aspects);
5191 tiling.element_bytes = block.bytes; 5411 tiling.element_bytes = block.bytes;
5192 tiling.block = block.block; 5412 tiling.block = block.block;
5413 tiling.samples = desc.SampleDesc.Count;
5193 return leonida::resource_tiling(tiling, out); 5414 return leonida::resource_tiling(tiling, out);
5194 } 5415 }
5195 5416
@@ -5288,6 +5509,11 @@ std::uintptr_t graphics_pipeline_id(ID3D12PipelineState* pipeline) {
5288 return p && p->graphics() ? p->id() : 0; 5509 return p && p->graphics() ? p->id() : 0;
5289} 5510}
5290 5511
5512const std::vector<leonida::SubgroupRequest>* pipeline_subgroup_requests(ID3D12PipelineState* pipeline) {
5513 const PipelineState* p = PipelineState::from<PipelineState>(pipeline);
5514 return p && (p->compute() || p->graphics()) ? &p->subgroup_requests() : nullptr;
5515}
5516
5291VkImage vulkan_image(ID3D12Resource* resource) { 5517VkImage vulkan_image(ID3D12Resource* resource) {
5292 const Resource* r = Resource::from<Resource>(resource); 5518 const Resource* r = Resource::from<Resource>(resource);
5293 return r ? r->image() : VK_NULL_HANDLE; 5519 return r ? r->image() : VK_NULL_HANDLE;
@@ -5509,7 +5735,15 @@ std::unique_ptr<WindowPresenter> create_window_presenter(ID3D12Device* device, H
5509 auto presenter = std::make_unique<leonida::VulkanPresenter>(*d->state().context, info.get_instance_proc, 5735 auto presenter = std::make_unique<leonida::VulkanPresenter>(*d->state().context, info.get_instance_proc,
5510 info.instance, info.physical, info.queue, 5736 info.instance, info.physical, info.queue,
5511 info.queue_family, surface, // owns the surface 5737 info.queue_family, surface, // owns the surface
5512 info.swapchain_maintenance1 && tear_allowed); 5738 info.swapchain_maintenance1 && tear_allowed,
5739 [window]() -> VkExtent2D {
5740 RECT r{};
5741 if (GetClientRect(window, &r)) {
5742 return {static_cast<uint32_t>(r.right - r.left),
5743 static_cast<uint32_t>(r.bottom - r.top)};
5744 }
5745 return {0, 0};
5746 });
5513 if (!presenter->ok()) { 5747 if (!presenter->ok()) {
5514 std::fprintf(stderr, "[rt] d3d12: cannot present to this window from the device's queue family\n"); 5748 std::fprintf(stderr, "[rt] d3d12: cannot present to this window from the device's queue family\n");
5515 return nullptr; 5749 return nullptr;
@@ -5636,6 +5870,7 @@ HRESULT create_vulkan_device_standalone(REFIID riid, void** out) {
5636 LEONIDA_INSTANCE(vkGetPhysicalDeviceProperties); 5870 LEONIDA_INSTANCE(vkGetPhysicalDeviceProperties);
5637 LEONIDA_INSTANCE(vkGetPhysicalDeviceQueueFamilyProperties); 5871 LEONIDA_INSTANCE(vkGetPhysicalDeviceQueueFamilyProperties);
5638 LEONIDA_INSTANCE(vkGetPhysicalDeviceFeatures2); 5872 LEONIDA_INSTANCE(vkGetPhysicalDeviceFeatures2);
5873 LEONIDA_INSTANCE(vkGetPhysicalDeviceProperties2);
5639 LEONIDA_INSTANCE(vkEnumerateDeviceExtensionProperties); 5874 LEONIDA_INSTANCE(vkEnumerateDeviceExtensionProperties);
5640 LEONIDA_INSTANCE(vkCreateDevice); 5875 LEONIDA_INSTANCE(vkCreateDevice);
5641 LEONIDA_INSTANCE(vkGetDeviceProcAddr); 5876 LEONIDA_INSTANCE(vkGetDeviceProcAddr);
@@ -5653,6 +5888,7 @@ HRESULT create_vulkan_device_standalone(REFIID riid, void** out) {
5653 bool chosen_bc = false; 5888 bool chosen_bc = false;
5654 VkPhysicalDeviceFeatures chosen_features{}; 5889 VkPhysicalDeviceFeatures chosen_features{};
5655 VkPhysicalDeviceVulkan12Features chosen12{}; 5890 VkPhysicalDeviceVulkan12Features chosen12{};
5891 VkPhysicalDeviceVulkan13Features chosen13{};
5656 bool chosen_draw_params = false; 5892 bool chosen_draw_params = false;
5657 for (VkPhysicalDevice candidate : physicals) { 5893 for (VkPhysicalDevice candidate : physicals) {
5658 VkPhysicalDeviceProperties props{}; 5894 VkPhysicalDeviceProperties props{};
@@ -5681,6 +5917,7 @@ HRESULT create_vulkan_device_standalone(REFIID riid, void** out) {
5681 chosen_bc = bc; 5917 chosen_bc = bc;
5682 chosen_features = features.features; 5918 chosen_features = features.features;
5683 chosen12 = f12; 5919 chosen12 = f12;
5920 chosen13 = f13;
5684 chosen_draw_params = draw_params; 5921 chosen_draw_params = draw_params;
5685 } 5922 }
5686 break; 5923 break;
@@ -5764,6 +6001,11 @@ HRESULT create_vulkan_device_standalone(REFIID riid, void** out) {
5764 VkPhysicalDeviceVulkan13Features enable13{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_3_FEATURES, ext_chain}; 6001 VkPhysicalDeviceVulkan13Features enable13{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_3_FEATURES, ext_chain};
5765 enable13.dynamicRendering = VK_TRUE; 6002 enable13.dynamicRendering = VK_TRUE;
5766 enable13.synchronization2 = VK_TRUE; 6003 enable13.synchronization2 = VK_TRUE;
6004 // Subgroup size control: a pipeline stage asks for the size its shader was translated for (src/subgroup_size.h).
6005 enable13.subgroupSizeControl = chosen13.subgroupSizeControl;
6006 enable13.computeFullSubgroups = chosen13.computeFullSubgroups;
6007 leonida::query_subgroup_size_caps(vkGetPhysicalDeviceProperties2, info.physical, chosen13.subgroupSizeControl,
6008 chosen13.computeFullSubgroups, info.subgroup);
5767 // Translated vertex shaders read BaseVertex / BaseInstance (SPIR-V DrawParameters) to give v0 / v3 the 6009 // Translated vertex shaders read BaseVertex / BaseInstance (SPIR-V DrawParameters) to give v0 / v3 the
5768 // hardware's zero-based vertex and instance ids (docs/design.md, Inputs and outputs). 6010 // hardware's zero-based vertex and instance ids (docs/design.md, Inputs and outputs).
5769 VkPhysicalDeviceVulkan11Features enable11{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_FEATURES, &enable13}; 6011 VkPhysicalDeviceVulkan11Features enable11{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_FEATURES, &enable13};
@@ -5905,9 +6147,10 @@ HRESULT create_vulkan_device_standalone(REFIID riid, void** out) {
5905 // Switching a vsync swapchain to IMMEDIATE or FIFO_RELAXED per present (PresentX's ImmediateThresholdPercent): 6147 // Switching a vsync swapchain to IMMEDIATE or FIFO_RELAXED per present (PresentX's ImmediateThresholdPercent):
5906 // the KHR extension (promoted from the EXT one, same structures) with the surface extension of the same name 6148 // the KHR extension (promoted from the EXT one, same structures) with the surface extension of the same name
5907 // on the instance, else the EXT one. Only enabled where the instance has the surface half and the GPU the feature. 6149 // on the instance, else the EXT one. Only enabled where the instance has the surface half and the GPU the feature.
6150 const char* swapchain_m1_name = nullptr;
6151#if defined(VK_KHR_swapchain_maintenance1)
5908 VkPhysicalDeviceSwapchainMaintenance1FeaturesKHR swapchain_m1{ 6152 VkPhysicalDeviceSwapchainMaintenance1FeaturesKHR swapchain_m1{
5909 VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SWAPCHAIN_MAINTENANCE_1_FEATURES_KHR}; 6153 VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SWAPCHAIN_MAINTENANCE_1_FEATURES_KHR};
5910 const char* swapchain_m1_name = nullptr;
5911 if (has_swapchain && instance_has_surface) { 6154 if (has_swapchain && instance_has_surface) {
5912 const auto device_has = [&](const char* name) { 6155 const auto device_has = [&](const char* name) {
5913 return std::any_of(extensions.begin(), extensions.end(), 6156 return std::any_of(extensions.begin(), extensions.end(),
@@ -5928,6 +6171,7 @@ HRESULT create_vulkan_device_standalone(REFIID riid, void** out) {
5928 } 6171 }
5929 } 6172 }
5930 } 6173 }
6174#endif
5931 info.swapchain_maintenance1 = swapchain_m1_name != nullptr; 6175 info.swapchain_maintenance1 = swapchain_m1_name != nullptr;
5932 6176
5933 VkDeviceCreateInfo device_info{VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO, &enable12}; 6177 VkDeviceCreateInfo device_info{VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO, &enable12};
@@ -5966,6 +6210,12 @@ HRESULT create_vulkan_device_standalone(REFIID riid, void** out) {
5966 info.push_constants_need_fallback = (info.max_push_constants_size < 144); 6210 info.push_constants_need_fallback = (info.max_push_constants_size < 144);
5967 std::fprintf(stderr, "[rt] d3d12: Vulkan device: %s (maxPushConstantsSize: %u bytes)\n", chosen.deviceName, 6211 std::fprintf(stderr, "[rt] d3d12: Vulkan device: %s (maxPushConstantsSize: %u bytes)\n", chosen.deviceName,
5968 chosen.limits.maxPushConstantsSize); 6212 chosen.limits.maxPushConstantsSize);
6213 std::fprintf(stderr,
6214 "[rt] d3d12: subgroup sizes %u..%u (default %u), requirable in stages 0x%x, subgroupSizeControl %s, "
6215 "computeFullSubgroups %s\n",
6216 info.subgroup.min_size, info.subgroup.max_size, info.subgroup.default_size,
6217 unsigned(info.subgroup.required_stages), info.subgroup.subgroup_size_control ? "on" : "off",
6218 info.subgroup.compute_full_subgroups ? "on" : "off");
5969 if (info.push_constants_need_fallback) { 6219 if (info.push_constants_need_fallback) {
5970 std::fprintf(stderr, 6220 std::fprintf(stderr,
5971 "[rt] d3d12: WARNING: GPU maxPushConstantsSize (%u bytes) is below the 144 bytes required by " 6221 "[rt] d3d12: WARNING: GPU maxPushConstantsSize (%u bytes) is below the 144 bytes required by "
diff --git a/runtime/shims/d3d12_xs_device.cpp b/runtime/shims/d3d12_xs_device.cpp
index 57cd292c7..65a4f3995 100644
--- a/runtime/shims/d3d12_xs_device.cpp
+++ b/runtime/shims/d3d12_xs_device.cpp
@@ -388,18 +388,29 @@ HRESULT create_heap_proxy(ID3D12DescriptorHeap* real, DeviceProxy* device, REFII
388// 388//
389// QueryInterface answers only the interfaces the proxy models (the base chain and its own interface, Fence1 when 389// QueryInterface answers only the interfaces the proxy models (the base chain and its own interface, Fence1 when
390// the real fence has it), like the device and heap proxies, so the COM identity holds and no real object leaks to 390// the real fence has it), like the device and heap proxies, so the COM identity holds and no real object leaks to
391// the title. Leonida's own code reaches the real object through queue_proxy_real_queue / fence_proxy_real_fence. 391// the title. Leonida's own code reaches the real object through queue_proxy_real_queue / fence_proxy_real_fence /
392// allocator_proxy_real_allocator.
393//
394// Command allocators (device slot 9) are the third kind: their public chain is 9 slots (Reset at 8). Slot 9 wraps
395// only an allocator that answers kLeonidaCommandAllocatorTag, because a list takes the title's allocator in
396// CreateCommandList and Reset and only the Vulkan layer's lists resolve a proxy there (CommandAllocator::from);
397// a PC runtime allocator is handed out unchanged until a command-list proxy unwraps it at Reset.
392 398
393enum class ChildKind { queue, fence }; 399enum class ChildKind { queue, fence, allocator };
394 400
395constexpr unsigned kQueueSlots = 128; // the table: 19 public slots plus a refused tail 401constexpr unsigned kQueueSlots = 128; // the table: 19 public slots plus a refused tail
396constexpr unsigned kFenceSlots = 64; // the table: 12 public slots plus a refused tail 402constexpr unsigned kFenceSlots = 64; // the table: 12 public slots plus a refused tail
397constexpr unsigned kQueuePublicSlots = 19; // ID3D12CommandQueue 403constexpr unsigned kQueuePublicSlots = 19; // ID3D12CommandQueue
398constexpr unsigned kFencePublicSlots = 11; // ID3D12Fence 404constexpr unsigned kFencePublicSlots = 11; // ID3D12Fence
399constexpr unsigned kFence1PublicSlots = 12; // ID3D12Fence1 405constexpr unsigned kFence1PublicSlots = 12; // ID3D12Fence1
406constexpr unsigned kAllocatorSlots = 64; // the table: 9 public slots plus a refused tail
407constexpr unsigned kAllocatorPublicSlots = 9; // ID3D12CommandAllocator: the base chain and Reset (slot 8)
400constexpr SIZE_T kTableRegion = 64 * 1024; // one allocation granule: the table page plus 15 never-committed pages 408constexpr SIZE_T kTableRegion = 64 * 1024; // one allocation granule: the table page plus 15 never-committed pages
401static_assert(kQueueSlots > kQueuePublicSlots && kFenceSlots > kFence1PublicSlots, "the tables need a tail"); 409static_assert(kQueueSlots > kQueuePublicSlots && kFenceSlots > kFence1PublicSlots &&
402static_assert(kQueueSlots * sizeof(void*) <= 4096 && kFenceSlots * sizeof(void*) <= 4096, 410 kAllocatorSlots > kAllocatorPublicSlots,
411 "the tables need a tail");
412static_assert(kQueueSlots * sizeof(void*) <= 4096 && kFenceSlots * sizeof(void*) <= 4096 &&
413 kAllocatorSlots * sizeof(void*) <= 4096,
403 "a table must fit in the first page of its reservation"); 414 "a table must fit in the first page of its reservation");
404 415
405constexpr unsigned kQueueSignal = 14, kQueueWait = 15; // (ID3D12Fence*, UINT64) 416constexpr unsigned kQueueSignal = 14, kQueueWait = 15; // (ID3D12Fence*, UINT64)
@@ -415,7 +426,9 @@ struct ChildProxy {
415 426
416template <ChildKind K> 427template <ChildKind K>
417struct ChildStats { 428struct ChildStats {
418 static constexpr unsigned kSlots = K == ChildKind::queue ? kQueueSlots : kFenceSlots; 429 static constexpr unsigned kSlots = K == ChildKind::queue ? kQueueSlots
430 : K == ChildKind::fence ? kFenceSlots
431 : kAllocatorSlots;
419 static inline std::atomic<std::uint64_t> hits[kSlots]; 432 static inline std::atomic<std::uint64_t> hits[kSlots];
420 static inline std::atomic<bool> first[kSlots]; 433 static inline std::atomic<bool> first[kSlots];
421 static inline std::atomic<bool> beyond_warned[kSlots]; 434 static inline std::atomic<bool> beyond_warned[kSlots];
@@ -426,7 +439,7 @@ struct ChildStats {
426 439
427template <ChildKind K> 440template <ChildKind K>
428constexpr const char* child_kind_name() { 441constexpr const char* child_kind_name() {
429 return K == ChildKind::queue ? "queue" : "fence"; 442 return K == ChildKind::queue ? "queue" : K == ChildKind::fence ? "fence" : "allocator";
430} 443}
431 444
432template <ChildKind K> 445template <ChildKind K>
@@ -441,8 +454,10 @@ const char* child_public_name(unsigned slot) {
441 if (slot < 8) return object[slot]; 454 if (slot < 8) return object[slot];
442 if constexpr (K == ChildKind::queue) { 455 if constexpr (K == ChildKind::queue) {
443 if (slot < kQueuePublicSlots) return queue[slot - 8]; 456 if (slot < kQueuePublicSlots) return queue[slot - 8];
444 } else { 457 } else if constexpr (K == ChildKind::fence) {
445 if (slot < kFence1PublicSlots) return fence[slot - 8]; 458 if (slot < kFence1PublicSlots) return fence[slot - 8];
459 } else {
460 if (slot == 8) return "Reset";
446 } 461 }
447 return nullptr; 462 return nullptr;
448} 463}
@@ -454,7 +469,9 @@ template <ChildKind K>
454const char* child_trace_name(unsigned slot) { 469const char* child_trace_name(unsigned slot) {
455 static const auto names = [] { 470 static const auto names = [] {
456 static char storage[ChildStats<K>::kSlots][64]; 471 static char storage[ChildStats<K>::kSlots][64];
457 const char* iface = K == ChildKind::queue ? "XboxID3D12CommandQueue" : "XboxID3D12Fence"; 472 const char* iface = K == ChildKind::queue ? "XboxID3D12CommandQueue"
473 : K == ChildKind::fence ? "XboxID3D12Fence"
474 : "XboxID3D12CommandAllocator";
458 for (unsigned s = 0; s < ChildStats<K>::kSlots; ++s) { 475 for (unsigned s = 0; s < ChildStats<K>::kSlots; ++s) {
459 const char* method = child_public_name<K>(s); 476 const char* method = child_public_name<K>(s);
460 if (method) 477 if (method)
@@ -528,8 +545,10 @@ bool is_child_iid(const IID& iid) {
528 return true; 545 return true;
529 if constexpr (K == ChildKind::queue) { 546 if constexpr (K == ChildKind::queue) {
530 return IsEqualIID(iid, __uuidof(ID3D12CommandQueue)); 547 return IsEqualIID(iid, __uuidof(ID3D12CommandQueue));
531 } else { 548 } else if constexpr (K == ChildKind::fence) {
532 return IsEqualIID(iid, __uuidof(ID3D12Fence)) || IsEqualIID(iid, __uuidof(ID3D12Fence1)); 549 return IsEqualIID(iid, __uuidof(ID3D12Fence)) || IsEqualIID(iid, __uuidof(ID3D12Fence1));
550 } else {
551 return IsEqualIID(iid, __uuidof(ID3D12CommandAllocator));
533 } 552 }
534} 553}
535 554
@@ -608,7 +627,8 @@ IUnknown* proxy_real_object(const void* object) {
608 void* const vtable = *reinterpret_cast<void* const*>(object); 627 void* const vtable = *reinterpret_cast<void* const*>(object);
609 if (vtable == reinterpret_cast<void*>(get_heap_vtable())) return static_cast<const HeapProxy*>(object)->real; 628 if (vtable == reinterpret_cast<void*>(get_heap_vtable())) return static_cast<const HeapProxy*>(object)->real;
610 if (vtable == reinterpret_cast<void*>(get_child_vtable<ChildKind::queue>()) || 629 if (vtable == reinterpret_cast<void*>(get_child_vtable<ChildKind::queue>()) ||
611 vtable == reinterpret_cast<void*>(get_child_vtable<ChildKind::fence>())) 630 vtable == reinterpret_cast<void*>(get_child_vtable<ChildKind::fence>()) ||
631 vtable == reinterpret_cast<void*>(get_child_vtable<ChildKind::allocator>()))
612 return static_cast<const ChildProxy*>(object)->real; 632 return static_cast<const ChildProxy*>(object)->real;
613 return nullptr; 633 return nullptr;
614} 634}
@@ -685,6 +705,7 @@ LONG CALLBACK table_overrun_handler(EXCEPTION_POINTERS* info) {
685 const auto address = static_cast<std::uintptr_t>(record->ExceptionInformation[1]); 705 const auto address = static_cast<std::uintptr_t>(record->ExceptionInformation[1]);
686 report_table_overrun<ChildKind::queue>(address); 706 report_table_overrun<ChildKind::queue>(address);
687 report_table_overrun<ChildKind::fence>(address); 707 report_table_overrun<ChildKind::fence>(address);
708 report_table_overrun<ChildKind::allocator>(address);
688 } 709 }
689 return EXCEPTION_CONTINUE_SEARCH; // diagnostics only: the fault goes on to the title's handlers or the crash 710 return EXCEPTION_CONTINUE_SEARCH; // diagnostics only: the fault goes on to the title's handlers or the crash
690} 711}
@@ -803,8 +824,10 @@ HRESULT wrap_child(IUnknown* created, DeviceProxy* device, const IID* riid, void
803 proxy->real_vtable = *reinterpret_cast<void***>(created); 824 proxy->real_vtable = *reinterpret_cast<void***>(created);
804 if constexpr (K == ChildKind::queue) { 825 if constexpr (K == ChildKind::queue) {
805 proxy->slot_count = kQueuePublicSlots; 826 proxy->slot_count = kQueuePublicSlots;
806 } else { 827 } else if constexpr (K == ChildKind::fence) {
807 proxy->slot_count = supports_iid(created, __uuidof(ID3D12Fence1)) ? kFence1PublicSlots : kFencePublicSlots; 828 proxy->slot_count = supports_iid(created, __uuidof(ID3D12Fence1)) ? kFence1PublicSlots : kFencePublicSlots;
829 } else {
830 proxy->slot_count = kAllocatorPublicSlots;
808 } 831 }
809 proxy->refs.store(1, std::memory_order_relaxed); 832 proxy->refs.store(1, std::memory_order_relaxed);
810 proxy_add_ref(device); // the object keeps its Xbox-ABI device alive for GetDevice 833 proxy_add_ref(device); // the object keeps its Xbox-ABI device alive for GetDevice
@@ -894,6 +917,43 @@ HRESULT proxy_create_fence(DeviceProxy* self, std::uint64_t initial_value, std::
894 return wrap_child<ChildKind::fence>(static_cast<IUnknown*>(created), self, riid, out); 917 return wrap_child<ChildKind::fence>(static_cast<IUnknown*>(created), self, riid, out);
895} 918}
896 919
920// True when `allocator` is one whose consumers resolve allocator proxies: Leonida's own Vulkan-layer allocator,
921// whose lists (CreateCommandList, Reset) find the real allocator through allocator_proxy_real_allocator. A PC
922// runtime allocator does not answer the tag, and its lists would take a proxy for their own allocator.
923bool resolves_allocator_proxies(IUnknown* allocator) {
924 void* found = nullptr;
925 if (FAILED(allocator->QueryInterface(kLeonidaCommandAllocatorTag, &found)) || !found) return false;
926 static_cast<IUnknown*>(found)->Release(); // the implementation pointer starts with its IUnknown chain
927 return true;
928}
929
930// Device slot 9: CreateCommandAllocator(type, riid, out). An allocator proxy where the list side resolves it (see
931// resolves_allocator_proxies); any other allocator goes back unchanged, logged once, so the host runtime's lists
932// never see a proxy. Null output and null IID as slot 8.
933HRESULT proxy_create_command_allocator(DeviceProxy* self, std::uint64_t type, const IID* riid, void** out) {
934 note_slot(9);
935 if (out) *out = nullptr; // as slot 8
936 if (!riid) return E_POINTER;
937 const auto list_type = static_cast<D3D12_COMMAND_LIST_TYPE>(static_cast<std::uint32_t>(type));
938#pragma warning(suppress : 6387) // the caller's null output, on purpose (see slot 8)
939 if (!out) return self->real->CreateCommandAllocator(list_type, *riid, nullptr);
940 void* created = nullptr;
941 const HRESULT hr = self->real->CreateCommandAllocator(list_type, __uuidof(ID3D12CommandAllocator), &created);
942 if (FAILED(hr)) return hr;
943 if (!created) return E_FAIL;
944 auto* allocator = static_cast<IUnknown*>(created);
945 if (!resolves_allocator_proxies(allocator)) {
946 static std::atomic<bool> logged{false};
947 if (!logged.exchange(true, std::memory_order_relaxed))
948 std::fprintf(stderr, "[rt] d3d12_xs: allocators of this device are not wrapped: its command lists "
949 "cannot resolve an allocator proxy\n");
950 const HRESULT asked = allocator->QueryInterface(*riid, out);
951 allocator->Release();
952 return asked;
953 }
954 return wrap_child<ChildKind::allocator>(allocator, self, riid, out);
955}
956
897// Device slot 32: OpenSharedHandle(handle, riid, out). The object is opened as asked; when it is a fence (whatever 957// Device slot 32: OpenSharedHandle(handle, riid, out). The object is opened as asked; when it is a fence (whatever
898// interface was asked for, IUnknown included) the title gets a fence proxy, anything else (heaps, resources) is 958// interface was asked for, IUnknown included) the title gets a fence proxy, anything else (heaps, resources) is
899// returned unchanged. 959// returned unchanged.
@@ -981,6 +1041,61 @@ HRESULT proxy_create_compute_pipeline_state(DeviceProxy* self, const D3D12_COMPU
981 return self->real->CreateComputePipelineState(desc, *riid, out); 1041 return self->real->CreateComputePipelineState(desc, *riid, out);
982} 1042}
983 1043
1044// The Xbox slot 67 creates a compute pipeline from native GPU code: (desc, riid, out), named
1045// DeserializeComputePipelineStateX in amd_fidelityfx_upscaler_xbox.dll's messages (call at RVA 0x56d9). The desc
1046// passes the root signature at +0x00, followed by pointer/size pairs for the shader's FSPX entries (docs/fspx.md):
1047// kind 0 (dispatch state) at +0x08/+0x10, kind 1 at +0x18/+0x20, kind 6 (the RDNA2 program) at +0x28/+0x30, and
1048// kind 7 (records) at +0x38/+0x40. Translates the console description to a standard D3D12_COMPUTE_PIPELINE_STATE_DESC
1049// with CS bytecode pointing at kind 6 and routes it to CreateComputePipelineState on the PC device (slot 11), which
1050// on the Vulkan device resolves through the translator. The PC slot 67 is CreateProtectedResourceSession1.
1051HRESULT proxy_create_compute_pipeline_from_native_code(DeviceProxy* self, const void* desc,
1052 const IID* riid, void** out) {
1053 note_slot(67);
1054 if (!out) return E_POINTER;
1055 *out = nullptr;
1056 if (!desc) return E_INVALIDARG;
1057 if (!riid) return E_POINTER;
1058
1059 // FSPX description layout (docs/fspx.md §How the DLL reads it):
1060 struct XboxNativeComputePipelineStateDesc {
1061 ID3D12RootSignature* root_signature; // +0x00
1062 const void* kind0; // +0x08: dispatch state
1063 std::uint64_t kind0_size; // +0x10: 28 bytes
1064 const void* kind1; // +0x18: unknown
1065 std::uint64_t kind1_size; // +0x20: 20 bytes
1066 const void* kind6; // +0x28: RDNA2 program code
1067 std::uint64_t kind6_size; // +0x30: program size in bytes
1068 const void* kind7; // +0x38: resource/hash records
1069 std::uint64_t kind7_size; // +0x40: records size in bytes
1070 };
1071 const auto* xbox_desc = static_cast<const XboxNativeComputePipelineStateDesc*>(desc);
1072
1073 if (xbox_desc->kind0 || xbox_desc->kind0_size || xbox_desc->kind1 || xbox_desc->kind1_size ||
1074 xbox_desc->kind7 || xbox_desc->kind7_size) {
1075 static std::atomic<bool> logged{false};
1076 if (!logged.exchange(true, std::memory_order_relaxed)) {
1077 std::fprintf(stderr,
1078 "[rt] d3d12_xs: slot 67 FSPX metadata: kind0 0x%llx (%llu B), kind1 0x%llx (%llu B), kind7 0x%llx (%llu B)\n",
1079 static_cast<unsigned long long>(reinterpret_cast<std::uintptr_t>(xbox_desc->kind0)),
1080 static_cast<unsigned long long>(xbox_desc->kind0_size),
1081 static_cast<unsigned long long>(reinterpret_cast<std::uintptr_t>(xbox_desc->kind1)),
1082 static_cast<unsigned long long>(xbox_desc->kind1_size),
1083 static_cast<unsigned long long>(reinterpret_cast<std::uintptr_t>(xbox_desc->kind7)),
1084 static_cast<unsigned long long>(xbox_desc->kind7_size));
1085 }
1086 }
1087
1088 D3D12_COMPUTE_PIPELINE_STATE_DESC pc_desc{};
1089 pc_desc.pRootSignature = xbox_desc->root_signature;
1090 pc_desc.CS.pShaderBytecode = xbox_desc->kind6;
1091 pc_desc.CS.BytecodeLength = static_cast<SIZE_T>(xbox_desc->kind6_size);
1092 pc_desc.NodeMask = 0;
1093 pc_desc.CachedPSO = {nullptr, 0};
1094 pc_desc.Flags = D3D12_PIPELINE_STATE_FLAG_NONE;
1095
1096 return self->real->CreateComputePipelineState(&pc_desc, *riid, out);
1097}
1098
984HRESULT proxy_create_resource(DeviceProxy* self, const D3D12_HEAP_PROPERTIES* heap_properties, 1099HRESULT proxy_create_resource(DeviceProxy* self, const D3D12_HEAP_PROPERTIES* heap_properties,
985 D3D12_HEAP_FLAGS heap_flags, const D3D12_RESOURCE_DESC* xbox_desc, 1100 D3D12_HEAP_FLAGS heap_flags, const D3D12_RESOURCE_DESC* xbox_desc,
986 D3D12_RESOURCE_STATES initial_state, const D3D12_CLEAR_VALUE* clear_value, 1101 D3D12_RESOURCE_STATES initial_state, const D3D12_CLEAR_VALUE* clear_value,
@@ -1024,6 +1139,9 @@ std::uint64_t WINAPI proxy_slot(DeviceProxy* self, std::uint64_t a1, std::uint64
1024 } else if constexpr (Slot == 8) { 1139 } else if constexpr (Slot == 8) {
1025 return hr_to_u64(proxy_create_command_queue(self, reinterpret_cast<const D3D12_COMMAND_QUEUE_DESC*>(a1), 1140 return hr_to_u64(proxy_create_command_queue(self, reinterpret_cast<const D3D12_COMMAND_QUEUE_DESC*>(a1),
1026 reinterpret_cast<const IID*>(a2), reinterpret_cast<void**>(a3))); 1141 reinterpret_cast<const IID*>(a2), reinterpret_cast<void**>(a3)));
1142 } else if constexpr (Slot == 9) {
1143 return hr_to_u64(proxy_create_command_allocator(self, a1, reinterpret_cast<const IID*>(a2),
1144 reinterpret_cast<void**>(a3)));
1027 } else if constexpr (Slot == 36) { 1145 } else if constexpr (Slot == 36) {
1028 return hr_to_u64(proxy_create_fence(self, a1, a2, reinterpret_cast<const IID*>(a3), 1146 return hr_to_u64(proxy_create_fence(self, a1, a2, reinterpret_cast<const IID*>(a3),
1029 reinterpret_cast<void**>(a4))); 1147 reinterpret_cast<void**>(a4)));
@@ -1044,18 +1162,9 @@ std::uint64_t WINAPI proxy_slot(DeviceProxy* self, std::uint64_t a1, std::uint64
1044 self, reinterpret_cast<const D3D12_COMPUTE_PIPELINE_STATE_DESC*>(a1), a2, a3, 1162 self, reinterpret_cast<const D3D12_COMPUTE_PIPELINE_STATE_DESC*>(a1), a2, a3,
1045 reinterpret_cast<const IID*>(a4), reinterpret_cast<void**>(a5))); 1163 reinterpret_cast<const IID*>(a4), reinterpret_cast<void**>(a5)));
1046 } else if constexpr (Slot == 67) { 1164 } else if constexpr (Slot == 67) {
1047 // Measured in amd_fidelityfx_upscaler_xbox.dll (call at RVA 0x56d9): (desc, riid, out), named 1165 return hr_to_u64(proxy_create_compute_pipeline_from_native_code(
1048 // DeserializeComputePipelineStateX in the DLL's own messages. The desc is the root signature at +0x00, then 1166 self, reinterpret_cast<const void*>(a1), reinterpret_cast<const IID*>(a2),
1049 // pointer/size pairs for the shader's FSPX entries, with the native RDNA2 program at +0x28 (docs/fspx.md); 1167 reinterpret_cast<void**>(a3)));
1050 // the DLL falls back to slot 62 when it fails. The PC device's slot 67 is CreateProtectedResourceSession1, a
1051 // different method, so it is refused here, not forwarded.
1052 note_slot(67);
1053 static std::atomic<bool> logged{false};
1054 if (!logged.exchange(true, std::memory_order_relaxed))
1055 std::fprintf(stderr,
1056 "[rt] d3d12_xs: device slot 67 (Xbox DeserializeComputePipelineStateX) -> E_NOTIMPL\n");
1057 if (a3) *reinterpret_cast<void**>(a3) = nullptr;
1058 return hr_to_u64(E_NOTIMPL);
1059 } else if constexpr (Slot == 76) { 1168 } else if constexpr (Slot == 76) {
1060 return hr_to_u64(proxy_create_resource( 1169 return hr_to_u64(proxy_create_resource(
1061 self, reinterpret_cast<const D3D12_HEAP_PROPERTIES*>(a1), 1170 self, reinterpret_cast<const D3D12_HEAP_PROPERTIES*>(a1),
@@ -1186,13 +1295,19 @@ ID3D12Device* device_proxy_real_device(const void* device) {
1186} 1295}
1187 1296
1188bool device_slot_overridden(unsigned slot) { 1297bool device_slot_overridden(unsigned slot) {
1189 return slot <= 2 || slot == 8 || slot == 14 || slot == 31 || slot == 32 || slot == 34 || slot == 35 || 1298 return slot <= 2 || slot == 8 || slot == 9 || slot == 14 || slot == 31 || slot == 32 || slot == 34 || slot == 35 ||
1190 slot == 36 || slot == 45 || slot == 46 || slot == 50 || slot == 62 || slot == 67 || 1299 slot == 36 || slot == 45 || slot == 46 || slot == 50 || slot == 62 || slot == 67 ||
1191 slot == 75 || slot == 76; 1300 slot == 75 || slot == 76;
1192} 1301}
1193 1302
1194bool is_queue_proxy(const void* queue) { return is_child_proxy<ChildKind::queue>(queue); } 1303bool is_queue_proxy(const void* queue) { return is_child_proxy<ChildKind::queue>(queue); }
1195bool is_fence_proxy(const void* fence) { return is_child_proxy<ChildKind::fence>(fence); } 1304bool is_fence_proxy(const void* fence) { return is_child_proxy<ChildKind::fence>(fence); }
1305bool is_allocator_proxy(const void* allocator) { return is_child_proxy<ChildKind::allocator>(allocator); }
1306
1307ID3D12CommandAllocator* allocator_proxy_real_allocator(const void* allocator) {
1308 if (!is_allocator_proxy(allocator)) return nullptr;
1309 return reinterpret_cast<ID3D12CommandAllocator*>(static_cast<const ChildProxy*>(allocator)->real);
1310}
1196 1311
1197ID3D12CommandQueue* queue_proxy_real_queue(const void* queue) { 1312ID3D12CommandQueue* queue_proxy_real_queue(const void* queue) {
1198 if (!is_queue_proxy(queue)) return nullptr; 1313 if (!is_queue_proxy(queue)) return nullptr;
@@ -1214,9 +1329,13 @@ unsigned fence_proxy_slot_count(const void* fence) {
1214 1329
1215unsigned queue_proxy_table_size() { return kQueueSlots; } 1330unsigned queue_proxy_table_size() { return kQueueSlots; }
1216unsigned fence_proxy_table_size() { return kFenceSlots; } 1331unsigned fence_proxy_table_size() { return kFenceSlots; }
1332unsigned allocator_proxy_table_size() { return kAllocatorSlots; }
1333unsigned allocator_proxy_slot_count(const void* allocator) {
1334 return is_allocator_proxy(allocator) ? static_cast<const ChildProxy*>(allocator)->slot_count : 0;
1335}
1217 1336
1218unsigned long command_object_proxy_ref_count(const void* object) { 1337unsigned long command_object_proxy_ref_count(const void* object) {
1219 if (!is_queue_proxy(object) && !is_fence_proxy(object)) return 0; 1338 if (!is_queue_proxy(object) && !is_fence_proxy(object) && !is_allocator_proxy(object)) return 0;
1220 return static_cast<const ChildProxy*>(object)->refs.load(std::memory_order_relaxed); 1339 return static_cast<const ChildProxy*>(object)->refs.load(std::memory_order_relaxed);
1221} 1340}
1222 1341
@@ -1251,8 +1370,24 @@ std::uint64_t fence_table_overruns() {
1251bool command_object_tables_guarded() { 1370bool command_object_tables_guarded() {
1252 get_child_vtable<ChildKind::queue>(); 1371 get_child_vtable<ChildKind::queue>();
1253 get_child_vtable<ChildKind::fence>(); 1372 get_child_vtable<ChildKind::fence>();
1373 get_child_vtable<ChildKind::allocator>();
1254 return ChildStats<ChildKind::queue>::table_end.load(std::memory_order_acquire) && 1374 return ChildStats<ChildKind::queue>::table_end.load(std::memory_order_acquire) &&
1255 ChildStats<ChildKind::fence>::table_end.load(std::memory_order_acquire); 1375 ChildStats<ChildKind::fence>::table_end.load(std::memory_order_acquire) &&
1376 ChildStats<ChildKind::allocator>::table_end.load(std::memory_order_acquire);
1377}
1378
1379std::uint64_t allocator_slot_hits(unsigned slot) {
1380 using S = ChildStats<ChildKind::allocator>;
1381 return slot < S::kSlots ? S::hits[slot].load(std::memory_order_relaxed) : 0;
1382}
1383
1384bool allocator_slot_first_call_seen(unsigned slot) {
1385 using S = ChildStats<ChildKind::allocator>;
1386 return slot < S::kSlots && S::first[slot].load(std::memory_order_relaxed);
1387}
1388
1389std::uint64_t allocator_table_overruns() {
1390 return ChildStats<ChildKind::allocator>::overruns.load(std::memory_order_relaxed);
1256} 1391}
1257 1392
1258bool heap_slot_overridden(unsigned slot) { 1393bool heap_slot_overridden(unsigned slot) {
@@ -1292,6 +1427,7 @@ void reset_device_proxy_stats() {
1292 } 1427 }
1293 reset_child_stats<ChildKind::queue>(); 1428 reset_child_stats<ChildKind::queue>();
1294 reset_child_stats<ChildKind::fence>(); 1429 reset_child_stats<ChildKind::fence>();
1430 reset_child_stats<ChildKind::allocator>();
1295} 1431}
1296 1432
1297} // namespace rt::d3d12_xs 1433} // namespace rt::d3d12_xs
diff --git a/runtime/shims/d3d12_xs_device.h b/runtime/shims/d3d12_xs_device.h
index 510560516..12ac5a78f 100644
--- a/runtime/shims/d3d12_xs_device.h
+++ b/runtime/shims/d3d12_xs_device.h
@@ -3,6 +3,9 @@
3// Measured Xbox device deviations used here (vtable indices, x64): 3// Measured Xbox device deviations used here (vtable indices, x64):
4// slot 62 CreateComputePipelineState(desc, w2, w3, iid, out): two words (0 from XboxBvhBuilder, meaning unknown) 4// slot 62 CreateComputePipelineState(desc, w2, w3, iid, out): two words (0 from XboxBvhBuilder, meaning unknown)
5// before the IID. The PC slot 62 is CreateStateObject. 5// before the IID. The PC slot 62 is CreateStateObject.
6// slot 67 CreateComputePipelineState from native code (desc, iid, out): converts the Xbox native-code desc
7// (+0x00 root signature, +0x28 code, +0x30 size) to D3D12_COMPUTE_PIPELINE_STATE_DESC and forwards
8// to PC CreateComputePipelineState (slot 11). The PC slot 67 is CreateProtectedResourceSession1.
6// slot 76 resource creation -> PC CreateCommittedResource (PC slot 27), with the Xbox layout word ignored. 9// slot 76 resource creation -> PC CreateCommittedResource (PC slot 27), with the Xbox layout word ignored.
7// The measured slots 9/10 (GetCPU/GPUDescriptorHandleForHeapStart) are ID3D12DescriptorHeap methods, not device 10// The measured slots 9/10 (GetCPU/GPUDescriptorHandleForHeapStart) are ID3D12DescriptorHeap methods, not device
8// methods: the PC device's 9/10 are CreateCommandAllocator/CreateGraphicsPipelineState and are forwarded unchanged. 11// methods: the PC device's 9/10 are CreateCommandAllocator/CreateGraphicsPipelineState and are forwarded unchanged.
@@ -57,8 +60,9 @@ unsigned device_proxy_slot_count(const void* device);
57ID3D12Device* device_proxy_real_device(const void* device); 60ID3D12Device* device_proxy_real_device(const void* device);
58 61
59// True for slots the proxy handles itself rather than forwarding verbatim: IUnknown (0-2), 8 and 75 (queue 62// True for slots the proxy handles itself rather than forwarding verbatim: IUnknown (0-2), 8 and 75 (queue
60// proxies), 14, 31/34/35/45/46/50 (proxies unwrapped), 32 and 36 (fence proxies), 62, 67 and 76. 63// proxies), 9 (allocator proxies), 14, 31/34/35/45/46/50 (proxies unwrapped), 32 and 36 (fence proxies), 62, 67
61// Slots 9 and 10 are intentionally false; the handle conversion is on the heap proxy. 64// and 76. Slot 10 is intentionally false: the measured 9/10 handle conversion is on the heap proxy, and device
65// slot 9 is CreateCommandAllocator, which the proxy handles for the allocator proxy.
62bool device_slot_overridden(unsigned slot); 66bool device_slot_overridden(unsigned slot);
63 67
64// Queue and fence proxies created by device slots 8/75 and 36. The real_* accessors return the wrapped object 68// Queue and fence proxies created by device slots 8/75 and 36. The real_* accessors return the wrapped object
@@ -72,7 +76,7 @@ unsigned queue_proxy_slot_count(const void* queue);
72unsigned fence_proxy_slot_count(const void* fence); 76unsigned fence_proxy_slot_count(const void* fence);
73unsigned queue_proxy_table_size(); 77unsigned queue_proxy_table_size();
74unsigned fence_proxy_table_size(); 78unsigned fence_proxy_table_size();
75// Live references on a queue or fence proxy (0 for anything else). Test helper. 79// Live references on a queue, fence or allocator proxy (0 for anything else). Test helper.
76unsigned long command_object_proxy_ref_count(const void* object); 80unsigned long command_object_proxy_ref_count(const void* object);
77// Per-slot call counters and first-call flags, shared by all queue proxies and all fence proxies. 81// Per-slot call counters and first-call flags, shared by all queue proxies and all fence proxies.
78std::uint64_t queue_slot_hits(unsigned slot); 82std::uint64_t queue_slot_hits(unsigned slot);
@@ -82,8 +86,28 @@ bool fence_slot_first_call_seen(unsigned slot);
82// Vtable reads past a queue or fence proxy table that faulted in its guard region (counted by the fault logger). 86// Vtable reads past a queue or fence proxy table that faulted in its guard region (counted by the fault logger).
83std::uint64_t queue_table_overruns(); 87std::uint64_t queue_table_overruns();
84std::uint64_t fence_table_overruns(); 88std::uint64_t fence_table_overruns();
85// True when both tables sit in front of their guard region (false only if the reservation failed). 89// True when the queue, fence and allocator tables sit in front of their guard regions (false only if a reservation
90// or the fault logger failed).
86bool command_object_tables_guarded(); 91bool command_object_tables_guarded();
92
93// Command allocator proxies (device slot 9): the public chain (9 slots: the base chain and Reset) is forwarded, a
94// slot past it up to the end of the table (64 slots) is logged and refused with E_NOTIMPL, and a read past the
95// table faults in a guard region, as for queues and fences. The console allocator's extra methods are not
96// measured and not guessed. Slot 9 wraps only an allocator that answers kLeonidaCommandAllocatorTag, Leonida's
97// own Vulkan-layer allocator: its command lists resolve the proxy (CreateCommandList, Reset). A PC runtime
98// allocator goes back unchanged, because the PC runtime's lists would take a proxy for their own allocator; a
99// command-list proxy that unwraps at Reset is what lets the host backend wrap allocators too.
100// {7d0e6b51-34a2-4f0c-9a61-0c5b2e8f4a10}: the Vulkan layer's CommandAllocator answers it with its implementation.
101inline constexpr GUID kLeonidaCommandAllocatorTag{
102 0x7d0e6b51, 0x34a2, 0x4f0c, {0x9a, 0x61, 0x0c, 0x5b, 0x2e, 0x8f, 0x4a, 0x10}};
103bool is_allocator_proxy(const void* allocator);
104// The wrapped allocator (no reference added), or null when `allocator` is not an allocator proxy.
105ID3D12CommandAllocator* allocator_proxy_real_allocator(const void* allocator);
106unsigned allocator_proxy_slot_count(const void* allocator);
107unsigned allocator_proxy_table_size();
108std::uint64_t allocator_slot_hits(unsigned slot);
109bool allocator_slot_first_call_seen(unsigned slot);
110std::uint64_t allocator_table_overruns();
87// Heap slots 0-2, 7 (GetDevice -> device proxy) and 9/10 (handle conversion). 111// Heap slots 0-2, 7 (GetDevice -> device proxy) and 9/10 (handle conversion).
88bool heap_slot_overridden(unsigned slot); 112bool heap_slot_overridden(unsigned slot);
89 113
diff --git a/runtime/shims/dxgi_com.cpp b/runtime/shims/dxgi_com.cpp
index af3b96679..c4a7530c4 100644
--- a/runtime/shims/dxgi_com.cpp
+++ b/runtime/shims/dxgi_com.cpp
@@ -22,6 +22,10 @@ void stub(const char* method) {
22 if (seen.insert(method).second) std::fprintf(stderr, "[rt] dxgi: unimplemented %s\n", method); 22 if (seen.insert(method).second) std::fprintf(stderr, "[rt] dxgi: unimplemented %s\n", method);
23} 23}
24 24
25bool valid_flip_buffer_count(UINT count) {
26 return count >= 2 && count <= DXGI_MAX_SWAP_CHAIN_BUFFERS;
27}
28
25VkFormat dxgi_to_vk_format(DXGI_FORMAT fmt) { 29VkFormat dxgi_to_vk_format(DXGI_FORMAT fmt) {
26 switch (fmt) { 30 switch (fmt) {
27 case DXGI_FORMAT_B8G8R8A8_UNORM: return VK_FORMAT_B8G8R8A8_UNORM; 31 case DXGI_FORMAT_B8G8R8A8_UNORM: return VK_FORMAT_B8G8R8A8_UNORM;
@@ -128,14 +132,13 @@ public:
128 const VkExtent2D size = size_or_client(desc.Width, desc.Height, {256u, 256u}); 132 const VkExtent2D size = size_or_client(desc.Width, desc.Height, {256u, 256u});
129 const std::uint32_t w = size.width; 133 const std::uint32_t w = size.width;
130 const std::uint32_t h = size.height; 134 const std::uint32_t h = size.height;
131 const std::uint32_t count = desc.BufferCount ? desc.BufferCount : 2u;
132 VkFormat vk_fmt = VK_FORMAT_UNDEFINED; 135 VkFormat vk_fmt = VK_FORMAT_UNDEFINED;
133 if (desc.Format != DXGI_FORMAT_UNKNOWN) { 136 if (desc.Format != DXGI_FORMAT_UNKNOWN) {
134 vk_fmt = dxgi_to_vk_format(desc.Format); 137 vk_fmt = dxgi_to_vk_format(desc.Format);
135 if (vk_fmt == VK_FORMAT_UNDEFINED) return false; 138 if (vk_fmt == VK_FORMAT_UNDEFINED) return false;
136 } 139 }
137 const bool allow_tearing = (flags_ & DXGI_SWAP_CHAIN_FLAG_ALLOW_TEARING) != 0; 140 const bool allow_tearing = (flags_ & DXGI_SWAP_CHAIN_FLAG_ALLOW_TEARING) != 0;
138 if (!swapchain_.create(hwnd, w, h, vk_fmt, count, allow_tearing)) return false; 141 if (!swapchain_.create(hwnd, w, h, vk_fmt, desc.BufferCount, allow_tearing)) return false;
139 if (flags_ & DXGI_SWAP_CHAIN_FLAG_FRAME_LATENCY_WAITABLE_OBJECT) { 142 if (flags_ & DXGI_SWAP_CHAIN_FLAG_FRAME_LATENCY_WAITABLE_OBJECT) {
140 // DXGI: waitable swapchains default to maximum frame latency 1. 143 // DXGI: waitable swapchains default to maximum frame latency 1.
141 max_frame_latency_.store(1, std::memory_order_relaxed); 144 max_frame_latency_.store(1, std::memory_order_relaxed);
@@ -234,11 +237,15 @@ public:
234 } 237 }
235 238
236 HRESULT STDMETHODCALLTYPE ResizeBuffers(UINT count, UINT width, UINT height, DXGI_FORMAT fmt, UINT flags) override { 239 HRESULT STDMETHODCALLTYPE ResizeBuffers(UINT count, UINT width, UINT height, DXGI_FORMAT fmt, UINT flags) override {
240 if (count != 0 && !valid_flip_buffer_count(count)) return E_INVALIDARG;
237 VkFormat vk_fmt = VK_FORMAT_UNDEFINED; 241 VkFormat vk_fmt = VK_FORMAT_UNDEFINED;
238 if (fmt != DXGI_FORMAT_UNKNOWN) { 242 if (fmt != DXGI_FORMAT_UNKNOWN) {
239 vk_fmt = dxgi_to_vk_format(fmt); 243 vk_fmt = dxgi_to_vk_format(fmt);
240 if (vk_fmt == VK_FORMAT_UNDEFINED) return DXGI_ERROR_UNSUPPORTED; 244 if (vk_fmt == VK_FORMAT_UNDEFINED) return DXGI_ERROR_UNSUPPORTED;
241 } 245 }
246 constexpr UINT creation_only_flags = DXGI_SWAP_CHAIN_FLAG_FRAME_LATENCY_WAITABLE_OBJECT |
247 DXGI_SWAP_CHAIN_FLAG_ALLOW_TEARING;
248 if ((flags & creation_only_flags) != (flags_ & creation_only_flags)) return E_INVALIDARG;
242 // DXGI refuses to resize while the app still holds a back buffer reference. 249 // DXGI refuses to resize while the app still holds a back buffer reference.
243 for (auto* bb : buffers_) 250 for (auto* bb : buffers_)
244 if (bb->held_by_app()) return DXGI_ERROR_INVALID_CALL; 251 if (bb->held_by_app()) return DXGI_ERROR_INVALID_CALL;
@@ -246,10 +253,10 @@ public:
246 const VkExtent2D size = size_or_client(width, height, swapchain_.extent()); 253 const VkExtent2D size = size_or_client(width, height, swapchain_.extent());
247 const std::uint32_t w = size.width; 254 const std::uint32_t w = size.width;
248 const std::uint32_t h = size.height; 255 const std::uint32_t h = size.height;
249 const UINT waitable_bit = flags_ & DXGI_SWAP_CHAIN_FLAG_FRAME_LATENCY_WAITABLE_OBJECT; 256 const UINT next_flags = flags ? flags : flags_;
250 const UINT next_flags = (flags ? flags : flags_) | waitable_bit;
251 const bool allow_tearing = (next_flags & DXGI_SWAP_CHAIN_FLAG_ALLOW_TEARING) != 0; 257 const bool allow_tearing = (next_flags & DXGI_SWAP_CHAIN_FLAG_ALLOW_TEARING) != 0;
252 if (!swapchain_.resize(w, h, vk_fmt, count, allow_tearing)) return E_FAIL; 258 if (!swapchain_.resize(w, h, vk_fmt, count, allow_tearing)) return E_FAIL;
259 statistics_disjoint_.store(true, std::memory_order_relaxed);
253 flags_ = next_flags; 260 flags_ = next_flags;
254 register_buffers(); 261 register_buffers();
255 std::uint32_t next = 0; 262 std::uint32_t next = 0;
@@ -259,8 +266,11 @@ public:
259 HRESULT STDMETHODCALLTYPE ResizeTarget(const DXGI_MODE_DESC*) override { return S_OK; } 266 HRESULT STDMETHODCALLTYPE ResizeTarget(const DXGI_MODE_DESC*) override { return S_OK; }
260 HRESULT STDMETHODCALLTYPE GetContainingOutput(IDXGIOutput**) override { return DXGI_ERROR_NOT_CURRENTLY_AVAILABLE; } 267 HRESULT STDMETHODCALLTYPE GetContainingOutput(IDXGIOutput**) override { return DXGI_ERROR_NOT_CURRENTLY_AVAILABLE; }
261 HRESULT STDMETHODCALLTYPE GetFrameStatistics(DXGI_FRAME_STATISTICS* stats) override { 268 HRESULT STDMETHODCALLTYPE GetFrameStatistics(DXGI_FRAME_STATISTICS* stats) override {
262 if (!stats) return E_INVALIDARG; 269 if (!stats) return DXGI_ERROR_INVALID_CALL;
263 std::memset(stats, 0, sizeof(*stats)); 270 std::memset(stats, 0, sizeof(*stats));
271 // Native DXGI reports the discontinuity once, on the first valid query after creation or resize.
272 if (statistics_disjoint_.exchange(false, std::memory_order_relaxed))
273 return DXGI_ERROR_FRAME_STATISTICS_DISJOINT;
264 const UINT count = present_count_.load(std::memory_order_relaxed); 274 const UINT count = present_count_.load(std::memory_order_relaxed);
265 stats->PresentCount = count; 275 stats->PresentCount = count;
266 stats->PresentRefreshCount = count; 276 stats->PresentRefreshCount = count;
@@ -425,6 +435,7 @@ private:
425 HANDLE waitable_ = nullptr; 435 HANDLE waitable_ = nullptr;
426 std::vector<BackBufferResource*> buffers_; 436 std::vector<BackBufferResource*> buffers_;
427 std::atomic<UINT> present_count_{0}; 437 std::atomic<UINT> present_count_{0};
438 std::atomic<bool> statistics_disjoint_{true};
428 std::atomic<LONGLONG> last_present_qpc_{0}; 439 std::atomic<LONGLONG> last_present_qpc_{0};
429 std::atomic<UINT> max_frame_latency_{2}; 440 std::atomic<UINT> max_frame_latency_{2};
430 DXGI_RGBA background_color_{0, 0, 0, 0}; 441 DXGI_RGBA background_color_{0, 0, 0, 0};
@@ -777,6 +788,7 @@ public:
777 if (!out) return E_POINTER; 788 if (!out) return E_POINTER;
778 *out = nullptr; 789 *out = nullptr;
779 if (!hwnd || !desc) return E_INVALIDARG; 790 if (!hwnd || !desc) return E_INVALIDARG;
791 if (!valid_flip_buffer_count(desc->BufferCount)) return DXGI_ERROR_INVALID_CALL;
780 auto* sc = new SwapChain(this, device, context_, gipa_, instance_, physical_, gdpa_, queue_, queue_family_); 792 auto* sc = new SwapChain(this, device, context_, gipa_, instance_, physical_, gdpa_, queue_, queue_family_);
781 if (!sc->init(hwnd, *desc)) { 793 if (!sc->init(hwnd, *desc)) {
782 sc->Release(); 794 sc->Release();
@@ -785,16 +797,46 @@ public:
785 *out = static_cast<IDXGISwapChain1*>(sc); 797 *out = static_cast<IDXGISwapChain1*>(sc);
786 return S_OK; 798 return S_OK;
787 } 799 }
788 HRESULT STDMETHODCALLTYPE CreateSwapChainForCoreWindow(IUnknown*, IUnknown*, const DXGI_SWAP_CHAIN_DESC1*, 800 HRESULT STDMETHODCALLTYPE CreateSwapChainForCoreWindow(IUnknown* device, IUnknown* window,
789 IDXGIOutput*, IDXGISwapChain1**) override { 801 const DXGI_SWAP_CHAIN_DESC1* desc,
790 return E_NOTIMPL; 802 IDXGIOutput* restrict_to_output,
803 IDXGISwapChain1** out) override {
804 if (!out) return E_POINTER;
805 *out = nullptr;
806 if (!device || !window || !desc) return E_INVALIDARG;
807 // UWP / Game Core Scarlett titles present to an ICoreWindow. Extract the underlying
808 // Win32 HWND via ICoreWindowInterop.
809 static constexpr GUID kIID_ICoreWindowInterop = {
810 0x45D64A29, 0xA63E, 0x4CB6, {0xB4, 0x98, 0x57, 0x81, 0xD2, 0x98, 0xCB, 0x4F}};
811 struct ICoreWindowInterop : public IUnknown {
812 virtual HRESULT STDMETHODCALLTYPE get_WindowHandle(HWND* hwnd) = 0;
813 virtual HRESULT STDMETHODCALLTYPE put_MessageHandled(unsigned char value) = 0;
814 };
815 ICoreWindowInterop* interop = nullptr;
816 if (FAILED(window->QueryInterface(kIID_ICoreWindowInterop, reinterpret_cast<void**>(&interop))) || !interop) {
817 return DXGI_ERROR_INVALID_CALL;
818 }
819 HWND hwnd = nullptr;
820 const HRESULT hr = interop->get_WindowHandle(&hwnd);
821 interop->Release();
822 if (FAILED(hr) || !hwnd) return DXGI_ERROR_INVALID_CALL;
823 return CreateSwapChainForHwnd(device, hwnd, desc, nullptr, restrict_to_output, out);
791 } 824 }
792 HRESULT STDMETHODCALLTYPE GetSharedResourceAdapterLuid(HANDLE, LUID*) override { return E_NOTIMPL; } 825 HRESULT STDMETHODCALLTYPE GetSharedResourceAdapterLuid(HANDLE, LUID*) override { return E_NOTIMPL; }
793 HRESULT STDMETHODCALLTYPE RegisterStereoStatusWindow(HWND, UINT, DWORD*) override { return E_NOTIMPL; } 826 HRESULT STDMETHODCALLTYPE RegisterStereoStatusWindow(HWND, UINT, DWORD*) override { return E_NOTIMPL; }
794 HRESULT STDMETHODCALLTYPE RegisterStereoStatusEvent(HANDLE, DWORD*) override { return E_NOTIMPL; } 827 HRESULT STDMETHODCALLTYPE RegisterStereoStatusEvent(HANDLE, DWORD*) override { return E_NOTIMPL; }
795 void STDMETHODCALLTYPE UnregisterStereoStatus(DWORD) override {} 828 void STDMETHODCALLTYPE UnregisterStereoStatus(DWORD) override {}
796 HRESULT STDMETHODCALLTYPE RegisterOcclusionStatusWindow(HWND, UINT, DWORD*) override { return E_NOTIMPL; } 829 HRESULT STDMETHODCALLTYPE RegisterOcclusionStatusWindow(HWND hwnd, UINT msg, DWORD* cookie) override {
797 HRESULT STDMETHODCALLTYPE RegisterOcclusionStatusEvent(HANDLE, DWORD*) override { return E_NOTIMPL; } 830 (void)msg;
831 if (!hwnd || !cookie) return DXGI_ERROR_INVALID_CALL;
832 *cookie = next_occlusion_cookie_.fetch_add(1, std::memory_order_relaxed);
833 return S_OK;
834 }
835 HRESULT STDMETHODCALLTYPE RegisterOcclusionStatusEvent(HANDLE event, DWORD* cookie) override {
836 if (!event || !cookie) return DXGI_ERROR_INVALID_CALL;
837 *cookie = next_occlusion_cookie_.fetch_add(1, std::memory_order_relaxed);
838 return S_OK;
839 }
798 void STDMETHODCALLTYPE UnregisterOcclusionStatus(DWORD) override {} 840 void STDMETHODCALLTYPE UnregisterOcclusionStatus(DWORD) override {}
799 HRESULT STDMETHODCALLTYPE CreateSwapChainForComposition(IUnknown*, const DXGI_SWAP_CHAIN_DESC1*, IDXGIOutput*, 841 HRESULT STDMETHODCALLTYPE CreateSwapChainForComposition(IUnknown*, const DXGI_SWAP_CHAIN_DESC1*, IDXGIOutput*,
800 IDXGISwapChain1**) override { 842 IDXGISwapChain1**) override {
@@ -880,6 +922,7 @@ private:
880 HWND assoc_hwnd_ = nullptr; 922 HWND assoc_hwnd_ = nullptr;
881 mutable std::once_flag tearing_once_; 923 mutable std::once_flag tearing_once_;
882 bool tearing_supported_ = false; 924 bool tearing_supported_ = false;
925 std::atomic<DWORD> next_occlusion_cookie_{1};
883}; 926};
884 927
885} // namespace 928} // namespace
diff --git a/runtime/shims/file_system.cpp b/runtime/shims/file_system.cpp
index 38c3194fe..f0ae08811 100644
--- a/runtime/shims/file_system.cpp
+++ b/runtime/shims/file_system.cpp
@@ -142,7 +142,9 @@ std::filesystem::path marker(const std::filesystem::path& overlay, const std::ve
142bool deleted(const std::filesystem::path& overlay, const std::vector<std::wstring>& parts) { 142bool deleted(const std::filesystem::path& overlay, const std::vector<std::wstring>& parts) {
143 if (overlay.empty() || parts.empty()) return false; 143 if (overlay.empty() || parts.empty()) return false;
144 std::error_code ec; 144 std::error_code ec;
145 return std::filesystem::exists(marker(overlay, parts), ec); 145 // Only regular files are deletion markers; parent directories inside .gta6rt-deleted/ exist only to hold markers
146 // for nested deleted files and must not hide the corresponding ancestor directories in the package.
147 return std::filesystem::is_regular_file(marker(overlay, parts), ec);
146} 148}
147 149
148Target read_target(const std::wstring& path) { 150Target read_target(const std::wstring& path) {
diff --git a/runtime/shims/gameinput.cpp b/runtime/shims/gameinput.cpp
index 2b55022f4..3b66e2ab9 100644
--- a/runtime/shims/gameinput.cpp
+++ b/runtime/shims/gameinput.cpp
@@ -50,8 +50,9 @@ using namespace gi;
50 50
51namespace { 51namespace {
52 52
53constexpr uint32_t kSupportedKinds = 53constexpr uint32_t kBaseKinds =
54 GameInputKindControllerAxis | GameInputKindControllerButton | GameInputKindGamepad | GameInputKindUiNavigation; 54 GameInputKindControllerAxis | GameInputKindControllerButton | GameInputKindGamepad | GameInputKindUiNavigation;
55constexpr uint32_t kSupportedKinds = kBaseKinds | GameInputKindMotion; // everything a reading may carry
55constexpr uint32_t kAxisCount = 6; // LX, LY, RX, RY, LT, RT 56constexpr uint32_t kAxisCount = 6; // LX, LY, RX, RY, LT, RT
56constexpr uint32_t kButtonCount = SDL_GAMEPAD_BUTTON_COUNT; 57constexpr uint32_t kButtonCount = SDL_GAMEPAD_BUTTON_COUNT;
57constexpr uint32_t kConnectedStatus = GameInputDeviceConnected | GameInputDeviceInputEnabled | GameInputDeviceOutputEnabled; 58constexpr uint32_t kConnectedStatus = GameInputDeviceConnected | GameInputDeviceInputEnabled | GameInputDeviceOutputEnabled;
@@ -61,6 +62,14 @@ constexpr uint64_t kBatteryRefreshUs = 1'000'000;
61constexpr int kDsEffectSize = 47; // the DualSense effects block SDL_SendGamepadEffect forwards (SDL's DS5EffectsState_t) 62constexpr int kDsEffectSize = 47; // the DualSense effects block SDL_SendGamepadEffect forwards (SDL's DS5EffectsState_t)
62constexpr uint64_t kHistoryUs = 500'000; // a reading stays in the history until the one after it is this old 63constexpr uint64_t kHistoryUs = 500'000; // a reading stays in the history until the one after it is this old
63constexpr size_t kHistoryCap = 512; // readings per pad, whatever the poll rate 64constexpr size_t kHistoryCap = 512; // readings per pad, whatever the poll rate
65// Motion. SDL gives accel in m/s^2 (gravity included) and gyro in rad/s; the state the ABI defines carries signed
66// fractions of the maxima motionInfo reports, so a reading stays within -1..1 however hard the pad is shaken. The
67// maxima are this shim's choice: SDL does not expose a sensor range, and 2 g / 2000 deg/s are the ranges a
68// DualSense's accelerometer and gyro can express (VERIFY: against the game and a real pad, docs/gameinput.md).
69constexpr float kMaxAcceleration = 19.6133f; // 2 g in m/s^2
70constexpr float kMaxAngularVelocity = 34.9066f; // 2000 deg/s in rad/s
71constexpr float kMotionSensorRate = 250.0f; // requested sample rate; the device clamps to what it has
72constexpr uint64_t kMotionReadingUs = 8'000; // a motion pad streams readings at ~125 Hz so the history stays sane
64 73
65uint64_t now_us() { 74uint64_t now_us() {
66 static const LARGE_INTEGER freq = [] { LARGE_INTEGER f; QueryPerformanceFrequency(&f); return f; }(); 75 static const LARGE_INTEGER freq = [] { LARGE_INTEGER f; QueryPerformanceFrequency(&f); return f; }();
@@ -133,6 +142,8 @@ struct Snapshot {
133 float axes[kAxisCount] = {}; 142 float axes[kAxisCount] = {};
134 bool buttons[kButtonCount] = {}; 143 bool buttons[kButtonCount] = {};
135 bool guide = false; 144 bool guide = false;
145 GameInputMotionState motion{}; // valid only when has_motion; does not take part in operator==
146 bool has_motion = false;
136 bool operator==(const Snapshot& o) const { // field by field: the padding is not initialised 147 bool operator==(const Snapshot& o) const { // field by field: the padding is not initialised
137 const GameInputGamepadState &a = gamepad, &b = o.gamepad; 148 const GameInputGamepadState &a = gamepad, &b = o.gamepad;
138 return a.buttons == b.buttons && a.leftTrigger == b.leftTrigger && a.rightTrigger == b.rightTrigger && 149 return a.buttons == b.buttons && a.leftTrigger == b.leftTrigger && a.rightTrigger == b.rightTrigger &&
@@ -164,7 +175,9 @@ public:
164 return r; 175 return r;
165 } 176 }
166 177
167 uint32_t STDMETHODCALLTYPE GetInputKind() override { return kSupportedKinds; } 178 uint32_t STDMETHODCALLTYPE GetInputKind() override {
179 return s_.has_motion ? kSupportedKinds : kBaseKinds; // a reading of a pad without sensors carries no motion
180 }
168 uint64_t STDMETHODCALLTYPE GetSequenceNumber(uint32_t) override { return seq_; } 181 uint64_t STDMETHODCALLTYPE GetSequenceNumber(uint32_t) override { return seq_; }
169 uint64_t STDMETHODCALLTYPE GetTimestamp() override { return ts_; } 182 uint64_t STDMETHODCALLTYPE GetTimestamp() override { return ts_; }
170 void STDMETHODCALLTYPE GetDevice(IGameInputDevice** device) override; 183 void STDMETHODCALLTYPE GetDevice(IGameInputDevice** device) override;
@@ -191,7 +204,11 @@ public:
191 bool STDMETHODCALLTYPE GetMouseState(void*) override { return false; } 204 bool STDMETHODCALLTYPE GetMouseState(void*) override { return false; }
192 uint32_t STDMETHODCALLTYPE GetTouchCount() override { return 0; } 205 uint32_t STDMETHODCALLTYPE GetTouchCount() override { return 0; }
193 uint32_t STDMETHODCALLTYPE GetTouchState(uint32_t, void*) override { return 0; } 206 uint32_t STDMETHODCALLTYPE GetTouchState(uint32_t, void*) override { return 0; }
194 bool STDMETHODCALLTYPE GetMotionState(void*) override { return false; } 207 bool STDMETHODCALLTYPE GetMotionState(void* state) override {
208 if (!state || !s_.has_motion) return false;
209 *static_cast<GameInputMotionState*>(state) = s_.motion;
210 return true;
211 }
195 bool STDMETHODCALLTYPE GetArcadeStickState(void*) override { return false; } 212 bool STDMETHODCALLTYPE GetArcadeStickState(void*) override { return false; }
196 bool STDMETHODCALLTYPE GetFlightStickState(void*) override { return false; } 213 bool STDMETHODCALLTYPE GetFlightStickState(void*) override { return false; }
197 bool STDMETHODCALLTYPE GetGamepadState(GameInputGamepadState* state) override { 214 bool STDMETHODCALLTYPE GetGamepadState(GameInputGamepadState* state) override {
@@ -281,6 +298,7 @@ public:
281 GameInputControllerButtonInfo button_info[kButtonCount]{}; 298 GameInputControllerButtonInfo button_info[kButtonCount]{};
282 GameInputGamepadInfo gamepad_info{}; 299 GameInputGamepadInfo gamepad_info{};
283 GameInputUiNavigationInfo ui_info{}; 300 GameInputUiNavigationInfo ui_info{};
301 GameInputMotionInfo motion_info{}; // filled only when the pad has sensors; info.motionInfo points at it
284 std::atomic<uint32_t> status{GameInputDeviceNoStatus}; 302 std::atomic<uint32_t> status{GameInputDeviceNoStatus};
285 std::deque<Reading*> history; // one reference each, oldest first; the newest is the current reading 303 std::deque<Reading*> history; // one reference each, oldest first; the newest is the current reading
286 uint64_t evicted_order = 0; // order of the newest reading dropped from history 304 uint64_t evicted_order = 0; // order of the newest reading dropped from history
@@ -294,9 +312,10 @@ public:
294 SDL_Gamepad* pad = nullptr; 312 SDL_Gamepad* pad = nullptr;
295 SDL_JoystickID id = 0; 313 SDL_JoystickID id = 0;
296 int player = -1; 314 int player = -1;
297 bool is_dualsense = false, has_rumble = false, has_trigger_rumble = false; 315 bool is_dualsense = false, has_rumble = false, has_trigger_rumble = false, has_motion = false;
298 rt::gameinput::OutputState sent{}; 316 rt::gameinput::OutputState sent{};
299 Snapshot last_snap{}; // what the latest reading holds 317 Snapshot last_snap{}; // what the latest reading holds
318 uint64_t last_reading_us = 0; // for the motion cadence: readings stream at ~125 Hz on pads with sensors
300 uint64_t motors_sent_at = 0, triggers_sent_at = 0, battery_at = 0; 319 uint64_t motors_sent_at = 0, triggers_sent_at = 0, battery_at = 0;
301 bool ds_sent_once = false; 320 bool ds_sent_once = false;
302 321
@@ -446,7 +465,10 @@ uint16_t to_u16(float v) { return static_cast<uint16_t>(std::lround(std::clamp(v
446 465
447float axis(SDL_Gamepad* p, SDL_GamepadAxis a) { return std::max(-1.0f, SDL_GetGamepadAxis(p, a) / 32767.0f); } 466float axis(SDL_Gamepad* p, SDL_GamepadAxis a) { return std::max(-1.0f, SDL_GetGamepadAxis(p, a) / 32767.0f); }
448 467
449Snapshot read_pad(SDL_Gamepad* p) { 468float norm(float v, float max) { return std::clamp(v / max, -1.0f, 1.0f); }
469
470Snapshot read_pad(Device* d) {
471 SDL_Gamepad* p = d->pad;
450 Snapshot s; 472 Snapshot s;
451 auto down = [p](SDL_GamepadButton b) { return SDL_GetGamepadButton(p, b); }; 473 auto down = [p](SDL_GamepadButton b) { return SDL_GetGamepadButton(p, b); };
452 struct Map { SDL_GamepadButton sdl; uint32_t gi; }; 474 struct Map { SDL_GamepadButton sdl; uint32_t gi; };
@@ -486,6 +508,31 @@ Snapshot read_pad(SDL_Gamepad* p) {
486 for (uint32_t i = 0; i < kButtonCount; ++i) s.buttons[i] = down(static_cast<SDL_GamepadButton>(i)); 508 for (uint32_t i = 0; i < kButtonCount; ++i) s.buttons[i] = down(static_cast<SDL_GamepadButton>(i));
487 s.guide = down(SDL_GAMEPAD_BUTTON_GUIDE); 509 s.guide = down(SDL_GAMEPAD_BUTTON_GUIDE);
488 510
511 // Motion, normalised against the maxima motionInfo reports (the ABI's fraction convention). Sensors were enabled
512 // when the pad was opened; a pad whose sensor read fails just reports no motion this poll. SDL answers reads
513 // with zeros before the device's first sample arrives, and gravity makes a real accelerometer never read
514 // exactly zero, so all-zero accel means "no sample yet" and the reading carries no motion at all.
515 if (d->has_motion) {
516 float accel[3], gyro[3];
517 if (SDL_GetGamepadSensorData(p, SDL_SENSOR_ACCEL, accel, 3) &&
518 SDL_GetGamepadSensorData(p, SDL_SENSOR_GYRO, gyro, 3) &&
519 (accel[0] != 0.0f || accel[1] != 0.0f || accel[2] != 0.0f)) {
520 s.has_motion = true;
521 s.motion.accelerationX = norm(accel[0], kMaxAcceleration);
522 s.motion.accelerationY = norm(accel[1], kMaxAcceleration);
523 s.motion.accelerationZ = norm(accel[2], kMaxAcceleration);
524 s.motion.angularVelocityX = norm(gyro[0], kMaxAngularVelocity);
525 s.motion.angularVelocityY = norm(gyro[1], kMaxAngularVelocity);
526 s.motion.angularVelocityZ = norm(gyro[2], kMaxAngularVelocity);
527 // SDL's gamepad API has no compass and the shim synthesises no orientation, so those stay zero and
528 // unknown rather than a made-up value.
529 s.motion.accelerometerAccuracy = GameInputMotionAccuracyHigh;
530 s.motion.gyroscopeAccuracy = GameInputMotionAccuracyHigh;
531 s.motion.magnetometerAccuracy = GameInputMotionAccuracyUnknown;
532 s.motion.orientationAccuracy = GameInputMotionAccuracyUnknown;
533 }
534 }
535
489 // UI navigation derived from the gamepad (VERIFY against the console's own mapping). 536 // UI navigation derived from the gamepad (VERIFY against the console's own mapping).
490 const uint32_t b = s.gamepad.buttons; 537 const uint32_t b = s.gamepad.buttons;
491 const float t = 0.5f; 538 const float t = 0.5f;
@@ -544,10 +591,19 @@ void fill_info(Device* d, SDL_Gamepad* p, const AppLocalDeviceId& id) {
544 // filters on the family). 591 // filters on the family).
545 i.deviceFamily = GameInputFamilyXboxOne; 592 i.deviceFamily = GameInputFamilyXboxOne;
546 if (SDL_GetGamepadConnectionState(p) == SDL_JOYSTICK_CONNECTION_WIRELESS) i.capabilities |= GameInputDeviceCapabilityWireless; 593 if (SDL_GetGamepadConnectionState(p) == SDL_JOYSTICK_CONNECTION_WIRELESS) i.capabilities |= GameInputDeviceCapabilityWireless;
547 i.supportedInput = kSupportedKinds; 594 // The per-device kind set: the reading-kind searches take the global kSupportedKinds as the outer bound and this
595 // as the per-device one, so only pads with sensors answer a motion query.
596 i.supportedInput = kBaseKinds;
548 if (d->has_rumble) i.supportedRumbleMotors |= GameInputRumbleLowFrequency | GameInputRumbleHighFrequency; 597 if (d->has_rumble) i.supportedRumbleMotors |= GameInputRumbleLowFrequency | GameInputRumbleHighFrequency;
549 if (d->has_trigger_rumble || (d->is_dualsense && g().config.ds_triggers != rt::gameinput::DsTriggerMode::Off)) 598 if (d->has_trigger_rumble || (d->is_dualsense && g().config.ds_triggers != rt::gameinput::DsTriggerMode::Off))
550 i.supportedRumbleMotors |= GameInputRumbleLeftTrigger | GameInputRumbleRightTrigger; 599 i.supportedRumbleMotors |= GameInputRumbleLeftTrigger | GameInputRumbleRightTrigger;
600 if (d->has_motion) {
601 i.supportedInput |= GameInputKindMotion;
602 // The maxima GetMotionState's fractions divide by. The magnetometer is not available: SDL's gamepad API has
603 // no compass, and maxMagneticFieldStrength 0 says so (Microsoft's GameInputMotionInfo remarks).
604 d->motion_info = {kMaxAcceleration, kMaxAngularVelocity, 0.0f};
605 i.motionInfo = &d->motion_info;
606 }
551 i.controllerAxisCount = kAxisCount; 607 i.controllerAxisCount = kAxisCount;
552 i.controllerButtonCount = kButtonCount; 608 i.controllerButtonCount = kButtonCount;
553 for (uint32_t a = 0; a < kAxisCount; ++a) { 609 for (uint32_t a = 0; a < kAxisCount; ++a) {
@@ -583,6 +639,7 @@ void fill_info(Device* d, SDL_Gamepad* p, const AppLocalDeviceId& id) {
583// the title holds outlive their place here (~Reading only releases the device, which takes no lock). Under g().mu. 639// the title holds outlive their place here (~Reading only releases the device, which takes no lock). Under g().mu.
584Reading* push_reading(Device* d, const Snapshot& snap, uint64_t ts) { 640Reading* push_reading(Device* d, const Snapshot& snap, uint64_t ts) {
585 std::deque<Reading*>& h = d->history; 641 std::deque<Reading*>& h = d->history;
642 d->last_reading_us = ts;
586 h.push_back(new Reading(d, snap, ++d->seq, ts, ++g().last_order)); 643 h.push_back(new Reading(d, snap, ++d->seq, ts, ++g().last_order));
587 while (h.size() > kHistoryCap || (h.size() > 1 && h[1]->GetTimestamp() + kHistoryUs < ts)) { 644 while (h.size() > kHistoryCap || (h.size() > 1 && h[1]->GetTimestamp() + kHistoryUs < ts)) {
588 d->evicted_order = h.front()->order(); 645 d->evicted_order = h.front()->order();
@@ -637,6 +694,13 @@ void open_pad(SDL_JoystickID jid, uint64_t ts) {
637 d->is_dualsense = SDL_GetGamepadType(p) == SDL_GAMEPAD_TYPE_PS5; 694 d->is_dualsense = SDL_GetGamepadType(p) == SDL_GAMEPAD_TYPE_PS5;
638 d->has_rumble = SDL_GetBooleanProperty(props, SDL_PROP_GAMEPAD_CAP_RUMBLE_BOOLEAN, false); 695 d->has_rumble = SDL_GetBooleanProperty(props, SDL_PROP_GAMEPAD_CAP_RUMBLE_BOOLEAN, false);
639 d->has_trigger_rumble = SDL_GetBooleanProperty(props, SDL_PROP_GAMEPAD_CAP_TRIGGER_RUMBLE_BOOLEAN, false); 696 d->has_trigger_rumble = SDL_GetBooleanProperty(props, SDL_PROP_GAMEPAD_CAP_TRIGGER_RUMBLE_BOOLEAN, false);
697 // Motion needs both sensors; SDL's orientation quaternion is left alone (no title asks for it, and a synthesised
698 // one would lie). Enabling at open: SDL delivers samples only for enabled sensors.
699 d->has_motion = SDL_GamepadHasSensor(p, SDL_SENSOR_GYRO) && SDL_GamepadHasSensor(p, SDL_SENSOR_ACCEL);
700 if (d->has_motion) {
701 SDL_SetGamepadSensorEnabled(p, SDL_SENSOR_GYRO, kMotionSensorRate);
702 SDL_SetGamepadSensorEnabled(p, SDL_SENSOR_ACCEL, kMotionSensorRate);
703 }
640 d->sent = {}; 704 d->sent = {};
641 d->sent.is_dualsense = d->is_dualsense; 705 d->sent.is_dualsense = d->is_dualsense;
642 d->sent.trigger_rumble = d->has_trigger_rumble; 706 d->sent.trigger_rumble = d->has_trigger_rumble;
@@ -662,13 +726,13 @@ void open_pad(SDL_JoystickID jid, uint64_t ts) {
662 d->status = status; 726 d->status = status;
663 s.connected.push_back(d); 727 s.connected.push_back(d);
664 728
665 const Snapshot snap = read_pad(p); 729 const Snapshot snap = read_pad(d);
666 d->last_snap = snap; 730 d->last_snap = snap;
667 push_reading(d, snap, ts); 731 push_reading(d, snap, ts);
668 queue_event({CbType::Device, d, nullptr, ts, status, GameInputDeviceNoStatus, false, 0}); 732 queue_event({CbType::Device, d, nullptr, ts, status, GameInputDeviceNoStatus, false, 0});
669 std::fprintf(stderr, "[rt] gameinput: connected %s (%04x:%04x, player %d%s%s)\n", d->name.c_str(), d->info.vendorId, 733 std::fprintf(stderr, "[rt] gameinput: connected %s (%04x:%04x, player %d%s%s%s)\n", d->name.c_str(),
670 d->info.productId, player + 1, d->is_dualsense ? ", DualSense trigger effects" : "", 734 d->info.vendorId, d->info.productId, player + 1, d->is_dualsense ? ", DualSense trigger effects" : "",
671 d->has_trigger_rumble ? ", trigger rumble" : ""); 735 d->has_trigger_rumble ? ", trigger rumble" : "", d->has_motion ? ", gyro" : "");
672} 736}
673 737
674void close_pad(Device* d, uint64_t ts) { 738void close_pad(Device* d, uint64_t ts) {
@@ -984,11 +1048,15 @@ void poll_once() {
984 connected = s.connected; 1048 connected = s.connected;
985 } 1049 }
986 for (Device* d : connected) { 1050 for (Device* d : connected) {
987 const Snapshot snap = read_pad(d->pad); 1051 const Snapshot snap = read_pad(d);
988 const bool guide_changed = d->last_snap.guide != snap.guide; 1052 const bool guide_changed = d->last_snap.guide != snap.guide;
989 const bool changed = !(d->last_snap == snap); 1053 const bool changed = !(d->last_snap == snap);
990 d->last_snap = snap; 1054 d->last_snap = snap;
991 if (changed) { 1055 // A pad with sensors streams readings at ~125 Hz even when nothing else changes, so motion the title reads
1056 // between its frames is never stuck at the last button event; pads without sensors only read on change, as
1057 // before. push_reading stamps last_reading_us, so the cadence follows the actual history.
1058 const bool motion_tick = snap.has_motion && now - d->last_reading_us >= kMotionReadingUs;
1059 if (changed || motion_tick) {
992 std::lock_guard lock(s.mu); 1060 std::lock_guard lock(s.mu);
993 queue_event({CbType::Reading, d, push_reading(d, snap, now), now, 0, 0, false, 0}); 1061 queue_event({CbType::Reading, d, push_reading(d, snap, now), now, 0, 0, false, 0});
994 } 1062 }
@@ -1121,6 +1189,8 @@ HRESULT find_reading(IGameInputReading* ref, uint32_t kind, IGameInputDevice* de
1121 uint64_t horizon = 0; 1189 uint64_t horizon = 0;
1122 if (device) { 1190 if (device) {
1123 if (as_device(device)->status == GameInputDeviceNoStatus) return GAMEINPUT_E_DEVICE_DISCONNECTED; 1191 if (as_device(device)->status == GameInputDeviceNoStatus) return GAMEINPUT_E_DEVICE_DISCONNECTED;
1192 if (kind != GameInputKindUnknown && !(kind & as_device(device)->info.supportedInput))
1193 return GAMEINPUT_E_READING_NOT_FOUND; // the device does not do this kind (motion on a plain pad)
1124 scope = {as_device(device)}; 1194 scope = {as_device(device)};
1125 } else { 1195 } else {
1126 horizon = r->device()->evicted_order; 1196 horizon = r->device()->evicted_order;
@@ -1165,6 +1235,8 @@ public:
1165 if (device) { 1235 if (device) {
1166 Device* d = as_device(device); 1236 Device* d = as_device(device);
1167 if (d->status == GameInputDeviceNoStatus) return GAMEINPUT_E_DEVICE_DISCONNECTED; 1237 if (d->status == GameInputDeviceNoStatus) return GAMEINPUT_E_DEVICE_DISCONNECTED;
1238 if (kind != GameInputKindUnknown && !(kind & d->info.supportedInput))
1239 return GAMEINPUT_E_READING_NOT_FOUND; // the device does not do this kind (motion on a plain pad)
1168 best = d->latest(); 1240 best = d->latest();
1169 } else { 1241 } else {
1170 for (Device* d : g().connected) // the most recent reading from any gamepad 1242 for (Device* d : g().connected) // the most recent reading from any gamepad
diff --git a/runtime/shims/gameinput_abi.h b/runtime/shims/gameinput_abi.h
index 3ac6380cf..053b00cc9 100644
--- a/runtime/shims/gameinput_abi.h
+++ b/runtime/shims/gameinput_abi.h
@@ -224,6 +224,46 @@ struct GameInputControllerButtonInfo {
224struct GameInputGamepadInfo {}; 224struct GameInputGamepadInfo {};
225struct GameInputUiNavigationInfo {}; 225struct GameInputUiNavigationInfo {};
226 226
227// Motion: layouts from Microsoft's v0 documentation (learn.microsoft.com GameInputMotionInfo / GameInputMotionState /
228// GameInputMotionAccuracy; the GDK public header spells the same members). Accuracy is deprecated only in GameInput
229// v1 and later; v0 still uses it in GameInputMotionState.
230enum GameInputMotionAccuracy : int32_t {
231 GameInputMotionAccuracyUnknown = -1,
232 GameInputMotionAccuracyUnreliable = 0,
233 GameInputMotionAccuracyLow = 1,
234 GameInputMotionAccuracyMedium = 2,
235 GameInputMotionAccuracyHigh = 3,
236};
237
238struct GameInputMotionInfo {
239 float maxAcceleration; // m/s^2; 0 says acceleration input is not available
240 float maxAngularVelocity; // rad/s; 0 says angular-velocity input is not available
241 float maxMagneticFieldStrength; // teslas; 0 says magnetic-field input is not available
242};
243
244// The state GetMotionState writes. Each float is the signed fraction of the GameInputMotionInfo maximum for its
245// sensor (1.0 = full magnitude); orientation is a quaternion. SDL delivers accel in m/s^2 (gravity included) and
246// gyro in rad/s, so the shim divides by the maxima it reports in motionInfo.
247struct GameInputMotionState {
248 float accelerationX;
249 float accelerationY;
250 float accelerationZ;
251 float angularVelocityX;
252 float angularVelocityY;
253 float angularVelocityZ;
254 float magneticFieldX;
255 float magneticFieldY;
256 float magneticFieldZ;
257 float orientationW;
258 float orientationX;
259 float orientationY;
260 float orientationZ;
261 GameInputMotionAccuracy accelerometerAccuracy;
262 GameInputMotionAccuracy gyroscopeAccuracy;
263 GameInputMotionAccuracy magnetometerAccuracy;
264 GameInputMotionAccuracy orientationAccuracy;
265};
266
227struct GameInputDeviceInfo { 267struct GameInputDeviceInfo {
228 uint32_t infoSize; 268 uint32_t infoSize;
229 uint16_t vendorId; 269 uint16_t vendorId;
@@ -280,6 +320,8 @@ static_assert(sizeof(GameInputGamepadState) == 28);
280static_assert(sizeof(GameInputRumbleParams) == 16); 320static_assert(sizeof(GameInputRumbleParams) == 16);
281static_assert(sizeof(GameInputBatteryState) == 20); 321static_assert(sizeof(GameInputBatteryState) == 20);
282static_assert(sizeof(GameInputString) == 16); 322static_assert(sizeof(GameInputString) == 16);
323static_assert(sizeof(GameInputMotionInfo) == 12);
324static_assert(sizeof(GameInputMotionState) == 68);
283static_assert(sizeof(GameInputControllerAxisInfo) == 48); 325static_assert(sizeof(GameInputControllerAxisInfo) == 48);
284static_assert(sizeof(GameInputControllerButtonInfo) == 32); 326static_assert(sizeof(GameInputControllerButtonInfo) == 32);
285static_assert(offsetof(GameInputDeviceInfo, deviceId) == 32); 327static_assert(offsetof(GameInputDeviceInfo, deviceId) == 32);
diff --git a/runtime/shims/library_loader.cpp b/runtime/shims/library_loader.cpp
index 4bcc57704..585c6a299 100644
--- a/runtime/shims/library_loader.cpp
+++ b/runtime/shims/library_loader.cpp
@@ -32,10 +32,16 @@ struct Pseudo {
32 32
33namespace { 33namespace {
34 34
35std::mutex g_mutex; 35// Intentionally immortal: mapped-DLL DLL_PROCESS_DETACH and earlier atexit handlers can call GetProcAddress or
36// FreeLibrary on pseudo-handles during process teardown, after normal statics would have been destroyed.
37std::mutex& loader_mutex() {
38 static auto* m = new std::mutex;
39 return *m;
40}
41
36std::deque<Pseudo>& pseudos() { // a deque never moves its elements, so handed-out handles stay valid 42std::deque<Pseudo>& pseudos() { // a deque never moves its elements, so handed-out handles stay valid
37 static std::deque<Pseudo> d; 43 static auto* d = new std::deque<Pseudo>;
38 return d; 44 return *d;
39} 45}
40 46
41std::string lower_ascii(std::string s) { 47std::string lower_ascii(std::string s) {
@@ -67,7 +73,7 @@ std::string module_name(std::string path) {
67HMODULE owned_handle(const std::string& path) { 73HMODULE owned_handle(const std::string& path) {
68 const std::string dll = module_name(path); 74 const std::string dll = module_name(path);
69 if (dll.empty() || !owns_dll(dll)) return nullptr; 75 if (dll.empty() || !owns_dll(dll)) return nullptr;
70 std::lock_guard lock(g_mutex); 76 std::lock_guard lock(loader_mutex());
71 for (auto& p : pseudos()) 77 for (auto& p : pseudos())
72 if (p.dll == dll) return reinterpret_cast<HMODULE>(&p); 78 if (p.dll == dll) return reinterpret_cast<HMODULE>(&p);
73 pseudos().push_back(Pseudo{}); 79 pseudos().push_back(Pseudo{});
@@ -78,7 +84,7 @@ HMODULE owned_handle(const std::string& path) {
78 84
79// The owned module a handle names, or nullptr for a host module. 85// The owned module a handle names, or nullptr for a host module.
80const Pseudo* pseudo(HMODULE h) { 86const Pseudo* pseudo(HMODULE h) {
81 std::lock_guard lock(g_mutex); 87 std::lock_guard lock(loader_mutex());
82 for (auto& p : pseudos()) 88 for (auto& p : pseudos())
83 if (reinterpret_cast<HMODULE>(&p) == h) return &p; 89 if (reinterpret_cast<HMODULE>(&p) == h) return &p;
84 return nullptr; 90 return nullptr;
@@ -120,14 +126,18 @@ HMODULE WINAPI get_module_handle_w(LPCWSTR name) {
120FARPROC WINAPI get_proc_address(HMODULE module, LPCSTR name) { 126FARPROC WINAPI get_proc_address(HMODULE module, LPCSTR name) {
121 const Pseudo* p = pseudo(module); 127 const Pseudo* p = pseudo(module);
122 if (!p) return GetProcAddress(module, name); 128 if (!p) return GetProcAddress(module, name);
129 if (!name) {
130 SetLastError(ERROR_PROC_NOT_FOUND);
131 return nullptr;
132 }
123 // A value below 0x10000 is an ordinal (IS_INTRESOURCE), as in the real GetProcAddress. 133 // A value below 0x10000 is an ordinal (IS_INTRESOURCE), as in the real GetProcAddress.
124 const std::string what = IS_INTRESOURCE(name) ? "#" + std::to_string(reinterpret_cast<uintptr_t>(name)) : name; 134 const std::string what = IS_INTRESOURCE(name) ? "#" + std::to_string(reinterpret_cast<uintptr_t>(name)) : name;
125 if (void* fn = find(p->dll, what)) return reinterpret_cast<FARPROC>(fn); 135 if (void* fn = find(p->dll, what)) return reinterpret_cast<FARPROC>(fn);
126 { 136 {
127 static std::mutex m; 137 static auto* m = new std::mutex;
128 static std::set<std::string> seen; 138 static auto* seen = new std::set<std::string>;
129 std::lock_guard lock(m); 139 std::lock_guard lock(*m);
130 if (seen.insert(p->dll + "!" + what).second) 140 if (seen->insert(p->dll + "!" + what).second)
131 std::fprintf(stderr, "[rt] loader: GetProcAddress(%s, %s): not served\n", p->dll.c_str(), what.c_str()); 141 std::fprintf(stderr, "[rt] loader: GetProcAddress(%s, %s): not served\n", p->dll.c_str(), what.c_str());
132 } 142 }
133 SetLastError(ERROR_PROC_NOT_FOUND); 143 SetLastError(ERROR_PROC_NOT_FOUND);
diff --git a/runtime/shims/process.cpp b/runtime/shims/process.cpp
index c0070782f..d3f76a684 100644
--- a/runtime/shims/process.cpp
+++ b/runtime/shims/process.cpp
@@ -9,6 +9,10 @@
9// process-wide atexit table also holds gta6rt's own). 9// process-wide atexit table also holds gta6rt's own).
10// Covered CRTs: the Universal CRT (api-ms-win-crt-runtime-l1-1-0.dll / ucrtbase.dll, what MSVC links; ucrtbased.dll in Debug) and 10// Covered CRTs: the Universal CRT (api-ms-win-crt-runtime-l1-1-0.dll / ucrtbase.dll, what MSVC links; ucrtbased.dll in Debug) and
11// msvcrt.dll (MinGW). Calls made inside host DLLs, not through the game's imports, are not seen here. 11// msvcrt.dll (MinGW). Calls made inside host DLLs, not through the game's imports, are not seen here.
12// The loader matches imports by exact DLL name, so GetCommandLineA/W and ExitProcess are served under every name a
13// title can import them by: kernel32.dll (the classic import libraries), kernelbase.dll, and the API sets that the
14// umbrella libraries a GDK title links (OneCore_apiset.lib, mincore.lib) bind them to. The retail package's own DLLs
15// import ExitProcess from api-ms-win-core-processthreads-l1-1-0.dll.
12#include <windows.h> 16#include <windows.h>
13 17
14#include <atomic> 18#include <atomic>
@@ -16,6 +20,7 @@
16#include <cstdlib> 20#include <cstdlib>
17#include <cstring> 21#include <cstring>
18#include <string> 22#include <string>
23#include <type_traits>
19#include <vector> 24#include <vector>
20 25
21#include "process_shim.h" 26#include "process_shim.h"
@@ -107,6 +112,24 @@ wchar_t** __cdecl game_p_wcmdln_storage() {
107 return &p; 112 return &p;
108} 113}
109 114
115// What the UCRT's _get_narrow/_get_wide_winmain_command_line return, and the CRT's WinMain startup passes as
116// lpCmdLine: the command line after the program name and the blanks that follow it. The program name ends at the
117// first character up to ' ' outside quotes, the UCRT's own scan. The comparison is unsigned, so a non-ASCII byte of
118// the narrow line is part of the name; a DBCS trail byte is never '"' or a blank, so it needs no lead-byte step.
119template <typename C>
120C* after_program_name(C* p) {
121 using U = std::make_unsigned_t<C>;
122 bool quoted = false;
123 while (U(*p) > U(' ') || (*p && quoted)) {
124 if (*p == C('"')) quoted = !quoted;
125 ++p;
126 }
127 while (*p && U(*p) <= U(' ')) ++p;
128 return p;
129}
130char* __cdecl game_get_narrow_winmain_command_line() { return after_program_name(g_cmdline.data()); }
131wchar_t* __cdecl game_get_wide_winmain_command_line() { return after_program_name(g_wcmdline.data()); }
132
110// msvcrt.dll: int __getmainargs(int* argc, char*** argv, char*** env, int expand, void* startinfo) 133// msvcrt.dll: int __getmainargs(int* argc, char*** argv, char*** env, int expand, void* startinfo)
111int __cdecl game_getmainargs(int* argc, char*** argv, char*** env, int, void*) { 134int __cdecl game_getmainargs(int* argc, char*** argv, char*** env, int, void*) {
112 *argc = g_argc; 135 *argc = g_argc;
@@ -197,7 +220,13 @@ using namespace rt::process;
197 {dll, "_configure_narrow_argv", reinterpret_cast<void*>(&game_configure_argv)}, \ 220 {dll, "_configure_narrow_argv", reinterpret_cast<void*>(&game_configure_argv)}, \
198 {dll, "_configure_wide_argv", reinterpret_cast<void*>(&game_configure_argv)}, \ 221 {dll, "_configure_wide_argv", reinterpret_cast<void*>(&game_configure_argv)}, \
199 {dll, "__p__acmdln", reinterpret_cast<void*>(&game_p_acmdln_storage)}, \ 222 {dll, "__p__acmdln", reinterpret_cast<void*>(&game_p_acmdln_storage)}, \
200 {dll, "__p__wcmdln", reinterpret_cast<void*>(&game_p_wcmdln_storage)} 223 {dll, "__p__wcmdln", reinterpret_cast<void*>(&game_p_wcmdln_storage)}, \
224 {dll, "_get_narrow_winmain_command_line", reinterpret_cast<void*>(&game_get_narrow_winmain_command_line)}, \
225 {dll, "_get_wide_winmain_command_line", reinterpret_cast<void*>(&game_get_wide_winmain_command_line)}
226#define EXIT_PROCESS(dll) {dll, "ExitProcess", reinterpret_cast<void*>(&game_exit_process)}
227#define COMMAND_LINE(dll) \
228 {dll, "GetCommandLineA", reinterpret_cast<void*>(&game_get_command_line_a)}, \
229 {dll, "GetCommandLineW", reinterpret_cast<void*>(&game_get_command_line_w)}
201} // namespace 230} // namespace
202 231
203SHIM_TABLE(process, 232SHIM_TABLE(process,
@@ -209,7 +238,10 @@ SHIM_TABLE(process,
209 {"msvcrt.dll", "abort", reinterpret_cast<void*>(&game_abort)}, 238 {"msvcrt.dll", "abort", reinterpret_cast<void*>(&game_abort)},
210 {"msvcrt.dll", "__getmainargs", reinterpret_cast<void*>(&game_getmainargs)}, 239 {"msvcrt.dll", "__getmainargs", reinterpret_cast<void*>(&game_getmainargs)},
211 {"msvcrt.dll", "__wgetmainargs", reinterpret_cast<void*>(&game_wgetmainargs)}, 240 {"msvcrt.dll", "__wgetmainargs", reinterpret_cast<void*>(&game_wgetmainargs)},
212 {"kernel32.dll", "ExitProcess", reinterpret_cast<void*>(&game_exit_process)}, 241 EXIT_PROCESS("kernel32.dll"),
213 {"kernel32.dll", "GetCommandLineA", reinterpret_cast<void*>(&game_get_command_line_a)}, 242 EXIT_PROCESS("kernelbase.dll"),
214 {"kernel32.dll", "GetCommandLineW", reinterpret_cast<void*>(&game_get_command_line_w)}, 243 EXIT_PROCESS("api-ms-win-core-processthreads-l1-1-0.dll"),
244 COMMAND_LINE("kernel32.dll"),
245 COMMAND_LINE("kernelbase.dll"),
246 COMMAND_LINE("api-ms-win-core-processenvironment-l1-1-0.dll"),
215); 247);
diff --git a/runtime/src/base_reservation.h b/runtime/src/base_reservation.h
new file mode 100644
index 000000000..76fb530ce
--- /dev/null
+++ b/runtime/src/base_reservation.h
@@ -0,0 +1,139 @@
1#pragma once
2
3// Keeping a relocation-less game image's preferred range free until the loader maps it there.
4//
5// An EXE without a .reloc directory can only run at its ImageBase (0x140000000 by default). Windows and x86-64 Wine
6// leave that range alone, but arm64 Wine on macOS (CrossOver's arm64 bottles, whose x86-64 code runs under FEX) puts
7// its own start-up allocations at 0x100000000 and up, over that range, before gta6rt's first line runs. So gta6rt
8// starts itself again, suspended, reserves [ImageBase, ImageBase + SizeOfImage) in that child before any of its code
9// runs, and resumes it; the child's loader then commits the image inside the reservation (commit_reserved), so
10// nothing else can take the range in between. The child is told by LEONIDA_BASE_RESERVED=<base>:<size> (hex), which
11// also stops it from starting itself again. Measured on CrossOver Preview 20260821 (arm64 bottle, M2 Max): in a
12// suspended child 0x140000000-0x170000000 is free and reservable; macOS maps its own regions above that (the arm64
13// shared region starts at 0x180000000), so a range there can't be had either way.
14//
15// Nothing changes where the range is free at start-up (Windows, x86-64 Wine) or where the image has relocations.
16
17#include <windows.h>
18
19#include <cstdint>
20#include <cstdio>
21#include <cstdlib>
22#include <cwchar>
23#include <filesystem>
24#include <fstream>
25#include <optional>
26#include <string>
27#include <vector>
28
29namespace rt::base_reservation {
30
31inline constexpr wchar_t kVariable[] = L"LEONIDA_BASE_RESERVED";
32
33struct Range {
34 std::uint64_t base = 0;
35 std::uint64_t size = 0;
36};
37
38// The range this process was started with (LEONIDA_BASE_RESERVED), if any.
39inline std::optional<Range> inherited() {
40 wchar_t value[64] = {};
41 const DWORD length = GetEnvironmentVariableW(kVariable, value, 64);
42 if (!length || length >= 64) return std::nullopt;
43 Range r{};
44 if (std::swscanf(value, L"%llx:%llx", reinterpret_cast<unsigned long long*>(&r.base),
45 reinterpret_cast<unsigned long long*>(&r.size)) != 2 ||
46 !r.size)
47 return std::nullopt;
48 return r;
49}
50
51// Commits [base, base + size) for the loader when it lies inside the reservation this process was started with and
52// that reservation is still in place; returns null otherwise (the caller then allocates as usual). The reservation
53// is the allocation, so VirtualFree(base, 0, MEM_RELEASE) frees it as it frees any image.
54inline void* commit_reserved(std::uint64_t base, std::uint64_t size) {
55 const auto r = inherited();
56 if (!r || base != r->base || size > r->size) return nullptr;
57 MEMORY_BASIC_INFORMATION info{};
58 if (!VirtualQuery(reinterpret_cast<void*>(base), &info, sizeof info) || info.State != MEM_RESERVE ||
59 reinterpret_cast<std::uint64_t>(info.AllocationBase) != base)
60 return nullptr;
61 return VirtualAlloc(reinterpret_cast<void*>(base), static_cast<SIZE_T>(size), MEM_COMMIT, PAGE_READWRITE);
62}
63
64// The preferred range of `image` when it has no relocations and that range is not free in this process; nullopt
65// when the image can be mapped as it is (or is not a readable PE32+, which the loader reports itself).
66inline std::optional<Range> needed(const std::filesystem::path& image) {
67 std::ifstream file(image, std::ios::binary);
68 IMAGE_DOS_HEADER dos{};
69 if (!file.read(reinterpret_cast<char*>(&dos), sizeof dos) || dos.e_magic != IMAGE_DOS_SIGNATURE || dos.e_lfanew < 0)
70 return std::nullopt;
71 IMAGE_NT_HEADERS64 nt{};
72 if (!file.seekg(dos.e_lfanew) || !file.read(reinterpret_cast<char*>(&nt), sizeof nt) ||
73 nt.Signature != IMAGE_NT_SIGNATURE || nt.OptionalHeader.Magic != IMAGE_NT_OPTIONAL_HDR64_MAGIC ||
74 !nt.OptionalHeader.SizeOfImage)
75 return std::nullopt;
76 const auto& oh = nt.OptionalHeader;
77 if (oh.NumberOfRvaAndSizes > IMAGE_DIRECTORY_ENTRY_BASERELOC &&
78 oh.DataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC].Size)
79 return std::nullopt; // relocatable: the loader moves it if the base is taken
80 const Range r{oh.ImageBase, (static_cast<std::uint64_t>(oh.SizeOfImage) + 0xffff) & ~std::uint64_t{0xffff}};
81 for (std::uint64_t at = r.base; at < r.base + r.size;) {
82 MEMORY_BASIC_INFORMATION info{};
83 if (!VirtualQuery(reinterpret_cast<void*>(at), &info, sizeof info)) return r;
84 if (info.State != MEM_FREE) return r;
85 at = reinterpret_cast<std::uint64_t>(info.BaseAddress) + info.RegionSize;
86 }
87 return std::nullopt;
88}
89
90// Runs this program again with the same command line, suspended, reserves `r` in the new process, resumes it and
91// returns its exit code. On failure prints why and returns 1 (the child, if any, is ended unrun).
92inline int relaunch(const Range& r) {
93 wchar_t self[MAX_PATH * 4] = {};
94 if (!GetModuleFileNameW(nullptr, self, MAX_PATH * 4)) {
95 std::fprintf(stderr, "error: GetModuleFileName failed (%lu)\n", GetLastError());
96 return 1;
97 }
98 wchar_t marker[64];
99 std::swprintf(marker, 64, L"%llx:%llx", static_cast<unsigned long long>(r.base),
100 static_cast<unsigned long long>(r.size));
101 SetEnvironmentVariableW(kVariable, marker); // inherited by the child; this process only waits from here on
102 std::wstring command_line = GetCommandLineW();
103 STARTUPINFOW startup{sizeof startup};
104 startup.dwFlags = STARTF_USESTDHANDLES;
105 startup.hStdInput = GetStdHandle(STD_INPUT_HANDLE);
106 startup.hStdOutput = GetStdHandle(STD_OUTPUT_HANDLE);
107 startup.hStdError = GetStdHandle(STD_ERROR_HANDLE);
108 for (HANDLE h : {startup.hStdInput, startup.hStdOutput, startup.hStdError})
109 if (h && h != INVALID_HANDLE_VALUE) SetHandleInformation(h, HANDLE_FLAG_INHERIT, HANDLE_FLAG_INHERIT);
110 PROCESS_INFORMATION process{};
111 std::fflush(stdout);
112 std::fflush(stderr);
113 if (!CreateProcessW(self, command_line.data(), nullptr, nullptr, TRUE, CREATE_SUSPENDED, nullptr, nullptr,
114 &startup, &process)) {
115 std::fprintf(stderr, "error: starting gta6rt again to reserve the image range failed (%lu)\n", GetLastError());
116 return 1;
117 }
118 if (!VirtualAllocEx(process.hProcess, reinterpret_cast<void*>(r.base), static_cast<SIZE_T>(r.size), MEM_RESERVE,
119 PAGE_NOACCESS)) {
120 const DWORD error = GetLastError();
121 TerminateProcess(process.hProcess, 1);
122 CloseHandle(process.hThread);
123 CloseHandle(process.hProcess);
124 std::fprintf(stderr,
125 "error: the image has no relocations and its range %#llx-%#llx is taken, also in a new "
126 "process (VirtualAllocEx %lu)\n",
127 static_cast<unsigned long long>(r.base), static_cast<unsigned long long>(r.base + r.size), error);
128 return 1;
129 }
130 ResumeThread(process.hThread);
131 WaitForSingleObject(process.hProcess, INFINITE);
132 DWORD code = 1;
133 GetExitCodeProcess(process.hProcess, &code);
134 CloseHandle(process.hThread);
135 CloseHandle(process.hProcess);
136 return static_cast<int>(code);
137}
138
139} // namespace rt::base_reservation
diff --git a/runtime/src/main.cpp b/runtime/src/main.cpp
index 7d3491653..560f68349 100644
--- a/runtime/src/main.cpp
+++ b/runtime/src/main.cpp
@@ -23,6 +23,7 @@
23#include <string> 23#include <string>
24#include <vector> 24#include <vector>
25 25
26#include "base_reservation.h"
26#include "pe_loader.h" 27#include "pe_loader.h"
27#include "../shims/d3d12_trace.h" 28#include "../shims/d3d12_trace.h"
28#include "../shims/file_system.h" 29#include "../shims/file_system.h"
@@ -73,6 +74,10 @@ int wmain(int argc, wchar_t** argv) {
73 // Exactly one mode: --dry-run --run would otherwise initialise the modules and call the entry point. 74 // Exactly one mode: --dry-run --run would otherwise initialise the modules and call the entry point.
74 if (dry_run + init + run != 1) return usage(); 75 if (dry_run + init + run != 1) return usage();
75 if (game_dir.empty()) game_dir = image.parent_path(); 76 if (game_dir.empty()) game_dir = image.parent_path();
77 // An image without relocations whose range this process already uses (arm64 Wine on macOS) runs in a new
78 // process that has the range reserved from the start (base_reservation.h); that process does not do this again.
79 if (!rt::base_reservation::inherited())
80 if (const auto range = rt::base_reservation::needed(image)) return rt::base_reservation::relaunch(*range);
76 // GAME: paths read under --game-dir; whatever a title writes lands in the overlay, never in the package. 81 // GAME: paths read under --game-dir; whatever a title writes lands in the overlay, never in the package.
77 if (overlay_dir.empty()) overlay_dir = game_dir / "overlay"; 82 if (overlay_dir.empty()) overlay_dir = game_dir / "overlay";
78 rt::fs::configure(game_dir, overlay_dir); 83 rt::fs::configure(game_dir, overlay_dir);
diff --git a/runtime/src/pe_loader.cpp b/runtime/src/pe_loader.cpp
index 1ab9c7801..387051756 100644
--- a/runtime/src/pe_loader.cpp
+++ b/runtime/src/pe_loader.cpp
@@ -14,6 +14,7 @@
14#include <vector> 14#include <vector>
15 15
16#include "../shims/shims.h" 16#include "../shims/shims.h"
17#include "base_reservation.h"
17 18
18namespace rt { 19namespace rt {
19 20
@@ -506,8 +507,11 @@ Module& Loader::map_image(const std::filesystem::path& path) {
506 by_name_[lower(m->name)] = m; 507 by_name_[lower(m->name)] = m;
507 order_.push_back(m); 508 order_.push_back(m);
508 509
509 m->base = static_cast<uint8_t*>( 510 // Inside the range gta6rt reserved for this image before the process started (base_reservation.h), else as usual.
510 VirtualAlloc(reinterpret_cast<void*>(oh.ImageBase), oh.SizeOfImage, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)); 511 m->base = static_cast<uint8_t*>(base_reservation::commit_reserved(oh.ImageBase, oh.SizeOfImage));
512 if (!m->base)
513 m->base = static_cast<uint8_t*>(VirtualAlloc(reinterpret_cast<void*>(oh.ImageBase), oh.SizeOfImage,
514 MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE));
511 if (!m->base) { 515 if (!m->base) {
512 const auto relocs = directory(nt, IMAGE_DIRECTORY_ENTRY_BASERELOC); 516 const auto relocs = directory(nt, IMAGE_DIRECTORY_ENTRY_BASERELOC);
513 if (!relocs.Size) 517 if (!relocs.Size)
diff --git a/runtime/src/resource_tiling.h b/runtime/src/resource_tiling.h
index 6bd890ae8..a9d95ae9f 100644
--- a/runtime/src/resource_tiling.h
+++ b/runtime/src/resource_tiling.h
@@ -43,6 +43,7 @@ struct TilingDesc {
43 std::uint32_t mips = 1; 43 std::uint32_t mips = 1;
44 std::uint32_t element_bytes = 0; // bytes per texel, or per block of a block-compressed format 44 std::uint32_t element_bytes = 0; // bytes per texel, or per block of a block-compressed format
45 std::uint32_t block = 1; // texels per block side: 4 for BC1-7 45 std::uint32_t block = 1; // texels per block side: 4 for BC1-7
46 std::uint32_t samples = 1; // 1, or 4 for 2D single-mip MSAA
46}; 47};
47 48
48// D3D12_SUBRESOURCE_TILING: a packed mip has no tiles of its own and starts at packed_tile. 49// D3D12_SUBRESOURCE_TILING: a packed mip has no tiles of its own and starts at packed_tile.
@@ -63,9 +64,22 @@ struct ResourceTiling {
63 std::vector<SubresourceTiling> subresources; // mip + layer * mips 64 std::vector<SubresourceTiling> subresources; // mip + layer * mips
64}; 65};
65 66
66// The standard tile shape in elements (D3D12 "standard swizzle" tile shapes for 64 KiB tiles), or {} for an 67// The standard tile shape in elements (D3D12 "standard swizzle" tile shapes for 64 KiB tiles; 2D 4x MSAA scales the
67// element size that cannot be tiled (3- and 12-byte formats). 68// tile shape down by 4 samples per texel, measured on RTX 5070 Ti and WARP), or {} for an unsupported sample count or
68constexpr TileShape element_tile_shape(bool volume, std::uint32_t element_bytes) { 69// an element size that cannot be tiled (3- and 12-byte formats).
70constexpr TileShape element_tile_shape(bool volume, std::uint32_t element_bytes, std::uint32_t samples = 1) {
71 if (samples == 4) {
72 if (volume) return {};
73 switch (element_bytes) {
74 case 1: return {128, 128, 1};
75 case 2: return {128, 64, 1};
76 case 4: return {64, 64, 1};
77 case 8: return {64, 32, 1};
78 case 16: return {32, 32, 1};
79 default: return {};
80 }
81 }
82 if (samples != 1) return {};
69 switch (element_bytes) { 83 switch (element_bytes) {
70 case 1: return volume ? TileShape{64, 32, 32} : TileShape{256, 256, 1}; 84 case 1: return volume ? TileShape{64, 32, 32} : TileShape{256, 256, 1};
71 case 2: return volume ? TileShape{32, 32, 32} : TileShape{256, 128, 1}; 85 case 2: return volume ? TileShape{32, 32, 32} : TileShape{256, 128, 1};
@@ -103,7 +117,8 @@ inline bool resource_tiling(const TilingDesc& desc, ResourceTiling& out) {
103 return true; 117 return true;
104 } 118 }
105 const bool volume = desc.kind == TiledKind::texture3d; 119 const bool volume = desc.kind == TiledKind::texture3d;
106 const TileShape elements = element_tile_shape(volume, desc.element_bytes); 120 if (desc.samples != 1 && (desc.samples != 4 || volume || desc.mips != 1 || desc.block != 1)) return false;
121 const TileShape elements = element_tile_shape(volume, desc.element_bytes, desc.samples);
107 if (!elements.width || !desc.mips || !desc.block || !desc.width || !desc.height || !desc.depth_or_layers) 122 if (!elements.width || !desc.mips || !desc.block || !desc.width || !desc.height || !desc.depth_or_layers)
108 return false; 123 return false;
109 out.shape = {elements.width * desc.block, elements.height * desc.block, elements.depth}; 124 out.shape = {elements.width * desc.block, elements.height * desc.block, elements.depth};
@@ -124,7 +139,7 @@ inline bool resource_tiling(const TilingDesc& desc, ResourceTiling& out) {
124 ++out.standard_mips; 139 ++out.standard_mips;
125 } else { 140 } else {
126 slice[mip] = {0, 0, 0, packed_tile}; 141 slice[mip] = {0, 0, 0, packed_tile};
127 packed_bytes += up(w, desc.block) * up(h, desc.block) * d * desc.element_bytes; 142 packed_bytes += up(w, desc.block) * up(h, desc.block) * d * desc.element_bytes * desc.samples;
128 ++out.packed_mips; 143 ++out.packed_mips;
129 } 144 }
130 } 145 }
diff --git a/runtime/src/retire_tickets.h b/runtime/src/retire_tickets.h
index 17c3f589e..714cf40a4 100644
--- a/runtime/src/retire_tickets.h
+++ b/runtime/src/retire_tickets.h
@@ -7,7 +7,9 @@ namespace leonida {
7 7
8// Global submission tickets may finish out of order on independent Vulkan queues. Only the 8// Global submission tickets may finish out of order on independent Vulkan queues. Only the
9// contiguous completed prefix is safe for deferred resource destruction. The caller serializes 9// contiguous completed prefix is safe for deferred resource destruction. The caller serializes
10// record(), completed() and queue_idle() with the device submission mutex. 10// record(), completed() and queue_idle() with the device submission mutex. record() must
11// receive strictly increasing global ticket numbers; otherwise a duplicate or backward ticket
12// can make the completed prefix stall or move backward.
11template<class Semaphore> 13template<class Semaphore>
12class RetireTickets { 14class RetireTickets {
13public: 15public:
@@ -26,7 +28,8 @@ public:
26 return completed_; 28 return completed_;
27 } 29 }
28 30
29 // The owning queue has been waited idle and may now destroy its progress semaphore. 31 // Call only after the owning queue's wait-idle succeeded. Merely requesting idle does not
32 // prove its submissions completed and must not advance the retirement prefix.
30 void queue_idle(Semaphore semaphore) { 33 void queue_idle(Semaphore semaphore) {
31 for (Entry& entry : pending_) 34 for (Entry& entry : pending_)
32 if (entry.semaphore == semaphore) entry.idle = true; 35 if (entry.semaphore == semaphore) entry.idle = true;
diff --git a/runtime/src/shader_library.h b/runtime/src/shader_library.h
index 17705a5d1..0f31269a0 100644
--- a/runtime/src/shader_library.h
+++ b/runtime/src/shader_library.h
@@ -532,6 +532,13 @@ struct ShaderEntry {
532 std::array<std::uint32_t, 3> local_size{1, 1, 1}; 532 std::array<std::uint32_t, 3> local_size{1, 1, 1};
533 bool uses_code_base = false; 533 bool uses_code_base = false;
534 bool wave64 = false; 534 bool wave64 = false;
535 // The subgroup size the translator assumed (64 for a wave64 shader, 32 otherwise); 0 when the entry says null,
536 // as one translated with --wave64-emulate does, or has none.
537 std::uint32_t subgroup_size = 0;
538 // "workgroup" for a shader translated with --wave64-emulate: it uses no subgroup operation and is exact on any
539 // subgroup size. Empty for a native translation.
540 std::string wave64_exchange;
541 bool emulated() const { return !wave64_exchange.empty(); }
535 std::vector<SignatureElement> input_signature; // vertex shaders: what the input layout must feed 542 std::vector<SignatureElement> input_signature; // vertex shaders: what the input layout must feed
536 std::vector<std::uint32_t> outputs; // pixel shaders: the render-target locations written 543 std::vector<std::uint32_t> outputs; // pixel shaders: the render-target locations written
537}; 544};
@@ -613,6 +620,10 @@ private:
613 for (std::size_t i = 0; i < l->array.size() && i < 3; ++i) e.local_size[i] = u32(&l->array[i]); 620 for (std::size_t i = 0; i < l->array.size() && i < 3; ++i) e.local_size[i] = u32(&l->array[i]);
614 if (const Json* c = meta.find("uses_code_base"); c && c->kind == Json::Kind::boolean) e.uses_code_base = c->boolean; 621 if (const Json* c = meta.find("uses_code_base"); c && c->kind == Json::Kind::boolean) e.uses_code_base = c->boolean;
615 if (const Json* w = meta.find("wave64"); w && w->kind == Json::Kind::boolean) e.wave64 = w->boolean; 622 if (const Json* w = meta.find("wave64"); w && w->kind == Json::Kind::boolean) e.wave64 = w->boolean;
623 if (const Json* g = meta.find("subgroup_size"); g && g->kind == Json::Kind::number)
624 e.subgroup_size = u32(g);
625 if (const Json* x = meta.find("wave64_exchange"); x && x->kind == Json::Kind::string)
626 e.wave64_exchange = x->string;
616 if (const Json* s = meta.find("input_signature"); s && s->kind == Json::Kind::array) { 627 if (const Json* s = meta.find("input_signature"); s && s->kind == Json::Kind::array) {
617 for (const Json& item : s->array) { 628 for (const Json& item : s->array) {
618 SignatureElement element; 629 SignatureElement element;
diff --git a/runtime/src/subgroup_size.h b/runtime/src/subgroup_size.h
new file mode 100644
index 000000000..2df643fdf
--- /dev/null
+++ b/runtime/src/subgroup_size.h
@@ -0,0 +1,152 @@
1#pragma once
2
3// Subgroup size control for pipeline creation (docs/d3d12_vulkan.md, "Subgroup size"). A translated shader assumes
4// one subgroup size: 64 when the game's shader was wave64, 32 otherwise (spirv/index.json `subgroup_size`). A GPU
5// whose default differs runs it inexact (a wave64 shader reads lanes 32-63 of a 32-wide subgroup; a wave32 pixel
6// shader on a 64-wide default reads the other half's lanes), so each stage asks for the size it was translated for
7// where Vulkan allows (VK_EXT_subgroup_size_control, core in 1.3).
8//
9// The decision is a pure function of the shader's index entry and what the device offers, so it is tested without
10// a GPU (subgroup_size_test). It depends only on the Vulkan headers.
11
12#include "shader_library.h"
13
14#include <vulkan/vulkan_core.h>
15
16#include <cstdint>
17#include <string_view>
18
19namespace leonida {
20
21// What the device offers. `subgroup_size_control` and `compute_full_subgroups` say the feature is ENABLED on the
22// device (the validation layers reject the structure and the flag otherwise), not merely supported.
23struct SubgroupSizeCaps {
24 bool subgroup_size_control = false;
25 bool compute_full_subgroups = false;
26 std::uint32_t min_size = 0;
27 std::uint32_t max_size = 0;
28 std::uint32_t default_size = 0; // VkPhysicalDeviceSubgroupProperties::subgroupSize
29 std::uint32_t max_compute_workgroup_subgroups = 0;
30 VkShaderStageFlags required_stages = 0; // requiredSubgroupSizeStages
31};
32
33// Fills the limits of `caps` from vkGetPhysicalDeviceProperties2 and sets the two feature flags from what the
34// caller enables. Returns false when the device reports no subgroup size at all.
35template <class GetProperties2>
36bool query_subgroup_size_caps(GetProperties2 get_properties2, VkPhysicalDevice physical, bool enable_size_control,
37 bool enable_full_subgroups, SubgroupSizeCaps& caps) {
38 VkPhysicalDeviceSubgroupSizeControlProperties control{
39 VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SUBGROUP_SIZE_CONTROL_PROPERTIES};
40 VkPhysicalDeviceSubgroupProperties subgroup{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SUBGROUP_PROPERTIES, &control};
41 VkPhysicalDeviceProperties2 properties{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2, &subgroup};
42 get_properties2(physical, &properties);
43 caps = {};
44 caps.default_size = subgroup.subgroupSize;
45 caps.min_size = control.minSubgroupSize;
46 caps.max_size = control.maxSubgroupSize;
47 caps.max_compute_workgroup_subgroups = control.maxComputeWorkgroupSubgroups;
48 caps.required_stages = control.requiredSubgroupSizeStages;
49 caps.subgroup_size_control = enable_size_control;
50 caps.compute_full_subgroups = enable_full_subgroups;
51 return caps.default_size != 0;
52}
53
54// The Vulkan stage of an index entry's `stage` ("cs", "ps", ...); 0 for one this layer has no pipeline for.
55inline VkShaderStageFlagBits subgroup_stage_bit(std::string_view stage) {
56 if (stage == "cs") return VK_SHADER_STAGE_COMPUTE_BIT;
57 if (stage == "ps") return VK_SHADER_STAGE_FRAGMENT_BIT;
58 if (stage == "vs") return VK_SHADER_STAGE_VERTEX_BIT;
59 if (stage == "gs") return VK_SHADER_STAGE_GEOMETRY_BIT;
60 if (stage == "ms") return VK_SHADER_STAGE_MESH_BIT_EXT;
61 return VkShaderStageFlagBits(0);
62}
63
64enum class SubgroupOutcome {
65 emulated, // --wave64-emulate: exact on any size, nothing is required
66 required, // the stage asks for `size`
67 device_fixed, // the device has one size and it is the wanted one: nothing to ask for
68 device_default, // cannot be required, but the default size is the wanted one: works, not guaranteed stable
69 unavailable, // the wanted size cannot be had: the shader runs at another size and may be inexact
70 unknown_stage, // no Vulkan stage for this entry
71 unknown_device, // the device sizes were not queried (all zero): nothing is asked for
72};
73
74struct SubgroupRequest {
75 SubgroupOutcome outcome = SubgroupOutcome::unknown_stage;
76 VkShaderStageFlagBits stage = VkShaderStageFlagBits(0);
77 std::uint32_t wanted = 0; // the size the translation assumed
78 std::uint32_t size = 0; // requiredSubgroupSize to chain; 0: chain nothing
79 VkPipelineShaderStageCreateFlags flags = 0; // REQUIRE_FULL_SUBGROUPS, compute only
80};
81
82inline bool subgroup_is_power_of_two(std::uint32_t v) { return v && !(v & (v - 1)); }
83
84// What to ask for one stage of a pipeline made from `entry`.
85// - Emulated (`wave64_exchange` present): nothing.
86// - Otherwise the wanted size is the entry's `subgroup_size`, or 64 for a wave64 entry without one and 32 for the
87// rest. VkPipelineShaderStageRequiredSubgroupSizeCreateInfo is chained when the subgroupSizeControl feature is
88// enabled, the stage is in requiredSubgroupSizeStages, the size is a power of two in [min, max] and, for
89// compute and mesh, the workgroup fits in size * maxComputeWorkgroupSubgroups
90// (VUID-VkPipelineShaderStageCreateInfo-pNext-02755 and -02756,
91// VUID-VkPipelineShaderStageRequiredSubgroupSizeCreateInfo-requiredSubgroupSize-02760..02762).
92// - A compute stage also gets VK_PIPELINE_SHADER_STAGE_CREATE_REQUIRE_FULL_SUBGROUPS_BIT when computeFullSubgroups
93// is enabled and the local size X is a multiple of the size (VUID-VkPipelineShaderStageCreateInfo-flags-02785:
94// the flag needs the feature; -flags-08988: a compute, task or mesh stage; with a required size, -pNext-02757
95// wants X to be a multiple of it).
96// - A device whose one and only subgroup size (min == max) is the wanted one needs nothing (`device_fixed`).
97// - Where the size cannot be required (stage not listed, feature off) but the device default is the wanted size,
98// the shader works as it is (`device_default`): nothing guarantees it, a driver may change its default.
99// Otherwise the outcome is `unavailable`.
100inline SubgroupRequest decide_subgroup_size(const ShaderEntry& entry, const SubgroupSizeCaps& caps) {
101 SubgroupRequest r;
102 r.stage = subgroup_stage_bit(entry.stage);
103 if (!r.stage) return r;
104 if (entry.emulated()) {
105 r.outcome = SubgroupOutcome::emulated;
106 return r;
107 }
108 r.wanted = entry.subgroup_size ? entry.subgroup_size : (entry.wave64 ? 64 : 32);
109 if (!caps.default_size && !caps.max_size) {
110 r.outcome = SubgroupOutcome::unknown_device;
111 return r;
112 }
113
114 const bool compute_like = r.stage == VK_SHADER_STAGE_COMPUTE_BIT || r.stage == VK_SHADER_STAGE_MESH_BIT_EXT;
115 const std::uint64_t invocations =
116 std::uint64_t(entry.local_size[0]) * entry.local_size[1] * entry.local_size[2];
117 const bool fixed = caps.min_size && caps.min_size == caps.max_size && caps.min_size == r.wanted;
118 const bool requirable =
119 caps.subgroup_size_control && (caps.required_stages & r.stage) && subgroup_is_power_of_two(r.wanted) &&
120 r.wanted >= caps.min_size && r.wanted <= caps.max_size &&
121 (!compute_like || invocations <= std::uint64_t(r.wanted) * caps.max_compute_workgroup_subgroups);
122
123 if (fixed) {
124 r.outcome = SubgroupOutcome::device_fixed;
125 } else if (requirable) {
126 r.outcome = SubgroupOutcome::required;
127 r.size = r.wanted;
128 if (r.stage == VK_SHADER_STAGE_COMPUTE_BIT && caps.compute_full_subgroups &&
129 entry.local_size[0] % r.wanted == 0)
130 r.flags |= VK_PIPELINE_SHADER_STAGE_CREATE_REQUIRE_FULL_SUBGROUPS_BIT;
131 } else if (caps.default_size == r.wanted) {
132 r.outcome = SubgroupOutcome::device_default;
133 } else {
134 r.outcome = SubgroupOutcome::unavailable;
135 }
136 return r;
137}
138
139// Puts a request into a stage create-info. `storage` holds the chained structure and must outlive the
140// vkCreate*Pipelines call. Chains in front of whatever pNext already holds.
141inline void apply_subgroup_request(const SubgroupRequest& request,
142 VkPipelineShaderStageRequiredSubgroupSizeCreateInfo& storage,
143 VkPipelineShaderStageCreateInfo& stage) {
144 stage.flags |= request.flags;
145 if (!request.size) return;
146 storage = {VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_REQUIRED_SUBGROUP_SIZE_CREATE_INFO};
147 storage.requiredSubgroupSize = request.size;
148 storage.pNext = const_cast<void*>(stage.pNext);
149 stage.pNext = &storage;
150}
151
152} // namespace leonida
diff --git a/runtime/src/vulkan_backend.h b/runtime/src/vulkan_backend.h
index d4b6b00a7..e577e6af0 100644
--- a/runtime/src/vulkan_backend.h
+++ b/runtime/src/vulkan_backend.h
@@ -732,13 +732,16 @@ public:
732 const std::uint64_t base = replay_.heap_base; 732 const std::uint64_t base = replay_.heap_base;
733 XdxrLayout layout; 733 XdxrLayout layout;
734 layout.compute(xdxr_elements(b), b.is_tlas); 734 layout.compute(xdxr_elements(b), b.is_tlas);
735 // PERFORM_UPDATE refits the source (the destination itself when no source is given, as D3D12
736 // allows for an in-place update); a full build otherwise.
737 const std::uint64_t from = b.update ? base + (b.src_va ? b.src_va : b.dst_va) : 0;
735 if (b.is_tlas) { 738 if (b.is_tlas) {
736 xdxr_->record_tlas(cb, layout, b.instances_va ? base + b.instances_va : 0, base + b.dst_va, 739 xdxr_->record_tlas(cb, layout, b.instances_va ? base + b.instances_va : 0, base + b.dst_va,
737 base + b.scratch_va, base); 740 base + b.scratch_va, base, from);
738 } else { 741 } else {
739 std::vector<XdxrTriangles> geometries; 742 std::vector<XdxrTriangles> geometries;
740 xdxr_inputs(b, &geometries, base); 743 xdxr_inputs(b, &geometries, base);
741 xdxr_->record_blas(cb, layout, geometries, base + b.dst_va, base + b.scratch_va); 744 xdxr_->record_blas(cb, layout, geometries, base + b.dst_va, base + b.scratch_va, from);
742 } 745 }
743 }; 746 };
744 } else { 747 } else {
@@ -845,7 +848,10 @@ public:
845 query_pools_[id] = pool; 848 query_pools_[id] = pool;
846 } 849 }
847 void remove_query_pool(QueryHeapId id) { 850 void remove_query_pool(QueryHeapId id) {
851 // Lock hierarchy: resource_mutex_ -> tracker_mutex_. Holding tracker_mutex_ before erasing keeps the
852 // QueryPool node alive until any in-flight execute() that unlocked resource_mutex_ finishes QueryReplay::commit().
848 std::unique_lock lock(resource_mutex_); 853 std::unique_lock lock(resource_mutex_);
854 std::lock_guard tlock(tracker_mutex_);
849 query_pools_.erase(id); 855 query_pools_.erase(id);
850 } 856 }
851 // The heap's d3d12_query_heap type, or ~0u for a heap that is not registered. 857 // The heap's d3d12_query_heap type, or ~0u for a heap that is not registered.
@@ -1024,6 +1030,7 @@ public:
1024 1030
1025 std::uint64_t completed_retire_ticket() { 1031 std::uint64_t completed_retire_ticket() {
1026 std::lock_guard lock(submit_mutex_); 1032 std::lock_guard lock(submit_mutex_);
1033 if (is_device_lost()) return 0;
1027 return retire_tickets_.completed([this](VkSemaphore semaphore, std::uint64_t value) { 1034 return retire_tickets_.completed([this](VkSemaphore semaphore, std::uint64_t value) {
1028 std::uint64_t done = 0; 1035 std::uint64_t done = 0;
1029 return vk.vkGetSemaphoreCounterValue(device_, semaphore, &done) == VK_SUCCESS && done >= value; 1036 return vk.vkGetSemaphoreCounterValue(device_, semaphore, &done) == VK_SUCCESS && done >= value;
@@ -1220,8 +1227,12 @@ public:
1220 if (queue_) { 1227 if (queue_) {
1221 std::lock_guard lock(context_.submit_mutex()); 1228 std::lock_guard lock(context_.submit_mutex());
1222 for (; open_labels_; --open_labels_) context_.labels_.queue_end(queue_); 1229 for (; open_labels_; --open_labels_) context_.labels_.queue_end(queue_);
1223 vk.vkQueueWaitIdle(queue_); 1230 const VkResult idle_result = vk.vkQueueWaitIdle(queue_);
1224 if (progress_) context_.retire_queue_idle_locked(progress_); 1231 if (idle_result == VK_SUCCESS) {
1232 if (progress_) context_.retire_queue_idle_locked(progress_);
1233 } else {
1234 context_.mark_device_lost();
1235 }
1225 } 1236 }
1226 if (progress_) { 1237 if (progress_) {
1227 std::lock_guard lock(context_.tracker_mutex_); 1238 std::lock_guard lock(context_.tracker_mutex_);
@@ -1342,6 +1353,7 @@ public:
1342 } 1353 }
1343 const auto resolve = [this](ResourceId id) { return context_.resolve(id); }; 1354 const auto resolve = [this](ResourceId id) { return context_.resolve(id); };
1344 std::uint32_t segments = 0, statistics_segments = 0; 1355 std::uint32_t segments = 0, statistics_segments = 0;
1356 bool has_queries = false;
1345 for (std::size_t i = 0; i < lists.size(); ++i) { 1357 for (std::size_t i = 0; i < lists.size(); ++i) {
1346 const auto result = prepare(*lists[i], resolve, replay, prepared[i]); 1358 const auto result = prepare(*lists[i], resolve, replay, prepared[i]);
1347 if (result != ReplayResult::success) return result; 1359 if (result != ReplayResult::success) return result;
@@ -1350,6 +1362,7 @@ public:
1350 return ReplayResult::unsupported; 1362 return ReplayResult::unsupported;
1351 segments += prepared[i].segment_count; 1363 segments += prepared[i].segment_count;
1352 statistics_segments += prepared[i].statistics_segment_count; 1364 statistics_segments += prepared[i].statistics_segment_count;
1365 has_queries = has_queries || !prepared[i].queries.empty();
1353 } 1366 }
1354 const auto segment_pool = [this](VkQueryType type, std::uint32_t count, 1367 const auto segment_pool = [this](VkQueryType type, std::uint32_t count,
1355 std::shared_ptr<OcclusionSegmentPool>& out) { 1368 std::shared_ptr<OcclusionSegmentPool>& out) {
@@ -1371,6 +1384,10 @@ public:
1371 if (statistics_segments && can_resolve_occlusion && 1384 if (statistics_segments && can_resolve_occlusion &&
1372 !segment_pool(VK_QUERY_TYPE_PIPELINE_STATISTICS, statistics_segments, statistics)) 1385 !segment_pool(VK_QUERY_TYPE_PIPELINE_STATISTICS, statistics_segments, statistics))
1373 return ReplayResult::unsupported; 1386 return ReplayResult::unsupported;
1387 // QueryReplay::plan() reads QueryPool::ended / occlusion and QueryReplay::commit() writes them after
1388 // resource_lock is unlocked. Hold tracker_mutex_ across plan -> emit -> submit -> commit so concurrent queues
1389 // see submission-order query state and remove_query_pool() waits until commit finishes.
1390 if (has_queries && !tracker_lock.owns_lock()) tracker_lock.lock();
1374 QueryReplay queries; 1391 QueryReplay queries;
1375 std::uint32_t base = 0, statistics_base = 0; 1392 std::uint32_t base = 0, statistics_base = 0;
1376 for (auto& list : prepared) { 1393 for (auto& list : prepared) {
@@ -1595,10 +1612,12 @@ private:
1595 return false; 1612 return false;
1596 } 1613 }
1597 const bool ok = (res == VK_SUCCESS); 1614 const bool ok = (res == VK_SUCCESS);
1598 waits_.clear(); 1615 if (ok) {
1599 wait_values_.clear(); 1616 waits_.clear();
1600 for (auto& slot : buffers_) 1617 wait_values_.clear();
1601 if (slot.buffer == command_buffer) slot.ticket = ticket; 1618 for (auto& slot : buffers_)
1619 if (slot.buffer == command_buffer) slot.ticket = ticket;
1620 }
1602 return ok; 1621 return ok;
1603 } 1622 }
1604 1623
diff --git a/runtime/src/vulkan_bindless.h b/runtime/src/vulkan_bindless.h
index c599eb7c2..9111f764c 100644
--- a/runtime/src/vulkan_bindless.h
+++ b/runtime/src/vulkan_bindless.h
@@ -47,6 +47,7 @@
47#include <array> 47#include <array>
48#include <cstdint> 48#include <cstdint>
49#include <cstring> 49#include <cstring>
50#include <functional>
50#include <unordered_map> 51#include <unordered_map>
51#include <vector> 52#include <vector>
52 53
@@ -162,6 +163,35 @@ constexpr std::uint32_t r32ui_binding(ImageDimension dimension) {
162 return dimension == ImageDimension::dim_2d ? 4 : dimension == ImageDimension::dim_3d ? 7 : no_binding; 163 return dimension == ImageDimension::dim_2d ? 4 : dimension == ImageDimension::dim_3d ? 7 : no_binding;
163} 164}
164 165
166// Set 0's descriptor set layout at features' counts: what create_layout creates and what size_bindings'
167// layout_supported asks vkGetDescriptorSetLayoutSupport about. It points into itself, so it is not copied.
168struct SetLayout {
169 std::array<VkDescriptorSetLayoutBinding, binding_count> entries{};
170 std::array<VkDescriptorBindingFlags, binding_count> flags{};
171 VkDescriptorSetLayoutBindingFlagsCreateInfo flags_info{
172 VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_BINDING_FLAGS_CREATE_INFO};
173 VkDescriptorSetLayoutCreateInfo info{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO};
174
175 explicit SetLayout(const BindlessFeatures& features) {
176 std::uint32_t count = 0;
177 for (std::uint32_t b = 0; b < binding_count; ++b) {
178 if (!binding_enabled(b, features)) continue;
179 entries[count] = {b, bindings[b].type, features.counts[b], VK_SHADER_STAGE_ALL, nullptr};
180 flags[count] = (features.update_after_bind ? VK_DESCRIPTOR_BINDING_UPDATE_AFTER_BIND_BIT : 0) |
181 (features.partially_bound ? VK_DESCRIPTOR_BINDING_PARTIALLY_BOUND_BIT : 0);
182 ++count;
183 }
184 flags_info.bindingCount = count;
185 flags_info.pBindingFlags = flags.data();
186 info.pNext = &flags_info;
187 info.flags = features.update_after_bind ? VK_DESCRIPTOR_SET_LAYOUT_CREATE_UPDATE_AFTER_BIND_POOL_BIT : 0;
188 info.bindingCount = count;
189 info.pBindings = entries.data();
190 }
191 SetLayout(const SetLayout&) = delete;
192 SetLayout& operator=(const SetLayout&) = delete;
193};
194
165// What size_bindings() grows to where the device's limits allow. At 32-64 bytes a descriptor the whole set is then 195// What size_bindings() grows to where the device's limits allow. At 32-64 bytes a descriptor the whole set is then
166// 3-6 MiB (93793 descriptors on an RTX 5070). 196// 3-6 MiB (93793 descriptors on an RTX 5070).
167inline constexpr std::uint32_t max_2d_images = 65536; 197inline constexpr std::uint32_t max_2d_images = 65536;
@@ -183,10 +213,14 @@ inline constexpr std::uint32_t growth_headroom = 64;
183// what is sure to work (vkGetDescriptorSetLayoutSupport may allow more), so it never shrinks step 1. 213// what is sure to work (vkGetDescriptorSetLayoutSupport may allow more), so it never shrinks step 1.
184// A storage array holds the smaller of the storage count and its dimension's images: add_image never gives a 214// A storage array holds the smaller of the storage count and its dimension's images: add_image never gives a
185// storage view an index past the sampled array. The other bindings keep their default counts. 215// storage view an index past the sampled array. The other bindings keep their default counts.
216// layout_supported, when given, answers vkGetDescriptorSetLayoutSupport for set 0 at the counts in its argument:
217// step 3 then also grows past maxPerSetDescriptors where the device says the layout works (Intel's Xe-LP reports
218// 6159 and supports the full sizes, D3D-219). It is asked only once the sum is above maxPerSetDescriptors.
186// Sets features.counts; returns false when a count is below its default because the device's limits are. 219// Sets features.counts; returns false when a count is below its default because the device's limits are.
187inline bool size_bindings(BindlessFeatures& features, const VkPhysicalDeviceLimits& limits, 220inline bool size_bindings(BindlessFeatures& features, const VkPhysicalDeviceLimits& limits,
188 const VkPhysicalDeviceVulkan11Properties& v11, 221 const VkPhysicalDeviceVulkan11Properties& v11,
189 const VkPhysicalDeviceVulkan12Properties& v12) { 222 const VkPhysicalDeviceVulkan12Properties& v12,
223 const std::function<bool(const BindlessFeatures&)>& layout_supported = {}) {
190 const bool uab = features.update_after_bind; 224 const bool uab = features.update_after_bind;
191 const std::uint32_t sampled_limit = 225 const std::uint32_t sampled_limit =
192 uab ? std::min(v12.maxPerStageDescriptorUpdateAfterBindSampledImages, 226 uab ? std::min(v12.maxPerStageDescriptorUpdateAfterBindSampledImages,
@@ -233,7 +267,8 @@ inline bool size_bindings(BindlessFeatures& features, const VkPhysicalDeviceLimi
233 const auto within = [&](std::uint64_t n, std::uint32_t limit) { return n + headroom <= limit; }; 267 const auto within = [&](std::uint64_t n, std::uint32_t limit) { return n + headroom <= limit; };
234 const std::uint64_t all = sampled + sampler + stored + buffers; 268 const std::uint64_t all = sampled + sampler + stored + buffers;
235 return within(sampled, sampled_limit) && within(sampler, sampler_limit) && within(stored, storage_limit) && 269 return within(sampled, sampled_limit) && within(sampler, sampler_limit) && within(stored, storage_limit) &&
236 within(sampled + stored + buffers, resource_limit) && all <= pool_limit && all <= set_limit; 270 within(sampled + stored + buffers, resource_limit) && all <= pool_limit &&
271 (all <= set_limit || (layout_supported && layout_supported(features)));
237 }; 272 };
238 // Raises n to the largest value up to `high` that fits; leaves it where it is when none does. 273 // Raises n to the largest value up to `high` that fits; leaves it where it is when none does.
239 const auto grow = [&](std::uint32_t& n, std::uint32_t high, std::uint32_t headroom, std::uint64_t set_limit) { 274 const auto grow = [&](std::uint32_t& n, std::uint32_t high, std::uint32_t headroom, std::uint64_t set_limit) {
@@ -532,27 +567,12 @@ private:
532 } 567 }
533 568
534 bool create_layout() { 569 bool create_layout() {
535 std::array<VkDescriptorSetLayoutBinding, bindless::bindings.size()> entries{}; 570 const bindless::SetLayout layout(features_);
536 std::array<VkDescriptorBindingFlags, bindless::bindings.size()> flags{}; 571 const std::uint32_t count = layout.info.bindingCount;
537 std::array<VkDescriptorPoolSize, bindless::bindings.size()> sizes{}; 572 std::array<VkDescriptorPoolSize, bindless::bindings.size()> sizes{};
538 std::uint32_t count = 0; 573 for (std::uint32_t i = 0; i < count; ++i)
539 for (std::uint32_t b = 0; b < bindless::bindings.size(); ++b) { 574 sizes[i] = {layout.entries[i].descriptorType, layout.entries[i].descriptorCount};
540 if (!bindless::binding_enabled(b, features_)) continue; 575 if (vk_.vkCreateDescriptorSetLayout(device_, &layout.info, nullptr, &layout_) != VK_SUCCESS) return false;
541 entries[count] = {b, bindless::bindings[b].type, features_.counts[b], VK_SHADER_STAGE_ALL, nullptr};
542 flags[count] = (features_.update_after_bind ? VK_DESCRIPTOR_BINDING_UPDATE_AFTER_BIND_BIT : 0) |
543 (features_.partially_bound ? VK_DESCRIPTOR_BINDING_PARTIALLY_BOUND_BIT : 0);
544 sizes[count] = {bindless::bindings[b].type, features_.counts[b]};
545 ++count;
546 }
547 VkDescriptorSetLayoutBindingFlagsCreateInfo flags_info{
548 VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_BINDING_FLAGS_CREATE_INFO};
549 flags_info.bindingCount = count;
550 flags_info.pBindingFlags = flags.data();
551 VkDescriptorSetLayoutCreateInfo layout_info{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO, &flags_info};
552 layout_info.flags = features_.update_after_bind ? VK_DESCRIPTOR_SET_LAYOUT_CREATE_UPDATE_AFTER_BIND_POOL_BIT : 0;
553 layout_info.bindingCount = count;
554 layout_info.pBindings = entries.data();
555 if (vk_.vkCreateDescriptorSetLayout(device_, &layout_info, nullptr, &layout_) != VK_SUCCESS) return false;
556 576
557 VkDescriptorPoolCreateInfo pool_info{VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO}; 577 VkDescriptorPoolCreateInfo pool_info{VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO};
558 pool_info.flags = features_.update_after_bind ? VK_DESCRIPTOR_POOL_CREATE_UPDATE_AFTER_BIND_BIT : 0; 578 pool_info.flags = features_.update_after_bind ? VK_DESCRIPTOR_POOL_CREATE_UPDATE_AFTER_BIND_BIT : 0;
diff --git a/runtime/src/vulkan_depth24.h b/runtime/src/vulkan_depth24.h
index 1bc9c8ba5..988b79d9f 100644
--- a/runtime/src/vulkan_depth24.h
+++ b/runtime/src/vulkan_depth24.h
@@ -143,11 +143,14 @@ public:
143 // Frees (or keeps for reuse) what finished submissions used. 143 // Frees (or keeps for reuse) what finished submissions used.
144 void collect() { 144 void collect() {
145 for (std::size_t i = 0; i < retired_.size();) { 145 for (std::size_t i = 0; i < retired_.size();) {
146 std::uint64_t done = 0; 146 if (retired_[i].ticket != 0) {
147 vk_.vkGetSemaphoreCounterValue(device_, retired_[i].timeline, &done); 147 std::uint64_t done = 0;
148 if (done < retired_[i].ticket) { 148 if (!retired_[i].timeline ||
149 ++i; 149 vk_.vkGetSemaphoreCounterValue(device_, retired_[i].timeline, &done) != VK_SUCCESS ||
150 continue; 150 done < retired_[i].ticket) {
151 ++i;
152 continue;
153 }
151 } 154 }
152 for (auto& chunk : retired_[i].chunks) { 155 for (auto& chunk : retired_[i].chunks) {
153 chunk.used = 0; 156 chunk.used = 0;
diff --git a/runtime/src/vulkan_present.h b/runtime/src/vulkan_present.h
index 5d59a301f..d9f53baa5 100644
--- a/runtime/src/vulkan_present.h
+++ b/runtime/src/vulkan_present.h
@@ -35,7 +35,6 @@
35#include <cstring> 35#include <cstring>
36#include <functional> 36#include <functional>
37#include <map> 37#include <map>
38#include <optional>
39#include <vector> 38#include <vector>
40 39
41namespace leonida { 40namespace leonida {
@@ -75,9 +74,10 @@ class VulkanPresenter {
75public: 74public:
76 VulkanPresenter(VulkanContext& context, PFN_vkGetInstanceProcAddr get_instance, VkInstance instance, 75 VulkanPresenter(VulkanContext& context, PFN_vkGetInstanceProcAddr get_instance, VkInstance instance,
77 VkPhysicalDevice physical, VkQueue queue, std::uint32_t family, VkSurfaceKHR surface, 76 VkPhysicalDevice physical, VkQueue queue, std::uint32_t family, VkSurfaceKHR surface,
78 bool swapchain_maintenance1 = false) 77 bool swapchain_maintenance1 = false,
78 std::function<VkExtent2D()> extent_fn = nullptr)
79 : context_(context), instance_(instance), physical_(physical), queue_(queue), surface_(surface), 79 : context_(context), instance_(instance), physical_(physical), queue_(queue), surface_(surface),
80 maintenance1_(swapchain_maintenance1) { 80 maintenance1_(swapchain_maintenance1), extent_fn_(std::move(extent_fn)) {
81#define LEONIDA_INSTANCE_FN(name) name##_ = reinterpret_cast<PFN_##name>(get_instance(instance, #name)); 81#define LEONIDA_INSTANCE_FN(name) name##_ = reinterpret_cast<PFN_##name>(get_instance(instance, #name));
82 LEONIDA_INSTANCE_FN(vkGetPhysicalDeviceSurfaceSupportKHR) 82 LEONIDA_INSTANCE_FN(vkGetPhysicalDeviceSurfaceSupportKHR)
83 LEONIDA_INSTANCE_FN(vkGetPhysicalDeviceSurfaceCapabilitiesKHR) 83 LEONIDA_INSTANCE_FN(vkGetPhysicalDeviceSurfaceCapabilitiesKHR)
@@ -270,25 +270,34 @@ public:
270 270
271 bool recorded = false; 271 bool recorded = false;
272 std::unique_lock tracker_lock(context_.tracker_mutex_, std::defer_lock); 272 std::unique_lock tracker_lock(context_.tracker_mutex_, std::defer_lock);
273 std::optional<LayoutTracker> next_tracker; 273 bool rollback_source = false;
274 VkImageLayout prev_layout = VK_IMAGE_LAYOUT_UNDEFINED;
274 if (binding) { 275 if (binding) {
275 // Lock hierarchy: resource_mutex_ -> tracker_mutex_ -> submit_mutex_ (vulkan_backend.h). 276 // Lock hierarchy: resource_mutex_ -> tracker_mutex_ -> submit_mutex_ (vulkan_backend.h).
276 // Release resource_mutex_ before vkQueueSubmit while keeping tracker_mutex_ held so layout updates 277 // record() only touches subresource 0 (mip 0, layer 0, color) of `source`, so saving that one layout
277 // commit in submission order and roll back if vkQueueSubmit fails. 278 // rolls back a failed submit in O(1) without copying the entire LayoutTracker map.
278 std::shared_lock resource_lock(context_.resource_mutex_); 279 std::shared_lock resource_lock(context_.resource_mutex_);
279 const ResourceBinding* current = context_.resolve(source); 280 const ResourceBinding* current = context_.resolve(source);
280 if (current && current->image && current->aspects == VK_IMAGE_ASPECT_COLOR_BIT) { 281 if (current && current->image && current->aspects == VK_IMAGE_ASPECT_COLOR_BIT) {
281 tracker_lock.lock(); 282 tracker_lock.lock();
282 next_tracker.emplace(context_.tracker_); 283 rollback_source = context_.tracker_.tracked(source);
283 record(frame.commands, *current, source, image, source_rect, *next_tracker); 284 if (rollback_source) prev_layout = context_.tracker_.layout(source, 0);
285 record(frame.commands, *current, source, image, source_rect);
284 recorded = true; 286 recorded = true;
285 } 287 }
286 } else { 288 } else {
287 record_blank(frame.commands, image); 289 record_blank(frame.commands, image);
288 recorded = true; 290 recorded = true;
289 } 291 }
292 const auto rollback = [&] {
293 if (rollback_source)
294 context_.tracker_.set(source, {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}, prev_layout);
295 };
290 if (!recorded) return give_back(frame, VK_ERROR_UNKNOWN); // released by another thread since presentable() 296 if (!recorded) return give_back(frame, VK_ERROR_UNKNOWN); // released by another thread since presentable()
291 if (const VkResult reset = vkResetFences_(device, 1, &frame.done); reset != VK_SUCCESS) return stop(reset); 297 if (const VkResult reset = vkResetFences_(device, 1, &frame.done); reset != VK_SUCCESS) {
298 rollback();
299 return stop(reset);
300 }
292 const VkPipelineStageFlags wait_stage = VK_PIPELINE_STAGE_TRANSFER_BIT; 301 const VkPipelineStageFlags wait_stage = VK_PIPELINE_STAGE_TRANSFER_BIT;
293 VkSubmitInfo submit_info{VK_STRUCTURE_TYPE_SUBMIT_INFO}; 302 VkSubmitInfo submit_info{VK_STRUCTURE_TYPE_SUBMIT_INFO};
294 submit_info.waitSemaphoreCount = 1; 303 submit_info.waitSemaphoreCount = 1;
@@ -321,10 +330,12 @@ public:
321 { 330 {
322 std::lock_guard lock(context_.submit_mutex()); 331 std::lock_guard lock(context_.submit_mutex());
323 submitted = vk.vkQueueSubmit(queue_, 1, &submit_info, frame.done); 332 submitted = vk.vkQueueSubmit(queue_, 1, &submit_info, frame.done);
333 if (submitted != VK_SUCCESS) rollback();
334 // Commit/rollback happened before releasing tracker_mutex_ inside submit_mutex(), preserving submission
335 // order without holding tracker_mutex_ across vkQueuePresentKHR.
336 if (tracker_lock.owns_lock()) tracker_lock.unlock();
324 if (submitted == VK_SUCCESS) result = vkQueuePresentKHR_(queue_, &present); 337 if (submitted == VK_SUCCESS) result = vkQueuePresentKHR_(queue_, &present);
325 } 338 }
326 if (submitted == VK_SUCCESS && next_tracker) context_.tracker_ = std::move(*next_tracker);
327 if (tracker_lock.owns_lock()) tracker_lock.unlock();
328 if (submitted != VK_SUCCESS) return give_back(frame, submitted); 339 if (submitted != VK_SUCCESS) return give_back(frame, submitted);
329 ++frame_index_; 340 ++frame_index_;
330 // Only a present the engine took counts (SUBOPTIMAL is shown too). OUT_OF_DATE was not shown: the swapchain 341 // Only a present the engine took counts (SUBOPTIMAL is shown too). OUT_OF_DATE was not shown: the swapchain
@@ -400,7 +411,7 @@ private:
400 } 411 }
401 412
402 void record(VkCommandBuffer commands, const ResourceBinding& binding, ResourceId source, std::uint32_t image, 413 void record(VkCommandBuffer commands, const ResourceBinding& binding, ResourceId source, std::uint32_t image,
403 const PresentRect* source_rect, LayoutTracker& tracker) { 414 const PresentRect* source_rect) {
404 auto& vk = context_.vk; 415 auto& vk = context_.vk;
405 const ReplayFunctions& fn = context_.replay_; 416 const ReplayFunctions& fn = context_.replay_;
406 vk.vkResetCommandBuffer(commands, 0); 417 vk.vkResetCommandBuffer(commands, 0);
@@ -413,8 +424,8 @@ private:
413 // PRESENT is D3D12's common state: GENERAL for an ordinary texture. A never-written back buffer is 424 // PRESENT is D3D12's common state: GENERAL for an ordinary texture. A never-written back buffer is
414 // zero-filled first, as any committed resource is. 425 // zero-filled first, as any committed resource is.
415 const VkImageLayout common = image_layout(binding, VK_IMAGE_LAYOUT_GENERAL); 426 const VkImageLayout common = image_layout(binding, VK_IMAGE_LAYOUT_GENERAL);
416 auto pieces = detail::current(&tracker, source, range, common); 427 auto pieces = detail::current(&context_.tracker_, source, range, common);
417 detail::initialize(fn, commands, binding, source, pieces, common, &tracker); 428 detail::initialize(fn, commands, binding, source, pieces, common, &context_.tracker_);
418 for (const auto& piece : pieces) 429 for (const auto& piece : pieces)
419 detail::image_barrier(fn, commands, binding, piece.range, piece.layout, 430 detail::image_barrier(fn, commands, binding, piece.range, piece.layout,
420 VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, VK_ACCESS_MEMORY_WRITE_BIT, 431 VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, VK_ACCESS_MEMORY_WRITE_BIT,
@@ -595,7 +606,21 @@ private:
595 tear_mode_ = VK_PRESENT_MODE_MAX_ENUM_KHR; 606 tear_mode_ = VK_PRESENT_MODE_MAX_ENUM_KHR;
596 VkSurfaceCapabilitiesKHR caps{}; 607 VkSurfaceCapabilitiesKHR caps{};
597 if (vkGetPhysicalDeviceSurfaceCapabilitiesKHR_(physical_, surface_, &caps) != VK_SUCCESS) return false; 608 if (vkGetPhysicalDeviceSurfaceCapabilitiesKHR_(physical_, surface_, &caps) != VK_SUCCESS) return false;
598 if (caps.currentExtent.width == 0 || caps.currentExtent.height == 0) { 609 VkExtent2D extent = caps.currentExtent;
610 // When the platform leaves the swapchain extent to the application (0xFFFFFFFF, as on Intel UHD / Win32 WSI),
611 // query the window client area or fall back to the last known extent, and clamp to the surface bounds (D3D-165).
612 if (extent.width == 0xFFFFFFFF || extent.height == 0xFFFFFFFF) {
613 if (extent_fn_) extent = extent_fn_();
614 // ponytail: if no window extent function was supplied, fall back to last extent_ or minImageExtent
615 if (extent.width == 0xFFFFFFFF || extent.height == 0xFFFFFFFF || (extent.width == 0 && extent.height == 0)) {
616 extent = extent_.width && extent_.height ? extent_ : caps.minImageExtent;
617 }
618 if (extent.width && extent.height) {
619 extent.width = std::clamp(extent.width, caps.minImageExtent.width, caps.maxImageExtent.width);
620 extent.height = std::clamp(extent.height, caps.minImageExtent.height, caps.maxImageExtent.height);
621 }
622 }
623 if (extent.width == 0 || extent.height == 0) {
599 release(swapchain_); 624 release(swapchain_);
600 swapchain_ = VK_NULL_HANDLE; 625 swapchain_ = VK_NULL_HANDLE;
601 vsync_ = vsync; 626 vsync_ = vsync;
@@ -659,7 +684,7 @@ private:
659 if (caps.maxImageCount) info.minImageCount = std::min(info.minImageCount, caps.maxImageCount); 684 if (caps.maxImageCount) info.minImageCount = std::min(info.minImageCount, caps.maxImageCount);
660 info.imageFormat = chosen.format; 685 info.imageFormat = chosen.format;
661 info.imageColorSpace = chosen.colorSpace; 686 info.imageColorSpace = chosen.colorSpace;
662 info.imageExtent = caps.currentExtent; 687 info.imageExtent = extent;
663 info.imageArrayLayers = 1; 688 info.imageArrayLayers = 1;
664 info.imageUsage = usage; 689 info.imageUsage = usage;
665 info.imageSharingMode = VK_SHARING_MODE_EXCLUSIVE; 690 info.imageSharingMode = VK_SHARING_MODE_EXCLUSIVE;
@@ -713,7 +738,7 @@ private:
713 images_ = std::move(images); 738 images_ = std::move(images);
714 ready_ = std::move(ready); 739 ready_ = std::move(ready);
715 format_ = chosen.format; 740 format_ = chosen.format;
716 extent_ = caps.currentExtent; 741 extent_ = extent;
717 if (capture_) { 742 if (capture_) {
718 // A capture that cannot be made fails the recreation with the swapchain in place and stale_ still set. 743 // A capture that cannot be made fails the recreation with the swapchain in place and stale_ still set.
719 const bool four_bytes = format_ == VK_FORMAT_B8G8R8A8_UNORM || format_ == VK_FORMAT_R8G8B8A8_UNORM || 744 const bool four_bytes = format_ == VK_FORMAT_B8G8R8A8_UNORM || format_ == VK_FORMAT_R8G8B8A8_UNORM ||
@@ -812,6 +837,7 @@ private:
812 bool ok_ = false; 837 bool ok_ = false;
813 bool swapchain_srgb_ = false; // the swapchain format follows the source being presented (set once it exists) 838 bool swapchain_srgb_ = false; // the swapchain format follows the source being presented (set once it exists)
814 std::function<bool()> abort_; 839 std::function<bool()> abort_;
840 std::function<VkExtent2D()> extent_fn_;
815 std::map<VkFormat, VkFormatFeatureFlags> features_; 841 std::map<VkFormat, VkFormatFeatureFlags> features_;
816 bool warned_srgb_ = false; 842 bool warned_srgb_ = false;
817 bool capture_ = false; 843 bool capture_ = false;
diff --git a/runtime/src/vulkan_replay.h b/runtime/src/vulkan_replay.h
index 89fe7381d..0b46198a9 100644
--- a/runtime/src/vulkan_replay.h
+++ b/runtime/src/vulkan_replay.h
@@ -1058,20 +1058,180 @@ inline std::vector<LayoutPiece> current(const LayoutTracker* tracker, ResourceId
1058 return out; 1058 return out;
1059} 1059}
1060 1060
1061// Zero-fills a block-compressed image range via vkCmdCopyBufferToImage from either the device's zero page
1062// (`vk.zero_buffer`) or a zeroed transfer-scratch chunk (`vk.copy_scratch` + `vk.fill_buffer`). Vulkan forbids
1063// vkCmdClearColorImage on BC formats, yet D3D12 committed resources start zeroed unless CREATE_NOT_ZEROED is set
1064// (D3D-220).
1065inline bool zero_compressed_image(const ReplayFunctions& vk, VkCommandBuffer command_buffer,
1066 const ResourceBinding& resource, const VkImageSubresourceRange& range,
1067 VkImageLayout dst_layout) {
1068 const BlockFormat fmt = block_format(resource.format, VK_IMAGE_ASPECT_COLOR_BIT);
1069 if (fmt.block <= 1 || !fmt.bytes || !vk.copy_buffer_to_image) return false;
1070 const std::uint32_t mip_begin = range.baseMipLevel;
1071 const std::uint32_t mip_end =
1072 range.levelCount == VK_REMAINING_MIP_LEVELS ? resource.mip_levels
1073 : std::min(resource.mip_levels, mip_begin + range.levelCount);
1074 const std::uint32_t layer_begin = range.baseArrayLayer;
1075 const std::uint32_t layer_end =
1076 range.layerCount == VK_REMAINING_ARRAY_LAYERS ? resource.array_layers
1077 : std::min(resource.array_layers, layer_begin + range.layerCount);
1078 if (mip_begin >= mip_end || layer_begin >= layer_end) return true;
1079
1080 constexpr VkDeviceSize kMaxChunk = 64u * 1024u;
1081 const std::uint32_t layer_count = layer_end - layer_begin;
1082 VkDeviceSize needed = 0;
1083 for (std::uint32_t mip = mip_begin; mip < mip_end; ++mip) {
1084 const VkExtent2D ext = mip_extent(resource, mip);
1085 const std::uint64_t bx = (std::uint64_t(ext.width) + fmt.block - 1) / fmt.block;
1086 const std::uint64_t by = (std::uint64_t(ext.height) + fmt.block - 1) / fmt.block;
1087 const std::uint64_t mip_d = std::max(1u, resource.depth >> mip);
1088 const std::uint64_t slice_bytes = bx * by * fmt.bytes;
1089 if (slice_bytes >= kMaxChunk || mip_d > kMaxChunk / slice_bytes ||
1090 layer_count > kMaxChunk / (slice_bytes * mip_d)) {
1091 needed = kMaxChunk;
1092 break;
1093 }
1094 needed = std::max<VkDeviceSize>(needed, slice_bytes * mip_d * layer_count);
1095 }
1096 if (!needed) return true;
1097
1098 VkBuffer zero_buf = VK_NULL_HANDLE;
1099 VkDeviceSize zero_off = 0;
1100 VkDeviceSize zero_cap = 0;
1101 if (vk.zero_buffer && vk.zero_size >= fmt.bytes) {
1102 const VkDeviceSize align = fmt.bytes;
1103 const VkDeviceSize pad = (align - (vk.zero_offset % align)) % align;
1104 if (vk.zero_size >= pad + fmt.bytes) {
1105 zero_buf = vk.zero_buffer;
1106 zero_off = vk.zero_offset + pad;
1107 zero_cap = vk.zero_size - pad;
1108 }
1109 }
1110 if (!zero_buf && vk.copy_scratch && vk.fill_buffer) {
1111 // Round up to a multiple of fmt.bytes (8 or 16, always a multiple of 4 for vkCmdFillBuffer).
1112 const VkDeviceSize fill_bytes = ((needed + fmt.bytes - 1) / fmt.bytes) * fmt.bytes;
1113 VkBuffer scratch = VK_NULL_HANDLE;
1114 VkDeviceSize offset = 0;
1115 if (vk.copy_scratch(fill_bytes, scratch, offset)) {
1116 const VkDeviceSize align = fmt.bytes;
1117 const VkDeviceSize pad = (align - (offset % align)) % align;
1118 if (fill_bytes >= pad + fmt.bytes) {
1119 vk.fill_buffer(command_buffer, scratch, offset + pad, fill_bytes - pad, 0);
1120 memory_barrier(vk, command_buffer, VK_ACCESS_TRANSFER_WRITE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT,
1121 VK_ACCESS_TRANSFER_READ_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT);
1122 zero_buf = scratch;
1123 zero_off = offset + pad;
1124 zero_cap = fill_bytes - pad;
1125 }
1126 }
1127 }
1128 if (!zero_buf || zero_cap < fmt.bytes) return false;
1129
1130 std::vector<VkBufferImageCopy> regions;
1131 for (std::uint32_t mip = mip_begin; mip < mip_end; ++mip) {
1132 const VkExtent2D ext = mip_extent(resource, mip);
1133 const std::uint32_t mip_d = std::max(1u, resource.depth >> mip);
1134 const std::uint64_t bx_total = (std::uint64_t(ext.width) + fmt.block - 1) / fmt.block;
1135 const std::uint64_t by_total = (std::uint64_t(ext.height) + fmt.block - 1) / fmt.block;
1136 const std::uint64_t slice_bytes = bx_total * by_total * fmt.bytes;
1137 if (slice_bytes && slice_bytes <= zero_cap && mip_d <= zero_cap / slice_bytes &&
1138 layer_count <= zero_cap / (slice_bytes * mip_d)) {
1139 VkBufferImageCopy r{};
1140 r.bufferOffset = zero_off;
1141 r.imageSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, mip, layer_begin, layer_count};
1142 r.imageExtent = {ext.width, ext.height, mip_d};
1143 regions.push_back(r);
1144 continue;
1145 }
1146 const std::uint64_t row_bytes = bx_total * fmt.bytes;
1147 for (std::uint32_t layer = layer_begin; layer < layer_end; ++layer) {
1148 if (slice_bytes <= zero_cap) {
1149 const std::uint32_t slices_per_copy =
1150 std::max<std::uint32_t>(1u, std::uint32_t(std::min<std::uint64_t>(mip_d, zero_cap / slice_bytes)));
1151 for (std::uint32_t z = 0; z < mip_d; z += slices_per_copy) {
1152 VkBufferImageCopy r{};
1153 r.bufferOffset = zero_off;
1154 r.imageSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, mip, layer, 1};
1155 r.imageOffset = {0, 0, std::int32_t(z)};
1156 r.imageExtent = {ext.width, ext.height, std::min(slices_per_copy, mip_d - z)};
1157 regions.push_back(r);
1158 }
1159 } else if (row_bytes <= zero_cap) {
1160 const std::uint32_t rows_per_copy =
1161 std::max<std::uint32_t>(1u, std::uint32_t(std::min<std::uint64_t>(by_total, zero_cap / row_bytes)));
1162 for (std::uint32_t z = 0; z < mip_d; ++z) {
1163 for (std::uint64_t y_blk = 0; y_blk < by_total; y_blk += rows_per_copy) {
1164 const std::uint32_t oy = std::uint32_t(y_blk * fmt.block);
1165 const std::uint32_t eh = std::min<std::uint32_t>(rows_per_copy * fmt.block, ext.height - oy);
1166 VkBufferImageCopy r{};
1167 r.bufferOffset = zero_off;
1168 r.imageSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, mip, layer, 1};
1169 r.imageOffset = {0, std::int32_t(oy), std::int32_t(z)};
1170 r.imageExtent = {ext.width, eh, 1};
1171 regions.push_back(r);
1172 }
1173 }
1174 } else {
1175 const std::uint32_t cols_per_copy =
1176 std::max<std::uint32_t>(1u, std::uint32_t(std::min<std::uint64_t>(bx_total, zero_cap / fmt.bytes)));
1177 for (std::uint32_t z = 0; z < mip_d; ++z) {
1178 for (std::uint64_t y_blk = 0; y_blk < by_total; ++y_blk) {
1179 const std::uint32_t oy = std::uint32_t(y_blk * fmt.block);
1180 const std::uint32_t eh = std::min<std::uint32_t>(fmt.block, ext.height - oy);
1181 for (std::uint64_t x_blk = 0; x_blk < bx_total; x_blk += cols_per_copy) {
1182 const std::uint32_t ox = std::uint32_t(x_blk * fmt.block);
1183 const std::uint32_t ew =
1184 std::min<std::uint32_t>(cols_per_copy * fmt.block, ext.width - ox);
1185 VkBufferImageCopy r{};
1186 r.bufferOffset = zero_off;
1187 r.imageSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, mip, layer, 1};
1188 r.imageOffset = {std::int32_t(ox), std::int32_t(oy), std::int32_t(z)};
1189 r.imageExtent = {ew, eh, 1};
1190 regions.push_back(r);
1191 }
1192 }
1193 }
1194 }
1195 }
1196 }
1197 if (!regions.empty())
1198 vk.copy_buffer_to_image(command_buffer, zero_buf, resource.image, dst_layout,
1199 std::uint32_t(regions.size()), regions.data());
1200 return true;
1201}
1202
1061// Images registered with the tracker in UNDEFINED have never been used. D3D12 committed resources start zeroed, 1203// Images registered with the tracker in UNDEFINED have never been used. D3D12 committed resources start zeroed,
1062// so each such piece is cleared to zero (colour 0, depth 0, stencil 0) and moved to `layout`, the layout the 1204// so each such piece is zero-filled (clear for uncompressed images, zero-buffer copy for block-compressed formats
1063// operation about to run expects, before that operation; with not_zeroed, or a block-compressed format (which 1205// when a zero page or transfer scratch is available) and moved to `layout`, the layout the operation about to run
1064// Vulkan cannot clear), it is only moved. The tracker records it. 1206// expects; with not_zeroed, it is only moved. The tracker records it.
1065inline void initialize(const ReplayFunctions& vk, VkCommandBuffer command_buffer, const ResourceBinding& resource, 1207inline void initialize(const ReplayFunctions& vk, VkCommandBuffer command_buffer, const ResourceBinding& resource,
1066 ResourceId id, std::vector<LayoutPiece>& pieces, VkImageLayout layout, LayoutTracker* tracker) { 1208 ResourceId id, std::vector<LayoutPiece>& pieces, VkImageLayout layout, LayoutTracker* tracker) {
1067 constexpr VkAccessFlags any_memory = VK_ACCESS_MEMORY_READ_BIT | VK_ACCESS_MEMORY_WRITE_BIT; 1209 constexpr VkAccessFlags any_memory = VK_ACCESS_MEMORY_READ_BIT | VK_ACCESS_MEMORY_WRITE_BIT;
1068 for (auto& piece : pieces) { 1210 for (auto& piece : pieces) {
1069 if (piece.layout != VK_IMAGE_LAYOUT_UNDEFINED) continue; 1211 if (piece.layout != VK_IMAGE_LAYOUT_UNDEFINED) continue;
1070 // Vulkan cannot clear block-compressed images; those start undefined (applications upload them first). 1212 const BlockFormat fmt = block_format(resource.format, VK_IMAGE_ASPECT_COLOR_BIT);
1071 const bool compressed = block_format(resource.format, VK_IMAGE_ASPECT_COLOR_BIT).block > 1; 1213 const bool compressed = fmt.block > 1;
1072 if (resource.not_zeroed || compressed) { 1214 if (resource.not_zeroed) {
1073 image_barrier(vk, command_buffer, resource, piece.range, VK_IMAGE_LAYOUT_UNDEFINED, layout, 0, 1215 image_barrier(vk, command_buffer, resource, piece.range, VK_IMAGE_LAYOUT_UNDEFINED, layout, 0,
1074 VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, any_memory, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT); 1216 VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, any_memory, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT);
1217 } else if (compressed) {
1218 const bool can_zero =
1219 vk.copy_buffer_to_image &&
1220 ((vk.zero_buffer && vk.zero_size >= fmt.bytes) || (vk.copy_scratch && vk.fill_buffer));
1221 if (can_zero) {
1222 const VkImageLayout dst = image_layout(resource, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL);
1223 image_barrier(vk, command_buffer, resource, piece.range, VK_IMAGE_LAYOUT_UNDEFINED, dst, 0,
1224 VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_ACCESS_TRANSFER_WRITE_BIT,
1225 VK_PIPELINE_STAGE_TRANSFER_BIT);
1226 const bool zeroed = zero_compressed_image(vk, command_buffer, resource, piece.range, dst);
1227 image_barrier(vk, command_buffer, resource, piece.range, dst, layout,
1228 zeroed ? VK_ACCESS_TRANSFER_WRITE_BIT : 0,
1229 zeroed ? VK_PIPELINE_STAGE_TRANSFER_BIT : VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, any_memory,
1230 VK_PIPELINE_STAGE_ALL_COMMANDS_BIT);
1231 } else {
1232 image_barrier(vk, command_buffer, resource, piece.range, VK_IMAGE_LAYOUT_UNDEFINED, layout, 0,
1233 VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, any_memory, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT);
1234 }
1075 } else { 1235 } else {
1076 const VkImageLayout dst = image_layout(resource, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL); 1236 const VkImageLayout dst = image_layout(resource, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL);
1077 image_barrier(vk, command_buffer, resource, piece.range, VK_IMAGE_LAYOUT_UNDEFINED, dst, 0, 1237 image_barrier(vk, command_buffer, resource, piece.range, VK_IMAGE_LAYOUT_UNDEFINED, dst, 0,
@@ -2007,8 +2167,15 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun
2007 // A depth plane footprint of a D24 texture stored as D32: words of 24-bit UNORM, floats in the image. 2167 // A depth plane footprint of a D24 texture stored as D32: words of 24-bit UNORM, floats in the image.
2008 const bool upload = texture_copy->src.footprint; 2168 const bool upload = texture_copy->src.footprint;
2009 const ResourceBinding& image = upload ? p.binding : p.source; 2169 const ResourceBinding& image = upload ? p.binding : p.source;
2010 if (result == ReplayResult::success && image.depth24_as_float && !p.buffer_image_copies.empty() && 2170 const bool depth24_footprint = result == ReplayResult::success && image.depth24_as_float &&
2011 p.buffer_image_copies[0].imageSubresource.aspectMask == VK_IMAGE_ASPECT_DEPTH_BIT) { 2171 !p.buffer_image_copies.empty() &&
2172 p.buffer_image_copies[0].imageSubresource.aspectMask == VK_IMAGE_ASPECT_DEPTH_BIT;
2173 const bool rgb96_footprint = result == ReplayResult::success && image.rgb96 &&
2174 !p.buffer_image_copies.empty();
2175 // These footprint conversions emit compute dispatches in emit(). Refuse them before allocating their
2176 // conversion scratch/descriptors because an active statistics query would include their CSInvocations.
2177 if (statistics_active && (depth24_footprint || rgb96_footprint)) return ReplayResult::unsupported;
2178 if (depth24_footprint) {
2012 const VkBufferImageCopy& region = p.buffer_image_copies[0]; 2179 const VkBufferImageCopy& region = p.buffer_image_copies[0];
2013 const ResourceBinding& buffer = upload ? p.source : p.binding; 2180 const ResourceBinding& buffer = upload ? p.source : p.binding;
2014 Depth24Job& job = p.depth24; 2181 Depth24Job& job = p.depth24;
@@ -2023,7 +2190,7 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun
2023 job.app_slice_words = job.app_row_words * (region.bufferImageHeight ? region.bufferImageHeight : job.height); 2190 job.app_slice_words = job.app_row_words * (region.bufferImageHeight ? region.bufferImageHeight : job.height);
2024 if (!vk.depth24_prepare || !vk.depth24_run || !vk.depth24_prepare(job, p.depth24_parts)) return ReplayResult::unsupported; 2191 if (!vk.depth24_prepare || !vk.depth24_run || !vk.depth24_prepare(job, p.depth24_parts)) return ReplayResult::unsupported;
2025 p.has_depth24 = true; 2192 p.has_depth24 = true;
2026 } else if (result == ReplayResult::success && image.rgb96 && !p.buffer_image_copies.empty()) { 2193 } else if (rgb96_footprint) {
2027 // A footprint of a 96-bit texture: 12-byte texels, 16 in the image. The same pass and scratch. 2194 // A footprint of a 96-bit texture: 12-byte texels, 16 in the image. The same pass and scratch.
2028 const VkBufferImageCopy& region = p.buffer_image_copies[0]; 2195 const VkBufferImageCopy& region = p.buffer_image_copies[0];
2029 const ResourceBinding& buffer = upload ? p.source : p.binding; 2196 const ResourceBinding& buffer = upload ? p.source : p.binding;
@@ -2041,9 +2208,6 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun
2041 if (!vk.depth24_prepare || !vk.depth24_run || !vk.depth24_prepare(job, p.depth24_parts)) return ReplayResult::unsupported; 2208 if (!vk.depth24_prepare || !vk.depth24_run || !vk.depth24_prepare(job, p.depth24_parts)) return ReplayResult::unsupported;
2042 p.has_depth24 = true; 2209 p.has_depth24 = true;
2043 } 2210 }
2044 // These footprint conversions emit compute dispatches in emit(). Until pipeline-statistics
2045 // segmentation can bracket arbitrary helper dispatches, don't let them inflate CSInvocations.
2046 if (p.has_depth24 && statistics_active) return ReplayResult::unsupported;
2047 } else { 2211 } else {
2048 result = detail::prepare_resource_copy(p); 2212 result = detail::prepare_resource_copy(p);
2049 } 2213 }
@@ -2955,8 +3119,9 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c
2955 } 3119 }
2956 } 3120 }
2957 } 3121 }
2958 } else if (const auto* build = std::get_if<BuildAccelerationStructure>(&command); build && vk.xdxr_record) { 3122 } else if (const auto* xdxr_build = std::get_if<BuildAccelerationStructure>(&command);
2959 vk.xdxr_record(command_buffer, *build); 3123 xdxr_build && vk.xdxr_record) {
3124 vk.xdxr_record(command_buffer, *xdxr_build);
2960 } else if (const auto* build = std::get_if<BuildAccelerationStructure>(&command)) { 3125 } else if (const auto* build = std::get_if<BuildAccelerationStructure>(&command)) {
2961 // The build's addresses are console VAs into the GPU address arena (heap_base is its device address). 3126 // The build's addresses are console VAs into the GPU address arena (heap_base is its device address).
2962 // A null VA (no index buffer, no transform) stays null: heap_base + 0 would name the arena's zero page. 3127 // A null VA (no index buffer, no transform) stays null: heap_base + 0 would name the arena's zero page.
diff --git a/runtime/src/vulkan_scratch.h b/runtime/src/vulkan_scratch.h
index fe29d1a5c..4a8a59ddd 100644
--- a/runtime/src/vulkan_scratch.h
+++ b/runtime/src/vulkan_scratch.h
@@ -94,11 +94,14 @@ public:
94 // Keeps for reuse (or frees) the chunks of finished submissions. 94 // Keeps for reuse (or frees) the chunks of finished submissions.
95 void collect() { 95 void collect() {
96 for (std::size_t i = 0; i < retired_.size();) { 96 for (std::size_t i = 0; i < retired_.size();) {
97 std::uint64_t done = 0; 97 if (retired_[i].ticket != 0) {
98 if (retired_[i].timeline) vk_.vkGetSemaphoreCounterValue(device_, retired_[i].timeline, &done); 98 std::uint64_t done = 0;
99 if (done < retired_[i].ticket) { 99 if (!retired_[i].timeline ||
100 ++i; 100 vk_.vkGetSemaphoreCounterValue(device_, retired_[i].timeline, &done) != VK_SUCCESS ||
101 continue; 101 done < retired_[i].ticket) {
102 ++i;
103 continue;
104 }
102 } 105 }
103 for (auto& chunk : retired_[i].chunks) { 106 for (auto& chunk : retired_[i].chunks) {
104 chunk.used = 0; 107 chunk.used = 0;
diff --git a/runtime/src/xdxr_build.comp b/runtime/src/xdxr_build.comp
index 7b5b9d034..d5bbe8253 100644
--- a/runtime/src/xdxr_build.comp
+++ b/runtime/src/xdxr_build.comp
@@ -13,8 +13,16 @@
13// MODE_RADIX_* a stable LSD radix sort of the keys with their element indices: 8 passes of 4-bit digits, each 13// MODE_RADIX_* a stable LSD radix sort of the keys with their element indices: 8 passes of 4-bit digits, each
14// a count per tile of RADIX_TILE elements, one exclusive scan, and a scatter (24 dispatches in all, 14// a count per tile of RADIX_TILE elements, one exclusive scan, and a scatter (24 dispatches in all,
15// whatever the count; shared memory only, no subgroup operations) 15// whatever the count; shared memory only, no subgroup operations)
16// MODE_SMALL_SORT up to SMALL_SORT_MAX keys: one workgroup sorts them in shared memory (bitonic, ties by element
17// index, so the order is the stable one), in one dispatch instead of the radix sort's 24, whose
18// fixed latency dominated small builds
16// MODE_LEVEL one thread per BOX32 node of one level: four consecutive entries of the level below 19// MODE_LEVEL one thread per BOX32 node of one level: four consecutive entries of the level below
17// MODE_HEADER one thread: the 64-byte header 20// MODE_HEADER one thread: the 64-byte header
21// An update (D3D12 PERFORM_UPDATE: same topology, new positions or transforms) refits instead: MODE_COPY copies the
22// source structure to the destination when they differ, MODE_TRIANGLES / MODE_INSTANCES rewrite the elements at their
23// slots, MODE_LEVEL with arg2 = 1 recomputes each node's boxes from the children it already points to (the tree's
24// grouping is kept, so there is no Morton pass and no sort), and MODE_HEADER rewrites the bounds.
25// MODE_COPY one thread per word: count words from src0 to dst
18// The tree groups four consecutive children per node in Morton order, level by level, so its shape depends only on 26// The tree groups four consecutive children per node in Morton order, level by level, so its shape depends only on
19// the element count and the layout (xdxr_build.h XdxrLayout) is known when the command is recorded. 27// the element count and the layout (xdxr_build.h XdxrLayout) is known when the command is recorded.
20// 28//
@@ -31,9 +39,11 @@ layout(local_size_x = 64) in;
31layout(buffer_reference, std430, buffer_reference_align = 4) buffer Words { uint w[]; }; 39layout(buffer_reference, std430, buffer_reference_align = 4) buffer Words { uint w[]; };
32 40
33const uint MODE_INIT = 0u, MODE_TRIANGLES = 1u, MODE_INSTANCES = 2u, MODE_MORTON = 3u, MODE_LEVEL = 5u, 41const uint MODE_INIT = 0u, MODE_TRIANGLES = 1u, MODE_INSTANCES = 2u, MODE_MORTON = 3u, MODE_LEVEL = 5u,
34 MODE_HEADER = 6u, MODE_RADIX_COUNT = 7u, MODE_RADIX_SCAN = 8u, MODE_RADIX_SCATTER = 9u; 42 MODE_HEADER = 6u, MODE_RADIX_COUNT = 7u, MODE_RADIX_SCAN = 8u, MODE_RADIX_SCATTER = 9u,
43 MODE_SMALL_SORT = 10u, MODE_COPY = 11u;
44const uint SMALL_SORT_MAX = 1024u; // xdxr_build.h XdxrLayout::small_sort_max
35const uint RADIX_BITS = 4u, RADIX_BINS = 16u, RADIX_PASSES = 8u; 45const uint RADIX_BITS = 4u, RADIX_BINS = 16u, RADIX_PASSES = 8u;
36const uint RADIX_TILE = 2048u; // elements per workgroup in count and scatter: 32 chunks of 64 46const uint RADIX_TILE = 256u; // elements per workgroup in count and scatter: 4 chunks of 64
37const uint INVALID = 0xffffffffu; 47const uint INVALID = 0xffffffffu;
38const uint TRI0 = 0u, BOX32 = 5u, INSTANCE = 6u; 48const uint TRI0 = 0u, BOX32 = 5u, INSTANCE = 6u;
39const uint REMAP_IDENTITY = 0x09u; 49const uint REMAP_IDENTITY = 0x09u;
@@ -53,7 +63,7 @@ layout(push_constant) uniform Push {
53 uint arg0; // triangles: vertex stride; level: entries in the level below 63 uint arg0; // triangles: vertex stride; level: entries in the level below
54 uint arg1; // triangles: 0 = R32G32B32_FLOAT, 1 = R32G32_FLOAT; level: first node of the level below, 64 uint arg1; // triangles: 0 = R32G32B32_FLOAT, 1 = R32G32_FLOAT; level: first node of the level below,
55 // or INVALID when the level below is the elements 65 // or INVALID when the level below is the elements
56 uint arg2; // triangles: index type (0 none, 1 u16, 2 u32); level: 1 for the root level 66 uint arg2; // triangles: index type (0 none, 1 u16, 2 u32); level: 1 = refit the existing node
57 uint geometry; // triangles: geometry index << 8 | D3D12_RAYTRACING_GEOMETRY_FLAGS 67 uint geometry; // triangles: geometry index << 8 | D3D12_RAYTRACING_GEOMETRY_FLAGS
58 uint elements; // element count N 68 uint elements; // element count N
59 uint sort_size; // N: the keys sorted (one per element) 69 uint sort_size; // N: the keys sorted (one per element)
@@ -254,6 +264,41 @@ void morton(uint i) {
254 store(pc.scratch, keys_off() + 4u * i, key); 264 store(pc.scratch, keys_off() + 4u * i, key);
255 store(pc.scratch, vals_off() + 4u * i, i); 265 store(pc.scratch, vals_off() + 4u * i, i);
256} 266}
267// ---- MODE_SMALL_SORT ----
268// 8 KiB, with the radix arrays below about 12.5 KiB: under the 16 KiB every Vulkan device must allow.
269shared uint small_keys[SMALL_SORT_MAX];
270shared uint small_vals[SMALL_SORT_MAX];
271
272void small_sort(uint t) {
273 uint n = pc.sort_size, p = 1u;
274 while (p < n) p <<= 1;
275 for (uint i = t; i < p; i += 64u) {
276 small_keys[i] = i < n ? load(pc.scratch, keys_off() + 4u * i) : INVALID;
277 small_vals[i] = i < n ? load(pc.scratch, vals_off() + 4u * i) : INVALID;
278 }
279 barrier();
280 for (uint k = 2u; k <= p; k <<= 1) {
281 for (uint j = k >> 1; j > 0u; j >>= 1) {
282 for (uint i = t; i < p; i += 64u) {
283 uint l = i ^ j;
284 if (l > i) {
285 uint ki = small_keys[i], kl = small_keys[l], vi = small_vals[i], vl = small_vals[l];
286 bool greater = ki > kl || (ki == kl && vi > vl);
287 if (greater == ((i & k) == 0u)) {
288 small_keys[i] = kl; small_keys[l] = ki;
289 small_vals[i] = vl; small_vals[l] = vi;
290 }
291 }
292 }
293 barrier();
294 }
295 }
296 for (uint i = t; i < n; i += 64u) {
297 store(pc.scratch, keys_off() + 4u * i, small_keys[i]);
298 store(pc.scratch, vals_off() + 4u * i, small_vals[i]);
299 }
300}
301
257// ---- MODE_RADIX_* ---- 302// ---- MODE_RADIX_* ----
258shared uint radix_hist[RADIX_BINS]; 303shared uint radix_hist[RADIX_BINS];
259shared uint radix_rank[RADIX_BINS][64]; 304shared uint radix_rank[RADIX_BINS][64];
@@ -341,7 +386,22 @@ void build_node(uint n) {
341 uint entry = 4u * n + c; 386 uint entry = 4u * n + c;
342 uint child = INVALID; 387 uint child = INVALID;
343 vec3 lo = vec3(uintBitsToFloat(0x7f800000u)), hi = -lo; // min > max: the box test misses it 388 vec3 lo = vec3(uintBitsToFloat(0x7f800000u)), hi = -lo; // min > max: the box test misses it
344 if (entry < pc.arg0) { 389 if (pc.arg2 == 1u) {
390 // refit: the child this node already has; its new box is in scratch (an element's from MODE_TRIANGLES /
391 // MODE_INSTANCES, a node's from the level below)
392 child = load(pc.dst, o + 4u * c);
393 if (child != INVALID) {
394 uint at = ptr_unit(child) * 64u;
395 if ((child & 7u) == BOX32) {
396 load_box(pc.elements + (at - pc.nodes_off) / 128u, lo, hi);
397 } else {
398 uint e = (at - pc.elements_off) / element_size();
399 load_box(e, lo, hi);
400 if (pc.tlas != 0u) store(pc.dst, pc.elements_off + 128u * e + 116u, me);
401 }
402 if (!box_empty(lo, hi)) { ulo = min(ulo, lo); uhi = max(uhi, hi); }
403 }
404 } else if (entry < pc.arg0) {
345 if (pc.arg1 == INVALID) { 405 if (pc.arg1 == INVALID) {
346 uint e = load(pc.scratch, vals_off() + 4u * entry); 406 uint e = load(pc.scratch, vals_off() + 4u * entry);
347 child = element_ptr(e); 407 child = element_ptr(e);
@@ -389,12 +449,15 @@ void main() {
389 if (pc.mode == MODE_RADIX_COUNT) { radix_count(gl_WorkGroupID.x, gl_LocalInvocationID.x); return; } 449 if (pc.mode == MODE_RADIX_COUNT) { radix_count(gl_WorkGroupID.x, gl_LocalInvocationID.x); return; }
390 if (pc.mode == MODE_RADIX_SCAN) { radix_scan(gl_LocalInvocationID.x); return; } 450 if (pc.mode == MODE_RADIX_SCAN) { radix_scan(gl_LocalInvocationID.x); return; }
391 if (pc.mode == MODE_RADIX_SCATTER) { radix_scatter(gl_WorkGroupID.x, gl_LocalInvocationID.x); return; } 451 if (pc.mode == MODE_RADIX_SCATTER) { radix_scatter(gl_WorkGroupID.x, gl_LocalInvocationID.x); return; }
452 if (pc.mode == MODE_SMALL_SORT) { small_sort(gl_LocalInvocationID.x); return; }
392 if (pc.mode == MODE_HEADER) { 453 if (pc.mode == MODE_HEADER) {
393 if (i == 0u) build_header(); 454 if (i == 0u) build_header();
394 return; 455 return;
395 } 456 }
396 if (i >= pc.count) return; 457 if (i >= pc.count) return;
397 if (pc.mode == MODE_INIT) { 458 if (pc.mode == MODE_COPY) {
459 store(pc.dst, 4u * i, load(pc.src0, 4u * i));
460 } else if (pc.mode == MODE_INIT) {
398 store(pc.dst, pc.parents_off + 4u * i, INVALID); 461 store(pc.dst, pc.parents_off + 4u * i, INVALID);
399 if (i < 3u) { store(pc.scratch, 4u * i, INVALID); store(pc.scratch, 12u + 4u * i, 0u); } 462 if (i < 3u) { store(pc.scratch, 4u * i, INVALID); store(pc.scratch, 12u + 4u * i, 0u); }
400 } else if (pc.mode == MODE_TRIANGLES) { 463 } else if (pc.mode == MODE_TRIANGLES) {
diff --git a/runtime/src/xdxr_build.h b/runtime/src/xdxr_build.h
index 32ee111cb..64fe97a83 100644
--- a/runtime/src/xdxr_build.h
+++ b/runtime/src/xdxr_build.h
@@ -41,9 +41,10 @@ struct XdxrLayout {
41 std::uint32_t size = 0; // result data size in bytes, a multiple of 64 41 std::uint32_t size = 0; // result data size in bytes, a multiple of 64
42 std::uint32_t parent_entries = 0; // one per 64-byte unit from elements_off on 42 std::uint32_t parent_entries = 0; // one per 64-byte unit from elements_off on
43 std::uint32_t sort_size = 0; // keys the radix sort orders: one per element 43 std::uint32_t sort_size = 0; // keys the radix sort orders: one per element
44 static constexpr std::uint32_t radix_tile = 2048; // xdxr_build.comp RADIX_TILE 44 static constexpr std::uint32_t radix_tile = 256; // xdxr_build.comp RADIX_TILE
45 static constexpr std::uint32_t radix_bins = 16; 45 static constexpr std::uint32_t radix_bins = 16;
46 static constexpr std::uint32_t radix_passes = 8; 46 static constexpr std::uint32_t radix_passes = 8;
47 static constexpr std::uint32_t small_sort_max = 1024; // xdxr_build.comp SMALL_SORT_MAX: one-workgroup sort
47 std::uint64_t scratch = 0; // scratch bytes 48 std::uint64_t scratch = 0; // scratch bytes
48 49
49 // False when the count would overflow the 32-bit offsets of the format. 50 // False when the count would overflow the 32-bit offsets of the format.
@@ -108,11 +109,16 @@ public:
108 109
109 // Records a bottom-level build into `dst` (layout.size bytes) using `scratch` (layout.scratch bytes). `layout` 110 // Records a bottom-level build into `dst` (layout.size bytes) using `scratch` (layout.scratch bytes). `layout`
110 // must come from compute() with the sum of the geometries' triangle counts. 111 // must come from compute() with the sum of the geometries' triangle counts.
112 //
113 // With `update_from` set, an update (D3D12 PERFORM_UPDATE) instead: the structure at `update_from` (the
114 // destination itself, or another one, which is copied first) was built from the same topology, and is refitted
115 // to the new positions. Its tree is kept and only its boxes change, which is valid for any motion and costs no
116 // sort, though a refitted tree traverses more slowly as the geometry moves away from where it was built.
111 bool record_blas(VkCommandBuffer cb, const XdxrLayout& layout, const std::vector<XdxrTriangles>& geometries, 117 bool record_blas(VkCommandBuffer cb, const XdxrLayout& layout, const std::vector<XdxrTriangles>& geometries,
112 std::uint64_t dst, std::uint64_t scratch) { 118 std::uint64_t dst, std::uint64_t scratch, std::uint64_t update_from = 0) {
113 if (!loaded_ || layout.tlas) return false; 119 if (!loaded_ || layout.tlas) return false;
114 Push p = base(layout, dst, scratch); 120 Push p = base(layout, dst, scratch);
115 begin(cb, layout, p); 121 if (update_from) refit_begin(cb, layout, p, update_from); else begin(cb, layout, p);
116 std::uint32_t first = 0; 122 std::uint32_t first = 0;
117 for (std::size_t g = 0; g < geometries.size(); ++g) { 123 for (std::size_t g = 0; g < geometries.size(); ++g) {
118 const auto& geo = geometries[g]; 124 const auto& geo = geometries[g];
@@ -132,17 +138,18 @@ public:
132 first += geo.triangle_count; 138 first += geo.triangle_count;
133 } 139 }
134 if (first != layout.elements) return false; 140 if (first != layout.elements) return false;
135 finish(cb, layout, p); 141 if (update_from) refit_finish(cb, layout, p); else finish(cb, layout, p);
136 return true; 142 return true;
137 } 143 }
138 144
139 // Records a top-level build from `count` D3D12_RAYTRACING_INSTANCE_DESCs at `instances`. 145 // Records a top-level build from `count` D3D12_RAYTRACING_INSTANCE_DESCs at `instances`.
146 // `update_from`: as for record_blas; the instances may move, and name other BLASes.
140 bool record_tlas(VkCommandBuffer cb, const XdxrLayout& layout, std::uint64_t instances, std::uint64_t dst, 147 bool record_tlas(VkCommandBuffer cb, const XdxrLayout& layout, std::uint64_t instances, std::uint64_t dst,
141 std::uint64_t scratch, std::uint64_t bias = 0) { 148 std::uint64_t scratch, std::uint64_t bias = 0, std::uint64_t update_from = 0) {
142 if (!loaded_ || !layout.tlas) return false; 149 if (!loaded_ || !layout.tlas) return false;
143 Push p = base(layout, dst, scratch); 150 Push p = base(layout, dst, scratch);
144 p.bias = split(bias); 151 p.bias = split(bias);
145 begin(cb, layout, p); 152 if (update_from) refit_begin(cb, layout, p, update_from); else begin(cb, layout, p);
146 if (layout.elements) { 153 if (layout.elements) {
147 Push t = p; 154 Push t = p;
148 t.mode = mode_instances; 155 t.mode = mode_instances;
@@ -150,14 +157,14 @@ public:
150 t.src0 = split(instances); 157 t.src0 = split(instances);
151 dispatch(cb, t, t.count); 158 dispatch(cb, t, t.count);
152 } 159 }
153 finish(cb, layout, p); 160 if (update_from) refit_finish(cb, layout, p); else finish(cb, layout, p);
154 return true; 161 return true;
155 } 162 }
156 163
157private: 164private:
158 enum : std::uint32_t { 165 enum : std::uint32_t {
159 mode_init = 0, mode_triangles = 1, mode_instances = 2, mode_morton = 3, mode_level = 5, mode_header = 6, 166 mode_init = 0, mode_triangles = 1, mode_instances = 2, mode_morton = 3, mode_level = 5, mode_header = 6,
160 mode_radix_count = 7, mode_radix_scan = 8, mode_radix_scatter = 9 167 mode_radix_count = 7, mode_radix_scan = 8, mode_radix_scatter = 9, mode_small_sort = 10, mode_copy = 11
161 }; 168 };
162 struct Addr { std::uint32_t lo = 0, hi = 0; }; 169 struct Addr { std::uint32_t lo = 0, hi = 0; };
163 struct Push { // xdxr_build.comp `Push`, std430 push-constant layout 170 struct Push { // xdxr_build.comp `Push`, std430 push-constant layout
@@ -191,6 +198,36 @@ private:
191 dispatch(cb, init, init.count); 198 dispatch(cb, init, init.count);
192 } 199 }
193 200
201 // An update: the source's tree is copied unless it is the destination. Its parent table stays as it is, so there
202 // is no MODE_INIT.
203 void refit_begin(VkCommandBuffer cb, const XdxrLayout& l, const Push& p, std::uint64_t source) {
204 vk_.vkCmdBindPipeline(cb, VK_PIPELINE_BIND_POINT_COMPUTE, pipeline_);
205 const std::uint64_t dst = std::uint64_t(p.dst.hi) << 32 | p.dst.lo;
206 if (source == dst) return;
207 Push c = p;
208 c.mode = mode_copy;
209 c.count = l.size / 4;
210 c.src0 = split(source);
211 dispatch(cb, c, c.count);
212 }
213
214 // Boxes bottom-up through the existing nodes, then the header (its bounds change; nothing else does).
215 void refit_finish(VkCommandBuffer cb, const XdxrLayout& l, const Push& p) {
216 for (std::size_t level = 0; level < l.level_counts.size(); ++level) {
217 Push n = p;
218 n.mode = mode_level;
219 n.count = l.level_counts[level];
220 n.first = l.level_first[level];
221 n.arg2 = 1; // refit: read each node's children from the node
222 dispatch(cb, n, n.count);
223 }
224 Push h = p;
225 h.mode = mode_header;
226 h.count = 1;
227 h.first = l.root();
228 dispatch(cb, h, 1, false);
229 }
230
194 void finish(VkCommandBuffer cb, const XdxrLayout& l, const Push& p) { 231 void finish(VkCommandBuffer cb, const XdxrLayout& l, const Push& p) {
195 Push m = p; 232 Push m = p;
196 m.mode = mode_morton; 233 m.mode = mode_morton;
@@ -198,7 +235,11 @@ private:
198 dispatch(cb, m, m.count); 235 dispatch(cb, m, m.count);
199 // stable LSD radix sort, 4 bits a pass; an even pass count leaves the result where the keys started 236 // stable LSD radix sort, 4 bits a pass; an even pass count leaves the result where the keys started
200 static_assert(XdxrLayout::radix_passes % 2 == 0, "the sorted keys must end in the first buffer"); 237 static_assert(XdxrLayout::radix_passes % 2 == 0, "the sorted keys must end in the first buffer");
201 if (l.sort_size > 1) { 238 if (l.sort_size > 1 && l.sort_size <= XdxrLayout::small_sort_max) {
239 Push s = p;
240 s.mode = mode_small_sort;
241 dispatch(cb, s, 64); // one workgroup, shared memory
242 } else if (l.sort_size > 1) {
202 for (std::uint32_t pass = 0; pass < XdxrLayout::radix_passes; ++pass) { 243 for (std::uint32_t pass = 0; pass < XdxrLayout::radix_passes; ++pass) {
203 Push s = p; 244 Push s = p;
204 s.first = pass; 245 s.first = pass;
diff --git a/runtime/src/xdxr_build.inc b/runtime/src/xdxr_build.inc
index 8a43b04cd..71ce37fbb 100644
--- a/runtime/src/xdxr_build.inc
+++ b/runtime/src/xdxr_build.inc
@@ -1,3441 +1,3990 @@
1{0x07230203,0x00010500,0x000d000b,0x00002b73, 1{0x07230203,0x00010500,0x000d000b,0x000031a8,
20x00000000,0x00020011,0x00000001,0x00020011, 20x00000000,0x00020011,0x00000001,0x00020011,
30x000014e3,0x0006000b,0x00000001,0x4c534c47, 30x000014e3,0x0006000b,0x00000001,0x4c534c47,
40x6474732e,0x3035342e,0x00000000,0x0003000e, 40x6474732e,0x3035342e,0x00000000,0x0003000e,
50x000014e4,0x00000001,0x000d000f,0x00000005, 50x000014e4,0x00000001,0x000f000f,0x00000005,
60x00000004,0x6e69616d,0x00000000,0x000000f9, 60x00000004,0x6e69616d,0x00000000,0x000000fc,
70x000006d4,0x00000740,0x00000789,0x000007e2, 70x000006af,0x000006c4,0x000007a3,0x0000080d,
80x000009e6,0x000009f0,0x000009f1,0x00060010, 80x00000856,0x000008af,0x00000b0e,0x00000b17,
90x00000004,0x00000011,0x00000040,0x00000001, 90x00000b18,0x00060010,0x00000004,0x00000011,
100x00000001,0x00040047,0x00000015,0x00000006, 100x00000040,0x00000001,0x00000001,0x00040047,
110x00000004,0x00030047,0x00000016,0x00000002, 110x00000015,0x00000006,0x00000004,0x00030047,
120x00050048,0x00000016,0x00000000,0x00000023, 120x00000016,0x00000002,0x00050048,0x00000016,
130x00000000,0x00030047,0x000000f7,0x00000002, 130x00000000,0x00000023,0x00000000,0x00030047,
140x00050048,0x000000f7,0x00000000,0x00000023, 140x000000fa,0x00000002,0x00050048,0x000000fa,
150x00000000,0x00050048,0x000000f7,0x00000001, 150x00000000,0x00000023,0x00000000,0x00050048,
160x00000023,0x00000008,0x00050048,0x000000f7, 160x000000fa,0x00000001,0x00000023,0x00000008,
170x00000002,0x00000023,0x00000010,0x00050048, 170x00050048,0x000000fa,0x00000002,0x00000023,
180x000000f7,0x00000003,0x00000023,0x00000018, 180x00000010,0x00050048,0x000000fa,0x00000003,
190x00050048,0x000000f7,0x00000004,0x00000023, 190x00000023,0x00000018,0x00050048,0x000000fa,
200x00000020,0x00050048,0x000000f7,0x00000005, 200x00000004,0x00000023,0x00000020,0x00050048,
210x00000023,0x00000028,0x00050048,0x000000f7, 210x000000fa,0x00000005,0x00000023,0x00000028,
220x00000006,0x00000023,0x00000030,0x00050048, 220x00050048,0x000000fa,0x00000006,0x00000023,
230x000000f7,0x00000007,0x00000023,0x00000034, 230x00000030,0x00050048,0x000000fa,0x00000007,
240x00050048,0x000000f7,0x00000008,0x00000023, 240x00000023,0x00000034,0x00050048,0x000000fa,
250x00000038,0x00050048,0x000000f7,0x00000009, 250x00000008,0x00000023,0x00000038,0x00050048,
260x00000023,0x0000003c,0x00050048,0x000000f7, 260x000000fa,0x00000009,0x00000023,0x0000003c,
270x0000000a,0x00000023,0x00000040,0x00050048, 270x00050048,0x000000fa,0x0000000a,0x00000023,
280x000000f7,0x0000000b,0x00000023,0x00000044, 280x00000040,0x00050048,0x000000fa,0x0000000b,
290x00050048,0x000000f7,0x0000000c,0x00000023, 290x00000023,0x00000044,0x00050048,0x000000fa,
300x00000048,0x00050048,0x000000f7,0x0000000d, 300x0000000c,0x00000023,0x00000048,0x00050048,
310x00000023,0x0000004c,0x00050048,0x000000f7, 310x000000fa,0x0000000d,0x00000023,0x0000004c,
320x0000000e,0x00000023,0x00000050,0x00050048, 320x00050048,0x000000fa,0x0000000e,0x00000023,
330x000000f7,0x0000000f,0x00000023,0x00000054, 330x00000050,0x00050048,0x000000fa,0x0000000f,
340x00050048,0x000000f7,0x00000010,0x00000023, 340x00000023,0x00000054,0x00050048,0x000000fa,
350x00000058,0x00050048,0x000000f7,0x00000011, 350x00000010,0x00000023,0x00000058,0x00050048,
360x00000023,0x0000005c,0x00050048,0x000000f7, 360x000000fa,0x00000011,0x00000023,0x0000005c,
370x00000012,0x00000023,0x00000060,0x00050048, 370x00050048,0x000000fa,0x00000012,0x00000023,
380x000000f7,0x00000013,0x00000023,0x00000064, 380x00000060,0x00050048,0x000000fa,0x00000013,
390x00040047,0x000009e6,0x0000000b,0x0000001c, 390x00000023,0x00000064,0x00040047,0x00000b0e,
400x00040047,0x000009f0,0x0000000b,0x0000001a, 400x0000000b,0x0000001c,0x00040047,0x00000b17,
410x00040047,0x000009f1,0x0000000b,0x0000001b, 410x0000000b,0x0000001a,0x00040047,0x00000b18,
420x00040047,0x00000a6c,0x0000000b,0x00000019, 420x0000000b,0x0000001b,0x00040047,0x00000bb4,
430x00020013,0x00000002,0x00030021,0x00000003, 430x0000000b,0x00000019,0x00020013,0x00000002,
440x00000002,0x00040015,0x00000006,0x00000020, 440x00030021,0x00000003,0x00000002,0x00040015,
450x00000000,0x00040017,0x00000007,0x00000006, 450x00000006,0x00000020,0x00000000,0x00040017,
460x00000002,0x00040020,0x00000009,0x00000007, 460x00000007,0x00000006,0x00000002,0x00040020,
470x00000006,0x00030027,0x00000014,0x000014e5, 470x00000009,0x00000007,0x00000006,0x00030027,
480x0003001d,0x00000015,0x00000006,0x0003001e, 480x00000014,0x000014e5,0x0003001d,0x00000015,
490x00000016,0x00000015,0x00040020,0x00000014, 490x00000006,0x0003001e,0x00000016,0x00000015,
500x000014e5,0x00000016,0x00030016,0x00000027, 500x00040020,0x00000014,0x000014e5,0x00000016,
510x00000020,0x00040020,0x00000028,0x00000007, 510x00030016,0x00000027,0x00000020,0x00040020,
520x00000027,0x00020014,0x0000002f,0x00040017, 520x00000028,0x00000007,0x00000027,0x00020014,
530x0000004b,0x00000027,0x00000003,0x00040020, 530x0000002f,0x00040017,0x0000004b,0x00000027,
540x0000004c,0x00000007,0x0000004b,0x0004002b, 540x00000003,0x00040020,0x0000004c,0x00000007,
550x00000006,0x000000a3,0x00000000,0x0004001e, 550x0000004b,0x0004002b,0x00000006,0x000000a6,
560x000000a8,0x00000006,0x00000006,0x0004002b, 560x00000000,0x0004001e,0x000000ab,0x00000006,
570x00000006,0x000000ad,0x00000001,0x00040015, 570x00000006,0x0004002b,0x00000006,0x000000b0,
580x000000d6,0x00000020,0x00000001,0x0004002b, 580x00000001,0x00040015,0x000000d9,0x00000020,
590x000000d6,0x000000d7,0x00000000,0x00040020, 590x00000001,0x0004002b,0x000000d9,0x000000da,
600x000000d8,0x000014e5,0x00000006,0x0016001e, 600x00000000,0x00040020,0x000000db,0x000014e5,
610x000000f7,0x00000007,0x00000007,0x00000007, 610x00000006,0x0016001e,0x000000fa,0x00000007,
620x00000007,0x00000007,0x00000007,0x00000006, 620x00000007,0x00000007,0x00000007,0x00000007,
630x00000007,0x00000006,0x00000006,0x00000006,
630x00000006,0x00000006,0x00000006,0x00000006, 640x00000006,0x00000006,0x00000006,0x00000006,
640x00000006,0x00000006,0x00000006,0x00000006, 650x00000006,0x00000006,0x00000006,0x00000006,
650x00000006,0x00000006,0x00000006,0x00000006, 660x00000006,0x00000006,0x00000006,0x00040020,
660x00000006,0x00040020,0x000000f8,0x00000009, 670x000000fb,0x00000009,0x000000fa,0x0004003b,
670x000000f7,0x0004003b,0x000000f8,0x000000f9, 680x000000fb,0x000000fc,0x00000009,0x0004002b,
680x00000009,0x0004002b,0x000000d6,0x000000fa, 690x000000d9,0x000000fd,0x0000000e,0x00040020,
690x0000000e,0x00040020,0x000000fb,0x00000009, 700x000000fe,0x00000009,0x00000006,0x0004002b,
700x00000006,0x0004002b,0x00000006,0x000000fe, 710x00000006,0x00000101,0x00000100,0x0004002b,
710x00000800,0x0004002b,0x00000006,0x00000104, 720x00000006,0x00000107,0x00000040,0x0004002b,
720x00000040,0x0004002b,0x00000006,0x00000107, 730x00000006,0x0000010a,0x00000004,0x0004002b,
730x00000004,0x0004002b,0x00000006,0x0000010e, 740x00000006,0x00000111,0x00000008,0x0004002b,
740x00000008,0x0004002b,0x00000006,0x00000115, 750x00000006,0x00000118,0x0000000c,0x0004002b,
750x0000000c,0x0004002b,0x00000006,0x0000011c, 760x00000006,0x0000011f,0x00000010,0x0004002b,
760x00000010,0x0004002b,0x00000006,0x0000012d, 770x00000006,0x00000130,0x80000000,0x0004002b,
770x80000000,0x0004002b,0x00000006,0x00000142, 780x00000006,0x00000145,0x7fffffff,0x0004002b,
780x7fffffff,0x0004002b,0x00000006,0x0000014d, 790x00000006,0x00000150,0x00000018,0x0004002b,
790x00000018,0x0004002b,0x000000d6,0x00000151, 800x000000d9,0x00000154,0x00000001,0x00040020,
800x00000001,0x00040020,0x00000153,0x00000009, 810x00000156,0x00000009,0x00000007,0x0004002b,
810x00000007,0x0004002b,0x00000006,0x0000016d, 820x00000006,0x00000170,0x00000002,0x0004002b,
820x00000002,0x0004002b,0x00000006,0x00000186, 830x00000006,0x00000189,0x00000014,0x0004002b,
830x00000014,0x0004002b,0x00000027,0x000001ea, 840x00000027,0x000001ed,0x3f000000,0x0004002b,
840x3f000000,0x0004002b,0x000000d6,0x00000202, 850x000000d9,0x00000205,0x00000002,0x0004002b,
850x00000002,0x0004002b,0x000000d6,0x0000020a, 860x000000d9,0x0000020d,0x00000003,0x0004002b,
860x00000003,0x0004002b,0x000000d6,0x00000212, 870x000000d9,0x00000215,0x00000004,0x0004002b,
870x00000004,0x0004002b,0x000000d6,0x0000021a, 880x000000d9,0x0000021d,0x00000005,0x0004002b,
880x00000005,0x0004002b,0x000000d6,0x00000221, 890x000000d9,0x00000224,0x00000013,0x0004002b,
890x00000013,0x0004002b,0x00000006,0x00000225, 900x00000006,0x00000228,0x00000080,0x0004002b,
900x00000080,0x0004002b,0x000000d6,0x00000229, 910x000000d9,0x0000022c,0x0000000f,0x0004002b,
910x0000000f,0x0004002b,0x000000d6,0x00000230, 920x000000d9,0x00000233,0x00000006,0x0004002b,
920x00000006,0x0004002b,0x00000006,0x00000236, 930x00000006,0x00000239,0x00000006,0x0004002b,
930x00000006,0x0004002b,0x000000d6,0x0000023b, 940x000000d9,0x0000023e,0x00000010,0x0004002b,
940x00000010,0x0004002b,0x00000006,0x00000243, 950x00000006,0x00000246,0x00000005,0x0004002b,
950x00000005,0x0004002b,0x000000d6,0x0000024d, 960x000000d9,0x00000250,0x00000009,0x0004002b,
960x00000009,0x0004002b,0x000000d6,0x00000263, 970x000000d9,0x00000266,0x0000000a,0x0004002b,
970x0000000a,0x0004002b,0x00000027,0x0000026a, 980x00000027,0x0000026d,0x00000000,0x0004002b,
980x00000000,0x0004002b,0x000000d6,0x00000278, 990x000000d9,0x0000027b,0x0000000b,0x0004002b,
990x0000000b,0x0004002b,0x00000006,0x000002a0, 1000x00000006,0x000002a3,0x0000ffff,0x0004002b,
1000x0000ffff,0x0004002b,0x00000006,0x000002b4, 1010x00000006,0x000002b7,0x00000003,0x00040017,
1010x00000003,0x00040017,0x000002b9,0x00000027, 1020x000002bc,0x00000027,0x00000004,0x0004001c,
1020x00000004,0x0004001c,0x000002f3,0x0000004b, 1030x000002f6,0x0000004b,0x000002b7,0x00040020,
1030x000002b4,0x00040020,0x000002f4,0x00000007, 1040x000002f7,0x00000007,0x000002f6,0x0004002b,
1040x000002f3,0x0004002b,0x000000d6,0x00000305, 1050x000000d9,0x00000308,0x00000008,0x0004002b,
1050x00000008,0x0004002b,0x00000006,0x00000344, 1060x00000006,0x00000347,0x00000024,0x0004002b,
1060x00000024,0x0004002b,0x00000006,0x0000034f, 1070x00000006,0x00000352,0x00000028,0x0004002b,
1070x00000028,0x0004002b,0x00000006,0x0000035a, 1080x00000006,0x0000035d,0x0000002c,0x0004002b,
1080x0000002c,0x0004002b,0x00000006,0x00000365, 1090x00000006,0x00000368,0x00000030,0x0004002b,
1090x00000030,0x0004002b,0x000000d6,0x00000367, 1100x000000d9,0x0000036a,0x0000000c,0x0004002b,
1100x0000000c,0x0004002b,0x00000006,0x00000371, 1110x00000006,0x00000374,0x00000034,0x0004002b,
1110x00000034,0x0004002b,0x00000006,0x0000037b, 1120x00000006,0x0000037e,0x00000038,0x0004002b,
1120x00000038,0x0004002b,0x00000006,0x0000037d, 1130x00000006,0x00000380,0xffffffff,0x0004002b,
1130xffffffff,0x0004002b,0x00000006,0x00000385, 1140x00000006,0x00000388,0x0000003c,0x0004002b,
1140x0000003c,0x0004002b,0x00000006,0x00000387, 1150x00000006,0x0000038a,0x00000009,0x00040017,
1150x00000009,0x00040017,0x00000392,0x0000002f, 1160x00000395,0x0000002f,0x00000003,0x0004001c,
1160x00000003,0x0004001c,0x000003d6,0x00000027, 1170x000003d9,0x00000027,0x00000118,0x00040020,
1170x00000115,0x00040020,0x000003d7,0x00000007, 1180x000003da,0x00000007,0x000003d9,0x0004002b,
1180x000003d6,0x0004002b,0x00000006,0x00000460, 1190x00000006,0x00000463,0x0000001c,0x0004002b,
1190x0000001c,0x0004002b,0x00000006,0x00000466, 1200x00000006,0x00000469,0x00000020,0x0004002b,
1200x00000020,0x0004002b,0x000000d6,0x0000047b, 1210x000000d9,0x0000047e,0x00000018,0x0004002b,
1210x00000018,0x0004002b,0x000000d6,0x000004d5, 1220x000000d9,0x000004d8,0x00000007,0x0004002b,
1220x00000007,0x0004002b,0x00000027,0x000004f9, 1230x00000027,0x000004fc,0x3f800000,0x0004002b,
1230x3f800000,0x0004002b,0x00000006,0x0000052e, 1240x00000006,0x00000531,0x3fffffff,0x00040018,
1240x3fffffff,0x00040018,0x00000548,0x0000004b, 1250x0000054b,0x0000004b,0x00000003,0x00040020,
1250x00000003,0x00040020,0x00000549,0x00000007, 1260x0000054c,0x00000007,0x0000054b,0x0006002c,
1260x00000548,0x0006002c,0x0000004b,0x0000056d, 1270x0000004b,0x00000570,0x0000026d,0x0000026d,
1270x0000026a,0x0000026a,0x0000026a,0x0006002c, 1280x0000026d,0x0006002c,0x0000054b,0x00000571,
1280x00000548,0x0000056e,0x0000056d,0x0000056d, 1290x00000570,0x00000570,0x00000570,0x0004002b,
1290x0000056d,0x0004002b,0x00000006,0x00000594, 1300x00000006,0x00000597,0x00000044,0x0004002b,
1300x00000044,0x0004002b,0x00000006,0x000005a3, 1310x00000006,0x000005a6,0x00000048,0x0004002b,
1310x00000048,0x0004002b,0x00000006,0x000005b2, 1320x00000006,0x000005b5,0x0000004c,0x0004002b,
1320x0000004c,0x0004002b,0x00000006,0x000005c3, 1330x00000006,0x000005c6,0x00000070,0x0004002b,
1330x00000070,0x0004002b,0x00000006,0x000005cd, 1340x00000006,0x000005d0,0x00000074,0x0004002b,
1340x00000074,0x0004002b,0x00000006,0x000005d6, 1350x00000006,0x000005d9,0x00000078,0x0004002b,
1350x00000078,0x0004002b,0x00000006,0x000005df, 1360x00000006,0x000005e2,0x0000007c,0x0004002b,
1360x0000007c,0x0004002b,0x00000006,0x000005fb, 1370x00000006,0x000005fe,0x000003ff,0x0004002b,
1370x000003ff,0x0004002b,0x00000006,0x00000602, 1380x00000006,0x00000605,0x030000ff,0x0004002b,
1380x030000ff,0x0004002b,0x00000006,0x00000608, 1390x00000006,0x0000060b,0x0300f00f,0x0004002b,
1390x0300f00f,0x0004002b,0x00000006,0x0000060e, 1400x00000006,0x00000611,0x030c30c3,0x0004002b,
1400x030c30c3,0x0004002b,0x00000006,0x00000614, 1410x00000006,0x00000617,0x09249249,0x0004002b,
1410x09249249,0x0004002b,0x00000027,0x00000657, 1420x00000027,0x0000065a,0x0da24260,0x0006002c,
1420x0da24260,0x0006002c,0x0000004b,0x00000658, 1430x0000004b,0x0000065b,0x0000065a,0x0000065a,
1430x00000657,0x00000657,0x00000657,0x00040017, 1440x0000065a,0x00040017,0x0000065d,0x00000006,
1440x0000065a,0x00000006,0x00000003,0x0004002b, 1450x00000003,0x0004002b,0x00000027,0x0000066b,
1450x00000027,0x00000668,0x447fc000,0x0004002b, 1460x447fc000,0x0004002b,0x00000006,0x000006ac,
1460x00000006,0x000006ca,0x0000000f,0x0004001c, 1470x00000400,0x0004001c,0x000006ad,0x00000006,
1470x000006d2,0x00000006,0x0000011c,0x00040020, 1480x000006ac,0x00040020,0x000006ae,0x00000004,
1480x000006d3,0x00000004,0x000006d2,0x0004003b, 1490x000006ad,0x0004003b,0x000006ae,0x000006af,
1490x000006d3,0x000006d4,0x00000004,0x00040020, 1500x00000004,0x00040020,0x000006c2,0x00000004,
1500x000006d6,0x00000004,0x00000006,0x0004002b, 1510x00000006,0x0004003b,0x000006ae,0x000006c4,
1510x00000006,0x000006d8,0x00000108,0x0004002b, 1520x00000004,0x0004002b,0x00000006,0x000006da,
1520x00000006,0x00000717,0x0000003f,0x0004001c, 1530x00000108,0x0004002b,0x00000006,0x00000799,
1530x0000073e,0x00000006,0x00000104,0x00040020, 1540x0000000f,0x0004001c,0x000007a1,0x00000006,
1540x0000073f,0x00000004,0x0000073e,0x0004003b, 1550x0000011f,0x00040020,0x000007a2,0x00000004,
1550x0000073f,0x00000740,0x00000004,0x0004003b, 1560x000007a1,0x0004003b,0x000007a2,0x000007a3,
1560x000006d3,0x00000789,0x00000004,0x0004001c, 1570x00000004,0x0004002b,0x00000006,0x000007e4,
1570x000007e0,0x0000073e,0x0000011c,0x00040020, 1580x0000003f,0x0004001c,0x0000080b,0x00000006,
1580x000007e1,0x00000004,0x000007e0,0x0004003b, 1590x00000107,0x00040020,0x0000080c,0x00000004,
1590x000007e1,0x000007e2,0x00000004,0x00040020, 1600x0000080b,0x0004003b,0x0000080c,0x0000080d,
1600x000007fe,0x00000007,0x000006d2,0x0004002b, 1610x00000004,0x0004003b,0x000007a2,0x00000856,
1610x000000d6,0x00000850,0x0000003f,0x0004002b, 1620x00000004,0x0004001c,0x000008ad,0x0000080b,
1620x000000d6,0x000008bc,0x0000000d,0x0004002b, 1630x0000011f,0x00040020,0x000008ae,0x00000004,
1630x000000d6,0x000008c7,0x00000011,0x0004002b, 1640x000008ad,0x0004003b,0x000008ae,0x000008af,
1640x000000d6,0x0000096f,0x00000012,0x00040020, 1650x00000004,0x00040020,0x000008cb,0x00000007,
1650x000009e5,0x00000001,0x0000065a,0x0004003b, 1660x000007a1,0x0004002b,0x000000d9,0x0000091d,
1660x000009e5,0x000009e6,0x00000001,0x00040020, 1670x0000003f,0x0004002b,0x00000006,0x00000967,
1670x000009e7,0x00000001,0x00000006,0x0004002b, 1680x00000007,0x0004002b,0x000000d9,0x0000096c,
1680x00000006,0x000009ec,0x00000007,0x0004003b, 1690x0000000d,0x0004002b,0x000000d9,0x000009ef,
1690x000009e5,0x000009f0,0x00000001,0x0004003b, 1700x00000011,0x0004002b,0x000000d9,0x00000a97,
1700x000009e5,0x000009f1,0x00000001,0x0006002c, 1710x00000012,0x00040020,0x00000b0d,0x00000001,
1710x0000065a,0x00000a6c,0x00000104,0x000000ad, 1720x0000065d,0x0004003b,0x00000b0d,0x00000b0e,
1720x000000ad,0x0006002c,0x0000004b,0x00002b61, 1730x00000001,0x00040020,0x00000b0f,0x00000001,
1730x000004f9,0x000004f9,0x000004f9,0x0004002b, 1740x00000006,0x0004003b,0x00000b0d,0x00000b17,
1740x00000027,0x00002b63,0x7f800000,0x0006002c, 1750x00000001,0x0004003b,0x00000b0d,0x00000b18,
1750x0000004b,0x00002b64,0x00002b63,0x00002b63, 1760x00000001,0x0004002b,0x00000006,0x00000b3a,
1760x00002b63,0x0004002b,0x00000027,0x00002b65, 1770x0000000a,0x0004002b,0x00000006,0x00000b57,
1770xff800000,0x0006002c,0x0000004b,0x00002b66, 1780x0000000b,0x0006002c,0x0000065d,0x00000bb4,
1780x00002b65,0x00002b65,0x00002b65,0x0004002b, 1790x00000107,0x000000b0,0x000000b0,0x0006002c,
1790x00000006,0x00002b67,0x000007ff,0x00050036, 1800x0000004b,0x00003196,0x000004fc,0x000004fc,
1800x00000002,0x00000004,0x00000000,0x00000003, 1810x000004fc,0x0004002b,0x00000027,0x00003198,
1810x000200f8,0x00000005,0x0004003b,0x000003d7, 1820x7f800000,0x0006002c,0x0000004b,0x00003199,
1820x00001884,0x00000007,0x0004003b,0x00000549, 1830x00003198,0x00003198,0x00003198,0x0004002b,
1830x000018c5,0x00000007,0x0004003b,0x0000004c, 1840x00000027,0x0000319a,0xff800000,0x0006002c,
1840x000018c8,0x00000007,0x0004003b,0x0000004c, 1850x0000004b,0x0000319b,0x0000319a,0x0000319a,
1850x00001424,0x00000007,0x0004003b,0x000002f4, 1860x0000319a,0x0004002b,0x00000006,0x0000319c,
1860x00001239,0x00000007,0x0004003b,0x000007fe, 1870x000000ff,0x00050036,0x00000002,0x00000004,
1870x00000c2a,0x00000007,0x000300f7,0x00000a6e, 1880x00000000,0x00000003,0x000200f8,0x00000005,
1880x00000000,0x000300fb,0x000000a3,0x00000a6f, 1890x0004003b,0x000003da,0x00001b65,0x00000007,
1890x000200f8,0x00000a6f,0x00050041,0x000009e7, 1900x0004003b,0x0000054c,0x00001ba6,0x00000007,
1900x000009e8,0x000009e6,0x000000a3,0x0004003d, 1910x0004003b,0x0000004c,0x00001ba9,0x00000007,
1910x00000006,0x000009e9,0x000009e8,0x00050041, 1920x0004003b,0x0000004c,0x00001705,0x00000007,
1920x000000fb,0x000009ea,0x000000f9,0x00000230, 1930x0004003b,0x000002f7,0x0000151a,0x00000007,
1930x0004003d,0x00000006,0x000009eb,0x000009ea, 1940x0004003b,0x000008cb,0x00000d72,0x00000007,
1940x000500aa,0x0000002f,0x000009ed,0x000009eb, 1950x000300f7,0x00000bb6,0x00000000,0x000300fb,
1950x000009ec,0x000300f7,0x000009ef,0x00000000, 1960x000000a6,0x00000bb7,0x000200f8,0x00000bb7,
1960x000400fa,0x000009ed,0x000009ee,0x000009ef, 1970x00050041,0x00000b0f,0x00000b10,0x00000b0e,
1970x000200f8,0x000009ee,0x00050041,0x000009e7, 1980x000000a6,0x0004003d,0x00000006,0x00000b11,
1980x000009f3,0x000009f0,0x000000a3,0x0004003d, 1990x00000b10,0x00050041,0x000000fe,0x00000b12,
1990x00000006,0x000009f4,0x000009f3,0x00050041, 2000x000000fc,0x00000233,0x0004003d,0x00000006,
2000x000009e7,0x000009f6,0x000009f1,0x000000a3, 2010x00000b13,0x00000b12,0x000500aa,0x0000002f,
2010x0004003d,0x00000006,0x000009f7,0x000009f6, 2020x00000b14,0x00000b13,0x00000967,0x000300f7,
2020x000500b0,0x0000002f,0x00000a8b,0x000009f7, 2030x00000b16,0x00000000,0x000400fa,0x00000b14,
2030x0000011c,0x000300f7,0x00000a8f,0x00000000, 2040x00000b15,0x00000b16,0x000200f8,0x00000b15,
2040x000400fa,0x00000a8b,0x00000a8c,0x00000a8f, 2050x00050041,0x00000b0f,0x00000b1a,0x00000b17,
2050x000200f8,0x00000a8c,0x00050041,0x000006d6, 2060x000000a6,0x0004003d,0x00000006,0x00000b1b,
2060x00000a8e,0x000006d4,0x000009f7,0x0003003e, 2070x00000b1a,0x00050041,0x00000b0f,0x00000b1d,
2070x00000a8e,0x000000a3,0x000200f9,0x00000a8f, 2080x00000b18,0x000000a6,0x0004003d,0x00000006,
2080x000200f8,0x00000a8f,0x000400e0,0x0000016d, 2090x00000b1e,0x00000b1d,0x000500b0,0x0000002f,
2090x0000016d,0x000006d8,0x00050084,0x00000006, 2100x00000bd3,0x00000b1e,0x0000011f,0x000300f7,
2100x00000a91,0x000009f4,0x000000fe,0x00050080, 2110x00000bd7,0x00000000,0x000400fa,0x00000bd3,
2110x00000006,0x00000a93,0x00000a91,0x000000fe, 2120x00000bd4,0x00000bd7,0x000200f8,0x00000bd4,
2120x00050041,0x000000fb,0x00000a94,0x000000f9, 2130x00050041,0x000006c2,0x00000bd6,0x000007a3,
2130x000000fa,0x0004003d,0x00000006,0x00000a95, 2140x00000b1e,0x0003003e,0x00000bd6,0x000000a6,
2140x00000a94,0x0007000c,0x00000006,0x00000a96, 2150x000200f9,0x00000bd7,0x000200f8,0x00000bd7,
2150x00000001,0x00000026,0x00000a93,0x00000a95, 2160x000400e0,0x00000170,0x00000170,0x000006da,
2160x00050080,0x00000006,0x00000a99,0x00000a91, 2170x00050084,0x00000006,0x00000bd9,0x00000b1b,
2170x000009f7,0x000200f9,0x00000a9a,0x000200f8, 2180x00000101,0x00050080,0x00000006,0x00000bdb,
2180x00000a9a,0x000700f5,0x00000006,0x00002b52, 2190x00000bd9,0x00000101,0x00050041,0x000000fe,
2190x00000a99,0x00000a8f,0x00000aac,0x00000aaa, 2200x00000bdc,0x000000fc,0x000000fd,0x0004003d,
2200x000500b0,0x0000002f,0x00000a9e,0x00002b52, 2210x00000006,0x00000bdd,0x00000bdc,0x0007000c,
2210x00000a96,0x000400f6,0x00000aad,0x00000aaa, 2220x00000006,0x00000bde,0x00000001,0x00000026,
2220x00000000,0x000400fa,0x00000a9e,0x00000a9f, 2230x00000bdb,0x00000bdd,0x00050080,0x00000006,
2230x00000aad,0x000200f8,0x00000a9f,0x00050041, 2240x00000be1,0x00000bd9,0x00000b1e,0x000200f9,
2240x000000fb,0x00000ac3,0x000000f9,0x00000305, 2250x00000be2,0x000200f8,0x00000be2,0x000700f5,
2250x0004003d,0x00000006,0x00000ac4,0x00000ac3, 2260x00000006,0x00003177,0x00000be1,0x00000bd7,
2260x000500c7,0x00000006,0x00000ac5,0x00000ac4, 2270x00000bf4,0x00000bf2,0x000500b0,0x0000002f,
2270x000000ad,0x000500aa,0x0000002f,0x00000ac6, 2280x00000be6,0x00003177,0x00000bde,0x000400f6,
2280x00000ac5,0x000000a3,0x000300f7,0x00000acb, 2290x00000bf5,0x00000bf2,0x00000000,0x000400fa,
2290x00000000,0x000400fa,0x00000ac6,0x00000ac7, 2300x00000be6,0x00000be7,0x00000bf5,0x000200f8,
2300x00000ac9,0x000200f8,0x00000ac7,0x000200f9, 2310x00000be7,0x00050041,0x000000fe,0x00000c0b,
2310x00000acb,0x000200f8,0x00000ac9,0x00050084, 2320x000000fc,0x00000308,0x0004003d,0x00000006,
2320x00000006,0x00000ad3,0x0000010e,0x00000a95, 2330x00000c0c,0x00000c0b,0x000500c7,0x00000006,
2330x00050080,0x00000006,0x00000ad4,0x00000104, 2340x00000c0d,0x00000c0c,0x000000b0,0x000500aa,
2340x00000ad3,0x000200f9,0x00000acb,0x000200f8, 2350x0000002f,0x00000c0e,0x00000c0d,0x000000a6,
2350x00000acb,0x000700f5,0x00000006,0x00002b53, 2360x000300f7,0x00000c13,0x00000000,0x000400fa,
2360x00000104,0x00000ac7,0x00000ad4,0x00000ac9, 2370x00000c0e,0x00000c0f,0x00000c11,0x000200f8,
2370x00050084,0x00000006,0x00000aa2,0x00000107, 2380x00000c0f,0x000200f9,0x00000c13,0x000200f8,
2380x00002b52,0x00050080,0x00000006,0x00000aa3, 2390x00000c11,0x00050084,0x00000006,0x00000c1b,
2390x00002b53,0x00000aa2,0x00050041,0x00000153, 2400x00000111,0x00000bdd,0x00050080,0x00000006,
2400x00000aa4,0x000000f9,0x00000151,0x0004003d, 2410x00000c1c,0x00000107,0x00000c1b,0x000200f9,
2410x00000007,0x00000aa5,0x00000aa4,0x00050051, 2420x00000c13,0x000200f8,0x00000c13,0x000700f5,
2420x00000006,0x00000aeb,0x00000aa5,0x00000000, 2430x00000006,0x00003178,0x00000107,0x00000c0f,
2430x00050095,0x000000a8,0x00000aed,0x00000aeb, 2440x00000c1c,0x00000c11,0x00050084,0x00000006,
2440x00000aa3,0x00050051,0x00000006,0x00000aee, 2450x00000bea,0x0000010a,0x00003177,0x00050080,
2450x00000aed,0x00000001,0x00050051,0x00000006, 2460x00000006,0x00000beb,0x00003178,0x00000bea,
2460x00000aef,0x00000aed,0x00000000,0x00050051, 2470x00050041,0x00000156,0x00000bec,0x000000fc,
2470x00000006,0x00000af2,0x00000aa5,0x00000001, 2480x00000154,0x0004003d,0x00000007,0x00000bed,
2480x00050080,0x00000006,0x00000af4,0x00000af2, 2490x00000bec,0x00050051,0x00000006,0x00000c33,
2490x00000aee,0x00050050,0x00000007,0x00000af5, 2500x00000bed,0x00000000,0x00050095,0x000000ab,
2500x00000aef,0x00000af4,0x0004007c,0x00000014, 2510x00000c35,0x00000c33,0x00000beb,0x00050051,
2510x00000ae5,0x00000af5,0x00060041,0x000000d8, 2520x00000006,0x00000c36,0x00000c35,0x00000001,
2520x00000adc,0x00000ae5,0x000000d7,0x000000d7, 2530x00050051,0x00000006,0x00000c37,0x00000c35,
2530x0006003d,0x00000006,0x00000add,0x00000adc, 2540x00000000,0x00050051,0x00000006,0x00000c3a,
2550x00000bed,0x00000001,0x00050080,0x00000006,
2560x00000c3c,0x00000c3a,0x00000c36,0x00050050,
2570x00000007,0x00000c3d,0x00000c37,0x00000c3c,
2580x0004007c,0x00000014,0x00000c2d,0x00000c3d,
2590x00060041,0x000000db,0x00000c24,0x00000c2d,
2600x000000da,0x000000da,0x0006003d,0x00000006,
2610x00000c25,0x00000c24,0x00000002,0x00000004,
2620x00050084,0x00000006,0x00000c43,0x0000010a,
2630x00000c0c,0x000500c2,0x00000006,0x00000c44,
2640x00000c25,0x00000c43,0x000500c7,0x00000006,
2650x00000c45,0x00000c44,0x00000799,0x00050041,
2660x000006c2,0x00000bf0,0x000007a3,0x00000c45,
2670x000700ea,0x00000006,0x00000bf1,0x00000bf0,
2680x000000b0,0x000000a6,0x000000b0,0x000200f9,
2690x00000bf2,0x000200f8,0x00000bf2,0x00050080,
2700x00000006,0x00000bf4,0x00003177,0x00000107,
2710x000200f9,0x00000be2,0x000200f8,0x00000bf5,
2720x000400e0,0x00000170,0x00000170,0x000006da,
2730x000300f7,0x00000c07,0x00000000,0x000400fa,
2740x00000bd3,0x00000bf8,0x00000c07,0x000200f8,
2750x00000bf8,0x00050084,0x00000006,0x00000c4a,
2760x0000011f,0x00000bdd,0x00050080,0x00000006,
2770x00000c4b,0x00000107,0x00000c4a,0x00050080,
2780x00000006,0x00000c51,0x00000bdd,0x0000319c,
2790x00050086,0x00000006,0x00000c52,0x00000c51,
2800x00000101,0x00050084,0x00000006,0x00000bfc,
2810x00000b1e,0x00000c52,0x00050080,0x00000006,
2820x00000bfe,0x00000bfc,0x00000b1b,0x00050084,
2830x00000006,0x00000bff,0x0000010a,0x00000bfe,
2840x00050080,0x00000006,0x00000c00,0x00000c4b,
2850x00000bff,0x00050041,0x00000156,0x00000c02,
2860x000000fc,0x00000154,0x0004003d,0x00000007,
2870x00000c03,0x00000c02,0x00050041,0x000006c2,
2880x00000c04,0x000007a3,0x00000b1e,0x0004003d,
2890x00000006,0x00000c05,0x00000c04,0x00050051,
2900x00000006,0x00000c68,0x00000c03,0x00000000,
2910x00050095,0x000000ab,0x00000c6a,0x00000c68,
2920x00000c00,0x00050051,0x00000006,0x00000c6b,
2930x00000c6a,0x00000001,0x00050051,0x00000006,
2940x00000c6c,0x00000c6a,0x00000000,0x00050051,
2950x00000006,0x00000c6f,0x00000c03,0x00000001,
2960x00050080,0x00000006,0x00000c71,0x00000c6f,
2970x00000c6b,0x00050050,0x00000007,0x00000c72,
2980x00000c6c,0x00000c71,0x0004007c,0x00000014,
2990x00000c62,0x00000c72,0x00060041,0x000000db,
3000x00000c5a,0x00000c62,0x000000da,0x000000da,
3010x0005003e,0x00000c5a,0x00000c05,0x00000002,
3020x00000004,0x000200f9,0x00000c07,0x000200f8,
3030x00000c07,0x000200f9,0x00000bb6,0x000200f8,
3040x00000b16,0x000500aa,0x0000002f,0x00000b23,
3050x00000b13,0x00000111,0x000300f7,0x00000b25,
3060x00000000,0x000400fa,0x00000b23,0x00000b24,
3070x00000b25,0x000200f8,0x00000b24,0x00050041,
3080x00000b0f,0x00000b27,0x00000b18,0x000000a6,
3090x0004003d,0x00000006,0x00000b28,0x00000b27,
3100x00050041,0x000000fe,0x00000ce5,0x000000fc,
3110x000000fd,0x0004003d,0x00000006,0x00000ce6,
3120x00000ce5,0x00050080,0x00000006,0x00000ce8,
3130x00000ce6,0x0000319c,0x00050086,0x00000006,
3140x00000ce9,0x00000ce8,0x00000101,0x00050084,
3150x00000006,0x00000c88,0x0000011f,0x00000ce9,
3160x00050080,0x00000006,0x00000c8a,0x00000c88,
3170x000007e4,0x00050086,0x00000006,0x00000c8b,
3180x00000c8a,0x00000107,0x00050084,0x00000006,
3190x00000c8e,0x00000b28,0x00000c8b,0x0007000c,
3200x00000006,0x00000c90,0x00000001,0x00000026,
3210x00000c8e,0x00000c88,0x00050080,0x00000006,
3220x00000c93,0x00000c90,0x00000c8b,0x0007000c,
3230x00000006,0x00000c95,0x00000001,0x00000026,
3240x00000c93,0x00000c88,0x000200f9,0x00000c97,
3250x000200f8,0x00000c97,0x000700f5,0x00000006,
3260x00003172,0x000000a6,0x00000b24,0x00000ca5,
3270x00000c9c,0x000700f5,0x00000006,0x00003171,
3280x00000c90,0x00000b24,0x00000ca8,0x00000c9c,
3290x000500b0,0x0000002f,0x00000c9b,0x00003171,
3300x00000c95,0x000400f6,0x00000ca9,0x00000c9c,
3310x00000000,0x000400fa,0x00000c9b,0x00000c9c,
3320x00000ca9,0x000200f8,0x00000c9c,0x00050084,
3330x00000006,0x00000cee,0x0000011f,0x00000ce6,
3340x00050080,0x00000006,0x00000cef,0x00000107,
3350x00000cee,0x00050084,0x00000006,0x00000c9f,
3360x0000010a,0x00003171,0x00050080,0x00000006,
3370x00000ca0,0x00000cef,0x00000c9f,0x00050041,
3380x00000156,0x00000ca1,0x000000fc,0x00000154,
3390x0004003d,0x00000007,0x00000ca2,0x00000ca1,
3400x00050051,0x00000006,0x00000d06,0x00000ca2,
3410x00000000,0x00050095,0x000000ab,0x00000d08,
3420x00000d06,0x00000ca0,0x00050051,0x00000006,
3430x00000d09,0x00000d08,0x00000001,0x00050051,
3440x00000006,0x00000d0a,0x00000d08,0x00000000,
3450x00050051,0x00000006,0x00000d0d,0x00000ca2,
3460x00000001,0x00050080,0x00000006,0x00000d0f,
3470x00000d0d,0x00000d09,0x00050050,0x00000007,
3480x00000d10,0x00000d0a,0x00000d0f,0x0004007c,
3490x00000014,0x00000d00,0x00000d10,0x00060041,
3500x000000db,0x00000cf7,0x00000d00,0x000000da,
3510x000000da,0x0006003d,0x00000006,0x00000cf8,
3520x00000cf7,0x00000002,0x00000004,0x00050080,
3530x00000006,0x00000ca5,0x00003172,0x00000cf8,
3540x00050080,0x00000006,0x00000ca8,0x00003171,
3550x00000154,0x000200f9,0x00000c97,0x000200f8,
3560x00000ca9,0x00050041,0x000006c2,0x00000cac,
3570x0000080d,0x00000b28,0x0003003e,0x00000cac,
3580x00003172,0x000400e0,0x00000170,0x00000170,
3590x000006da,0x000500aa,0x0000002f,0x00000cae,
3600x00000b28,0x000000a6,0x000300f7,0x00000cc2,
3610x00000000,0x000400fa,0x00000cae,0x00000caf,
3620x00000cc2,0x000200f8,0x00000caf,0x000200f9,
3630x00000cb0,0x000200f8,0x00000cb0,0x000700f5,
3640x00000006,0x00003176,0x000000a6,0x00000caf,
3650x00000cbd,0x00000cb4,0x000700f5,0x00000006,
3660x00003173,0x000000a6,0x00000caf,0x00000cc0,
3670x00000cb4,0x000500b0,0x0000002f,0x00000cb3,
3680x00003173,0x00000107,0x000400f6,0x00000cc1,
3690x00000cb4,0x00000000,0x000400fa,0x00000cb3,
3700x00000cb4,0x00000cc1,0x000200f8,0x00000cb4,
3710x00050041,0x000006c2,0x00000cb6,0x0000080d,
3720x00003173,0x0004003d,0x00000006,0x00000cb7,
3730x00000cb6,0x0003003e,0x00000cb6,0x00003176,
3740x00050080,0x00000006,0x00000cbd,0x00003176,
3750x00000cb7,0x00050080,0x00000006,0x00000cc0,
3760x00003173,0x00000154,0x000200f9,0x00000cb0,
3770x000200f8,0x00000cc1,0x000200f9,0x00000cc2,
3780x000200f8,0x00000cc2,0x000400e0,0x00000170,
3790x00000170,0x000006da,0x0004003d,0x00000006,
3800x00000cc5,0x00000cac,0x000200f9,0x00000cc7,
3810x000200f8,0x00000cc7,0x000700f5,0x00000006,
3820x00003175,0x00000cc5,0x00000cc2,0x00000cde,
3830x00000ccc,0x000700f5,0x00000006,0x00003174,
3840x00000c90,0x00000cc2,0x00000ce1,0x00000ccc,
3850x000500b0,0x0000002f,0x00000ccb,0x00003174,
3860x00000c95,0x000400f6,0x00000ce2,0x00000ccc,
3870x00000000,0x000400fa,0x00000ccb,0x00000ccc,
3880x00000ce2,0x000200f8,0x00000ccc,0x00050084,
3890x00000006,0x00000d15,0x0000011f,0x00000ce6,
3900x00050080,0x00000006,0x00000d16,0x00000107,
3910x00000d15,0x00050084,0x00000006,0x00000ccf,
3920x0000010a,0x00003174,0x00050080,0x00000006,
3930x00000cd0,0x00000d16,0x00000ccf,0x00050041,
3940x00000156,0x00000cd1,0x000000fc,0x00000154,
3950x0004003d,0x00000007,0x00000cd2,0x00000cd1,
3960x00050051,0x00000006,0x00000d2d,0x00000cd2,
3970x00000000,0x00050095,0x000000ab,0x00000d2f,
3980x00000d2d,0x00000cd0,0x00050051,0x00000006,
3990x00000d30,0x00000d2f,0x00000001,0x00050051,
4000x00000006,0x00000d31,0x00000d2f,0x00000000,
4010x00050051,0x00000006,0x00000d34,0x00000cd2,
4020x00000001,0x00050080,0x00000006,0x00000d36,
4030x00000d34,0x00000d30,0x00050050,0x00000007,
4040x00000d37,0x00000d31,0x00000d36,0x0004007c,
4050x00000014,0x00000d27,0x00000d37,0x00060041,
4060x000000db,0x00000d1e,0x00000d27,0x000000da,
4070x000000da,0x0006003d,0x00000006,0x00000d1f,
4080x00000d1e,0x00000002,0x00000004,0x0005003e,
4090x00000d1e,0x00003175,0x00000002,0x00000004,
4100x00050080,0x00000006,0x00000cde,0x00003175,
4110x00000d1f,0x00050080,0x00000006,0x00000ce1,
4120x00003174,0x00000154,0x000200f9,0x00000cc7,
4130x000200f8,0x00000ce2,0x000200f9,0x00000bb6,
4140x000200f8,0x00000b25,0x000500aa,0x0000002f,
4150x00000b2d,0x00000b13,0x0000038a,0x000300f7,
4160x00000b2f,0x00000000,0x000400fa,0x00000b2d,
4170x00000b2e,0x00000b2f,0x000200f8,0x00000b2e,
4180x00050041,0x00000b0f,0x00000b31,0x00000b17,
4190x000000a6,0x0004003d,0x00000006,0x00000b32,
4200x00000b31,0x00050041,0x00000b0f,0x00000b34,
4210x00000b18,0x000000a6,0x0004003d,0x00000006,
4220x00000b35,0x00000b34,0x000500b0,0x0000002f,
4230x00000d7e,0x00000b35,0x0000011f,0x000300f7,
4240x00000d8d,0x00000000,0x000400fa,0x00000d7e,
4250x00000d7f,0x00000d8d,0x000200f8,0x00000d7f,
4260x00050041,0x000000fe,0x00000e2f,0x000000fc,
4270x000000fd,0x0004003d,0x00000006,0x00000e30,
4280x00000e2f,0x00050084,0x00000006,0x00000e31,
4290x0000011f,0x00000e30,0x00050080,0x00000006,
4300x00000e32,0x00000107,0x00000e31,0x00050080,
4310x00000006,0x00000e38,0x00000e30,0x0000319c,
4320x00050086,0x00000006,0x00000e39,0x00000e38,
4330x00000101,0x00050084,0x00000006,0x00000d84,
4340x00000b35,0x00000e39,0x00050080,0x00000006,
4350x00000d86,0x00000d84,0x00000b32,0x00050084,
4360x00000006,0x00000d87,0x0000010a,0x00000d86,
4370x00050080,0x00000006,0x00000d88,0x00000e32,
4380x00000d87,0x00050041,0x00000156,0x00000d89,
4390x000000fc,0x00000154,0x0004003d,0x00000007,
4400x00000d8a,0x00000d89,0x00050051,0x00000006,
4410x00000e50,0x00000d8a,0x00000000,0x00050095,
4420x000000ab,0x00000e52,0x00000e50,0x00000d88,
4430x00050051,0x00000006,0x00000e53,0x00000e52,
4440x00000001,0x00050051,0x00000006,0x00000e54,
4450x00000e52,0x00000000,0x00050051,0x00000006,
4460x00000e57,0x00000d8a,0x00000001,0x00050080,
4470x00000006,0x00000e59,0x00000e57,0x00000e53,
4480x00050050,0x00000007,0x00000e5a,0x00000e54,
4490x00000e59,0x0004007c,0x00000014,0x00000e4a,
4500x00000e5a,0x00060041,0x000000db,0x00000e41,
4510x00000e4a,0x000000da,0x000000da,0x0006003d,
4520x00000006,0x00000e42,0x00000e41,0x00000002,
4530x00000004,0x00050041,0x000006c2,0x00000d8c,
4540x00000856,0x00000b35,0x0003003e,0x00000d8c,
4550x00000e42,0x000200f9,0x00000d8d,0x000200f8,
4560x00000d8d,0x00050084,0x00000006,0x00000d8f,
4570x00000b32,0x00000101,0x00050080,0x00000006,
4580x00000d91,0x00000d8f,0x00000101,0x00050041,
4590x000000fe,0x00000d92,0x000000fc,0x000000fd,
4600x0004003d,0x00000006,0x00000d93,0x00000d92,
4610x0007000c,0x00000006,0x00000d94,0x00000001,
4620x00000026,0x00000d91,0x00000d93,0x000200f9,
4630x00000d96,0x000200f8,0x00000d96,0x000700f5,
4640x00000006,0x00003158,0x00000d8f,0x00000d8d,
4650x00000e2b,0x00000e29,0x000500b0,0x0000002f,
4660x00000d9a,0x00003158,0x00000d94,0x000400f6,
4670x00000e2c,0x00000e29,0x00000000,0x000400fa,
4680x00000d9a,0x00000d9b,0x00000e2c,0x000200f8,
4690x00000d9b,0x00050080,0x00000006,0x00000d9e,
4700x00003158,0x00000b35,0x000500b0,0x0000002f,
4710x00000da1,0x00000d9e,0x00000d94,0x000300f7,
4720x00000dac,0x00000000,0x000400fa,0x00000da1,
4730x00000da3,0x00000dab,0x000200f8,0x00000da3,
4740x00050041,0x000000fe,0x00000e5e,0x000000fc,
4750x00000308,0x0004003d,0x00000006,0x00000e5f,
4760x00000e5e,0x000500c7,0x00000006,0x00000e60,
4770x00000e5f,0x000000b0,0x000500aa,0x0000002f,
4780x00000e61,0x00000e60,0x000000a6,0x000300f7,
4790x00000e66,0x00000000,0x000400fa,0x00000e61,
4800x00000e62,0x00000e64,0x000200f8,0x00000e62,
4810x000200f9,0x00000e66,0x000200f8,0x00000e64,
4820x00050084,0x00000006,0x00000e6e,0x00000111,
4830x00000d93,0x00050080,0x00000006,0x00000e6f,
4840x00000107,0x00000e6e,0x000200f9,0x00000e66,
4850x000200f8,0x00000e66,0x000700f5,0x00000006,
4860x00003159,0x00000107,0x00000e62,0x00000e6f,
4870x00000e64,0x00050084,0x00000006,0x00000da6,
4880x0000010a,0x00000d9e,0x00050080,0x00000006,
4890x00000da7,0x00003159,0x00000da6,0x00050041,
4900x00000156,0x00000da8,0x000000fc,0x00000154,
4910x0004003d,0x00000007,0x00000da9,0x00000da8,
4920x00050051,0x00000006,0x00000e86,0x00000da9,
4930x00000000,0x00050095,0x000000ab,0x00000e88,
4940x00000e86,0x00000da7,0x00050051,0x00000006,
4950x00000e89,0x00000e88,0x00000001,0x00050051,
4960x00000006,0x00000e8a,0x00000e88,0x00000000,
4970x00050051,0x00000006,0x00000e8d,0x00000da9,
4980x00000001,0x00050080,0x00000006,0x00000e8f,
4990x00000e8d,0x00000e89,0x00050050,0x00000007,
5000x00000e90,0x00000e8a,0x00000e8f,0x0004007c,
5010x00000014,0x00000e80,0x00000e90,0x00060041,
5020x000000db,0x00000e77,0x00000e80,0x000000da,
5030x000000da,0x0006003d,0x00000006,0x00000e78,
5040x00000e77,0x00000002,0x00000004,0x000200f9,
5050x00000dac,0x000200f8,0x00000dab,0x000200f9,
5060x00000dac,0x000200f8,0x00000dac,0x000700f5,
5070x00000006,0x0000315a,0x00000e78,0x00000e66,
5080x000000a6,0x00000dab,0x000300f7,0x00000db8,
5090x00000000,0x000400fa,0x00000da1,0x00000daf,
5100x00000db7,0x000200f8,0x00000daf,0x00050041,
5110x000000fe,0x00000e94,0x000000fc,0x00000308,
5120x0004003d,0x00000006,0x00000e95,0x00000e94,
5130x000500c7,0x00000006,0x00000e96,0x00000e95,
5140x000000b0,0x000500aa,0x0000002f,0x00000e97,
5150x00000e96,0x000000a6,0x000300f7,0x00000e9c,
5160x00000000,0x000400fa,0x00000e97,0x00000e98,
5170x00000e9a,0x000200f8,0x00000e98,0x00050084,
5180x00000006,0x00000ea2,0x0000010a,0x00000d93,
5190x00050080,0x00000006,0x00000ea3,0x00000107,
5200x00000ea2,0x000200f9,0x00000e9c,0x000200f8,
5210x00000e9a,0x00050084,0x00000006,0x00000ea8,
5220x00000118,0x00000d93,0x00050080,0x00000006,
5230x00000ea9,0x00000107,0x00000ea8,0x000200f9,
5240x00000e9c,0x000200f8,0x00000e9c,0x000700f5,
5250x00000006,0x0000315b,0x00000ea3,0x00000e98,
5260x00000ea9,0x00000e9a,0x00050084,0x00000006,
5270x00000db2,0x0000010a,0x00000d9e,0x00050080,
5280x00000006,0x00000db3,0x0000315b,0x00000db2,
5290x00050041,0x00000156,0x00000db4,0x000000fc,
5300x00000154,0x0004003d,0x00000007,0x00000db5,
5310x00000db4,0x00050051,0x00000006,0x00000ec0,
5320x00000db5,0x00000000,0x00050095,0x000000ab,
5330x00000ec2,0x00000ec0,0x00000db3,0x00050051,
5340x00000006,0x00000ec3,0x00000ec2,0x00000001,
5350x00050051,0x00000006,0x00000ec4,0x00000ec2,
5360x00000000,0x00050051,0x00000006,0x00000ec7,
5370x00000db5,0x00000001,0x00050080,0x00000006,
5380x00000ec9,0x00000ec7,0x00000ec3,0x00050050,
5390x00000007,0x00000eca,0x00000ec4,0x00000ec9,
5400x0004007c,0x00000014,0x00000eba,0x00000eca,
5410x00060041,0x000000db,0x00000eb1,0x00000eba,
5420x000000da,0x000000da,0x0006003d,0x00000006,
5430x00000eb2,0x00000eb1,0x00000002,0x00000004,
5440x000200f9,0x00000db8,0x000200f8,0x00000db7,
5450x000200f9,0x00000db8,0x000200f8,0x00000db8,
5460x000700f5,0x00000006,0x0000315c,0x00000eb2,
5470x00000e9c,0x000000a6,0x00000db7,0x00050041,
5480x000000fe,0x00000ece,0x000000fc,0x00000308,
5490x0004003d,0x00000006,0x00000ecf,0x00000ece,
5500x00050084,0x00000006,0x00000ed0,0x0000010a,
5510x00000ecf,0x000500c2,0x00000006,0x00000ed1,
5520x0000315a,0x00000ed0,0x000500c7,0x00000006,
5530x00000ed2,0x00000ed1,0x00000799,0x000200f9,
5540x00000dbc,0x000200f8,0x00000dbc,0x000700f5,
5550x00000006,0x0000315d,0x000000a6,0x00000db8,
5560x00000dcc,0x00000dc0,0x000500b0,0x0000002f,
5570x00000dbf,0x0000315d,0x0000011f,0x000400f6,
5580x00000dcd,0x00000dc0,0x00000000,0x000400fa,
5590x00000dbf,0x00000dc0,0x00000dcd,0x000200f8,
5600x00000dc0,0x000500aa,0x0000002f,0x00000dc6,
5610x0000315d,0x00000ed2,0x000500a7,0x0000002f,
5620x00000dc7,0x00000da1,0x00000dc6,0x000600a9,
5630x00000006,0x00000dc8,0x00000dc7,0x000000b0,
5640x000000a6,0x00060041,0x000006c2,0x00000dc9,
5650x000008af,0x0000315d,0x00000b35,0x0003003e,
5660x00000dc9,0x00000dc8,0x00050080,0x00000006,
5670x00000dcc,0x0000315d,0x00000154,0x000200f9,
5680x00000dbc,0x000200f8,0x00000dcd,0x000400e0,
5690x00000170,0x00000170,0x000006da,0x000200f9,
5700x00000dce,0x000200f8,0x00000dce,0x000700f5,
5710x00000006,0x0000315e,0x000000b0,0x00000dcd,
5720x00000dff,0x00000dfd,0x000500b0,0x0000002f,
5730x00000dd1,0x0000315e,0x00000107,0x000400f6,
5740x00000e00,0x00000dfd,0x00000000,0x000400fa,
5750x00000dd1,0x00000dd2,0x00000e00,0x000200f8,
5760x00000dd2,0x000200f9,0x00000dd3,0x000200f8,
5770x00000dd3,0x000700f5,0x00000006,0x0000316b,
5780x000000a6,0x00000dd2,0x00000de9,0x00000de7,
5790x000500b0,0x0000002f,0x00000dd6,0x0000316b,
5800x0000011f,0x000400f6,0x00000dea,0x00000de7,
5810x00000000,0x000400fa,0x00000dd6,0x00000dd7,
5820x00000dea,0x000200f8,0x00000dd7,0x000500ae,
5830x0000002f,0x00000ddb,0x00000b35,0x0000315e,
5840x000300f7,0x00000de4,0x00000000,0x000400fa,
5850x00000ddb,0x00000ddc,0x00000de3,0x000200f8,
5860x00000ddc,0x00050082,0x00000006,0x00000de0,
5870x00000b35,0x0000315e,0x00060041,0x000006c2,
5880x00000de1,0x000008af,0x0000316b,0x00000de0,
5890x0004003d,0x00000006,0x00000de2,0x00000de1,
5900x000200f9,0x00000de4,0x000200f8,0x00000de3,
5910x000200f9,0x00000de4,0x000200f8,0x00000de4,
5920x000700f5,0x00000006,0x0000316f,0x00000de2,
5930x00000ddc,0x000000a6,0x00000de3,0x00050041,
5940x00000009,0x00000de6,0x00000d72,0x0000316b,
5950x0003003e,0x00000de6,0x0000316f,0x000200f9,
5960x00000de7,0x000200f8,0x00000de7,0x00050080,
5970x00000006,0x00000de9,0x0000316b,0x00000154,
5980x000200f9,0x00000dd3,0x000200f8,0x00000dea,
5990x000400e0,0x00000170,0x00000170,0x000006da,
6000x000200f9,0x00000deb,0x000200f8,0x00000deb,
6010x000700f5,0x00000006,0x0000316c,0x000000a6,
6020x00000dea,0x00000dfb,0x00000def,0x000500b0,
6030x0000002f,0x00000dee,0x0000316c,0x0000011f,
6040x000400f6,0x00000dfc,0x00000def,0x00000000,
6050x000400fa,0x00000dee,0x00000def,0x00000dfc,
6060x000200f8,0x00000def,0x00050041,0x00000009,
6070x00000df3,0x00000d72,0x0000316c,0x0004003d,
6080x00000006,0x00000df4,0x00000df3,0x00060041,
6090x000006c2,0x00000df5,0x000008af,0x0000316c,
6100x00000b35,0x0004003d,0x00000006,0x00000df6,
6110x00000df5,0x00050080,0x00000006,0x00000df7,
6120x00000df6,0x00000df4,0x0003003e,0x00000df5,
6130x00000df7,0x00050080,0x00000006,0x00000dfb,
6140x0000316c,0x00000154,0x000200f9,0x00000deb,
6150x000200f8,0x00000dfc,0x000400e0,0x00000170,
6160x00000170,0x000006da,0x000200f9,0x00000dfd,
6170x000200f8,0x00000dfd,0x000500c4,0x00000006,
6180x00000dff,0x0000315e,0x00000154,0x000200f9,
6190x00000dce,0x000200f8,0x00000e00,0x000300f7,
6200x00000e1c,0x00000000,0x000400fa,0x00000da1,
6210x00000e02,0x00000e1c,0x000200f8,0x00000e02,
6220x00050041,0x000006c2,0x00000e04,0x00000856,
6230x00000ed2,0x0004003d,0x00000006,0x00000e05,
6240x00000e04,0x00060041,0x000006c2,0x00000e08,
6250x000008af,0x00000ed2,0x00000b35,0x0004003d,
6260x00000006,0x00000e09,0x00000e08,0x00050080,
6270x00000006,0x00000e0a,0x00000e05,0x00000e09,
6280x00050082,0x00000006,0x00000e0b,0x00000e0a,
6290x000000b0,0x000500c7,0x00000006,0x00000ed8,
6300x00000ecf,0x000000b0,0x000500aa,0x0000002f,
6310x00000ed9,0x00000ed8,0x000000a6,0x000300f7,
6320x00000ede,0x00000000,0x000400fa,0x00000ed9,
6330x00000eda,0x00000edc,0x000200f8,0x00000eda,
6340x00050084,0x00000006,0x00000ee4,0x00000111,
6350x00000d93,0x00050080,0x00000006,0x00000ee5,
6360x00000107,0x00000ee4,0x000200f9,0x00000ede,
6370x000200f8,0x00000edc,0x000200f9,0x00000ede,
6380x000200f8,0x00000ede,0x000700f5,0x00000006,
6390x0000315f,0x00000ee5,0x00000eda,0x00000107,
6400x00000edc,0x00050084,0x00000006,0x00000e0e,
6410x0000010a,0x00000e0b,0x00050080,0x00000006,
6420x00000e0f,0x0000315f,0x00000e0e,0x00050041,
6430x00000156,0x00000e10,0x000000fc,0x00000154,
6440x0004003d,0x00000007,0x00000e11,0x00000e10,
6450x00050051,0x00000006,0x00000efd,0x00000e11,
6460x00000000,0x00050095,0x000000ab,0x00000eff,
6470x00000efd,0x00000e0f,0x00050051,0x00000006,
6480x00000f00,0x00000eff,0x00000001,0x00050051,
6490x00000006,0x00000f01,0x00000eff,0x00000000,
6500x00050051,0x00000006,0x00000f04,0x00000e11,
6510x00000001,0x00050080,0x00000006,0x00000f06,
6520x00000f04,0x00000f00,0x00050050,0x00000007,
6530x00000f07,0x00000f01,0x00000f06,0x0004007c,
6540x00000014,0x00000ef7,0x00000f07,0x00060041,
6550x000000db,0x00000eef,0x00000ef7,0x000000da,
6560x000000da,0x0005003e,0x00000eef,0x0000315a,
6570x00000002,0x00000004,0x000300f7,0x00000f13,
6580x00000000,0x000400fa,0x00000ed9,0x00000f0f,
6590x00000f11,0x000200f8,0x00000f0f,0x00050084,
6600x00000006,0x00000f19,0x00000118,0x00000d93,
6610x00050080,0x00000006,0x00000f1a,0x00000107,
6620x00000f19,0x000200f9,0x00000f13,0x000200f8,
6630x00000f11,0x00050084,0x00000006,0x00000f1f,
6640x0000010a,0x00000d93,0x00050080,0x00000006,
6650x00000f20,0x00000107,0x00000f1f,0x000200f9,
6660x00000f13,0x000200f8,0x00000f13,0x000700f5,
6670x00000006,0x00003160,0x00000f1a,0x00000f0f,
6680x00000f20,0x00000f11,0x00050080,0x00000006,
6690x00000e17,0x00003160,0x00000e0e,0x00050095,
6700x000000ab,0x00000f38,0x00000efd,0x00000e17,
6710x00050051,0x00000006,0x00000f39,0x00000f38,
6720x00000001,0x00050051,0x00000006,0x00000f3a,
6730x00000f38,0x00000000,0x00050080,0x00000006,
6740x00000f3f,0x00000f04,0x00000f39,0x00050050,
6750x00000007,0x00000f40,0x00000f3a,0x00000f3f,
6760x0004007c,0x00000014,0x00000f30,0x00000f40,
6770x00060041,0x000000db,0x00000f28,0x00000f30,
6780x000000da,0x000000da,0x0005003e,0x00000f28,
6790x0000315c,0x00000002,0x00000004,0x000200f9,
6800x00000e1c,0x000200f8,0x00000e1c,0x000400e0,
6810x00000170,0x00000170,0x000006da,0x000300f7,
6820x00000e28,0x00000000,0x000400fa,0x00000d7e,
6830x00000e1f,0x00000e28,0x000200f8,0x00000e1f,
6840x00060041,0x000006c2,0x00000e22,0x000008af,
6850x00000b35,0x0000091d,0x0004003d,0x00000006,
6860x00000e23,0x00000e22,0x00050041,0x000006c2,
6870x00000e24,0x00000856,0x00000b35,0x0004003d,
6880x00000006,0x00000e25,0x00000e24,0x00050080,
6890x00000006,0x00000e26,0x00000e25,0x00000e23,
6900x0003003e,0x00000e24,0x00000e26,0x000200f9,
6910x00000e28,0x000200f8,0x00000e28,0x000400e0,
6920x00000170,0x00000170,0x000006da,0x000200f9,
6930x00000e29,0x000200f8,0x00000e29,0x00050080,
6940x00000006,0x00000e2b,0x00003158,0x00000107,
6950x000200f9,0x00000d96,0x000200f8,0x00000e2c,
6960x000200f9,0x00000bb6,0x000200f8,0x00000b2f,
6970x000500aa,0x0000002f,0x00000b3b,0x00000b13,
6980x00000b3a,0x000300f7,0x00000b3d,0x00000000,
6990x000400fa,0x00000b3b,0x00000b3c,0x00000b3d,
7000x000200f8,0x00000b3c,0x00050041,0x00000b0f,
7010x00000b3f,0x00000b18,0x000000a6,0x0004003d,
7020x00000006,0x00000b40,0x00000b3f,0x00050041,
7030x000000fe,0x00000f5b,0x000000fc,0x000000fd,
7040x0004003d,0x00000006,0x00000f5c,0x00000f5b,
7050x000200f9,0x00000f5d,0x000200f8,0x00000f5d,
7060x000700f5,0x00000006,0x00003143,0x000000b0,
7070x00000b3c,0x00000f64,0x00000f62,0x000500b0,
7080x0000002f,0x00000f61,0x00003143,0x00000f5c,
7090x000400f6,0x00000f66,0x00000f62,0x00000000,
7100x000400fa,0x00000f61,0x00000f62,0x00000f66,
7110x000200f8,0x00000f62,0x000500c4,0x00000006,
7120x00000f64,0x00003143,0x00000154,0x000200f9,
7130x00000f5d,0x000200f8,0x00000f66,0x000200f9,
7140x00000f68,0x000200f8,0x00000f68,0x000700f5,
7150x00000006,0x00003144,0x00000b40,0x00000f66,
7160x00000f90,0x00000f8e,0x000500b0,0x0000002f,
7170x00000f6c,0x00003144,0x00003143,0x000400f6,
7180x00000f91,0x00000f8e,0x00000000,0x000400fa,
7190x00000f6c,0x00000f6d,0x00000f91,0x000200f8,
7200x00000f6d,0x000500b0,0x0000002f,0x00000f71,
7210x00003144,0x00000f5c,0x000300f7,0x00000f7b,
7220x00000000,0x000400fa,0x00000f71,0x00000f72,
7230x00000f7a,0x000200f8,0x00000f72,0x00050084,
7240x00000006,0x00000f75,0x0000010a,0x00003144,
7250x00050080,0x00000006,0x00000f76,0x00000107,
7260x00000f75,0x00050041,0x00000156,0x00000f77,
7270x000000fc,0x00000154,0x0004003d,0x00000007,
7280x00000f78,0x00000f77,0x00050051,0x00000006,
7290x0000101f,0x00000f78,0x00000000,0x00050095,
7300x000000ab,0x00001021,0x0000101f,0x00000f76,
7310x00050051,0x00000006,0x00001022,0x00001021,
7320x00000001,0x00050051,0x00000006,0x00001023,
7330x00001021,0x00000000,0x00050051,0x00000006,
7340x00001026,0x00000f78,0x00000001,0x00050080,
7350x00000006,0x00001028,0x00001026,0x00001022,
7360x00050050,0x00000007,0x00001029,0x00001023,
7370x00001028,0x0004007c,0x00000014,0x00001019,
7380x00001029,0x00060041,0x000000db,0x00001010,
7390x00001019,0x000000da,0x000000da,0x0006003d,
7400x00000006,0x00001011,0x00001010,0x00000002,
7410x00000004,0x000200f9,0x00000f7b,0x000200f8,
7420x00000f7a,0x000200f9,0x00000f7b,0x000200f8,
7430x00000f7b,0x000700f5,0x00000006,0x00003154,
7440x00001011,0x00000f72,0x00000380,0x00000f7a,
7450x00050041,0x000006c2,0x00000f7d,0x000006af,
7460x00003144,0x0003003e,0x00000f7d,0x00003154,
7470x000300f7,0x00000f8b,0x00000000,0x000400fa,
7480x00000f71,0x00000f82,0x00000f8a,0x000200f8,
7490x00000f82,0x00050084,0x00000006,0x0000102e,
7500x0000010a,0x00000f5c,0x00050080,0x00000006,
7510x0000102f,0x00000107,0x0000102e,0x00050084,
7520x00000006,0x00000f85,0x0000010a,0x00003144,
7530x00050080,0x00000006,0x00000f86,0x0000102f,
7540x00000f85,0x00050041,0x00000156,0x00000f87,
7550x000000fc,0x00000154,0x0004003d,0x00000007,
7560x00000f88,0x00000f87,0x00050051,0x00000006,
7570x00001046,0x00000f88,0x00000000,0x00050095,
7580x000000ab,0x00001048,0x00001046,0x00000f86,
7590x00050051,0x00000006,0x00001049,0x00001048,
7600x00000001,0x00050051,0x00000006,0x0000104a,
7610x00001048,0x00000000,0x00050051,0x00000006,
7620x0000104d,0x00000f88,0x00000001,0x00050080,
7630x00000006,0x0000104f,0x0000104d,0x00001049,
7640x00050050,0x00000007,0x00001050,0x0000104a,
7650x0000104f,0x0004007c,0x00000014,0x00001040,
7660x00001050,0x00060041,0x000000db,0x00001037,
7670x00001040,0x000000da,0x000000da,0x0006003d,
7680x00000006,0x00001038,0x00001037,0x00000002,
7690x00000004,0x000200f9,0x00000f8b,0x000200f8,
7700x00000f8a,0x000200f9,0x00000f8b,0x000200f8,
7710x00000f8b,0x000700f5,0x00000006,0x00003156,
7720x00001038,0x00000f82,0x00000380,0x00000f8a,
7730x00050041,0x000006c2,0x00000f8d,0x000006c4,
7740x00003144,0x0003003e,0x00000f8d,0x00003156,
7750x000200f9,0x00000f8e,0x000200f8,0x00000f8e,
7760x00050080,0x00000006,0x00000f90,0x00003144,
7770x00000107,0x000200f9,0x00000f68,0x000200f8,
7780x00000f91,0x000400e0,0x00000170,0x00000170,
7790x000006da,0x000200f9,0x00000f92,0x000200f8,
7800x00000f92,0x000700f5,0x00000006,0x00003146,
7810x00000170,0x00000f91,0x00000fe6,0x00000fe4,
7820x000500b2,0x0000002f,0x00000f96,0x00003146,
7830x00003143,0x000400f6,0x00000fe7,0x00000fe4,
7840x00000000,0x000400fa,0x00000f96,0x00000f97,
7850x00000fe7,0x000200f8,0x00000f97,0x000500c2,
7860x00000006,0x00000f99,0x00003146,0x00000154,
7870x000200f9,0x00000f9a,0x000200f8,0x00000f9a,
7880x000700f5,0x00000006,0x00003149,0x00000f99,
7890x00000f97,0x00000fe2,0x00000fe0,0x000500ac,
7900x0000002f,0x00000f9d,0x00003149,0x000000a6,
7910x000400f6,0x00000fe3,0x00000fe0,0x00000000,
7920x000400fa,0x00000f9d,0x00000f9e,0x00000fe3,
7930x000200f8,0x00000f9e,0x000200f9,0x00000fa0,
7940x000200f8,0x00000fa0,0x000700f5,0x00000006,
7950x0000314b,0x00000b40,0x00000f9e,0x00000fde,
7960x00000fdc,0x000500b0,0x0000002f,0x00000fa4,
7970x0000314b,0x00003143,0x000400f6,0x00000fdf,
7980x00000fdc,0x00000000,0x000400fa,0x00000fa4,
7990x00000fa5,0x00000fdf,0x000200f8,0x00000fa5,
8000x000500c6,0x00000006,0x00000fa8,0x0000314b,
8010x00003149,0x000500ac,0x0000002f,0x00000fab,
8020x00000fa8,0x0000314b,0x000300f7,0x00000fdb,
8030x00000000,0x000400fa,0x00000fab,0x00000fac,
8040x00000fdb,0x000200f8,0x00000fac,0x00050041,
8050x000006c2,0x00000fae,0x000006af,0x0000314b,
8060x0004003d,0x00000006,0x00000faf,0x00000fae,
8070x00050041,0x000006c2,0x00000fb1,0x000006af,
8080x00000fa8,0x0004003d,0x00000006,0x00000fb2,
8090x00000fb1,0x00050041,0x000006c2,0x00000fb4,
8100x000006c4,0x0000314b,0x0004003d,0x00000006,
8110x00000fb5,0x00000fb4,0x00050041,0x000006c2,
8120x00000fb7,0x000006c4,0x00000fa8,0x0004003d,
8130x00000006,0x00000fb8,0x00000fb7,0x000500ac,
8140x0000002f,0x00000fbb,0x00000faf,0x00000fb2,
8150x000400a8,0x0000002f,0x00000fbc,0x00000fbb,
8160x000300f7,0x00000fc5,0x00000000,0x000400fa,
8170x00000fbc,0x00000fbd,0x00000fc5,0x000200f8,
8180x00000fbd,0x000500aa,0x0000002f,0x00000fc0,
8190x00000faf,0x00000fb2,0x000500ac,0x0000002f,
8200x00000fc3,0x00000fb5,0x00000fb8,0x000500a7,
8210x0000002f,0x00000fc4,0x00000fc0,0x00000fc3,
8220x000200f9,0x00000fc5,0x000200f8,0x00000fc5,
8230x000700f5,0x0000002f,0x00000fc6,0x00000fbb,
8240x00000fac,0x00000fc4,0x00000fbd,0x000500c7,
8250x00000006,0x00000fca,0x0000314b,0x00003146,
8260x000500aa,0x0000002f,0x00000fcb,0x00000fca,
8270x000000a6,0x000500a4,0x0000002f,0x00000fcc,
8280x00000fc6,0x00000fcb,0x000300f7,0x00000fda,
8290x00000000,0x000400fa,0x00000fcc,0x00000fcd,
8300x00000fda,0x000200f8,0x00000fcd,0x0003003e,
8310x00000fae,0x00000fb2,0x0003003e,0x00000fb1,
8320x00000faf,0x0003003e,0x00000fb4,0x00000fb8,
8330x0003003e,0x00000fb7,0x00000fb5,0x000200f9,
8340x00000fda,0x000200f8,0x00000fda,0x000200f9,
8350x00000fdb,0x000200f8,0x00000fdb,0x000200f9,
8360x00000fdc,0x000200f8,0x00000fdc,0x00050080,
8370x00000006,0x00000fde,0x0000314b,0x00000107,
8380x000200f9,0x00000fa0,0x000200f8,0x00000fdf,
8390x000400e0,0x00000170,0x00000170,0x000006da,
8400x000200f9,0x00000fe0,0x000200f8,0x00000fe0,
8410x000500c2,0x00000006,0x00000fe2,0x00003149,
8420x00000154,0x000200f9,0x00000f9a,0x000200f8,
8430x00000fe3,0x000200f9,0x00000fe4,0x000200f8,
8440x00000fe4,0x000500c4,0x00000006,0x00000fe6,
8450x00003146,0x00000154,0x000200f9,0x00000f92,
8460x000200f8,0x00000fe7,0x000200f9,0x00000fe9,
8470x000200f8,0x00000fe9,0x000700f5,0x00000006,
8480x00003148,0x00000b40,0x00000fe7,0x00001005,
8490x00000fee,0x000500b0,0x0000002f,0x00000fed,
8500x00003148,0x00000f5c,0x000400f6,0x00001006,
8510x00000fee,0x00000000,0x000400fa,0x00000fed,
8520x00000fee,0x00001006,0x000200f8,0x00000fee,
8530x00050084,0x00000006,0x00000ff1,0x0000010a,
8540x00003148,0x00050080,0x00000006,0x00000ff2,
8550x00000107,0x00000ff1,0x00050041,0x00000156,
8560x00000ff4,0x000000fc,0x00000154,0x0004003d,
8570x00000007,0x00000ff5,0x00000ff4,0x00050041,
8580x000006c2,0x00000ff6,0x000006af,0x00003148,
8590x0004003d,0x00000006,0x00000ff7,0x00000ff6,
8600x00050051,0x00000006,0x00001068,0x00000ff5,
8610x00000000,0x00050095,0x000000ab,0x0000106a,
8620x00001068,0x00000ff2,0x00050051,0x00000006,
8630x0000106b,0x0000106a,0x00000001,0x00050051,
8640x00000006,0x0000106c,0x0000106a,0x00000000,
8650x00050051,0x00000006,0x0000106f,0x00000ff5,
8660x00000001,0x00050080,0x00000006,0x00001071,
8670x0000106f,0x0000106b,0x00050050,0x00000007,
8680x00001072,0x0000106c,0x00001071,0x0004007c,
8690x00000014,0x00001062,0x00001072,0x00060041,
8700x000000db,0x0000105a,0x00001062,0x000000da,
8710x000000da,0x0005003e,0x0000105a,0x00000ff7,
2540x00000002,0x00000004,0x00050084,0x00000006, 8720x00000002,0x00000004,0x00050084,0x00000006,
2550x00000afb,0x00000107,0x00000ac4,0x000500c2, 8730x00001077,0x0000010a,0x00000f5c,0x00050080,
2560x00000006,0x00000afc,0x00000add,0x00000afb, 8740x00000006,0x00001078,0x00000107,0x00001077,
2570x000500c7,0x00000006,0x00000afd,0x00000afc, 8750x00050080,0x00000006,0x00000ffc,0x00001078,
2580x000006ca,0x00050041,0x000006d6,0x00000aa8, 8760x00000ff1,0x00050041,0x000006c2,0x00001000,
2590x000006d4,0x00000afd,0x000700ea,0x00000006, 8770x000006c4,0x00003148,0x0004003d,0x00000006,
2600x00000aa9,0x00000aa8,0x000000ad,0x000000a3, 8780x00001001,0x00001000,0x00050095,0x000000ab,
2610x000000ad,0x000200f9,0x00000aaa,0x000200f8, 8790x00001090,0x00001068,0x00000ffc,0x00050051,
2620x00000aaa,0x00050080,0x00000006,0x00000aac, 8800x00000006,0x00001091,0x00001090,0x00000001,
2630x00002b52,0x00000104,0x000200f9,0x00000a9a, 8810x00050051,0x00000006,0x00001092,0x00001090,
2640x000200f8,0x00000aad,0x000400e0,0x0000016d, 8820x00000000,0x00050080,0x00000006,0x00001097,
2650x0000016d,0x000006d8,0x000300f7,0x00000abf, 8830x0000106f,0x00001091,0x00050050,0x00000007,
2660x00000000,0x000400fa,0x00000a8b,0x00000ab0, 8840x00001098,0x00001092,0x00001097,0x0004007c,
2670x00000abf,0x000200f8,0x00000ab0,0x00050084, 8850x00000014,0x00001088,0x00001098,0x00060041,
2680x00000006,0x00000b02,0x0000011c,0x00000a95, 8860x000000db,0x00001080,0x00001088,0x000000da,
2690x00050080,0x00000006,0x00000b03,0x00000104, 8870x000000da,0x0005003e,0x00001080,0x00001001,
2700x00000b02,0x00050080,0x00000006,0x00000b09,
2710x00000a95,0x00002b67,0x00050086,0x00000006,
2720x00000b0a,0x00000b09,0x000000fe,0x00050084,
2730x00000006,0x00000ab4,0x000009f7,0x00000b0a,
2740x00050080,0x00000006,0x00000ab6,0x00000ab4,
2750x000009f4,0x00050084,0x00000006,0x00000ab7,
2760x00000107,0x00000ab6,0x00050080,0x00000006,
2770x00000ab8,0x00000b03,0x00000ab7,0x00050041,
2780x00000153,0x00000aba,0x000000f9,0x00000151,
2790x0004003d,0x00000007,0x00000abb,0x00000aba,
2800x00050041,0x000006d6,0x00000abc,0x000006d4,
2810x000009f7,0x0004003d,0x00000006,0x00000abd,
2820x00000abc,0x00050051,0x00000006,0x00000b20,
2830x00000abb,0x00000000,0x00050095,0x000000a8,
2840x00000b22,0x00000b20,0x00000ab8,0x00050051,
2850x00000006,0x00000b23,0x00000b22,0x00000001,
2860x00050051,0x00000006,0x00000b24,0x00000b22,
2870x00000000,0x00050051,0x00000006,0x00000b27,
2880x00000abb,0x00000001,0x00050080,0x00000006,
2890x00000b29,0x00000b27,0x00000b23,0x00050050,
2900x00000007,0x00000b2a,0x00000b24,0x00000b29,
2910x0004007c,0x00000014,0x00000b1a,0x00000b2a,
2920x00060041,0x000000d8,0x00000b12,0x00000b1a,
2930x000000d7,0x000000d7,0x0005003e,0x00000b12,
2940x00000abd,0x00000002,0x00000004,0x000200f9,
2950x00000abf,0x000200f8,0x00000abf,0x000200f9,
2960x00000a6e,0x000200f8,0x000009ef,0x000500aa,
2970x0000002f,0x000009fc,0x000009eb,0x0000010e,
2980x000300f7,0x000009fe,0x00000000,0x000400fa,
2990x000009fc,0x000009fd,0x000009fe,0x000200f8,
3000x000009fd,0x00050041,0x000009e7,0x00000a00,
3010x000009f1,0x000000a3,0x0004003d,0x00000006,
3020x00000a01,0x00000a00,0x00050041,0x000000fb,
3030x00000b9d,0x000000f9,0x000000fa,0x0004003d,
3040x00000006,0x00000b9e,0x00000b9d,0x00050080,
3050x00000006,0x00000ba0,0x00000b9e,0x00002b67,
3060x00050086,0x00000006,0x00000ba1,0x00000ba0,
3070x000000fe,0x00050084,0x00000006,0x00000b40,
3080x0000011c,0x00000ba1,0x00050080,0x00000006,
3090x00000b42,0x00000b40,0x00000717,0x00050086,
3100x00000006,0x00000b43,0x00000b42,0x00000104,
3110x00050084,0x00000006,0x00000b46,0x00000a01,
3120x00000b43,0x0007000c,0x00000006,0x00000b48,
3130x00000001,0x00000026,0x00000b46,0x00000b40,
3140x00050080,0x00000006,0x00000b4b,0x00000b48,
3150x00000b43,0x0007000c,0x00000006,0x00000b4d,
3160x00000001,0x00000026,0x00000b4b,0x00000b40,
3170x000200f9,0x00000b4f,0x000200f8,0x00000b4f,
3180x000700f5,0x00000006,0x00002b4d,0x000000a3,
3190x000009fd,0x00000b5d,0x00000b54,0x000700f5,
3200x00000006,0x00002b4c,0x00000b48,0x000009fd,
3210x00000b60,0x00000b54,0x000500b0,0x0000002f,
3220x00000b53,0x00002b4c,0x00000b4d,0x000400f6,
3230x00000b61,0x00000b54,0x00000000,0x000400fa,
3240x00000b53,0x00000b54,0x00000b61,0x000200f8,
3250x00000b54,0x00050084,0x00000006,0x00000ba6,
3260x0000011c,0x00000b9e,0x00050080,0x00000006,
3270x00000ba7,0x00000104,0x00000ba6,0x00050084,
3280x00000006,0x00000b57,0x00000107,0x00002b4c,
3290x00050080,0x00000006,0x00000b58,0x00000ba7,
3300x00000b57,0x00050041,0x00000153,0x00000b59,
3310x000000f9,0x00000151,0x0004003d,0x00000007,
3320x00000b5a,0x00000b59,0x00050051,0x00000006,
3330x00000bbe,0x00000b5a,0x00000000,0x00050095,
3340x000000a8,0x00000bc0,0x00000bbe,0x00000b58,
3350x00050051,0x00000006,0x00000bc1,0x00000bc0,
3360x00000001,0x00050051,0x00000006,0x00000bc2,
3370x00000bc0,0x00000000,0x00050051,0x00000006,
3380x00000bc5,0x00000b5a,0x00000001,0x00050080,
3390x00000006,0x00000bc7,0x00000bc5,0x00000bc1,
3400x00050050,0x00000007,0x00000bc8,0x00000bc2,
3410x00000bc7,0x0004007c,0x00000014,0x00000bb8,
3420x00000bc8,0x00060041,0x000000d8,0x00000baf,
3430x00000bb8,0x000000d7,0x000000d7,0x0006003d,
3440x00000006,0x00000bb0,0x00000baf,0x00000002,
3450x00000004,0x00050080,0x00000006,0x00000b5d,
3460x00002b4d,0x00000bb0,0x00050080,0x00000006,
3470x00000b60,0x00002b4c,0x00000151,0x000200f9,
3480x00000b4f,0x000200f8,0x00000b61,0x00050041,
3490x000006d6,0x00000b64,0x00000740,0x00000a01,
3500x0003003e,0x00000b64,0x00002b4d,0x000400e0,
3510x0000016d,0x0000016d,0x000006d8,0x000500aa,
3520x0000002f,0x00000b66,0x00000a01,0x000000a3,
3530x000300f7,0x00000b7a,0x00000000,0x000400fa,
3540x00000b66,0x00000b67,0x00000b7a,0x000200f8,
3550x00000b67,0x000200f9,0x00000b68,0x000200f8,
3560x00000b68,0x000700f5,0x00000006,0x00002b51,
3570x000000a3,0x00000b67,0x00000b75,0x00000b6c,
3580x000700f5,0x00000006,0x00002b4e,0x000000a3,
3590x00000b67,0x00000b78,0x00000b6c,0x000500b0,
3600x0000002f,0x00000b6b,0x00002b4e,0x00000104,
3610x000400f6,0x00000b79,0x00000b6c,0x00000000,
3620x000400fa,0x00000b6b,0x00000b6c,0x00000b79,
3630x000200f8,0x00000b6c,0x00050041,0x000006d6,
3640x00000b6e,0x00000740,0x00002b4e,0x0004003d,
3650x00000006,0x00000b6f,0x00000b6e,0x0003003e,
3660x00000b6e,0x00002b51,0x00050080,0x00000006,
3670x00000b75,0x00002b51,0x00000b6f,0x00050080,
3680x00000006,0x00000b78,0x00002b4e,0x00000151,
3690x000200f9,0x00000b68,0x000200f8,0x00000b79,
3700x000200f9,0x00000b7a,0x000200f8,0x00000b7a,
3710x000400e0,0x0000016d,0x0000016d,0x000006d8,
3720x0004003d,0x00000006,0x00000b7d,0x00000b64,
3730x000200f9,0x00000b7f,0x000200f8,0x00000b7f,
3740x000700f5,0x00000006,0x00002b50,0x00000b7d,
3750x00000b7a,0x00000b96,0x00000b84,0x000700f5,
3760x00000006,0x00002b4f,0x00000b48,0x00000b7a,
3770x00000b99,0x00000b84,0x000500b0,0x0000002f,
3780x00000b83,0x00002b4f,0x00000b4d,0x000400f6,
3790x00000b9a,0x00000b84,0x00000000,0x000400fa,
3800x00000b83,0x00000b84,0x00000b9a,0x000200f8,
3810x00000b84,0x00050084,0x00000006,0x00000bcd,
3820x0000011c,0x00000b9e,0x00050080,0x00000006,
3830x00000bce,0x00000104,0x00000bcd,0x00050084,
3840x00000006,0x00000b87,0x00000107,0x00002b4f,
3850x00050080,0x00000006,0x00000b88,0x00000bce,
3860x00000b87,0x00050041,0x00000153,0x00000b89,
3870x000000f9,0x00000151,0x0004003d,0x00000007,
3880x00000b8a,0x00000b89,0x00050051,0x00000006,
3890x00000be5,0x00000b8a,0x00000000,0x00050095,
3900x000000a8,0x00000be7,0x00000be5,0x00000b88,
3910x00050051,0x00000006,0x00000be8,0x00000be7,
3920x00000001,0x00050051,0x00000006,0x00000be9,
3930x00000be7,0x00000000,0x00050051,0x00000006,
3940x00000bec,0x00000b8a,0x00000001,0x00050080,
3950x00000006,0x00000bee,0x00000bec,0x00000be8,
3960x00050050,0x00000007,0x00000bef,0x00000be9,
3970x00000bee,0x0004007c,0x00000014,0x00000bdf,
3980x00000bef,0x00060041,0x000000d8,0x00000bd6,
3990x00000bdf,0x000000d7,0x000000d7,0x0006003d,
4000x00000006,0x00000bd7,0x00000bd6,0x00000002,
4010x00000004,0x0005003e,0x00000bd6,0x00002b50,
4020x00000002,0x00000004,0x00050080,0x00000006,
4030x00000b96,0x00002b50,0x00000bd7,0x00050080,
4040x00000006,0x00000b99,0x00002b4f,0x00000151,
4050x000200f9,0x00000b7f,0x000200f8,0x00000b9a,
4060x000200f9,0x00000a6e,0x000200f8,0x000009fe,
4070x000500aa,0x0000002f,0x00000a06,0x000009eb,
4080x00000387,0x000300f7,0x00000a08,0x00000000,
4090x000400fa,0x00000a06,0x00000a07,0x00000a08,
4100x000200f8,0x00000a07,0x00050041,0x000009e7,
4110x00000a0a,0x000009f0,0x000000a3,0x0004003d,
4120x00000006,0x00000a0b,0x00000a0a,0x00050041,
4130x000009e7,0x00000a0d,0x000009f1,0x000000a3,
4140x0004003d,0x00000006,0x00000a0e,0x00000a0d,
4150x000500b0,0x0000002f,0x00000c36,0x00000a0e,
4160x0000011c,0x000300f7,0x00000c45,0x00000000,
4170x000400fa,0x00000c36,0x00000c37,0x00000c45,
4180x000200f8,0x00000c37,0x00050041,0x000000fb,
4190x00000ce7,0x000000f9,0x000000fa,0x0004003d,
4200x00000006,0x00000ce8,0x00000ce7,0x00050084,
4210x00000006,0x00000ce9,0x0000011c,0x00000ce8,
4220x00050080,0x00000006,0x00000cea,0x00000104,
4230x00000ce9,0x00050080,0x00000006,0x00000cf0,
4240x00000ce8,0x00002b67,0x00050086,0x00000006,
4250x00000cf1,0x00000cf0,0x000000fe,0x00050084,
4260x00000006,0x00000c3c,0x00000a0e,0x00000cf1,
4270x00050080,0x00000006,0x00000c3e,0x00000c3c,
4280x00000a0b,0x00050084,0x00000006,0x00000c3f,
4290x00000107,0x00000c3e,0x00050080,0x00000006,
4300x00000c40,0x00000cea,0x00000c3f,0x00050041,
4310x00000153,0x00000c41,0x000000f9,0x00000151,
4320x0004003d,0x00000007,0x00000c42,0x00000c41,
4330x00050051,0x00000006,0x00000d08,0x00000c42,
4340x00000000,0x00050095,0x000000a8,0x00000d0a,
4350x00000d08,0x00000c40,0x00050051,0x00000006,
4360x00000d0b,0x00000d0a,0x00000001,0x00050051,
4370x00000006,0x00000d0c,0x00000d0a,0x00000000,
4380x00050051,0x00000006,0x00000d0f,0x00000c42,
4390x00000001,0x00050080,0x00000006,0x00000d11,
4400x00000d0f,0x00000d0b,0x00050050,0x00000007,
4410x00000d12,0x00000d0c,0x00000d11,0x0004007c,
4420x00000014,0x00000d02,0x00000d12,0x00060041,
4430x000000d8,0x00000cf9,0x00000d02,0x000000d7,
4440x000000d7,0x0006003d,0x00000006,0x00000cfa,
4450x00000cf9,0x00000002,0x00000004,0x00050041,
4460x000006d6,0x00000c44,0x00000789,0x00000a0e,
4470x0003003e,0x00000c44,0x00000cfa,0x000200f9,
4480x00000c45,0x000200f8,0x00000c45,0x00050084,
4490x00000006,0x00000c47,0x00000a0b,0x000000fe,
4500x00050080,0x00000006,0x00000c49,0x00000c47,
4510x000000fe,0x00050041,0x000000fb,0x00000c4a,
4520x000000f9,0x000000fa,0x0004003d,0x00000006,
4530x00000c4b,0x00000c4a,0x0007000c,0x00000006,
4540x00000c4c,0x00000001,0x00000026,0x00000c49,
4550x00000c4b,0x000200f9,0x00000c4e,0x000200f8,
4560x00000c4e,0x000700f5,0x00000006,0x00002b33,
4570x00000c47,0x00000c45,0x00000ce3,0x00000ce1,
4580x000500b0,0x0000002f,0x00000c52,0x00002b33,
4590x00000c4c,0x000400f6,0x00000ce4,0x00000ce1,
4600x00000000,0x000400fa,0x00000c52,0x00000c53,
4610x00000ce4,0x000200f8,0x00000c53,0x00050080,
4620x00000006,0x00000c56,0x00002b33,0x00000a0e,
4630x000500b0,0x0000002f,0x00000c59,0x00000c56,
4640x00000c4c,0x000300f7,0x00000c64,0x00000000,
4650x000400fa,0x00000c59,0x00000c5b,0x00000c63,
4660x000200f8,0x00000c5b,0x00050041,0x000000fb,
4670x00000d16,0x000000f9,0x00000305,0x0004003d,
4680x00000006,0x00000d17,0x00000d16,0x000500c7,
4690x00000006,0x00000d18,0x00000d17,0x000000ad,
4700x000500aa,0x0000002f,0x00000d19,0x00000d18,
4710x000000a3,0x000300f7,0x00000d1e,0x00000000,
4720x000400fa,0x00000d19,0x00000d1a,0x00000d1c,
4730x000200f8,0x00000d1a,0x000200f9,0x00000d1e,
4740x000200f8,0x00000d1c,0x00050084,0x00000006,
4750x00000d26,0x0000010e,0x00000c4b,0x00050080,
4760x00000006,0x00000d27,0x00000104,0x00000d26,
4770x000200f9,0x00000d1e,0x000200f8,0x00000d1e,
4780x000700f5,0x00000006,0x00002b34,0x00000104,
4790x00000d1a,0x00000d27,0x00000d1c,0x00050084,
4800x00000006,0x00000c5e,0x00000107,0x00000c56,
4810x00050080,0x00000006,0x00000c5f,0x00002b34,
4820x00000c5e,0x00050041,0x00000153,0x00000c60,
4830x000000f9,0x00000151,0x0004003d,0x00000007,
4840x00000c61,0x00000c60,0x00050051,0x00000006,
4850x00000d3e,0x00000c61,0x00000000,0x00050095,
4860x000000a8,0x00000d40,0x00000d3e,0x00000c5f,
4870x00050051,0x00000006,0x00000d41,0x00000d40,
4880x00000001,0x00050051,0x00000006,0x00000d42,
4890x00000d40,0x00000000,0x00050051,0x00000006,
4900x00000d45,0x00000c61,0x00000001,0x00050080,
4910x00000006,0x00000d47,0x00000d45,0x00000d41,
4920x00050050,0x00000007,0x00000d48,0x00000d42,
4930x00000d47,0x0004007c,0x00000014,0x00000d38,
4940x00000d48,0x00060041,0x000000d8,0x00000d2f,
4950x00000d38,0x000000d7,0x000000d7,0x0006003d,
4960x00000006,0x00000d30,0x00000d2f,0x00000002,
4970x00000004,0x000200f9,0x00000c64,0x000200f8,
4980x00000c63,0x000200f9,0x00000c64,0x000200f8,
4990x00000c64,0x000700f5,0x00000006,0x00002b35,
5000x00000d30,0x00000d1e,0x000000a3,0x00000c63,
5010x000300f7,0x00000c70,0x00000000,0x000400fa,
5020x00000c59,0x00000c67,0x00000c6f,0x000200f8,
5030x00000c67,0x00050041,0x000000fb,0x00000d4c,
5040x000000f9,0x00000305,0x0004003d,0x00000006,
5050x00000d4d,0x00000d4c,0x000500c7,0x00000006,
5060x00000d4e,0x00000d4d,0x000000ad,0x000500aa,
5070x0000002f,0x00000d4f,0x00000d4e,0x000000a3,
5080x000300f7,0x00000d54,0x00000000,0x000400fa,
5090x00000d4f,0x00000d50,0x00000d52,0x000200f8,
5100x00000d50,0x00050084,0x00000006,0x00000d5a,
5110x00000107,0x00000c4b,0x00050080,0x00000006,
5120x00000d5b,0x00000104,0x00000d5a,0x000200f9,
5130x00000d54,0x000200f8,0x00000d52,0x00050084,
5140x00000006,0x00000d60,0x00000115,0x00000c4b,
5150x00050080,0x00000006,0x00000d61,0x00000104,
5160x00000d60,0x000200f9,0x00000d54,0x000200f8,
5170x00000d54,0x000700f5,0x00000006,0x00002b36,
5180x00000d5b,0x00000d50,0x00000d61,0x00000d52,
5190x00050084,0x00000006,0x00000c6a,0x00000107,
5200x00000c56,0x00050080,0x00000006,0x00000c6b,
5210x00002b36,0x00000c6a,0x00050041,0x00000153,
5220x00000c6c,0x000000f9,0x00000151,0x0004003d,
5230x00000007,0x00000c6d,0x00000c6c,0x00050051,
5240x00000006,0x00000d78,0x00000c6d,0x00000000,
5250x00050095,0x000000a8,0x00000d7a,0x00000d78,
5260x00000c6b,0x00050051,0x00000006,0x00000d7b,
5270x00000d7a,0x00000001,0x00050051,0x00000006,
5280x00000d7c,0x00000d7a,0x00000000,0x00050051,
5290x00000006,0x00000d7f,0x00000c6d,0x00000001,
5300x00050080,0x00000006,0x00000d81,0x00000d7f,
5310x00000d7b,0x00050050,0x00000007,0x00000d82,
5320x00000d7c,0x00000d81,0x0004007c,0x00000014,
5330x00000d72,0x00000d82,0x00060041,0x000000d8,
5340x00000d69,0x00000d72,0x000000d7,0x000000d7,
5350x0006003d,0x00000006,0x00000d6a,0x00000d69,
5360x00000002,0x00000004,0x000200f9,0x00000c70,
5370x000200f8,0x00000c6f,0x000200f9,0x00000c70,
5380x000200f8,0x00000c70,0x000700f5,0x00000006,
5390x00002b37,0x00000d6a,0x00000d54,0x000000a3,
5400x00000c6f,0x00050041,0x000000fb,0x00000d86,
5410x000000f9,0x00000305,0x0004003d,0x00000006,
5420x00000d87,0x00000d86,0x00050084,0x00000006,
5430x00000d88,0x00000107,0x00000d87,0x000500c2,
5440x00000006,0x00000d89,0x00002b35,0x00000d88,
5450x000500c7,0x00000006,0x00000d8a,0x00000d89,
5460x000006ca,0x000200f9,0x00000c74,0x000200f8,
5470x00000c74,0x000700f5,0x00000006,0x00002b38,
5480x000000a3,0x00000c70,0x00000c84,0x00000c78,
5490x000500b0,0x0000002f,0x00000c77,0x00002b38,
5500x0000011c,0x000400f6,0x00000c85,0x00000c78,
5510x00000000,0x000400fa,0x00000c77,0x00000c78,
5520x00000c85,0x000200f8,0x00000c78,0x000500aa,
5530x0000002f,0x00000c7e,0x00002b38,0x00000d8a,
5540x000500a7,0x0000002f,0x00000c7f,0x00000c59,
5550x00000c7e,0x000600a9,0x00000006,0x00000c80,
5560x00000c7f,0x000000ad,0x000000a3,0x00060041,
5570x000006d6,0x00000c81,0x000007e2,0x00002b38,
5580x00000a0e,0x0003003e,0x00000c81,0x00000c80,
5590x00050080,0x00000006,0x00000c84,0x00002b38,
5600x00000151,0x000200f9,0x00000c74,0x000200f8,
5610x00000c85,0x000400e0,0x0000016d,0x0000016d,
5620x000006d8,0x000200f9,0x00000c86,0x000200f8,
5630x00000c86,0x000700f5,0x00000006,0x00002b39,
5640x000000ad,0x00000c85,0x00000cb7,0x00000cb5,
5650x000500b0,0x0000002f,0x00000c89,0x00002b39,
5660x00000104,0x000400f6,0x00000cb8,0x00000cb5,
5670x00000000,0x000400fa,0x00000c89,0x00000c8a,
5680x00000cb8,0x000200f8,0x00000c8a,0x000200f9,
5690x00000c8b,0x000200f8,0x00000c8b,0x000700f5,
5700x00000006,0x00002b46,0x000000a3,0x00000c8a,
5710x00000ca1,0x00000c9f,0x000500b0,0x0000002f,
5720x00000c8e,0x00002b46,0x0000011c,0x000400f6,
5730x00000ca2,0x00000c9f,0x00000000,0x000400fa,
5740x00000c8e,0x00000c8f,0x00000ca2,0x000200f8,
5750x00000c8f,0x000500ae,0x0000002f,0x00000c93,
5760x00000a0e,0x00002b39,0x000300f7,0x00000c9c,
5770x00000000,0x000400fa,0x00000c93,0x00000c94,
5780x00000c9b,0x000200f8,0x00000c94,0x00050082,
5790x00000006,0x00000c98,0x00000a0e,0x00002b39,
5800x00060041,0x000006d6,0x00000c99,0x000007e2,
5810x00002b46,0x00000c98,0x0004003d,0x00000006,
5820x00000c9a,0x00000c99,0x000200f9,0x00000c9c,
5830x000200f8,0x00000c9b,0x000200f9,0x00000c9c,
5840x000200f8,0x00000c9c,0x000700f5,0x00000006,
5850x00002b4a,0x00000c9a,0x00000c94,0x000000a3,
5860x00000c9b,0x00050041,0x00000009,0x00000c9e,
5870x00000c2a,0x00002b46,0x0003003e,0x00000c9e,
5880x00002b4a,0x000200f9,0x00000c9f,0x000200f8,
5890x00000c9f,0x00050080,0x00000006,0x00000ca1,
5900x00002b46,0x00000151,0x000200f9,0x00000c8b,
5910x000200f8,0x00000ca2,0x000400e0,0x0000016d,
5920x0000016d,0x000006d8,0x000200f9,0x00000ca3,
5930x000200f8,0x00000ca3,0x000700f5,0x00000006,
5940x00002b47,0x000000a3,0x00000ca2,0x00000cb3,
5950x00000ca7,0x000500b0,0x0000002f,0x00000ca6,
5960x00002b47,0x0000011c,0x000400f6,0x00000cb4,
5970x00000ca7,0x00000000,0x000400fa,0x00000ca6,
5980x00000ca7,0x00000cb4,0x000200f8,0x00000ca7,
5990x00050041,0x00000009,0x00000cab,0x00000c2a,
6000x00002b47,0x0004003d,0x00000006,0x00000cac,
6010x00000cab,0x00060041,0x000006d6,0x00000cad,
6020x000007e2,0x00002b47,0x00000a0e,0x0004003d,
6030x00000006,0x00000cae,0x00000cad,0x00050080,
6040x00000006,0x00000caf,0x00000cae,0x00000cac,
6050x0003003e,0x00000cad,0x00000caf,0x00050080,
6060x00000006,0x00000cb3,0x00002b47,0x00000151,
6070x000200f9,0x00000ca3,0x000200f8,0x00000cb4,
6080x000400e0,0x0000016d,0x0000016d,0x000006d8,
6090x000200f9,0x00000cb5,0x000200f8,0x00000cb5,
6100x000500c4,0x00000006,0x00000cb7,0x00002b39,
6110x00000151,0x000200f9,0x00000c86,0x000200f8,
6120x00000cb8,0x000300f7,0x00000cd4,0x00000000,
6130x000400fa,0x00000c59,0x00000cba,0x00000cd4,
6140x000200f8,0x00000cba,0x00050041,0x000006d6,
6150x00000cbc,0x00000789,0x00000d8a,0x0004003d,
6160x00000006,0x00000cbd,0x00000cbc,0x00060041,
6170x000006d6,0x00000cc0,0x000007e2,0x00000d8a,
6180x00000a0e,0x0004003d,0x00000006,0x00000cc1,
6190x00000cc0,0x00050080,0x00000006,0x00000cc2,
6200x00000cbd,0x00000cc1,0x00050082,0x00000006,
6210x00000cc3,0x00000cc2,0x000000ad,0x000500c7,
6220x00000006,0x00000d90,0x00000d87,0x000000ad,
6230x000500aa,0x0000002f,0x00000d91,0x00000d90,
6240x000000a3,0x000300f7,0x00000d96,0x00000000,
6250x000400fa,0x00000d91,0x00000d92,0x00000d94,
6260x000200f8,0x00000d92,0x00050084,0x00000006,
6270x00000d9c,0x0000010e,0x00000c4b,0x00050080,
6280x00000006,0x00000d9d,0x00000104,0x00000d9c,
6290x000200f9,0x00000d96,0x000200f8,0x00000d94,
6300x000200f9,0x00000d96,0x000200f8,0x00000d96,
6310x000700f5,0x00000006,0x00002b3a,0x00000d9d,
6320x00000d92,0x00000104,0x00000d94,0x00050084,
6330x00000006,0x00000cc6,0x00000107,0x00000cc3,
6340x00050080,0x00000006,0x00000cc7,0x00002b3a,
6350x00000cc6,0x00050041,0x00000153,0x00000cc8,
6360x000000f9,0x00000151,0x0004003d,0x00000007,
6370x00000cc9,0x00000cc8,0x00050051,0x00000006,
6380x00000db5,0x00000cc9,0x00000000,0x00050095,
6390x000000a8,0x00000db7,0x00000db5,0x00000cc7,
6400x00050051,0x00000006,0x00000db8,0x00000db7,
6410x00000001,0x00050051,0x00000006,0x00000db9,
6420x00000db7,0x00000000,0x00050051,0x00000006,
6430x00000dbc,0x00000cc9,0x00000001,0x00050080,
6440x00000006,0x00000dbe,0x00000dbc,0x00000db8,
6450x00050050,0x00000007,0x00000dbf,0x00000db9,
6460x00000dbe,0x0004007c,0x00000014,0x00000daf,
6470x00000dbf,0x00060041,0x000000d8,0x00000da7,
6480x00000daf,0x000000d7,0x000000d7,0x0005003e,
6490x00000da7,0x00002b35,0x00000002,0x00000004,
6500x000300f7,0x00000dcb,0x00000000,0x000400fa,
6510x00000d91,0x00000dc7,0x00000dc9,0x000200f8,
6520x00000dc7,0x00050084,0x00000006,0x00000dd1,
6530x00000115,0x00000c4b,0x00050080,0x00000006,
6540x00000dd2,0x00000104,0x00000dd1,0x000200f9,
6550x00000dcb,0x000200f8,0x00000dc9,0x00050084,
6560x00000006,0x00000dd7,0x00000107,0x00000c4b,
6570x00050080,0x00000006,0x00000dd8,0x00000104,
6580x00000dd7,0x000200f9,0x00000dcb,0x000200f8,
6590x00000dcb,0x000700f5,0x00000006,0x00002b3b,
6600x00000dd2,0x00000dc7,0x00000dd8,0x00000dc9,
6610x00050080,0x00000006,0x00000ccf,0x00002b3b,
6620x00000cc6,0x00050095,0x000000a8,0x00000df0,
6630x00000db5,0x00000ccf,0x00050051,0x00000006,
6640x00000df1,0x00000df0,0x00000001,0x00050051,
6650x00000006,0x00000df2,0x00000df0,0x00000000,
6660x00050080,0x00000006,0x00000df7,0x00000dbc,
6670x00000df1,0x00050050,0x00000007,0x00000df8,
6680x00000df2,0x00000df7,0x0004007c,0x00000014,
6690x00000de8,0x00000df8,0x00060041,0x000000d8,
6700x00000de0,0x00000de8,0x000000d7,0x000000d7,
6710x0005003e,0x00000de0,0x00002b37,0x00000002,
6720x00000004,0x000200f9,0x00000cd4,0x000200f8,
6730x00000cd4,0x000400e0,0x0000016d,0x0000016d,
6740x000006d8,0x000300f7,0x00000ce0,0x00000000,
6750x000400fa,0x00000c36,0x00000cd7,0x00000ce0,
6760x000200f8,0x00000cd7,0x00060041,0x000006d6,
6770x00000cda,0x000007e2,0x00000a0e,0x00000850,
6780x0004003d,0x00000006,0x00000cdb,0x00000cda,
6790x00050041,0x000006d6,0x00000cdc,0x00000789,
6800x00000a0e,0x0004003d,0x00000006,0x00000cdd,
6810x00000cdc,0x00050080,0x00000006,0x00000cde,
6820x00000cdd,0x00000cdb,0x0003003e,0x00000cdc,
6830x00000cde,0x000200f9,0x00000ce0,0x000200f8,
6840x00000ce0,0x000400e0,0x0000016d,0x0000016d,
6850x000006d8,0x000200f9,0x00000ce1,0x000200f8,
6860x00000ce1,0x00050080,0x00000006,0x00000ce3,
6870x00002b33,0x00000104,0x000200f9,0x00000c4e,
6880x000200f8,0x00000ce4,0x000200f9,0x00000a6e,
6890x000200f8,0x00000a08,0x000500aa,0x0000002f,
6900x00000a13,0x000009eb,0x00000236,0x000300f7,
6910x00000a15,0x00000000,0x000400fa,0x00000a13,
6920x00000a14,0x00000a15,0x000200f8,0x00000a14,
6930x000500aa,0x0000002f,0x00000a17,0x000009e9,
6940x000000a3,0x000300f7,0x00000a19,0x00000000,
6950x000400fa,0x00000a17,0x00000a18,0x00000a19,
6960x000200f8,0x00000a18,0x00050041,0x000000fb,
6970x00000e31,0x000000f9,0x00000305,0x0004003d,
6980x00000006,0x00000e32,0x00000e31,0x00050041,
6990x000000fb,0x00000e33,0x000000f9,0x000008bc,
7000x0004003d,0x00000006,0x00000e34,0x00000e33,
7010x00050080,0x00000006,0x00000e36,0x00000e34,
7020x00000e32,0x00050041,0x000000fb,0x00000ec7,
7030x000000f9,0x000000fa,0x0004003d,0x00000006,
7040x00000ec8,0x00000ec7,0x00050084,0x00000006,
7050x00000ec9,0x0000011c,0x00000ec8,0x00050080,
7060x00000006,0x00000eca,0x00000104,0x00000ec9,
7070x00050080,0x00000006,0x00000ed0,0x00000ec8,
7080x00002b67,0x00050086,0x00000006,0x00000ed1,
7090x00000ed0,0x000000fe,0x00050084,0x00000006,
7100x00000ec3,0x00000104,0x00000ed1,0x00050080,
7110x00000006,0x00000ec4,0x00000eca,0x00000ec3,
7120x00050084,0x00000006,0x00000e98,0x0000014d,
7130x00000e36,0x00050080,0x00000006,0x00000e99,
7140x00000ec4,0x00000e98,0x00050041,0x00000153,
7150x00000e9a,0x000000f9,0x00000151,0x0004003d,
7160x00000007,0x00000e9b,0x00000e9a,0x00050051,
7170x00000006,0x00000ee8,0x00000e9b,0x00000000,
7180x00050095,0x000000a8,0x00000eea,0x00000ee8,
7190x00000e99,0x00050051,0x00000006,0x00000eeb,
7200x00000eea,0x00000001,0x00050051,0x00000006,
7210x00000eec,0x00000eea,0x00000000,0x00050051,
7220x00000006,0x00000eef,0x00000e9b,0x00000001,
7230x00050080,0x00000006,0x00000ef1,0x00000eef,
7240x00000eeb,0x00050050,0x00000007,0x00000ef2,
7250x00000eec,0x00000ef1,0x0004007c,0x00000014,
7260x00000ee2,0x00000ef2,0x00060041,0x000000d8,
7270x00000ed9,0x00000ee2,0x000000d7,0x000000d7,
7280x0006003d,0x00000006,0x00000eda,0x00000ed9,
7290x00000002,0x00000004,0x00050080,0x00000006,
7300x00000ea0,0x00000e99,0x00000107,0x00050095,
7310x000000a8,0x00000f0b,0x00000ee8,0x00000ea0,
7320x00050051,0x00000006,0x00000f0c,0x00000f0b,
7330x00000001,0x00050051,0x00000006,0x00000f0d,
7340x00000f0b,0x00000000,0x00050080,0x00000006,
7350x00000f12,0x00000eef,0x00000f0c,0x00050050,
7360x00000007,0x00000f13,0x00000f0d,0x00000f12,
7370x0004007c,0x00000014,0x00000f03,0x00000f13,
7380x00060041,0x000000d8,0x00000efa,0x00000f03,
7390x000000d7,0x000000d7,0x0006003d,0x00000006,
7400x00000efb,0x00000efa,0x00000002,0x00000004,
7410x00050080,0x00000006,0x00000ea6,0x00000e99,
7420x0000010e,0x00050095,0x000000a8,0x00000f2c,
7430x00000ee8,0x00000ea6,0x00050051,0x00000006,
7440x00000f2d,0x00000f2c,0x00000001,0x00050051,
7450x00000006,0x00000f2e,0x00000f2c,0x00000000,
7460x00050080,0x00000006,0x00000f33,0x00000eef,
7470x00000f2d,0x00050050,0x00000007,0x00000f34,
7480x00000f2e,0x00000f33,0x0004007c,0x00000014,
7490x00000f24,0x00000f34,0x00060041,0x000000d8,
7500x00000f1b,0x00000f24,0x000000d7,0x000000d7,
7510x0006003d,0x00000006,0x00000f1c,0x00000f1b,
7520x00000002,0x00000004,0x00050080,0x00000006,
7530x00000ead,0x00000e99,0x00000115,0x00050095,
7540x000000a8,0x00000f4d,0x00000ee8,0x00000ead,
7550x00050051,0x00000006,0x00000f4e,0x00000f4d,
7560x00000001,0x00050051,0x00000006,0x00000f4f,
7570x00000f4d,0x00000000,0x00050080,0x00000006,
7580x00000f54,0x00000eef,0x00000f4e,0x00050050,
7590x00000007,0x00000f55,0x00000f4f,0x00000f54,
7600x0004007c,0x00000014,0x00000f45,0x00000f55,
7610x00060041,0x000000d8,0x00000f3c,0x00000f45,
7620x000000d7,0x000000d7,0x0006003d,0x00000006,
7630x00000f3d,0x00000f3c,0x00000002,0x00000004,
7640x00050080,0x00000006,0x00000eb3,0x00000e99,
7650x0000011c,0x00050095,0x000000a8,0x00000f6e,
7660x00000ee8,0x00000eb3,0x00050051,0x00000006,
7670x00000f6f,0x00000f6e,0x00000001,0x00050051,
7680x00000006,0x00000f70,0x00000f6e,0x00000000,
7690x00050080,0x00000006,0x00000f75,0x00000eef,
7700x00000f6f,0x00050050,0x00000007,0x00000f76,
7710x00000f70,0x00000f75,0x0004007c,0x00000014,
7720x00000f66,0x00000f76,0x00060041,0x000000d8,
7730x00000f5d,0x00000f66,0x000000d7,0x000000d7,
7740x0006003d,0x00000006,0x00000f5e,0x00000f5d,
7750x00000002,0x00000004,0x00050080,0x00000006,
7760x00000eb9,0x00000e99,0x00000186,0x00050095,
7770x000000a8,0x00000f8f,0x00000ee8,0x00000eb9,
7780x00050051,0x00000006,0x00000f90,0x00000f8f,
7790x00000001,0x00050051,0x00000006,0x00000f91,
7800x00000f8f,0x00000000,0x00050080,0x00000006,
7810x00000f96,0x00000eef,0x00000f90,0x00050050,
7820x00000007,0x00000f97,0x00000f91,0x00000f96,
7830x0004007c,0x00000014,0x00000f87,0x00000f97,
7840x00060041,0x000000d8,0x00000f7e,0x00000f87,
7850x000000d7,0x000000d7,0x0006003d,0x00000006,
7860x00000f7f,0x00000f7e,0x00000002,0x00000004,
7870x00050041,0x000000fb,0x00000e3a,0x000000f9,
7880x00000221,0x0004003d,0x00000006,0x00000e3b,
7890x00000e3a,0x000500ab,0x0000002f,0x00000e3c,
7900x00000e3b,0x000000a3,0x000600a9,0x00000006,
7910x00000e3d,0x00000e3c,0x000000a3,0x0000012d,
7920x000500c5,0x00000006,0x00000e3e,0x00000e3d,
7930x00000236,0x00050041,0x00000153,0x00000e3f,
7940x000000f9,0x000000d7,0x0004003d,0x00000007,
7950x00000e40,0x00000e3f,0x00050051,0x00000006,
7960x00000fad,0x00000e40,0x00000000,0x00050095,
7970x000000a8,0x00000faf,0x00000fad,0x000000a3,
7980x00050051,0x00000006,0x00000fb0,0x00000faf,
7990x00000001,0x00050051,0x00000006,0x00000fb1,
8000x00000faf,0x00000000,0x00050051,0x00000006,
8010x00000fb4,0x00000e40,0x00000001,0x00050080,
8020x00000006,0x00000fb6,0x00000fb4,0x00000fb0,
8030x00050050,0x00000007,0x00000fb7,0x00000fb1,
8040x00000fb6,0x0004007c,0x00000014,0x00000fa7,
8050x00000fb7,0x00060041,0x000000d8,0x00000f9f,
8060x00000fa7,0x000000d7,0x000000d7,0x0005003e,
8070x00000f9f,0x00000e3e,0x00000002,0x00000004,
8080x00050041,0x000000fb,0x00000e42,0x000000f9,
8090x0000096f,0x0004003d,0x00000006,0x00000e43,
8100x00000e42,0x00050086,0x00000006,0x00000e44,
8110x00000e43,0x00000104,0x00050095,0x000000a8,
8120x00000fcf,0x00000fad,0x00000107,0x00050051,
8130x00000006,0x00000fd0,0x00000fcf,0x00000001,
8140x00050051,0x00000006,0x00000fd1,0x00000fcf,
8150x00000000,0x00050080,0x00000006,0x00000fd6,
8160x00000fb4,0x00000fd0,0x00050050,0x00000007,
8170x00000fd7,0x00000fd1,0x00000fd6,0x0004007c,
8180x00000014,0x00000fc7,0x00000fd7,0x00060041,
8190x000000d8,0x00000fbf,0x00000fc7,0x000000d7,
8200x000000d7,0x0005003e,0x00000fbf,0x00000e44,
8210x00000002,0x00000004,0x00050095,0x000000a8,
8220x00000fef,0x00000fad,0x0000010e,0x00050051,
8230x00000006,0x00000ff0,0x00000fef,0x00000001,
8240x00050051,0x00000006,0x00000ff1,0x00000fef,
8250x00000000,0x00050080,0x00000006,0x00000ff6,
8260x00000fb4,0x00000ff0,0x00050050,0x00000007,
8270x00000ff7,0x00000ff1,0x00000ff6,0x0004007c,
8280x00000014,0x00000fe7,0x00000ff7,0x00060041,
8290x000000d8,0x00000fdf,0x00000fe7,0x000000d7,
8300x000000d7,0x0005003e,0x00000fdf,0x000000a3,
8310x00000002,0x00000004,0x00050095,0x000000a8,
8320x0000100f,0x00000fad,0x00000115,0x00050051,
8330x00000006,0x00001010,0x0000100f,0x00000001,
8340x00050051,0x00000006,0x00001011,0x0000100f,
8350x00000000,0x00050080,0x00000006,0x00001016,
8360x00000fb4,0x00001010,0x00050050,0x00000007,
8370x00001017,0x00001011,0x00001016,0x0004007c,
8380x00000014,0x00001007,0x00001017,0x00060041,
8390x000000d8,0x00000fff,0x00001007,0x000000d7,
8400x000000d7,0x0005003e,0x00000fff,0x00000e34,
8410x00000002,0x00000004,0x00050095,0x000000a8,
8420x00001038,0x00000fad,0x0000011c,0x00050051,
8430x00000006,0x00001039,0x00001038,0x00000001,
8440x00050051,0x00000006,0x0000103a,0x00001038,
8450x00000000,0x00050080,0x00000006,0x0000103f,
8460x00000fb4,0x00001039,0x00050050,0x00000007,
8470x00001040,0x0000103a,0x0000103f,0x0004007c,
8480x00000014,0x00001030,0x00001040,0x00060041,
8490x000000d8,0x00001028,0x00001030,0x000000d7,
8500x000000d7,0x0005003e,0x00001028,0x00000eda,
8510x00000002,0x00000004,0x00050095,0x000000a8,
8520x00001061,0x00000fad,0x00000186,0x00050051,
8530x00000006,0x00001062,0x00001061,0x00000001,
8540x00050051,0x00000006,0x00001063,0x00001061,
8550x00000000,0x00050080,0x00000006,0x00001068,
8560x00000fb4,0x00001062,0x00050050,0x00000007,
8570x00001069,0x00001063,0x00001068,0x0004007c,
8580x00000014,0x00001059,0x00001069,0x00060041,
8590x000000d8,0x00001051,0x00001059,0x000000d7,
8600x000000d7,0x0005003e,0x00001051,0x00000efb,
8610x00000002,0x00000004,0x00050095,0x000000a8,
8620x0000108a,0x00000fad,0x0000014d,0x00050051,
8630x00000006,0x0000108b,0x0000108a,0x00000001,
8640x00050051,0x00000006,0x0000108c,0x0000108a,
8650x00000000,0x00050080,0x00000006,0x00001091,
8660x00000fb4,0x0000108b,0x00050050,0x00000007,
8670x00001092,0x0000108c,0x00001091,0x0004007c,
8680x00000014,0x00001082,0x00001092,0x00060041,
8690x000000d8,0x0000107a,0x00001082,0x000000d7,
8700x000000d7,0x0005003e,0x0000107a,0x00000f1c,
8710x00000002,0x00000004,0x00050095,0x000000a8,
8720x000010b3,0x00000fad,0x00000460,0x00050051,
8730x00000006,0x000010b4,0x000010b3,0x00000001,
8740x00050051,0x00000006,0x000010b5,0x000010b3,
8750x00000000,0x00050080,0x00000006,0x000010ba,
8760x00000fb4,0x000010b4,0x00050050,0x00000007,
8770x000010bb,0x000010b5,0x000010ba,0x0004007c,
8780x00000014,0x000010ab,0x000010bb,0x00060041,
8790x000000d8,0x000010a3,0x000010ab,0x000000d7,
8800x000000d7,0x0005003e,0x000010a3,0x00000f3d,
8810x00000002,0x00000004,0x00050095,0x000000a8,
8820x000010dc,0x00000fad,0x00000466,0x00050051,
8830x00000006,0x000010dd,0x000010dc,0x00000001,
8840x00050051,0x00000006,0x000010de,0x000010dc,
8850x00000000,0x00050080,0x00000006,0x000010e3,
8860x00000fb4,0x000010dd,0x00050050,0x00000007,
8870x000010e4,0x000010de,0x000010e3,0x0004007c,
8880x00000014,0x000010d4,0x000010e4,0x00060041,
8890x000000d8,0x000010cc,0x000010d4,0x000000d7,
8900x000000d7,0x0005003e,0x000010cc,0x00000f5e,
8910x00000002,0x00000004,0x00050095,0x000000a8,
8920x00001105,0x00000fad,0x00000344,0x00050051,
8930x00000006,0x00001106,0x00001105,0x00000001,
8940x00050051,0x00000006,0x00001107,0x00001105,
8950x00000000,0x00050080,0x00000006,0x0000110c,
8960x00000fb4,0x00001106,0x00050050,0x00000007,
8970x0000110d,0x00001107,0x0000110c,0x0004007c,
8980x00000014,0x000010fd,0x0000110d,0x00060041,
8990x000000d8,0x000010f5,0x000010fd,0x000000d7,
9000x000000d7,0x0005003e,0x000010f5,0x00000f7f,
9010x00000002,0x00000004,0x00050041,0x000000fb,
9020x00000e70,0x000000f9,0x0000023b,0x0004003d,
9030x00000006,0x00000e71,0x00000e70,0x00050095,
9040x000000a8,0x00001125,0x00000fad,0x0000034f,
9050x00050051,0x00000006,0x00001126,0x00001125,
9060x00000001,0x00050051,0x00000006,0x00001127,
9070x00001125,0x00000000,0x00050080,0x00000006,
9080x0000112c,0x00000fb4,0x00001126,0x00050050,
9090x00000007,0x0000112d,0x00001127,0x0000112c,
9100x0004007c,0x00000014,0x0000111d,0x0000112d,
9110x00060041,0x000000d8,0x00001115,0x0000111d,
9120x000000d7,0x000000d7,0x0005003e,0x00001115,
9130x00000e71,0x00000002,0x00000004,0x00050095,
9140x000000a8,0x00001145,0x00000fad,0x0000035a,
9150x00050051,0x00000006,0x00001146,0x00001145,
9160x00000001,0x00050051,0x00000006,0x00001147,
9170x00001145,0x00000000,0x00050080,0x00000006,
9180x0000114c,0x00000fb4,0x00001146,0x00050050,
9190x00000007,0x0000114d,0x00001147,0x0000114c,
9200x0004007c,0x00000014,0x0000113d,0x0000114d,
9210x00060041,0x000000d8,0x00001135,0x0000113d,
9220x000000d7,0x000000d7,0x0005003e,0x00001135,
9230x000000a3,0x00000002,0x00000004,0x00050084,
9240x00000006,0x00001153,0x00000e32,0x00000225,
9250x00050080,0x00000006,0x00001154,0x00000e71,
9260x00001153,0x000500c2,0x00000006,0x00001155,
9270x00001154,0x00000230,0x000500c4,0x00000006,
9280x00001156,0x00001155,0x0000020a,0x000500c5,
9290x00000006,0x00001157,0x00001156,0x00000243,
9300x00050095,0x000000a8,0x0000116f,0x00000fad,
9310x00000365,0x00050051,0x00000006,0x00001170,
9320x0000116f,0x00000001,0x00050051,0x00000006,
9330x00001171,0x0000116f,0x00000000,0x00050080,
9340x00000006,0x00001176,0x00000fb4,0x00001170,
9350x00050050,0x00000007,0x00001177,0x00001171,
9360x00001176,0x0004007c,0x00000014,0x00001167,
9370x00001177,0x00060041,0x000000d8,0x0000115f,
9380x00001167,0x000000d7,0x000000d7,0x0005003e,
9390x0000115f,0x00001157,0x00000002,0x00000004,
9400x00050041,0x000000fb,0x00000e7d,0x000000f9,
9410x00000229,0x0004003d,0x00000006,0x00000e7e,
9420x00000e7d,0x00050095,0x000000a8,0x0000118f,
9430x00000fad,0x00000371,0x00050051,0x00000006,
9440x00001190,0x0000118f,0x00000001,0x00050051,
9450x00000006,0x00001191,0x0000118f,0x00000000,
9460x00050080,0x00000006,0x00001196,0x00000fb4,
9470x00001190,0x00050050,0x00000007,0x00001197,
9480x00001191,0x00001196,0x0004007c,0x00000014,
9490x00001187,0x00001197,0x00060041,0x000000d8,
9500x0000117f,0x00001187,0x000000d7,0x000000d7,
9510x0005003e,0x0000117f,0x00000e7e,0x00000002,
9520x00000004,0x00050041,0x000000fb,0x00000e82,
9530x000000f9,0x000008c7,0x0004003d,0x00000006,
9540x00000e83,0x00000e82,0x00050095,0x000000a8,
9550x000011af,0x00000fad,0x0000037b,0x00050051,
9560x00000006,0x000011b0,0x000011af,0x00000001,
9570x00050051,0x00000006,0x000011b1,0x000011af,
9580x00000000,0x00050080,0x00000006,0x000011b6,
9590x00000fb4,0x000011b0,0x00050050,0x00000007,
9600x000011b7,0x000011b1,0x000011b6,0x0004007c,
9610x00000014,0x000011a7,0x000011b7,0x00060041,
9620x000000d8,0x0000119f,0x000011a7,0x000000d7,
9630x000000d7,0x0005003e,0x0000119f,0x00000e83,
9640x00000002,0x00000004,0x00050095,0x000000a8,
9650x000011cf,0x00000fad,0x00000385,0x00050051,
9660x00000006,0x000011d0,0x000011cf,0x00000001,
9670x00050051,0x00000006,0x000011d1,0x000011cf,
9680x00000000,0x00050080,0x00000006,0x000011d6,
9690x00000fb4,0x000011d0,0x00050050,0x00000007,
9700x000011d7,0x000011d1,0x000011d6,0x0004007c,
9710x00000014,0x000011c7,0x000011d7,0x00060041,
9720x000000d8,0x000011bf,0x000011c7,0x000000d7,
9730x000000d7,0x0005003e,0x000011bf,0x000000a3,
9740x00000002,0x00000004,0x000200f9,0x00000a19,
9750x000200f8,0x00000a19,0x000200f9,0x00000a6e,
9760x000200f8,0x00000a15,0x00050041,0x000000fb,
9770x00000a1d,0x000000f9,0x000004d5,0x0004003d,
9780x00000006,0x00000a1e,0x00000a1d,0x000500ae,
9790x0000002f,0x00000a1f,0x000009e9,0x00000a1e,
9800x000300f7,0x00000a21,0x00000000,0x000400fa,
9810x00000a1f,0x00000a20,0x00000a21,0x000200f8,
9820x00000a20,0x000200f9,0x00000a6e,0x000200f8,
9830x00000a21,0x000500aa,0x0000002f,0x00000a25,
9840x000009eb,0x000000a3,0x000300f7,0x00000a27,
9850x00000000,0x000400fa,0x00000a25,0x00000a26,
9860x00000a48,0x000200f8,0x00000a26,0x00050041,
9870x000000fb,0x00000a28,0x000000f9,0x000008c7,
9880x0004003d,0x00000006,0x00000a29,0x00000a28,
9890x00050084,0x00000006,0x00000a2b,0x00000107,
9900x000009e9,0x00050080,0x00000006,0x00000a2c,
9910x00000a29,0x00000a2b,0x00050041,0x00000153,
9920x00000a2e,0x000000f9,0x000000d7,0x0004003d,
9930x00000007,0x00000a2f,0x00000a2e,0x00050051,
9940x00000006,0x000011ed,0x00000a2f,0x00000000,
9950x00050095,0x000000a8,0x000011ef,0x000011ed,
9960x00000a2c,0x00050051,0x00000006,0x000011f0,
9970x000011ef,0x00000001,0x00050051,0x00000006,
9980x000011f1,0x000011ef,0x00000000,0x00050051,
9990x00000006,0x000011f4,0x00000a2f,0x00000001,
10000x00050080,0x00000006,0x000011f6,0x000011f4,
10010x000011f0,0x00050050,0x00000007,0x000011f7,
10020x000011f1,0x000011f6,0x0004007c,0x00000014,
10030x000011e7,0x000011f7,0x00060041,0x000000d8,
10040x000011df,0x000011e7,0x000000d7,0x000000d7,
10050x0005003e,0x000011df,0x0000037d,0x00000002,
10060x00000004,0x000500b0,0x0000002f,0x00000a34,
10070x000009e9,0x000002b4,0x000300f7,0x00000a36,
10080x00000000,0x000400fa,0x00000a34,0x00000a35,
10090x00000a36,0x000200f8,0x00000a35,0x00050041,
10100x00000153,0x00000a3a,0x000000f9,0x00000151,
10110x0004003d,0x00000007,0x00000a3b,0x00000a3a,
10120x00050051,0x00000006,0x0000120d,0x00000a3b,
10130x00000000,0x00050095,0x000000a8,0x0000120f,
10140x0000120d,0x00000a2b,0x00050051,0x00000006,
10150x00001210,0x0000120f,0x00000001,0x00050051,
10160x00000006,0x00001211,0x0000120f,0x00000000,
10170x00050051,0x00000006,0x00001214,0x00000a3b,
10180x00000001,0x00050080,0x00000006,0x00001216,
10190x00001214,0x00001210,0x00050050,0x00000007,
10200x00001217,0x00001211,0x00001216,0x0004007c,
10210x00000014,0x00001207,0x00001217,0x00060041,
10220x000000d8,0x000011ff,0x00001207,0x000000d7,
10230x000000d7,0x0005003e,0x000011ff,0x0000037d,
10240x00000002,0x00000004,0x00050080,0x00000006,
10250x00000a41,0x00000115,0x00000a2b,0x00050095,
10260x000000a8,0x0000122f,0x0000120d,0x00000a41,
10270x00050051,0x00000006,0x00001230,0x0000122f,
10280x00000001,0x00050051,0x00000006,0x00001231,
10290x0000122f,0x00000000,0x00050080,0x00000006,
10300x00001236,0x00001214,0x00001230,0x00050050,
10310x00000007,0x00001237,0x00001231,0x00001236,
10320x0004007c,0x00000014,0x00001227,0x00001237,
10330x00060041,0x000000d8,0x0000121f,0x00001227,
10340x000000d7,0x000000d7,0x0005003e,0x0000121f,
10350x000000a3,0x00000002,0x00000004,0x000200f9,
10360x00000a36,0x000200f8,0x00000a36,0x000200f9,
10370x00000a27,0x000200f8,0x00000a48,0x000500aa,
10380x0000002f,0x00000a4b,0x000009eb,0x000000ad,
10390x000300f7,0x00000a4d,0x00000000,0x000400fa,
10400x00000a4b,0x00000a4c,0x00000a51,0x000200f8,
10410x00000a4c,0x000200f9,0x00001267,0x000200f8,
10420x00001267,0x000700f5,0x00000006,0x00002b1e,
10430x000000a3,0x00000a4c,0x00001277,0x00001275,
10440x000500b0,0x0000002f,0x0000126a,0x00002b1e,
10450x000002b4,0x000400f6,0x00001278,0x00001275,
10460x00000000,0x000400fa,0x0000126a,0x0000126b,
10470x00001278,0x000200f8,0x0000126b,0x00050084,
10480x00000006,0x0000126e,0x000002b4,0x000009e9,
10490x00050080,0x00000006,0x00001270,0x0000126e,
10500x00002b1e,0x000300f7,0x00001335,0x00000000,
10510x000300fb,0x000000a3,0x00001313,0x000200f8,
10520x00001313,0x00050041,0x000000fb,0x00001314,
10530x000000f9,0x00000278,0x0004003d,0x00000006,
10540x00001315,0x00001314,0x000500aa,0x0000002f,
10550x00001316,0x00001315,0x000000a3,0x000300f7,
10560x00001319,0x00000000,0x000400fa,0x00001316,
10570x00001317,0x00001319,0x000200f8,0x00001317,
10580x000200f9,0x00001335,0x000200f8,0x00001319,
10590x000500aa,0x0000002f,0x0000131c,0x00001315,
10600x0000016d,0x000300f7,0x00001323,0x00000000,
10610x000400fa,0x0000131c,0x0000131d,0x00001323,
10620x000200f8,0x0000131d,0x00050084,0x00000006,
10630x0000131f,0x00000107,0x00001270,0x00050041,
10640x00000153,0x00001320,0x000000f9,0x0000020a,
10650x0004003d,0x00000007,0x00001321,0x00001320,
10660x00050051,0x00000006,0x0000134d,0x00001321,
10670x00000000,0x00050095,0x000000a8,0x0000134f,
10680x0000134d,0x0000131f,0x00050051,0x00000006,
10690x00001350,0x0000134f,0x00000001,0x00050051,
10700x00000006,0x00001351,0x0000134f,0x00000000,
10710x00050051,0x00000006,0x00001354,0x00001321,
10720x00000001,0x00050080,0x00000006,0x00001356,
10730x00001354,0x00001350,0x00050050,0x00000007,
10740x00001357,0x00001351,0x00001356,0x0004007c,
10750x00000014,0x00001347,0x00001357,0x00060041,
10760x000000d8,0x0000133e,0x00001347,0x000000d7,
10770x000000d7,0x0006003d,0x00000006,0x0000133f,
10780x0000133e,0x00000002,0x00000004,0x000200f9,
10790x00001335,0x000200f8,0x00001323,0x000500c2,
10800x00000006,0x00001325,0x00001270,0x00000151,
10810x00050084,0x00000006,0x00001326,0x00000107,
10820x00001325,0x00050041,0x00000153,0x00001327,
10830x000000f9,0x0000020a,0x0004003d,0x00000007,
10840x00001328,0x00001327,0x00050051,0x00000006,
10850x0000136e,0x00001328,0x00000000,0x00050095,
10860x000000a8,0x00001370,0x0000136e,0x00001326,
10870x00050051,0x00000006,0x00001371,0x00001370,
10880x00000001,0x00050051,0x00000006,0x00001372,
10890x00001370,0x00000000,0x00050051,0x00000006,
10900x00001375,0x00001328,0x00000001,0x00050080,
10910x00000006,0x00001377,0x00001375,0x00001371,
10920x00050050,0x00000007,0x00001378,0x00001372,
10930x00001377,0x0004007c,0x00000014,0x00001368,
10940x00001378,0x00060041,0x000000d8,0x0000135f,
10950x00001368,0x000000d7,0x000000d7,0x0006003d,
10960x00000006,0x00001360,0x0000135f,0x00000002,
10970x00000004,0x000500c7,0x00000006,0x0000132b,
10980x00001270,0x000000ad,0x000500ab,0x0000002f,
10990x0000132c,0x0000132b,0x000000a3,0x000300f7,
11000x00001333,0x00000000,0x000400fa,0x0000132c,
11010x0000132d,0x00001330,0x000200f8,0x0000132d,
11020x000500c2,0x00000006,0x0000132f,0x00001360,
11030x0000023b,0x000200f9,0x00001333,0x000200f8,
11040x00001330,0x000500c7,0x00000006,0x00001332,
11050x00001360,0x000002a0,0x000200f9,0x00001333,
11060x000200f8,0x00001333,0x000700f5,0x00000006,
11070x00002b28,0x0000132f,0x0000132d,0x00001332,
11080x00001330,0x000200f9,0x00001335,0x000200f8,
11090x00001335,0x000900f5,0x00000006,0x00002b29,
11100x00001270,0x00001317,0x0000133f,0x0000131d,
11110x00002b28,0x00001333,0x00050041,0x000000fb,
11120x00001389,0x000000f9,0x0000024d,0x0004003d,
11130x00000006,0x0000138a,0x00001389,0x00050084,
11140x00000006,0x0000138b,0x00002b29,0x0000138a,
11150x00050041,0x00000153,0x0000138c,0x000000f9,
11160x00000202,0x0004003d,0x00000007,0x0000138d,
11170x0000138c,0x00050051,0x00000006,0x000013a8,
11180x0000138d,0x00000000,0x00050095,0x000000a8,
11190x000013aa,0x000013a8,0x0000138b,0x00050051,
11200x00000006,0x000013ab,0x000013aa,0x00000001,
11210x00050051,0x00000006,0x000013ac,0x000013aa,
11220x00000000,0x00050051,0x00000006,0x000013af,
11230x0000138d,0x00000001,0x00050080,0x00000006,
11240x000013b1,0x000013af,0x000013ab,0x00050095,
11250x000000a8,0x000013cb,0x000013ac,0x000000a3,
11260x00050051,0x00000006,0x000013cc,0x000013cb,
11270x00000001,0x00050051,0x00000006,0x000013cd,
11280x000013cb,0x00000000,0x00050080,0x00000006,
11290x000013d2,0x000013b1,0x000013cc,0x00050050,
11300x00000007,0x000013d3,0x000013cd,0x000013d2,
11310x0004007c,0x00000014,0x000013c3,0x000013d3,
11320x00060041,0x000000d8,0x000013ba,0x000013c3,
11330x000000d7,0x000000d7,0x0006003d,0x00000006,
11340x000013bb,0x000013ba,0x00000002,0x00000004,
11350x0004007c,0x00000027,0x00001391,0x000013bb,
11360x00050095,0x000000a8,0x000013ec,0x000013ac,
11370x00000107,0x00050051,0x00000006,0x000013ed,
11380x000013ec,0x00000001,0x00050051,0x00000006,
11390x000013ee,0x000013ec,0x00000000,0x00050080,
11400x00000006,0x000013f3,0x000013b1,0x000013ed,
11410x00050050,0x00000007,0x000013f4,0x000013ee,
11420x000013f3,0x0004007c,0x00000014,0x000013e4,
11430x000013f4,0x00060041,0x000000d8,0x000013db,
11440x000013e4,0x000000d7,0x000000d7,0x0006003d,
11450x00000006,0x000013dc,0x000013db,0x00000002,
11460x00000004,0x0004007c,0x00000027,0x00001394,
11470x000013dc,0x00050041,0x000000fb,0x00001395,
11480x000000f9,0x00000263,0x0004003d,0x00000006,
11490x00001396,0x00001395,0x000500aa,0x0000002f,
11500x00001397,0x00001396,0x000000ad,0x000300f7,
11510x0000139d,0x00000000,0x000400fa,0x00001397,
11520x00001398,0x00001399,0x000200f8,0x00001398,
11530x000200f9,0x0000139d,0x000200f8,0x00001399,
11540x00050095,0x000000a8,0x0000140d,0x000013ac,
11550x0000010e,0x00050051,0x00000006,0x0000140e,
11560x0000140d,0x00000001,0x00050051,0x00000006,
11570x0000140f,0x0000140d,0x00000000,0x00050080,
11580x00000006,0x00001414,0x000013b1,0x0000140e,
11590x00050050,0x00000007,0x00001415,0x0000140f,
11600x00001414,0x0004007c,0x00000014,0x00001405,
11610x00001415,0x00060041,0x000000d8,0x000013fc,
11620x00001405,0x000000d7,0x000000d7,0x0006003d,
11630x00000006,0x000013fd,0x000013fc,0x00000002,
11640x00000004,0x0004007c,0x00000027,0x0000139c,
11650x000013fd,0x000200f9,0x0000139d,0x000200f8,
11660x0000139d,0x000700f5,0x00000027,0x00002b2a,
11670x0000026a,0x00001398,0x0000139c,0x00001399,
11680x00060050,0x0000004b,0x000013a2,0x00001391,
11690x00001394,0x00002b2a,0x000300f7,0x0000145b,
11700x00000000,0x000300fb,0x000000a3,0x00001427,
11710x000200f8,0x00001427,0x00050041,0x00000153,
11720x00001428,0x000000f9,0x00000212,0x0004003d,
11730x00000007,0x00001429,0x00001428,0x00050051,
11740x00000006,0x00001460,0x00001429,0x00000000,
11750x000500aa,0x0000002f,0x00001461,0x00001460,
11760x000000a3,0x000300f7,0x00001466,0x00000000,
11770x000400fa,0x00001461,0x00001462,0x00001466,
11780x000200f8,0x00001462,0x00050051,0x00000006,
11790x00001464,0x00001429,0x00000001,0x000500aa,
11800x0000002f,0x00001465,0x00001464,0x000000a3,
11810x000200f9,0x00001466,0x000200f8,0x00001466,
11820x000700f5,0x0000002f,0x00001467,0x00001461,
11830x00001427,0x00001465,0x00001462,0x000300f7,
11840x0000142d,0x00000000,0x000400fa,0x00001467,
11850x0000142b,0x0000142d,0x000200f8,0x0000142b,
11860x000200f9,0x0000145b,0x000200f8,0x0000142d,
11870x000200f9,0x0000142e,0x000200f8,0x0000142e,
11880x000700f5,0x00000006,0x00002b2b,0x000000a3,
11890x0000142d,0x00001458,0x00001432,0x000500b0,
11900x0000002f,0x00001431,0x00002b2b,0x000002b4,
11910x000400f6,0x00001459,0x00001432,0x00000000,
11920x000400fa,0x00001431,0x00001432,0x00001459,
11930x000200f8,0x00001432,0x00050084,0x00000006,
11940x00001434,0x0000011c,0x00002b2b,0x00050095,
11950x000000a8,0x00001480,0x00001460,0x00001434,
11960x00050051,0x00000006,0x00001481,0x00001480,
11970x00000001,0x00050051,0x00000006,0x00001482,
11980x00001480,0x00000000,0x00050051,0x00000006,
11990x00001485,0x00001429,0x00000001,0x00050080,
12000x00000006,0x00001487,0x00001485,0x00001481,
12010x00050050,0x00000007,0x00001488,0x00001482,
12020x00001487,0x0004007c,0x00000014,0x00001478,
12030x00001488,0x00060041,0x000000d8,0x0000146f,
12040x00001478,0x000000d7,0x000000d7,0x0006003d,
12050x00000006,0x00001470,0x0000146f,0x00000002,
12060x00000004,0x0004007c,0x00000027,0x00001439,
12070x00001470,0x00050080,0x00000006,0x0000143b,
12080x00001434,0x00000107,0x00050095,0x000000a8,
12090x000014a1,0x00001460,0x0000143b,0x00050051,
12100x00000006,0x000014a2,0x000014a1,0x00000001,
12110x00050051,0x00000006,0x000014a3,0x000014a1,
12120x00000000,0x00050080,0x00000006,0x000014a8,
12130x00001485,0x000014a2,0x00050050,0x00000007,
12140x000014a9,0x000014a3,0x000014a8,0x0004007c,
12150x00000014,0x00001499,0x000014a9,0x00060041,
12160x000000d8,0x00001490,0x00001499,0x000000d7,
12170x000000d7,0x0006003d,0x00000006,0x00001491,
12180x00001490,0x00000002,0x00000004,0x0004007c,
12190x00000027,0x0000143f,0x00001491,0x00050080,
12200x00000006,0x00001441,0x00001434,0x0000010e,
12210x00050095,0x000000a8,0x000014c2,0x00001460,
12220x00001441,0x00050051,0x00000006,0x000014c3,
12230x000014c2,0x00000001,0x00050051,0x00000006,
12240x000014c4,0x000014c2,0x00000000,0x00050080,
12250x00000006,0x000014c9,0x00001485,0x000014c3,
12260x00050050,0x00000007,0x000014ca,0x000014c4,
12270x000014c9,0x0004007c,0x00000014,0x000014ba,
12280x000014ca,0x00060041,0x000000d8,0x000014b1,
12290x000014ba,0x000000d7,0x000000d7,0x0006003d,
12300x00000006,0x000014b2,0x000014b1,0x00000002,
12310x00000004,0x0004007c,0x00000027,0x00001445,
12320x000014b2,0x00050080,0x00000006,0x00001447,
12330x00001434,0x00000115,0x00050095,0x000000a8,
12340x000014e3,0x00001460,0x00001447,0x00050051,
12350x00000006,0x000014e4,0x000014e3,0x00000001,
12360x00050051,0x00000006,0x000014e5,0x000014e3,
12370x00000000,0x00050080,0x00000006,0x000014ea,
12380x00001485,0x000014e4,0x00050050,0x00000007,
12390x000014eb,0x000014e5,0x000014ea,0x0004007c,
12400x00000014,0x000014db,0x000014eb,0x00060041,
12410x000000d8,0x000014d2,0x000014db,0x000000d7,
12420x000000d7,0x0006003d,0x00000006,0x000014d3,
12430x000014d2,0x00000002,0x00000004,0x0004007c,
12440x00000027,0x0000144b,0x000014d3,0x00070050,
12450x000002b9,0x0000144c,0x00001439,0x0000143f,
12460x00001445,0x0000144b,0x0008004f,0x0000004b,
12470x0000144f,0x0000144c,0x0000144c,0x00000000,
12480x00000001,0x00000002,0x00050094,0x00000027,
12490x00001451,0x0000144f,0x000013a2,0x00050081,
12500x00000027,0x00001454,0x00001451,0x0000144b,
12510x00050041,0x00000028,0x00001455,0x00001424,
12520x00002b2b,0x0003003e,0x00001455,0x00001454,
12530x00050080,0x00000006,0x00001458,0x00002b2b,
12540x00000151,0x000200f9,0x0000142e,0x000200f8,
12550x00001459,0x0004003d,0x0000004b,0x0000145a,
12560x00001424,0x000200f9,0x0000145b,0x000200f8,
12570x0000145b,0x000700f5,0x0000004b,0x00002b2c,
12580x000013a2,0x0000142b,0x0000145a,0x00001459,
12590x00050041,0x0000004c,0x00001274,0x00001239,
12600x00002b1e,0x0003003e,0x00001274,0x00002b2c,
12610x000200f9,0x00001275,0x000200f8,0x00001275,
12620x00050080,0x00000006,0x00001277,0x00002b1e,
12630x00000151,0x000200f9,0x00001267,0x000200f8,
12640x00001278,0x00050041,0x000000fb,0x00001279,
12650x000000f9,0x00000305,0x0004003d,0x00000006,
12660x0000127a,0x00001279,0x00050080,0x00000006,
12670x0000127c,0x0000127a,0x000009e9,0x00050041,
12680x000000fb,0x0000127d,0x000000f9,0x00000229,
12690x0004003d,0x00000006,0x0000127e,0x0000127d,
12700x00050084,0x00000006,0x00001280,0x00000104,
12710x0000127c,0x00050080,0x00000006,0x00001281,
12720x0000127e,0x00001280,0x000200f9,0x00001282,
12730x000200f8,0x00001282,0x000700f5,0x00000006,
12740x00002b1f,0x000000a3,0x00001278,0x000012a9,
12750x00001286,0x000500b0,0x0000002f,0x00001285,
12760x00002b1f,0x000002b4,0x000400f6,0x000012aa,
12770x00001286,0x00000000,0x000400fa,0x00001285,
12780x00001286,0x000012aa,0x000200f8,0x00001286,
12790x00050084,0x00000006,0x00001289,0x00000115,
12800x00002b1f,0x00050080,0x00000006,0x0000128a,
12810x00001281,0x00001289,0x00050041,0x00000153,
12820x0000128c,0x000000f9,0x000000d7,0x0004003d,
12830x00000007,0x0000128d,0x0000128c,0x00060041,
12840x00000028,0x0000128e,0x00001239,0x00002b1f,
12850x000000a3,0x0004003d,0x00000027,0x0000128f,
12860x0000128e,0x0004007c,0x00000006,0x000014f1,
12870x0000128f,0x00050051,0x00000006,0x0000150a,
12880x0000128d,0x00000000,0x00050095,0x000000a8,
12890x0000150c,0x0000150a,0x0000128a,0x00050051,
12900x00000006,0x0000150d,0x0000150c,0x00000001,
12910x00050051,0x00000006,0x0000150e,0x0000150c,
12920x00000000,0x00050051,0x00000006,0x00001511,
12930x0000128d,0x00000001,0x00050080,0x00000006,
12940x00001513,0x00001511,0x0000150d,0x00050050,
12950x00000007,0x00001514,0x0000150e,0x00001513,
12960x0004007c,0x00000014,0x00001504,0x00001514,
12970x00060041,0x000000d8,0x000014fc,0x00001504,
12980x000000d7,0x000000d7,0x0005003e,0x000014fc,
12990x000014f1,0x00000002,0x00000004,0x00050080,
13000x00000006,0x00001295,0x0000128a,0x00000107,
13010x00060041,0x00000028,0x00001299,0x00001239,
13020x00002b1f,0x000000ad,0x0004003d,0x00000027,
13030x0000129a,0x00001299,0x0004007c,0x00000006,
13040x0000151a,0x0000129a,0x00050095,0x000000a8,
13050x00001535,0x0000150a,0x00001295,0x00050051,
13060x00000006,0x00001536,0x00001535,0x00000001,
13070x00050051,0x00000006,0x00001537,0x00001535,
13080x00000000,0x00050080,0x00000006,0x0000153c,
13090x00001511,0x00001536,0x00050050,0x00000007,
13100x0000153d,0x00001537,0x0000153c,0x0004007c,
13110x00000014,0x0000152d,0x0000153d,0x00060041,
13120x000000d8,0x00001525,0x0000152d,0x000000d7,
13130x000000d7,0x0005003e,0x00001525,0x0000151a,
13140x00000002,0x00000004,0x00050080,0x00000006,
13150x000012a0,0x0000128a,0x0000010e,0x00060041,
13160x00000028,0x000012a4,0x00001239,0x00002b1f,
13170x0000016d,0x0004003d,0x00000027,0x000012a5,
13180x000012a4,0x0004007c,0x00000006,0x00001543,
13190x000012a5,0x00050095,0x000000a8,0x0000155e,
13200x0000150a,0x000012a0,0x00050051,0x00000006,
13210x0000155f,0x0000155e,0x00000001,0x00050051,
13220x00000006,0x00001560,0x0000155e,0x00000000,
13230x00050080,0x00000006,0x00001565,0x00001511,
13240x0000155f,0x00050050,0x00000007,0x00001566,
13250x00001560,0x00001565,0x0004007c,0x00000014,
13260x00001556,0x00001566,0x00060041,0x000000d8,
13270x0000154e,0x00001556,0x000000d7,0x000000d7,
13280x0005003e,0x0000154e,0x00001543,0x00000002,
13290x00000004,0x00050080,0x00000006,0x000012a9,
13300x00002b1f,0x00000151,0x000200f9,0x00001282,
13310x000200f8,0x000012aa,0x00050080,0x00000006,
13320x000012ac,0x00001281,0x00000344,0x00050041,
13330x00000153,0x000012ad,0x000000f9,0x000000d7,
13340x0004003d,0x00000007,0x000012ae,0x000012ad,
13350x00060041,0x00000028,0x000012af,0x00001239,
13360x00000202,0x000000a3,0x0004003d,0x00000027,
13370x000012b0,0x000012af,0x0004007c,0x00000006,
13380x0000156c,0x000012b0,0x00050051,0x00000006,
13390x00001585,0x000012ae,0x00000000,0x00050095,
13400x000000a8,0x00001587,0x00001585,0x000012ac,
13410x00050051,0x00000006,0x00001588,0x00001587,
13420x00000001,0x00050051,0x00000006,0x00001589,
13430x00001587,0x00000000,0x00050051,0x00000006,
13440x0000158c,0x000012ae,0x00000001,0x00050080,
13450x00000006,0x0000158e,0x0000158c,0x00001588,
13460x00050050,0x00000007,0x0000158f,0x00001589,
13470x0000158e,0x0004007c,0x00000014,0x0000157f,
13480x0000158f,0x00060041,0x000000d8,0x00001577,
13490x0000157f,0x000000d7,0x000000d7,0x0005003e,
13500x00001577,0x0000156c,0x00000002,0x00000004,
13510x00050080,0x00000006,0x000012b3,0x00001281,
13520x0000034f,0x00060041,0x00000028,0x000012b6,
13530x00001239,0x00000202,0x000000ad,0x0004003d,
13540x00000027,0x000012b7,0x000012b6,0x0004007c,
13550x00000006,0x00001595,0x000012b7,0x00050095,
13560x000000a8,0x000015b0,0x00001585,0x000012b3,
13570x00050051,0x00000006,0x000015b1,0x000015b0,
13580x00000001,0x00050051,0x00000006,0x000015b2,
13590x000015b0,0x00000000,0x00050080,0x00000006,
13600x000015b7,0x0000158c,0x000015b1,0x00050050,
13610x00000007,0x000015b8,0x000015b2,0x000015b7,
13620x0004007c,0x00000014,0x000015a8,0x000015b8,
13630x00060041,0x000000d8,0x000015a0,0x000015a8,
13640x000000d7,0x000000d7,0x0005003e,0x000015a0,
13650x00001595,0x00000002,0x00000004,0x00050080,
13660x00000006,0x000012ba,0x00001281,0x0000035a,
13670x00060041,0x00000028,0x000012bd,0x00001239,
13680x00000202,0x0000016d,0x0004003d,0x00000027,
13690x000012be,0x000012bd,0x0004007c,0x00000006,
13700x000015be,0x000012be,0x00050095,0x000000a8,
13710x000015d9,0x00001585,0x000012ba,0x00050051,
13720x00000006,0x000015da,0x000015d9,0x00000001,
13730x00050051,0x00000006,0x000015db,0x000015d9,
13740x00000000,0x00050080,0x00000006,0x000015e0,
13750x0000158c,0x000015da,0x00050050,0x00000007,
13760x000015e1,0x000015db,0x000015e0,0x0004007c,
13770x00000014,0x000015d1,0x000015e1,0x00060041,
13780x000000d8,0x000015c9,0x000015d1,0x000000d7,
13790x000000d7,0x0005003e,0x000015c9,0x000015be,
13800x00000002,0x00000004,0x00050080,0x00000006,
13810x000012c1,0x00001281,0x00000365,0x00050041,
13820x000000fb,0x000012c4,0x000000f9,0x00000367,
13830x0004003d,0x00000006,0x000012c5,0x000012c4,
13840x00050095,0x000000a8,0x000015f9,0x00001585,
13850x000012c1,0x00050051,0x00000006,0x000015fa,
13860x000015f9,0x00000001,0x00050051,0x00000006,
13870x000015fb,0x000015f9,0x00000000,0x00050080,
13880x00000006,0x00001600,0x0000158c,0x000015fa,
13890x00050050,0x00000007,0x00001601,0x000015fb,
13900x00001600,0x0004007c,0x00000014,0x000015f1,
13910x00001601,0x00060041,0x000000d8,0x000015e9,
13920x000015f1,0x000000d7,0x000000d7,0x0005003e,
13930x000015e9,0x000012c5,0x00000002,0x00000004,
13940x00050080,0x00000006,0x000012c8,0x00001281,
13950x00000371,0x00050095,0x000000a8,0x00001619,
13960x00001585,0x000012c8,0x00050051,0x00000006,
13970x0000161a,0x00001619,0x00000001,0x00050051,
13980x00000006,0x0000161b,0x00001619,0x00000000,
13990x00050080,0x00000006,0x00001620,0x0000158c,
14000x0000161a,0x00050050,0x00000007,0x00001621,
14010x0000161b,0x00001620,0x0004007c,0x00000014,
14020x00001611,0x00001621,0x00060041,0x000000d8,
14030x00001609,0x00001611,0x000000d7,0x000000d7,
14040x0005003e,0x00001609,0x000009e9,0x00000002,
14050x00000004,0x00050080,0x00000006,0x000012ce,
14060x00001281,0x0000037b,0x00050095,0x000000a8,
14070x00001639,0x00001585,0x000012ce,0x00050051,
14080x00000006,0x0000163a,0x00001639,0x00000001,
14090x00050051,0x00000006,0x0000163b,0x00001639,
14100x00000000,0x00050080,0x00000006,0x00001640,
14110x0000158c,0x0000163a,0x00050050,0x00000007,
14120x00001641,0x0000163b,0x00001640,0x0004007c,
14130x00000014,0x00001631,0x00001641,0x00060041,
14140x000000d8,0x00001629,0x00001631,0x000000d7,
14150x000000d7,0x0005003e,0x00001629,0x0000037d,
14160x00000002,0x00000004,0x00050080,0x00000006,
14170x000012d3,0x00001281,0x00000385,0x00050095,
14180x000000a8,0x00001659,0x00001585,0x000012d3,
14190x00050051,0x00000006,0x0000165a,0x00001659,
14200x00000001,0x00050051,0x00000006,0x0000165b,
14210x00001659,0x00000000,0x00050080,0x00000006,
14220x00001660,0x0000158c,0x0000165a,0x00050050,
14230x00000007,0x00001661,0x0000165b,0x00001660,
14240x0004007c,0x00000014,0x00001651,0x00001661,
14250x00060041,0x000000d8,0x00001649,0x00001651,
14260x000000d7,0x000000d7,0x0005003e,0x00001649,
14270x00000387,0x00000002,0x00000004,0x00050041,
14280x0000004c,0x000012d7,0x00001239,0x000000d7,
14290x0004003d,0x0000004b,0x000012d8,0x000012d7,
14300x0004009c,0x00000392,0x000012d9,0x000012d8,
14310x0004009a,0x0000002f,0x000012da,0x000012d9,
14320x000400a8,0x0000002f,0x000012db,0x000012da,
14330x000300f7,0x000012e1,0x00000000,0x000400fa,
14340x000012db,0x000012dc,0x000012e1,0x000200f8,
14350x000012dc,0x00050041,0x0000004c,0x000012dd,
14360x00001239,0x00000151,0x0004003d,0x0000004b,
14370x000012de,0x000012dd,0x0004009c,0x00000392,
14380x000012df,0x000012de,0x0004009a,0x0000002f,
14390x000012e0,0x000012df,0x000200f9,0x000012e1,
14400x000200f8,0x000012e1,0x000700f5,0x0000002f,
14410x000012e2,0x000012da,0x000012aa,0x000012e0,
14420x000012dc,0x000400a8,0x0000002f,0x000012e3,
14430x000012e2,0x000300f7,0x000012e9,0x00000000,
14440x000400fa,0x000012e3,0x000012e4,0x000012e9,
14450x000200f8,0x000012e4,0x00050041,0x0000004c,
14460x000012e5,0x00001239,0x00000202,0x0004003d,
14470x0000004b,0x000012e6,0x000012e5,0x0004009c,
14480x00000392,0x000012e7,0x000012e6,0x0004009a,
14490x0000002f,0x000012e8,0x000012e7,0x000200f9,
14500x000012e9,0x000200f8,0x000012e9,0x000700f5,
14510x0000002f,0x000012ea,0x000012e2,0x000012e1,
14520x000012e8,0x000012e4,0x0004003d,0x0000004b,
14530x000012ec,0x000012d7,0x00050041,0x0000004c,
14540x000012ed,0x00001239,0x00000151,0x0004003d,
14550x0000004b,0x000012ee,0x000012ed,0x0007000c,
14560x0000004b,0x000012ef,0x00000001,0x00000025,
14570x000012ec,0x000012ee,0x00050041,0x0000004c,
14580x000012f0,0x00001239,0x00000202,0x0004003d,
14590x0000004b,0x000012f1,0x000012f0,0x0007000c,
14600x0000004b,0x000012f2,0x00000001,0x00000025,
14610x000012ef,0x000012f1,0x0004003d,0x0000004b,
14620x000012f4,0x000012d7,0x0004003d,0x0000004b,
14630x000012f6,0x000012ed,0x0007000c,0x0000004b,
14640x000012f7,0x00000001,0x00000028,0x000012f4,
14650x000012f6,0x0004003d,0x0000004b,0x000012f9,
14660x000012f0,0x0007000c,0x0000004b,0x000012fa,
14670x00000001,0x00000028,0x000012f7,0x000012f9,
14680x00060050,0x00000392,0x00002b68,0x000012ea,
14690x000012ea,0x000012ea,0x000600a9,0x0000004b,
14700x00002b69,0x00002b68,0x00002b66,0x000012fa,
14710x000600a9,0x0000004b,0x00002b6b,0x00002b68,
14720x00002b64,0x000012f2,0x00050041,0x000000fb,
14730x000016ab,0x000000f9,0x000000fa,0x0004003d,
14740x00000006,0x000016ac,0x000016ab,0x00050084,
14750x00000006,0x000016ad,0x0000011c,0x000016ac,
14760x00050080,0x00000006,0x000016ae,0x00000104,
14770x000016ad,0x00050080,0x00000006,0x000016b4,
14780x000016ac,0x00002b67,0x00050086,0x00000006,
14790x000016b5,0x000016b4,0x000000fe,0x00050084,
14800x00000006,0x000016a7,0x00000104,0x000016b5,
14810x00050080,0x00000006,0x000016a8,0x000016ae,
14820x000016a7,0x00050084,0x00000006,0x00001678,
14830x0000014d,0x0000127c,0x00050080,0x00000006,
14840x00001679,0x000016a8,0x00001678,0x00050041,
14850x00000153,0x0000167a,0x000000f9,0x00000151,
14860x0004003d,0x00000007,0x0000167b,0x0000167a,
14870x00050051,0x00000027,0x0000167e,0x00002b6b,
14880x00000000,0x0004007c,0x00000006,0x000016bb,
14890x0000167e,0x00050051,0x00000006,0x000016d4,
14900x0000167b,0x00000000,0x00050095,0x000000a8,
14910x000016d6,0x000016d4,0x00001679,0x00050051,
14920x00000006,0x000016d7,0x000016d6,0x00000001,
14930x00050051,0x00000006,0x000016d8,0x000016d6,
14940x00000000,0x00050051,0x00000006,0x000016db,
14950x0000167b,0x00000001,0x00050080,0x00000006,
14960x000016dd,0x000016db,0x000016d7,0x00050050,
14970x00000007,0x000016de,0x000016d8,0x000016dd,
14980x0004007c,0x00000014,0x000016ce,0x000016de,
14990x00060041,0x000000d8,0x000016c6,0x000016ce,
15000x000000d7,0x000000d7,0x0005003e,0x000016c6,
15010x000016bb,0x00000002,0x00000004,0x00050080,
15020x00000006,0x00001681,0x00001679,0x00000107,
15030x00050051,0x00000027,0x00001685,0x00002b6b,
15040x00000001,0x0004007c,0x00000006,0x000016e4,
15050x00001685,0x00050095,0x000000a8,0x000016ff,
15060x000016d4,0x00001681,0x00050051,0x00000006,
15070x00001700,0x000016ff,0x00000001,0x00050051,
15080x00000006,0x00001701,0x000016ff,0x00000000,
15090x00050080,0x00000006,0x00001706,0x000016db,
15100x00001700,0x00050050,0x00000007,0x00001707,
15110x00001701,0x00001706,0x0004007c,0x00000014,
15120x000016f7,0x00001707,0x00060041,0x000000d8,
15130x000016ef,0x000016f7,0x000000d7,0x000000d7,
15140x0005003e,0x000016ef,0x000016e4,0x00000002,
15150x00000004,0x00050080,0x00000006,0x00001688,
15160x00001679,0x0000010e,0x00050051,0x00000027,
15170x0000168c,0x00002b6b,0x00000002,0x0004007c,
15180x00000006,0x0000170d,0x0000168c,0x00050095,
15190x000000a8,0x00001728,0x000016d4,0x00001688,
15200x00050051,0x00000006,0x00001729,0x00001728,
15210x00000001,0x00050051,0x00000006,0x0000172a,
15220x00001728,0x00000000,0x00050080,0x00000006,
15230x0000172f,0x000016db,0x00001729,0x00050050,
15240x00000007,0x00001730,0x0000172a,0x0000172f,
15250x0004007c,0x00000014,0x00001720,0x00001730,
15260x00060041,0x000000d8,0x00001718,0x00001720,
15270x000000d7,0x000000d7,0x0005003e,0x00001718,
15280x0000170d,0x00000002,0x00000004,0x00050080,
15290x00000006,0x0000168f,0x00001679,0x00000115,
15300x00050051,0x00000027,0x00001693,0x00002b69,
15310x00000000,0x0004007c,0x00000006,0x00001736,
15320x00001693,0x00050095,0x000000a8,0x00001751,
15330x000016d4,0x0000168f,0x00050051,0x00000006,
15340x00001752,0x00001751,0x00000001,0x00050051,
15350x00000006,0x00001753,0x00001751,0x00000000,
15360x00050080,0x00000006,0x00001758,0x000016db,
15370x00001752,0x00050050,0x00000007,0x00001759,
15380x00001753,0x00001758,0x0004007c,0x00000014,
15390x00001749,0x00001759,0x00060041,0x000000d8,
15400x00001741,0x00001749,0x000000d7,0x000000d7,
15410x0005003e,0x00001741,0x00001736,0x00000002,
15420x00000004,0x00050080,0x00000006,0x00001696,
15430x00001679,0x0000011c,0x00050051,0x00000027,
15440x0000169a,0x00002b69,0x00000001,0x0004007c,
15450x00000006,0x0000175f,0x0000169a,0x00050095,
15460x000000a8,0x0000177a,0x000016d4,0x00001696,
15470x00050051,0x00000006,0x0000177b,0x0000177a,
15480x00000001,0x00050051,0x00000006,0x0000177c,
15490x0000177a,0x00000000,0x00050080,0x00000006,
15500x00001781,0x000016db,0x0000177b,0x00050050,
15510x00000007,0x00001782,0x0000177c,0x00001781,
15520x0004007c,0x00000014,0x00001772,0x00001782,
15530x00060041,0x000000d8,0x0000176a,0x00001772,
15540x000000d7,0x000000d7,0x0005003e,0x0000176a,
15550x0000175f,0x00000002,0x00000004,0x00050080,
15560x00000006,0x0000169d,0x00001679,0x00000186,
15570x00050051,0x00000027,0x000016a1,0x00002b69,
15580x00000002,0x0004007c,0x00000006,0x00001788,
15590x000016a1,0x00050095,0x000000a8,0x000017a3,
15600x000016d4,0x0000169d,0x00050051,0x00000006,
15610x000017a4,0x000017a3,0x00000001,0x00050051,
15620x00000006,0x000017a5,0x000017a3,0x00000000,
15630x00050080,0x00000006,0x000017aa,0x000016db,
15640x000017a4,0x00050050,0x00000007,0x000017ab,
15650x000017a5,0x000017aa,0x0004007c,0x00000014,
15660x0000179b,0x000017ab,0x00060041,0x000000d8,
15670x00001793,0x0000179b,0x000000d7,0x000000d7,
15680x0005003e,0x00001793,0x00001788,0x00000002,
15690x00000004,0x000300f7,0x000017eb,0x00000000,
15700x000300fb,0x000000a3,0x000017ba,0x000200f8,
15710x000017ba,0x000500bc,0x0000002f,0x000017f2,
15720x0000167e,0x00001693,0x000300f7,0x000017f9,
15730x00000000,0x000400fa,0x000017f2,0x000017f3,
15740x000017f9,0x000200f8,0x000017f3,0x000500bc,
15750x0000002f,0x000017f8,0x00001685,0x0000169a,
15760x000200f9,0x000017f9,0x000200f8,0x000017f9,
15770x000700f5,0x0000002f,0x000017fa,0x000017f2,
15780x000017ba,0x000017f8,0x000017f3,0x000300f7,
15790x00001801,0x00000000,0x000400fa,0x000017fa,
15800x000017fb,0x00001801,0x000200f8,0x000017fb,
15810x000500bc,0x0000002f,0x00001800,0x0000168c,
15820x000016a1,0x000200f9,0x00001801,0x000200f8,
15830x00001801,0x000700f5,0x0000002f,0x00001802,
15840x000017fa,0x000017f9,0x00001800,0x000017fb,
15850x000400a8,0x0000002f,0x00001803,0x00001802,
15860x000300f7,0x000017bf,0x00000000,0x000400fa,
15870x00001803,0x000017be,0x000017bf,0x000200f8,
15880x000017be,0x000200f9,0x000017eb,0x000200f8,
15890x000017bf,0x00050081,0x0000004b,0x000017c2,
15900x00002b6b,0x00002b69,0x0005008e,0x0000004b,
15910x000017c3,0x000017c2,0x000001ea,0x00050095,
15920x000000a8,0x00001813,0x000016d4,0x000000a3,
15930x00050051,0x00000006,0x00001814,0x00001813,
15940x00000001,0x00050051,0x00000006,0x00001815,
15950x00001813,0x00000000,0x00050080,0x00000006,
15960x0000181a,0x000016db,0x00001814,0x00050050,
15970x00000007,0x0000181b,0x00001815,0x0000181a,
15980x0004007c,0x00000014,0x0000180b,0x0000181b,
15990x00060041,0x000000d8,0x000017c8,0x0000180b,
16000x000000d7,0x000000d7,0x00050051,0x00000027,
16010x000017ca,0x000017c3,0x00000000,0x0004007c,
16020x00000006,0x00001821,0x000017ca,0x000500c7,
16030x00000006,0x00001823,0x00001821,0x0000012d,
16040x000500ab,0x0000002f,0x00001824,0x00001823,
16050x000000a3,0x000300f7,0x0000182b,0x00000000,
16060x000400fa,0x00001824,0x00001825,0x00001828,
16070x000200f8,0x00001825,0x000400c8,0x00000006,
16080x00001827,0x00001821,0x000200f9,0x0000182b,
16090x000200f8,0x00001828,0x000500c5,0x00000006,
16100x0000182a,0x00001821,0x0000012d,0x000200f9,
16110x0000182b,0x000200f8,0x0000182b,0x000700f5,
16120x00000006,0x00002b22,0x00001827,0x00001825,
16130x0000182a,0x00001828,0x000700ed,0x00000006,
16140x000017cc,0x000017c8,0x000000ad,0x000000a3,
16150x00002b22,0x00060041,0x000000d8,0x000017ce,
16160x0000180b,0x000000d7,0x00000151,0x00050051,
16170x00000027,0x000017d0,0x000017c3,0x00000001,
16180x0004007c,0x00000006,0x00001832,0x000017d0,
16190x000500c7,0x00000006,0x00001834,0x00001832,
16200x0000012d,0x000500ab,0x0000002f,0x00001835,
16210x00001834,0x000000a3,0x000300f7,0x0000183c,
16220x00000000,0x000400fa,0x00001835,0x00001836,
16230x00001839,0x000200f8,0x00001836,0x000400c8,
16240x00000006,0x00001838,0x00001832,0x000200f9,
16250x0000183c,0x000200f8,0x00001839,0x000500c5,
16260x00000006,0x0000183b,0x00001832,0x0000012d,
16270x000200f9,0x0000183c,0x000200f8,0x0000183c,
16280x000700f5,0x00000006,0x00002b23,0x00001838,
16290x00001836,0x0000183b,0x00001839,0x000700ed,
16300x00000006,0x000017d2,0x000017ce,0x000000ad,
16310x000000a3,0x00002b23,0x00060041,0x000000d8,
16320x000017d4,0x0000180b,0x000000d7,0x00000202,
16330x00050051,0x00000027,0x000017d6,0x000017c3,
16340x00000002,0x0004007c,0x00000006,0x00001843,
16350x000017d6,0x000500c7,0x00000006,0x00001845,
16360x00001843,0x0000012d,0x000500ab,0x0000002f,
16370x00001846,0x00001845,0x000000a3,0x000300f7,
16380x0000184d,0x00000000,0x000400fa,0x00001846,
16390x00001847,0x0000184a,0x000200f8,0x00001847,
16400x000400c8,0x00000006,0x00001849,0x00001843,
16410x000200f9,0x0000184d,0x000200f8,0x0000184a,
16420x000500c5,0x00000006,0x0000184c,0x00001843,
16430x0000012d,0x000200f9,0x0000184d,0x000200f8,
16440x0000184d,0x000700f5,0x00000006,0x00002b24,
16450x00001849,0x00001847,0x0000184c,0x0000184a,
16460x000700ed,0x00000006,0x000017d8,0x000017d4,
16470x000000ad,0x000000a3,0x00002b24,0x00060041,
16480x000000d8,0x000017da,0x0000180b,0x000000d7,
16490x0000020a,0x000300f7,0x0000185e,0x00000000,
16500x000400fa,0x00001824,0x00001858,0x0000185b,
16510x000200f8,0x00001858,0x000400c8,0x00000006,
16520x0000185a,0x00001821,0x000200f9,0x0000185e,
16530x000200f8,0x0000185b,0x000500c5,0x00000006,
16540x0000185d,0x00001821,0x0000012d,0x000200f9,
16550x0000185e,0x000200f8,0x0000185e,0x000700f5,
16560x00000006,0x00002b25,0x0000185a,0x00001858,
16570x0000185d,0x0000185b,0x000700ef,0x00000006,
16580x000017de,0x000017da,0x000000ad,0x000000a3,
16590x00002b25,0x00060041,0x000000d8,0x000017e0,
16600x0000180b,0x000000d7,0x00000212,0x000300f7,
16610x0000186f,0x00000000,0x000400fa,0x00001835,
16620x00001869,0x0000186c,0x000200f8,0x00001869,
16630x000400c8,0x00000006,0x0000186b,0x00001832,
16640x000200f9,0x0000186f,0x000200f8,0x0000186c,
16650x000500c5,0x00000006,0x0000186e,0x00001832,
16660x0000012d,0x000200f9,0x0000186f,0x000200f8,
16670x0000186f,0x000700f5,0x00000006,0x00002b26,
16680x0000186b,0x00001869,0x0000186e,0x0000186c,
16690x000700ef,0x00000006,0x000017e4,0x000017e0,
16700x000000ad,0x000000a3,0x00002b26,0x00060041,
16710x000000d8,0x000017e6,0x0000180b,0x000000d7,
16720x0000021a,0x000300f7,0x00001880,0x00000000,
16730x000400fa,0x00001846,0x0000187a,0x0000187d,
16740x000200f8,0x0000187a,0x000400c8,0x00000006,
16750x0000187c,0x00001843,0x000200f9,0x00001880,
16760x000200f8,0x0000187d,0x000500c5,0x00000006,
16770x0000187f,0x00001843,0x0000012d,0x000200f9,
16780x00001880,0x000200f8,0x00001880,0x000700f5,
16790x00000006,0x00002b27,0x0000187c,0x0000187a,
16800x0000187f,0x0000187d,0x000700ef,0x00000006,
16810x000017ea,0x000017e6,0x000000ad,0x000000a3,
16820x00002b27,0x000200f9,0x000017eb,0x000200f8,
16830x000017eb,0x000200f9,0x00000a4d,0x000200f8,
16840x00000a51,0x000500aa,0x0000002f,0x00000a54,
16850x000009eb,0x0000016d,0x000300f7,0x00000a56,
16860x00000000,0x000400fa,0x00000a54,0x00000a55,
16870x00000a5a,0x000200f8,0x00000a55,0x00050084,
16880x00000006,0x000018e9,0x00000104,0x000009e9,
16890x000200f9,0x000018ea,0x000200f8,0x000018ea,
16900x000700f5,0x00000006,0x00002ad4,0x000000a3,
16910x00000a55,0x000018fb,0x000018ee,0x000500b0,
16920x0000002f,0x000018ed,0x00002ad4,0x00000115,
16930x000400f6,0x000018fc,0x000018ee,0x00000000,
16940x000400fa,0x000018ed,0x000018ee,0x000018fc,
16950x000200f8,0x000018ee,0x00050084,0x00000006,
16960x000018f2,0x00000107,0x00002ad4,0x00050080,
16970x00000006,0x000018f3,0x000018e9,0x000018f2,
16980x00050041,0x00000153,0x000018f4,0x000000f9,
16990x00000202,0x0004003d,0x00000007,0x000018f5,
17000x000018f4,0x00050051,0x00000006,0x00001ab6,
17010x000018f5,0x00000000,0x00050095,0x000000a8,
17020x00001ab8,0x00001ab6,0x000018f3,0x00050051,
17030x00000006,0x00001ab9,0x00001ab8,0x00000001,
17040x00050051,0x00000006,0x00001aba,0x00001ab8,
17050x00000000,0x00050051,0x00000006,0x00001abd,
17060x000018f5,0x00000001,0x00050080,0x00000006,
17070x00001abf,0x00001abd,0x00001ab9,0x00050050,
17080x00000007,0x00001ac0,0x00001aba,0x00001abf,
17090x0004007c,0x00000014,0x00001ab0,0x00001ac0,
17100x00060041,0x000000d8,0x00001aa7,0x00001ab0,
17110x000000d7,0x000000d7,0x0006003d,0x00000006,
17120x00001aa8,0x00001aa7,0x00000002,0x00000004,
17130x0004007c,0x00000027,0x000018f7,0x00001aa8,
17140x00050041,0x00000028,0x000018f8,0x00001884,
17150x00002ad4,0x0003003e,0x000018f8,0x000018f7,
17160x00050080,0x00000006,0x000018fb,0x00002ad4,
17170x00000151,0x000200f9,0x000018ea,0x000200f8,
17180x000018fc,0x00050080,0x00000006,0x000018fe,
17190x000018e9,0x00000365,0x00050041,0x00000153,
17200x000018ff,0x000000f9,0x00000202,0x0004003d,
17210x00000007,0x00001900,0x000018ff,0x00050051,
17220x00000006,0x00001ad7,0x00001900,0x00000000,
17230x00050095,0x000000a8,0x00001ad9,0x00001ad7,
17240x000018fe,0x00050051,0x00000006,0x00001ada,
17250x00001ad9,0x00000001,0x00050051,0x00000006,
17260x00001adb,0x00001ad9,0x00000000,0x00050051,
17270x00000006,0x00001ade,0x00001900,0x00000001,
17280x00050080,0x00000006,0x00001ae0,0x00001ade,
17290x00001ada,0x00050050,0x00000007,0x00001ae1,
17300x00001adb,0x00001ae0,0x0004007c,0x00000014,
17310x00001ad1,0x00001ae1,0x00060041,0x000000d8,
17320x00001ac8,0x00001ad1,0x000000d7,0x000000d7,
17330x0006003d,0x00000006,0x00001ac9,0x00001ac8,
17340x00000002,0x00000004,0x00050080,0x00000006, 8880x00000002,0x00000004,0x00050080,0x00000006,
17350x00001903,0x000018e9,0x00000371,0x00050095, 8890x00001005,0x00003148,0x00000107,0x000200f9,
17360x000000a8,0x00001afa,0x00001ad7,0x00001903, 8900x00000fe9,0x000200f8,0x00001006,0x000200f9,
17370x00050051,0x00000006,0x00001afb,0x00001afa, 8910x00000bb6,0x000200f8,0x00000b3d,0x000500aa,
17380x00000001,0x00050051,0x00000006,0x00001afc, 8920x0000002f,0x00000b45,0x00000b13,0x00000239,
17390x00001afa,0x00000000,0x00050080,0x00000006, 8930x000300f7,0x00000b47,0x00000000,0x000400fa,
17400x00001b01,0x00001ade,0x00001afb,0x00050050, 8940x00000b45,0x00000b46,0x00000b47,0x000200f8,
17410x00000007,0x00001b02,0x00001afc,0x00001b01, 8950x00000b46,0x000500aa,0x0000002f,0x00000b49,
17420x0004007c,0x00000014,0x00001af2,0x00001b02, 8960x00000b11,0x000000a6,0x000300f7,0x00000b4b,
17430x00060041,0x000000d8,0x00001ae9,0x00001af2, 8970x00000000,0x000400fa,0x00000b49,0x00000b4a,
17440x000000d7,0x000000d7,0x0006003d,0x00000006, 8980x00000b4b,0x000200f8,0x00000b4a,0x00050041,
17450x00001aea,0x00001ae9,0x00000002,0x00000004, 8990x000000fe,0x000010d1,0x000000fc,0x00000308,
17460x00050080,0x00000006,0x00001908,0x000018e9, 9000x0004003d,0x00000006,0x000010d2,0x000010d1,
17470x0000037b,0x00050095,0x000000a8,0x00001b1b, 9010x00050041,0x000000fe,0x000010d3,0x000000fc,
17480x00001ad7,0x00001908,0x00050051,0x00000006, 9020x0000096c,0x0004003d,0x00000006,0x000010d4,
17490x00001b1c,0x00001b1b,0x00000001,0x00050051, 9030x000010d3,0x00050080,0x00000006,0x000010d6,
17500x00000006,0x00001b1d,0x00001b1b,0x00000000, 9040x000010d4,0x000010d2,0x00050041,0x000000fe,
17510x00050080,0x00000006,0x00001b22,0x00001ade, 9050x00001167,0x000000fc,0x000000fd,0x0004003d,
17520x00001b1c,0x00050050,0x00000007,0x00001b23, 9060x00000006,0x00001168,0x00001167,0x00050084,
17530x00001b1d,0x00001b22,0x0004007c,0x00000014, 9070x00000006,0x00001169,0x0000011f,0x00001168,
17540x00001b13,0x00001b23,0x00060041,0x000000d8, 9080x00050080,0x00000006,0x0000116a,0x00000107,
17550x00001b0a,0x00001b13,0x000000d7,0x000000d7, 9090x00001169,0x00050080,0x00000006,0x00001170,
17560x0006003d,0x00000006,0x00001b0b,0x00001b0a, 9100x00001168,0x0000319c,0x00050086,0x00000006,
17570x00000002,0x00000004,0x00050080,0x00000006, 9110x00001171,0x00001170,0x00000101,0x00050084,
17580x0000190d,0x000018e9,0x00000385,0x00050095, 9120x00000006,0x00001163,0x00000107,0x00001171,
17590x000000a8,0x00001b3c,0x00001ad7,0x0000190d, 9130x00050080,0x00000006,0x00001164,0x0000116a,
17600x00050051,0x00000006,0x00001b3d,0x00001b3c, 9140x00001163,0x00050084,0x00000006,0x00001138,
17610x00000001,0x00050051,0x00000006,0x00001b3e, 9150x00000150,0x000010d6,0x00050080,0x00000006,
17620x00001b3c,0x00000000,0x00050080,0x00000006, 9160x00001139,0x00001164,0x00001138,0x00050041,
17630x00001b43,0x00001ade,0x00001b3d,0x00050050, 9170x00000156,0x0000113a,0x000000fc,0x00000154,
17640x00000007,0x00001b44,0x00001b3e,0x00001b43, 9180x0004003d,0x00000007,0x0000113b,0x0000113a,
17650x0004007c,0x00000014,0x00001b34,0x00001b44, 9190x00050051,0x00000006,0x00001188,0x0000113b,
17660x00060041,0x000000d8,0x00001b2b,0x00001b34, 9200x00000000,0x00050095,0x000000ab,0x0000118a,
17670x000000d7,0x000000d7,0x0006003d,0x00000006, 9210x00001188,0x00001139,0x00050051,0x00000006,
17680x00001b2c,0x00001b2b,0x00000002,0x00000004, 9220x0000118b,0x0000118a,0x00000001,0x00050051,
17690x00050041,0x000000fb,0x00001912,0x000000f9, 9230x00000006,0x0000118c,0x0000118a,0x00000000,
17700x00000229,0x0004003d,0x00000006,0x00001913, 9240x00050051,0x00000006,0x0000118f,0x0000113b,
17710x00001912,0x00050084,0x00000006,0x00001915, 9250x00000001,0x00050080,0x00000006,0x00001191,
17720x00000225,0x000009e9,0x00050080,0x00000006, 9260x0000118f,0x0000118b,0x00050050,0x00000007,
17730x00001916,0x00001913,0x00001915,0x000200f9, 9270x00001192,0x0000118c,0x00001191,0x0004007c,
17740x00001917,0x000200f8,0x00001917,0x000700f5, 9280x00000014,0x00001182,0x00001192,0x00060041,
17750x00000006,0x00002ad5,0x000000a3,0x000018fc, 9290x000000db,0x00001179,0x00001182,0x000000da,
17760x00001928,0x0000191b,0x000500b0,0x0000002f, 9300x000000da,0x0006003d,0x00000006,0x0000117a,
17770x0000191a,0x00002ad5,0x00000115,0x000400f6, 9310x00001179,0x00000002,0x00000004,0x00050080,
17780x00001929,0x0000191b,0x00000000,0x000400fa, 9320x00000006,0x00001140,0x00001139,0x0000010a,
17790x0000191a,0x0000191b,0x00001929,0x000200f8, 9330x00050095,0x000000ab,0x000011ab,0x00001188,
17800x0000191b,0x00050084,0x00000006,0x0000191e, 9340x00001140,0x00050051,0x00000006,0x000011ac,
17810x00000107,0x00002ad5,0x00050080,0x00000006, 9350x000011ab,0x00000001,0x00050051,0x00000006,
17820x0000191f,0x00001916,0x0000191e,0x00050041, 9360x000011ad,0x000011ab,0x00000000,0x00050080,
17830x00000153,0x00001921,0x000000f9,0x000000d7, 9370x00000006,0x000011b2,0x0000118f,0x000011ac,
17840x0004003d,0x00000007,0x00001922,0x00001921, 9380x00050050,0x00000007,0x000011b3,0x000011ad,
17850x00050041,0x00000028,0x00001923,0x00001884, 9390x000011b2,0x0004007c,0x00000014,0x000011a3,
17860x00002ad5,0x0004003d,0x00000027,0x00001924, 9400x000011b3,0x00060041,0x000000db,0x0000119a,
17870x00001923,0x0004007c,0x00000006,0x00001b4a, 9410x000011a3,0x000000da,0x000000da,0x0006003d,
17880x00001924,0x00050051,0x00000006,0x00001b63, 9420x00000006,0x0000119b,0x0000119a,0x00000002,
17890x00001922,0x00000000,0x00050095,0x000000a8, 9430x00000004,0x00050080,0x00000006,0x00001146,
17900x00001b65,0x00001b63,0x0000191f,0x00050051, 9440x00001139,0x00000111,0x00050095,0x000000ab,
17910x00000006,0x00001b66,0x00001b65,0x00000001, 9450x000011cc,0x00001188,0x00001146,0x00050051,
17920x00050051,0x00000006,0x00001b67,0x00001b65, 9460x00000006,0x000011cd,0x000011cc,0x00000001,
17930x00000000,0x00050051,0x00000006,0x00001b6a, 9470x00050051,0x00000006,0x000011ce,0x000011cc,
17940x00001922,0x00000001,0x00050080,0x00000006, 9480x00000000,0x00050080,0x00000006,0x000011d3,
17950x00001b6c,0x00001b6a,0x00001b66,0x00050050, 9490x0000118f,0x000011cd,0x00050050,0x00000007,
17960x00000007,0x00001b6d,0x00001b67,0x00001b6c, 9500x000011d4,0x000011ce,0x000011d3,0x0004007c,
17970x0004007c,0x00000014,0x00001b5d,0x00001b6d, 9510x00000014,0x000011c4,0x000011d4,0x00060041,
17980x00060041,0x000000d8,0x00001b55,0x00001b5d, 9520x000000db,0x000011bb,0x000011c4,0x000000da,
17990x000000d7,0x000000d7,0x0005003e,0x00001b55, 9530x000000da,0x0006003d,0x00000006,0x000011bc,
18000x00001b4a,0x00000002,0x00000004,0x00050080, 9540x000011bb,0x00000002,0x00000004,0x00050080,
18010x00000006,0x00001928,0x00002ad5,0x00000151, 9550x00000006,0x0000114d,0x00001139,0x00000118,
18020x000200f9,0x00001917,0x000200f8,0x00001929, 9560x00050095,0x000000ab,0x000011ed,0x00001188,
18030x00050080,0x00000006,0x0000192b,0x00001916, 9570x0000114d,0x00050051,0x00000006,0x000011ee,
18040x00000365,0x00050041,0x00000153,0x0000192c, 9580x000011ed,0x00000001,0x00050051,0x00000006,
18050x000000f9,0x000000d7,0x0004003d,0x00000007, 9590x000011ef,0x000011ed,0x00000000,0x00050080,
18060x0000192d,0x0000192c,0x00050051,0x00000006, 9600x00000006,0x000011f4,0x0000118f,0x000011ee,
18070x00001b83,0x0000192d,0x00000000,0x00050095, 9610x00050050,0x00000007,0x000011f5,0x000011ef,
18080x000000a8,0x00001b85,0x00001b83,0x0000192b, 9620x000011f4,0x0004007c,0x00000014,0x000011e5,
18090x00050051,0x00000006,0x00001b86,0x00001b85, 9630x000011f5,0x00060041,0x000000db,0x000011dc,
18100x00000001,0x00050051,0x00000006,0x00001b87, 9640x000011e5,0x000000da,0x000000da,0x0006003d,
18110x00001b85,0x00000000,0x00050051,0x00000006, 9650x00000006,0x000011dd,0x000011dc,0x00000002,
18120x00001b8a,0x0000192d,0x00000001,0x00050080, 9660x00000004,0x00050080,0x00000006,0x00001153,
18130x00000006,0x00001b8c,0x00001b8a,0x00001b86, 9670x00001139,0x0000011f,0x00050095,0x000000ab,
18140x00050050,0x00000007,0x00001b8d,0x00001b87, 9680x0000120e,0x00001188,0x00001153,0x00050051,
18150x00001b8c,0x0004007c,0x00000014,0x00001b7d, 9690x00000006,0x0000120f,0x0000120e,0x00000001,
18160x00001b8d,0x00060041,0x000000d8,0x00001b75, 9700x00050051,0x00000006,0x00001210,0x0000120e,
18170x00001b7d,0x000000d7,0x000000d7,0x0005003e, 9710x00000000,0x00050080,0x00000006,0x00001215,
18180x00001b75,0x00001ac9,0x00000002,0x00000004, 9720x0000118f,0x0000120f,0x00050050,0x00000007,
18190x00050080,0x00000006,0x00001931,0x00001916, 9730x00001216,0x00001210,0x00001215,0x0004007c,
18200x00000371,0x00050095,0x000000a8,0x00001ba5, 9740x00000014,0x00001206,0x00001216,0x00060041,
18210x00001b83,0x00001931,0x00050051,0x00000006, 9750x000000db,0x000011fd,0x00001206,0x000000da,
18220x00001ba6,0x00001ba5,0x00000001,0x00050051, 9760x000000da,0x0006003d,0x00000006,0x000011fe,
18230x00000006,0x00001ba7,0x00001ba5,0x00000000, 9770x000011fd,0x00000002,0x00000004,0x00050080,
18240x00050080,0x00000006,0x00001bac,0x00001b8a, 9780x00000006,0x00001159,0x00001139,0x00000189,
18250x00001ba6,0x00050050,0x00000007,0x00001bad, 9790x00050095,0x000000ab,0x0000122f,0x00001188,
18260x00001ba7,0x00001bac,0x0004007c,0x00000014, 9800x00001159,0x00050051,0x00000006,0x00001230,
18270x00001b9d,0x00001bad,0x00060041,0x000000d8, 9810x0000122f,0x00000001,0x00050051,0x00000006,
18280x00001b95,0x00001b9d,0x000000d7,0x000000d7, 9820x00001231,0x0000122f,0x00000000,0x00050080,
18290x0005003e,0x00001b95,0x00001aea,0x00000002, 9830x00000006,0x00001236,0x0000118f,0x00001230,
18300x00000004,0x000500aa,0x0000002f,0x00001bb2, 9840x00050050,0x00000007,0x00001237,0x00001231,
18310x00001b0b,0x000000a3,0x000300f7,0x00001bb7, 9850x00001236,0x0004007c,0x00000014,0x00001227,
18320x00000000,0x000400fa,0x00001bb2,0x00001bb3, 9860x00001237,0x00060041,0x000000db,0x0000121e,
18330x00001bb7,0x000200f8,0x00001bb3,0x000500aa, 9870x00001227,0x000000da,0x000000da,0x0006003d,
18340x0000002f,0x00001bb6,0x00001b2c,0x000000a3, 9880x00000006,0x0000121f,0x0000121e,0x00000002,
18350x000200f9,0x00001bb7,0x000200f8,0x00001bb7, 9890x00000004,0x00050041,0x000000fe,0x000010da,
18360x000700f5,0x0000002f,0x00001bb8,0x00001bb2, 9900x000000fc,0x00000224,0x0004003d,0x00000006,
18370x00001929,0x00001bb6,0x00001bb3,0x000400a8, 9910x000010db,0x000010da,0x000500ab,0x0000002f,
18380x0000002f,0x0000193c,0x00001bb8,0x000300f7, 9920x000010dc,0x000010db,0x000000a6,0x000600a9,
18390x000019d2,0x00000000,0x000400fa,0x0000193c, 9930x00000006,0x000010dd,0x000010dc,0x000000a6,
18400x0000193d,0x000019d2,0x000200f8,0x0000193d, 9940x00000130,0x000500c5,0x00000006,0x000010de,
18410x00050041,0x00000153,0x0000193f,0x000000f9, 9950x000010dd,0x00000239,0x00050041,0x00000156,
18420x0000021a,0x0004003d,0x00000007,0x00001940, 9960x000010df,0x000000fc,0x000000da,0x0004003d,
18430x0000193f,0x00050051,0x00000006,0x00001bc0, 9970x00000007,0x000010e0,0x000010df,0x00050051,
18440x00001940,0x00000000,0x00050095,0x000000a8, 9980x00000006,0x0000124d,0x000010e0,0x00000000,
18450x00001bc1,0x00001b0b,0x00001bc0,0x00050051, 9990x00050095,0x000000ab,0x0000124f,0x0000124d,
18460x00000006,0x00001bc2,0x00001bc1,0x00000001, 10000x000000a6,0x00050051,0x00000006,0x00001250,
18470x00050051,0x00000006,0x00001bc3,0x00001bc1, 10010x0000124f,0x00000001,0x00050051,0x00000006,
18480x00000000,0x00050051,0x00000006,0x00001bc8, 10020x00001251,0x0000124f,0x00000000,0x00050051,
18490x00001940,0x00000001,0x00050080,0x00000006, 10030x00000006,0x00001254,0x000010e0,0x00000001,
18500x00001bc9,0x00001b2c,0x00001bc8,0x00050080, 10040x00050080,0x00000006,0x00001256,0x00001254,
18510x00000006,0x00001bcb,0x00001bc9,0x00001bc2, 10050x00001250,0x00050050,0x00000007,0x00001257,
18520x00050095,0x000000a8,0x00001be5,0x00001bc3, 10060x00001251,0x00001256,0x0004007c,0x00000014,
18530x00000365,0x00050051,0x00000006,0x00001be6, 10070x00001247,0x00001257,0x00060041,0x000000db,
18540x00001be5,0x00000001,0x00050051,0x00000006, 10080x0000123f,0x00001247,0x000000da,0x000000da,
18550x00001be7,0x00001be5,0x00000000,0x00050080, 10090x0005003e,0x0000123f,0x000010de,0x00000002,
18560x00000006,0x00001bec,0x00001bcb,0x00001be6, 10100x00000004,0x00050041,0x000000fe,0x000010e2,
18570x00050050,0x00000007,0x00001bed,0x00001be7, 10110x000000fc,0x00000a97,0x0004003d,0x00000006,
18580x00001bec,0x0004007c,0x00000014,0x00001bdd, 10120x000010e3,0x000010e2,0x00050086,0x00000006,
18590x00001bed,0x00060041,0x000000d8,0x00001bd4, 10130x000010e4,0x000010e3,0x00000107,0x00050095,
18600x00001bdd,0x000000d7,0x000000d7,0x0006003d, 10140x000000ab,0x0000126f,0x0000124d,0x0000010a,
18610x00000006,0x00001bd5,0x00001bd4,0x00000002, 10150x00050051,0x00000006,0x00001270,0x0000126f,
18620x00000004,0x00050095,0x000000a8,0x00001c06, 10160x00000001,0x00050051,0x00000006,0x00001271,
18630x00001bc3,0x0000011c,0x00050051,0x00000006, 10170x0000126f,0x00000000,0x00050080,0x00000006,
18640x00001c07,0x00001c06,0x00000001,0x00050051, 10180x00001276,0x00001254,0x00001270,0x00050050,
18650x00000006,0x00001c08,0x00001c06,0x00000000, 10190x00000007,0x00001277,0x00001271,0x00001276,
18660x00050080,0x00000006,0x00001c0d,0x00001bcb, 10200x0004007c,0x00000014,0x00001267,0x00001277,
18670x00001c07,0x00050050,0x00000007,0x00001c0e, 10210x00060041,0x000000db,0x0000125f,0x00001267,
18680x00001c08,0x00001c0d,0x0004007c,0x00000014, 10220x000000da,0x000000da,0x0005003e,0x0000125f,
18690x00001bfe,0x00001c0e,0x00060041,0x000000d8, 10230x000010e4,0x00000002,0x00000004,0x00050095,
18700x00001bf5,0x00001bfe,0x000000d7,0x000000d7, 10240x000000ab,0x0000128f,0x0000124d,0x00000111,
18710x0006003d,0x00000006,0x00001bf6,0x00001bf5, 10250x00050051,0x00000006,0x00001290,0x0000128f,
10260x00000001,0x00050051,0x00000006,0x00001291,
10270x0000128f,0x00000000,0x00050080,0x00000006,
10280x00001296,0x00001254,0x00001290,0x00050050,
10290x00000007,0x00001297,0x00001291,0x00001296,
10300x0004007c,0x00000014,0x00001287,0x00001297,
10310x00060041,0x000000db,0x0000127f,0x00001287,
10320x000000da,0x000000da,0x0005003e,0x0000127f,
10330x000000a6,0x00000002,0x00000004,0x00050095,
10340x000000ab,0x000012af,0x0000124d,0x00000118,
10350x00050051,0x00000006,0x000012b0,0x000012af,
10360x00000001,0x00050051,0x00000006,0x000012b1,
10370x000012af,0x00000000,0x00050080,0x00000006,
10380x000012b6,0x00001254,0x000012b0,0x00050050,
10390x00000007,0x000012b7,0x000012b1,0x000012b6,
10400x0004007c,0x00000014,0x000012a7,0x000012b7,
10410x00060041,0x000000db,0x0000129f,0x000012a7,
10420x000000da,0x000000da,0x0005003e,0x0000129f,
10430x000010d4,0x00000002,0x00000004,0x00050095,
10440x000000ab,0x000012d8,0x0000124d,0x0000011f,
10450x00050051,0x00000006,0x000012d9,0x000012d8,
10460x00000001,0x00050051,0x00000006,0x000012da,
10470x000012d8,0x00000000,0x00050080,0x00000006,
10480x000012df,0x00001254,0x000012d9,0x00050050,
10490x00000007,0x000012e0,0x000012da,0x000012df,
10500x0004007c,0x00000014,0x000012d0,0x000012e0,
10510x00060041,0x000000db,0x000012c8,0x000012d0,
10520x000000da,0x000000da,0x0005003e,0x000012c8,
10530x0000117a,0x00000002,0x00000004,0x00050095,
10540x000000ab,0x00001301,0x0000124d,0x00000189,
10550x00050051,0x00000006,0x00001302,0x00001301,
10560x00000001,0x00050051,0x00000006,0x00001303,
10570x00001301,0x00000000,0x00050080,0x00000006,
10580x00001308,0x00001254,0x00001302,0x00050050,
10590x00000007,0x00001309,0x00001303,0x00001308,
10600x0004007c,0x00000014,0x000012f9,0x00001309,
10610x00060041,0x000000db,0x000012f1,0x000012f9,
10620x000000da,0x000000da,0x0005003e,0x000012f1,
10630x0000119b,0x00000002,0x00000004,0x00050095,
10640x000000ab,0x0000132a,0x0000124d,0x00000150,
10650x00050051,0x00000006,0x0000132b,0x0000132a,
10660x00000001,0x00050051,0x00000006,0x0000132c,
10670x0000132a,0x00000000,0x00050080,0x00000006,
10680x00001331,0x00001254,0x0000132b,0x00050050,
10690x00000007,0x00001332,0x0000132c,0x00001331,
10700x0004007c,0x00000014,0x00001322,0x00001332,
10710x00060041,0x000000db,0x0000131a,0x00001322,
10720x000000da,0x000000da,0x0005003e,0x0000131a,
10730x000011bc,0x00000002,0x00000004,0x00050095,
10740x000000ab,0x00001353,0x0000124d,0x00000463,
10750x00050051,0x00000006,0x00001354,0x00001353,
10760x00000001,0x00050051,0x00000006,0x00001355,
10770x00001353,0x00000000,0x00050080,0x00000006,
10780x0000135a,0x00001254,0x00001354,0x00050050,
10790x00000007,0x0000135b,0x00001355,0x0000135a,
10800x0004007c,0x00000014,0x0000134b,0x0000135b,
10810x00060041,0x000000db,0x00001343,0x0000134b,
10820x000000da,0x000000da,0x0005003e,0x00001343,
10830x000011dd,0x00000002,0x00000004,0x00050095,
10840x000000ab,0x0000137c,0x0000124d,0x00000469,
10850x00050051,0x00000006,0x0000137d,0x0000137c,
10860x00000001,0x00050051,0x00000006,0x0000137e,
10870x0000137c,0x00000000,0x00050080,0x00000006,
10880x00001383,0x00001254,0x0000137d,0x00050050,
10890x00000007,0x00001384,0x0000137e,0x00001383,
10900x0004007c,0x00000014,0x00001374,0x00001384,
10910x00060041,0x000000db,0x0000136c,0x00001374,
10920x000000da,0x000000da,0x0005003e,0x0000136c,
10930x000011fe,0x00000002,0x00000004,0x00050095,
10940x000000ab,0x000013a5,0x0000124d,0x00000347,
10950x00050051,0x00000006,0x000013a6,0x000013a5,
10960x00000001,0x00050051,0x00000006,0x000013a7,
10970x000013a5,0x00000000,0x00050080,0x00000006,
10980x000013ac,0x00001254,0x000013a6,0x00050050,
10990x00000007,0x000013ad,0x000013a7,0x000013ac,
11000x0004007c,0x00000014,0x0000139d,0x000013ad,
11010x00060041,0x000000db,0x00001395,0x0000139d,
11020x000000da,0x000000da,0x0005003e,0x00001395,
11030x0000121f,0x00000002,0x00000004,0x00050041,
11040x000000fe,0x00001110,0x000000fc,0x0000023e,
11050x0004003d,0x00000006,0x00001111,0x00001110,
11060x00050095,0x000000ab,0x000013c5,0x0000124d,
11070x00000352,0x00050051,0x00000006,0x000013c6,
11080x000013c5,0x00000001,0x00050051,0x00000006,
11090x000013c7,0x000013c5,0x00000000,0x00050080,
11100x00000006,0x000013cc,0x00001254,0x000013c6,
11110x00050050,0x00000007,0x000013cd,0x000013c7,
11120x000013cc,0x0004007c,0x00000014,0x000013bd,
11130x000013cd,0x00060041,0x000000db,0x000013b5,
11140x000013bd,0x000000da,0x000000da,0x0005003e,
11150x000013b5,0x00001111,0x00000002,0x00000004,
11160x00050095,0x000000ab,0x000013e5,0x0000124d,
11170x0000035d,0x00050051,0x00000006,0x000013e6,
11180x000013e5,0x00000001,0x00050051,0x00000006,
11190x000013e7,0x000013e5,0x00000000,0x00050080,
11200x00000006,0x000013ec,0x00001254,0x000013e6,
11210x00050050,0x00000007,0x000013ed,0x000013e7,
11220x000013ec,0x0004007c,0x00000014,0x000013dd,
11230x000013ed,0x00060041,0x000000db,0x000013d5,
11240x000013dd,0x000000da,0x000000da,0x0005003e,
11250x000013d5,0x000000a6,0x00000002,0x00000004,
11260x00050084,0x00000006,0x000013f3,0x000010d2,
11270x00000228,0x00050080,0x00000006,0x000013f4,
11280x00001111,0x000013f3,0x000500c2,0x00000006,
11290x000013f5,0x000013f4,0x00000233,0x000500c4,
11300x00000006,0x000013f6,0x000013f5,0x0000020d,
11310x000500c5,0x00000006,0x000013f7,0x000013f6,
11320x00000246,0x00050095,0x000000ab,0x0000140f,
11330x0000124d,0x00000368,0x00050051,0x00000006,
11340x00001410,0x0000140f,0x00000001,0x00050051,
11350x00000006,0x00001411,0x0000140f,0x00000000,
11360x00050080,0x00000006,0x00001416,0x00001254,
11370x00001410,0x00050050,0x00000007,0x00001417,
11380x00001411,0x00001416,0x0004007c,0x00000014,
11390x00001407,0x00001417,0x00060041,0x000000db,
11400x000013ff,0x00001407,0x000000da,0x000000da,
11410x0005003e,0x000013ff,0x000013f7,0x00000002,
11420x00000004,0x00050041,0x000000fe,0x0000111d,
11430x000000fc,0x0000022c,0x0004003d,0x00000006,
11440x0000111e,0x0000111d,0x00050095,0x000000ab,
11450x0000142f,0x0000124d,0x00000374,0x00050051,
11460x00000006,0x00001430,0x0000142f,0x00000001,
11470x00050051,0x00000006,0x00001431,0x0000142f,
11480x00000000,0x00050080,0x00000006,0x00001436,
11490x00001254,0x00001430,0x00050050,0x00000007,
11500x00001437,0x00001431,0x00001436,0x0004007c,
11510x00000014,0x00001427,0x00001437,0x00060041,
11520x000000db,0x0000141f,0x00001427,0x000000da,
11530x000000da,0x0005003e,0x0000141f,0x0000111e,
11540x00000002,0x00000004,0x00050041,0x000000fe,
11550x00001122,0x000000fc,0x000009ef,0x0004003d,
11560x00000006,0x00001123,0x00001122,0x00050095,
11570x000000ab,0x0000144f,0x0000124d,0x0000037e,
11580x00050051,0x00000006,0x00001450,0x0000144f,
11590x00000001,0x00050051,0x00000006,0x00001451,
11600x0000144f,0x00000000,0x00050080,0x00000006,
11610x00001456,0x00001254,0x00001450,0x00050050,
11620x00000007,0x00001457,0x00001451,0x00001456,
11630x0004007c,0x00000014,0x00001447,0x00001457,
11640x00060041,0x000000db,0x0000143f,0x00001447,
11650x000000da,0x000000da,0x0005003e,0x0000143f,
11660x00001123,0x00000002,0x00000004,0x00050095,
11670x000000ab,0x0000146f,0x0000124d,0x00000388,
11680x00050051,0x00000006,0x00001470,0x0000146f,
11690x00000001,0x00050051,0x00000006,0x00001471,
11700x0000146f,0x00000000,0x00050080,0x00000006,
11710x00001476,0x00001254,0x00001470,0x00050050,
11720x00000007,0x00001477,0x00001471,0x00001476,
11730x0004007c,0x00000014,0x00001467,0x00001477,
11740x00060041,0x000000db,0x0000145f,0x00001467,
11750x000000da,0x000000da,0x0005003e,0x0000145f,
11760x000000a6,0x00000002,0x00000004,0x000200f9,
11770x00000b4b,0x000200f8,0x00000b4b,0x000200f9,
11780x00000bb6,0x000200f8,0x00000b47,0x00050041,
11790x000000fe,0x00000b4f,0x000000fc,0x000004d8,
11800x0004003d,0x00000006,0x00000b50,0x00000b4f,
11810x000500ae,0x0000002f,0x00000b51,0x00000b11,
11820x00000b50,0x000300f7,0x00000b53,0x00000000,
11830x000400fa,0x00000b51,0x00000b52,0x00000b53,
11840x000200f8,0x00000b52,0x000200f9,0x00000bb6,
11850x000200f8,0x00000b53,0x000500aa,0x0000002f,
11860x00000b58,0x00000b13,0x00000b57,0x000300f7,
11870x00000b5a,0x00000000,0x000400fa,0x00000b58,
11880x00000b59,0x00000b6a,0x000200f8,0x00000b59,
11890x00050084,0x00000006,0x00000b5c,0x0000010a,
11900x00000b11,0x00050041,0x00000156,0x00000b60,
11910x000000fc,0x00000205,0x0004003d,0x00000007,
11920x00000b61,0x00000b60,0x00050051,0x00000006,
11930x0000148e,0x00000b61,0x00000000,0x00050095,
11940x000000ab,0x00001490,0x0000148e,0x00000b5c,
11950x00050051,0x00000006,0x00001491,0x00001490,
11960x00000001,0x00050051,0x00000006,0x00001492,
11970x00001490,0x00000000,0x00050051,0x00000006,
11980x00001495,0x00000b61,0x00000001,0x00050080,
11990x00000006,0x00001497,0x00001495,0x00001491,
12000x00050050,0x00000007,0x00001498,0x00001492,
12010x00001497,0x0004007c,0x00000014,0x00001488,
12020x00001498,0x00060041,0x000000db,0x0000147f,
12030x00001488,0x000000da,0x000000da,0x0006003d,
12040x00000006,0x00001480,0x0000147f,0x00000002,
12050x00000004,0x00050041,0x00000156,0x00000b65,
12060x000000fc,0x000000da,0x0004003d,0x00000007,
12070x00000b66,0x00000b65,0x00050051,0x00000006,
12080x000014ae,0x00000b66,0x00000000,0x00050095,
12090x000000ab,0x000014b0,0x000014ae,0x00000b5c,
12100x00050051,0x00000006,0x000014b1,0x000014b0,
12110x00000001,0x00050051,0x00000006,0x000014b2,
12120x000014b0,0x00000000,0x00050051,0x00000006,
12130x000014b5,0x00000b66,0x00000001,0x00050080,
12140x00000006,0x000014b7,0x000014b5,0x000014b1,
12150x00050050,0x00000007,0x000014b8,0x000014b2,
12160x000014b7,0x0004007c,0x00000014,0x000014a8,
12170x000014b8,0x00060041,0x000000db,0x000014a0,
12180x000014a8,0x000000da,0x000000da,0x0005003e,
12190x000014a0,0x00001480,0x00000002,0x00000004,
12200x000200f9,0x00000b5a,0x000200f8,0x00000b6a,
12210x000500aa,0x0000002f,0x00000b6d,0x00000b13,
12220x000000a6,0x000300f7,0x00000b6f,0x00000000,
12230x000400fa,0x00000b6d,0x00000b6e,0x00000b90,
12240x000200f8,0x00000b6e,0x00050041,0x000000fe,
12250x00000b70,0x000000fc,0x000009ef,0x0004003d,
12260x00000006,0x00000b71,0x00000b70,0x00050084,
12270x00000006,0x00000b73,0x0000010a,0x00000b11,
12280x00050080,0x00000006,0x00000b74,0x00000b71,
12290x00000b73,0x00050041,0x00000156,0x00000b76,
12300x000000fc,0x000000da,0x0004003d,0x00000007,
12310x00000b77,0x00000b76,0x00050051,0x00000006,
12320x000014ce,0x00000b77,0x00000000,0x00050095,
12330x000000ab,0x000014d0,0x000014ce,0x00000b74,
12340x00050051,0x00000006,0x000014d1,0x000014d0,
12350x00000001,0x00050051,0x00000006,0x000014d2,
12360x000014d0,0x00000000,0x00050051,0x00000006,
12370x000014d5,0x00000b77,0x00000001,0x00050080,
12380x00000006,0x000014d7,0x000014d5,0x000014d1,
12390x00050050,0x00000007,0x000014d8,0x000014d2,
12400x000014d7,0x0004007c,0x00000014,0x000014c8,
12410x000014d8,0x00060041,0x000000db,0x000014c0,
12420x000014c8,0x000000da,0x000000da,0x0005003e,
12430x000014c0,0x00000380,0x00000002,0x00000004,
12440x000500b0,0x0000002f,0x00000b7c,0x00000b11,
12450x000002b7,0x000300f7,0x00000b7e,0x00000000,
12460x000400fa,0x00000b7c,0x00000b7d,0x00000b7e,
12470x000200f8,0x00000b7d,0x00050041,0x00000156,
12480x00000b82,0x000000fc,0x00000154,0x0004003d,
12490x00000007,0x00000b83,0x00000b82,0x00050051,
12500x00000006,0x000014ee,0x00000b83,0x00000000,
12510x00050095,0x000000ab,0x000014f0,0x000014ee,
12520x00000b73,0x00050051,0x00000006,0x000014f1,
12530x000014f0,0x00000001,0x00050051,0x00000006,
12540x000014f2,0x000014f0,0x00000000,0x00050051,
12550x00000006,0x000014f5,0x00000b83,0x00000001,
12560x00050080,0x00000006,0x000014f7,0x000014f5,
12570x000014f1,0x00050050,0x00000007,0x000014f8,
12580x000014f2,0x000014f7,0x0004007c,0x00000014,
12590x000014e8,0x000014f8,0x00060041,0x000000db,
12600x000014e0,0x000014e8,0x000000da,0x000000da,
12610x0005003e,0x000014e0,0x00000380,0x00000002,
12620x00000004,0x00050080,0x00000006,0x00000b89,
12630x00000118,0x00000b73,0x00050095,0x000000ab,
12640x00001510,0x000014ee,0x00000b89,0x00050051,
12650x00000006,0x00001511,0x00001510,0x00000001,
12660x00050051,0x00000006,0x00001512,0x00001510,
12670x00000000,0x00050080,0x00000006,0x00001517,
12680x000014f5,0x00001511,0x00050050,0x00000007,
12690x00001518,0x00001512,0x00001517,0x0004007c,
12700x00000014,0x00001508,0x00001518,0x00060041,
12710x000000db,0x00001500,0x00001508,0x000000da,
12720x000000da,0x0005003e,0x00001500,0x000000a6,
12730x00000002,0x00000004,0x000200f9,0x00000b7e,
12740x000200f8,0x00000b7e,0x000200f9,0x00000b6f,
12750x000200f8,0x00000b90,0x000500aa,0x0000002f,
12760x00000b93,0x00000b13,0x000000b0,0x000300f7,
12770x00000b95,0x00000000,0x000400fa,0x00000b93,
12780x00000b94,0x00000b99,0x000200f8,0x00000b94,
12790x000200f9,0x00001548,0x000200f8,0x00001548,
12800x000700f5,0x00000006,0x0000312e,0x000000a6,
12810x00000b94,0x00001558,0x00001556,0x000500b0,
12820x0000002f,0x0000154b,0x0000312e,0x000002b7,
12830x000400f6,0x00001559,0x00001556,0x00000000,
12840x000400fa,0x0000154b,0x0000154c,0x00001559,
12850x000200f8,0x0000154c,0x00050084,0x00000006,
12860x0000154f,0x000002b7,0x00000b11,0x00050080,
12870x00000006,0x00001551,0x0000154f,0x0000312e,
12880x000300f7,0x00001616,0x00000000,0x000300fb,
12890x000000a6,0x000015f4,0x000200f8,0x000015f4,
12900x00050041,0x000000fe,0x000015f5,0x000000fc,
12910x0000027b,0x0004003d,0x00000006,0x000015f6,
12920x000015f5,0x000500aa,0x0000002f,0x000015f7,
12930x000015f6,0x000000a6,0x000300f7,0x000015fa,
12940x00000000,0x000400fa,0x000015f7,0x000015f8,
12950x000015fa,0x000200f8,0x000015f8,0x000200f9,
12960x00001616,0x000200f8,0x000015fa,0x000500aa,
12970x0000002f,0x000015fd,0x000015f6,0x00000170,
12980x000300f7,0x00001604,0x00000000,0x000400fa,
12990x000015fd,0x000015fe,0x00001604,0x000200f8,
13000x000015fe,0x00050084,0x00000006,0x00001600,
13010x0000010a,0x00001551,0x00050041,0x00000156,
13020x00001601,0x000000fc,0x0000020d,0x0004003d,
13030x00000007,0x00001602,0x00001601,0x00050051,
13040x00000006,0x0000162e,0x00001602,0x00000000,
13050x00050095,0x000000ab,0x00001630,0x0000162e,
13060x00001600,0x00050051,0x00000006,0x00001631,
13070x00001630,0x00000001,0x00050051,0x00000006,
13080x00001632,0x00001630,0x00000000,0x00050051,
13090x00000006,0x00001635,0x00001602,0x00000001,
13100x00050080,0x00000006,0x00001637,0x00001635,
13110x00001631,0x00050050,0x00000007,0x00001638,
13120x00001632,0x00001637,0x0004007c,0x00000014,
13130x00001628,0x00001638,0x00060041,0x000000db,
13140x0000161f,0x00001628,0x000000da,0x000000da,
13150x0006003d,0x00000006,0x00001620,0x0000161f,
13160x00000002,0x00000004,0x000200f9,0x00001616,
13170x000200f8,0x00001604,0x000500c2,0x00000006,
13180x00001606,0x00001551,0x00000154,0x00050084,
13190x00000006,0x00001607,0x0000010a,0x00001606,
13200x00050041,0x00000156,0x00001608,0x000000fc,
13210x0000020d,0x0004003d,0x00000007,0x00001609,
13220x00001608,0x00050051,0x00000006,0x0000164f,
13230x00001609,0x00000000,0x00050095,0x000000ab,
13240x00001651,0x0000164f,0x00001607,0x00050051,
13250x00000006,0x00001652,0x00001651,0x00000001,
13260x00050051,0x00000006,0x00001653,0x00001651,
13270x00000000,0x00050051,0x00000006,0x00001656,
13280x00001609,0x00000001,0x00050080,0x00000006,
13290x00001658,0x00001656,0x00001652,0x00050050,
13300x00000007,0x00001659,0x00001653,0x00001658,
13310x0004007c,0x00000014,0x00001649,0x00001659,
13320x00060041,0x000000db,0x00001640,0x00001649,
13330x000000da,0x000000da,0x0006003d,0x00000006,
13340x00001641,0x00001640,0x00000002,0x00000004,
13350x000500c7,0x00000006,0x0000160c,0x00001551,
13360x000000b0,0x000500ab,0x0000002f,0x0000160d,
13370x0000160c,0x000000a6,0x000300f7,0x00001614,
13380x00000000,0x000400fa,0x0000160d,0x0000160e,
13390x00001611,0x000200f8,0x0000160e,0x000500c2,
13400x00000006,0x00001610,0x00001641,0x0000023e,
13410x000200f9,0x00001614,0x000200f8,0x00001611,
13420x000500c7,0x00000006,0x00001613,0x00001641,
13430x000002a3,0x000200f9,0x00001614,0x000200f8,
13440x00001614,0x000700f5,0x00000006,0x00003138,
13450x00001610,0x0000160e,0x00001613,0x00001611,
13460x000200f9,0x00001616,0x000200f8,0x00001616,
13470x000900f5,0x00000006,0x00003139,0x00001551,
13480x000015f8,0x00001620,0x000015fe,0x00003138,
13490x00001614,0x00050041,0x000000fe,0x0000166a,
13500x000000fc,0x00000250,0x0004003d,0x00000006,
13510x0000166b,0x0000166a,0x00050084,0x00000006,
13520x0000166c,0x00003139,0x0000166b,0x00050041,
13530x00000156,0x0000166d,0x000000fc,0x00000205,
13540x0004003d,0x00000007,0x0000166e,0x0000166d,
13550x00050051,0x00000006,0x00001689,0x0000166e,
13560x00000000,0x00050095,0x000000ab,0x0000168b,
13570x00001689,0x0000166c,0x00050051,0x00000006,
13580x0000168c,0x0000168b,0x00000001,0x00050051,
13590x00000006,0x0000168d,0x0000168b,0x00000000,
13600x00050051,0x00000006,0x00001690,0x0000166e,
13610x00000001,0x00050080,0x00000006,0x00001692,
13620x00001690,0x0000168c,0x00050095,0x000000ab,
13630x000016ac,0x0000168d,0x000000a6,0x00050051,
13640x00000006,0x000016ad,0x000016ac,0x00000001,
13650x00050051,0x00000006,0x000016ae,0x000016ac,
13660x00000000,0x00050080,0x00000006,0x000016b3,
13670x00001692,0x000016ad,0x00050050,0x00000007,
13680x000016b4,0x000016ae,0x000016b3,0x0004007c,
13690x00000014,0x000016a4,0x000016b4,0x00060041,
13700x000000db,0x0000169b,0x000016a4,0x000000da,
13710x000000da,0x0006003d,0x00000006,0x0000169c,
13720x0000169b,0x00000002,0x00000004,0x0004007c,
13730x00000027,0x00001672,0x0000169c,0x00050095,
13740x000000ab,0x000016cd,0x0000168d,0x0000010a,
13750x00050051,0x00000006,0x000016ce,0x000016cd,
13760x00000001,0x00050051,0x00000006,0x000016cf,
13770x000016cd,0x00000000,0x00050080,0x00000006,
13780x000016d4,0x00001692,0x000016ce,0x00050050,
13790x00000007,0x000016d5,0x000016cf,0x000016d4,
13800x0004007c,0x00000014,0x000016c5,0x000016d5,
13810x00060041,0x000000db,0x000016bc,0x000016c5,
13820x000000da,0x000000da,0x0006003d,0x00000006,
13830x000016bd,0x000016bc,0x00000002,0x00000004,
13840x0004007c,0x00000027,0x00001675,0x000016bd,
13850x00050041,0x000000fe,0x00001676,0x000000fc,
13860x00000266,0x0004003d,0x00000006,0x00001677,
13870x00001676,0x000500aa,0x0000002f,0x00001678,
13880x00001677,0x000000b0,0x000300f7,0x0000167e,
13890x00000000,0x000400fa,0x00001678,0x00001679,
13900x0000167a,0x000200f8,0x00001679,0x000200f9,
13910x0000167e,0x000200f8,0x0000167a,0x00050095,
13920x000000ab,0x000016ee,0x0000168d,0x00000111,
13930x00050051,0x00000006,0x000016ef,0x000016ee,
13940x00000001,0x00050051,0x00000006,0x000016f0,
13950x000016ee,0x00000000,0x00050080,0x00000006,
13960x000016f5,0x00001692,0x000016ef,0x00050050,
13970x00000007,0x000016f6,0x000016f0,0x000016f5,
13980x0004007c,0x00000014,0x000016e6,0x000016f6,
13990x00060041,0x000000db,0x000016dd,0x000016e6,
14000x000000da,0x000000da,0x0006003d,0x00000006,
14010x000016de,0x000016dd,0x00000002,0x00000004,
14020x0004007c,0x00000027,0x0000167d,0x000016de,
14030x000200f9,0x0000167e,0x000200f8,0x0000167e,
14040x000700f5,0x00000027,0x0000313a,0x0000026d,
14050x00001679,0x0000167d,0x0000167a,0x00060050,
14060x0000004b,0x00001683,0x00001672,0x00001675,
14070x0000313a,0x000300f7,0x0000173c,0x00000000,
14080x000300fb,0x000000a6,0x00001708,0x000200f8,
14090x00001708,0x00050041,0x00000156,0x00001709,
14100x000000fc,0x00000215,0x0004003d,0x00000007,
14110x0000170a,0x00001709,0x00050051,0x00000006,
14120x00001741,0x0000170a,0x00000000,0x000500aa,
14130x0000002f,0x00001742,0x00001741,0x000000a6,
14140x000300f7,0x00001747,0x00000000,0x000400fa,
14150x00001742,0x00001743,0x00001747,0x000200f8,
14160x00001743,0x00050051,0x00000006,0x00001745,
14170x0000170a,0x00000001,0x000500aa,0x0000002f,
14180x00001746,0x00001745,0x000000a6,0x000200f9,
14190x00001747,0x000200f8,0x00001747,0x000700f5,
14200x0000002f,0x00001748,0x00001742,0x00001708,
14210x00001746,0x00001743,0x000300f7,0x0000170e,
14220x00000000,0x000400fa,0x00001748,0x0000170c,
14230x0000170e,0x000200f8,0x0000170c,0x000200f9,
14240x0000173c,0x000200f8,0x0000170e,0x000200f9,
14250x0000170f,0x000200f8,0x0000170f,0x000700f5,
14260x00000006,0x0000313b,0x000000a6,0x0000170e,
14270x00001739,0x00001713,0x000500b0,0x0000002f,
14280x00001712,0x0000313b,0x000002b7,0x000400f6,
14290x0000173a,0x00001713,0x00000000,0x000400fa,
14300x00001712,0x00001713,0x0000173a,0x000200f8,
14310x00001713,0x00050084,0x00000006,0x00001715,
14320x0000011f,0x0000313b,0x00050095,0x000000ab,
14330x00001761,0x00001741,0x00001715,0x00050051,
14340x00000006,0x00001762,0x00001761,0x00000001,
14350x00050051,0x00000006,0x00001763,0x00001761,
14360x00000000,0x00050051,0x00000006,0x00001766,
14370x0000170a,0x00000001,0x00050080,0x00000006,
14380x00001768,0x00001766,0x00001762,0x00050050,
14390x00000007,0x00001769,0x00001763,0x00001768,
14400x0004007c,0x00000014,0x00001759,0x00001769,
14410x00060041,0x000000db,0x00001750,0x00001759,
14420x000000da,0x000000da,0x0006003d,0x00000006,
14430x00001751,0x00001750,0x00000002,0x00000004,
14440x0004007c,0x00000027,0x0000171a,0x00001751,
14450x00050080,0x00000006,0x0000171c,0x00001715,
14460x0000010a,0x00050095,0x000000ab,0x00001782,
14470x00001741,0x0000171c,0x00050051,0x00000006,
14480x00001783,0x00001782,0x00000001,0x00050051,
14490x00000006,0x00001784,0x00001782,0x00000000,
14500x00050080,0x00000006,0x00001789,0x00001766,
14510x00001783,0x00050050,0x00000007,0x0000178a,
14520x00001784,0x00001789,0x0004007c,0x00000014,
14530x0000177a,0x0000178a,0x00060041,0x000000db,
14540x00001771,0x0000177a,0x000000da,0x000000da,
14550x0006003d,0x00000006,0x00001772,0x00001771,
18720x00000002,0x00000004,0x0004007c,0x00000027, 14560x00000002,0x00000004,0x0004007c,0x00000027,
18730x00001946,0x00001bf6,0x00050095,0x000000a8, 14570x00001720,0x00001772,0x00050080,0x00000006,
18740x00001c27,0x00001bc3,0x00000186,0x00050051, 14580x00001722,0x00001715,0x00000111,0x00050095,
18750x00000006,0x00001c28,0x00001c27,0x00000001, 14590x000000ab,0x000017a3,0x00001741,0x00001722,
18760x00050051,0x00000006,0x00001c29,0x00001c27, 14600x00050051,0x00000006,0x000017a4,0x000017a3,
18770x00000000,0x00050080,0x00000006,0x00001c2e, 14610x00000001,0x00050051,0x00000006,0x000017a5,
18780x00001bcb,0x00001c28,0x00050050,0x00000007, 14620x000017a3,0x00000000,0x00050080,0x00000006,
18790x00001c2f,0x00001c29,0x00001c2e,0x0004007c, 14630x000017aa,0x00001766,0x000017a4,0x00050050,
18800x00000014,0x00001c1f,0x00001c2f,0x00060041, 14640x00000007,0x000017ab,0x000017a5,0x000017aa,
18810x000000d8,0x00001c16,0x00001c1f,0x000000d7, 14650x0004007c,0x00000014,0x0000179b,0x000017ab,
18820x000000d7,0x0006003d,0x00000006,0x00001c17, 14660x00060041,0x000000db,0x00001792,0x0000179b,
18830x00001c16,0x00000002,0x00000004,0x0004007c, 14670x000000da,0x000000da,0x0006003d,0x00000006,
18840x00000027,0x00001949,0x00001c17,0x00050095, 14680x00001793,0x00001792,0x00000002,0x00000004,
18850x000000a8,0x00001c48,0x00001bc3,0x0000014d, 14690x0004007c,0x00000027,0x00001726,0x00001793,
18860x00050051,0x00000006,0x00001c49,0x00001c48, 14700x00050080,0x00000006,0x00001728,0x00001715,
18870x00000001,0x00050051,0x00000006,0x00001c4a, 14710x00000118,0x00050095,0x000000ab,0x000017c4,
18880x00001c48,0x00000000,0x00050080,0x00000006, 14720x00001741,0x00001728,0x00050051,0x00000006,
18890x00001c4f,0x00001bcb,0x00001c49,0x00050050, 14730x000017c5,0x000017c4,0x00000001,0x00050051,
18900x00000007,0x00001c50,0x00001c4a,0x00001c4f, 14740x00000006,0x000017c6,0x000017c4,0x00000000,
18910x0004007c,0x00000014,0x00001c40,0x00001c50, 14750x00050080,0x00000006,0x000017cb,0x00001766,
18920x00060041,0x000000d8,0x00001c37,0x00001c40, 14760x000017c5,0x00050050,0x00000007,0x000017cc,
18930x000000d7,0x000000d7,0x0006003d,0x00000006, 14770x000017c6,0x000017cb,0x0004007c,0x00000014,
18940x00001c38,0x00001c37,0x00000002,0x00000004, 14780x000017bc,0x000017cc,0x00060041,0x000000db,
18950x0004007c,0x00000027,0x0000194c,0x00001c38, 14790x000017b3,0x000017bc,0x000000da,0x000000da,
18960x00050095,0x000000a8,0x00001c69,0x00001bc3, 14800x0006003d,0x00000006,0x000017b4,0x000017b3,
18970x00000460,0x00050051,0x00000006,0x00001c6a,
18980x00001c69,0x00000001,0x00050051,0x00000006,
18990x00001c6b,0x00001c69,0x00000000,0x00050080,
19000x00000006,0x00001c70,0x00001bcb,0x00001c6a,
19010x00050050,0x00000007,0x00001c71,0x00001c6b,
19020x00001c70,0x0004007c,0x00000014,0x00001c61,
19030x00001c71,0x00060041,0x000000d8,0x00001c58,
19040x00001c61,0x000000d7,0x000000d7,0x0006003d,
19050x00000006,0x00001c59,0x00001c58,0x00000002,
19060x00000004,0x0004007c,0x00000027,0x00001950,
19070x00001c59,0x00050095,0x000000a8,0x00001c8a,
19080x00001bc3,0x00000466,0x00050051,0x00000006,
19090x00001c8b,0x00001c8a,0x00000001,0x00050051,
19100x00000006,0x00001c8c,0x00001c8a,0x00000000,
19110x00050080,0x00000006,0x00001c91,0x00001bcb,
19120x00001c8b,0x00050050,0x00000007,0x00001c92,
19130x00001c8c,0x00001c91,0x0004007c,0x00000014,
19140x00001c82,0x00001c92,0x00060041,0x000000d8,
19150x00001c79,0x00001c82,0x000000d7,0x000000d7,
19160x0006003d,0x00000006,0x00001c7a,0x00001c79,
19170x00000002,0x00000004,0x0004007c,0x00000027, 14810x00000002,0x00000004,0x0004007c,0x00000027,
19180x00001953,0x00001c7a,0x00050095,0x000000a8, 14820x0000172c,0x000017b4,0x00070050,0x000002bc,
19190x00001cab,0x00001bc3,0x00000344,0x00050051, 14830x0000172d,0x0000171a,0x00001720,0x00001726,
19200x00000006,0x00001cac,0x00001cab,0x00000001, 14840x0000172c,0x0008004f,0x0000004b,0x00001730,
19210x00050051,0x00000006,0x00001cad,0x00001cab, 14850x0000172d,0x0000172d,0x00000000,0x00000001,
19220x00000000,0x00050080,0x00000006,0x00001cb2, 14860x00000002,0x00050094,0x00000027,0x00001732,
19230x00001bcb,0x00001cac,0x00050050,0x00000007, 14870x00001730,0x00001683,0x00050081,0x00000027,
19240x00001cb3,0x00001cad,0x00001cb2,0x0004007c, 14880x00001735,0x00001732,0x0000172c,0x00050041,
19250x00000014,0x00001ca3,0x00001cb3,0x00060041, 14890x00000028,0x00001736,0x00001705,0x0000313b,
19260x000000d8,0x00001c9a,0x00001ca3,0x000000d7, 14900x0003003e,0x00001736,0x00001735,0x00050080,
19270x000000d7,0x0006003d,0x00000006,0x00001c9b, 14910x00000006,0x00001739,0x0000313b,0x00000154,
19280x00001c9a,0x00000002,0x00000004,0x0004007c, 14920x000200f9,0x0000170f,0x000200f8,0x0000173a,
19290x00000027,0x00001956,0x00001c9b,0x000500bc, 14930x0004003d,0x0000004b,0x0000173b,0x00001705,
19300x0000002f,0x00001cba,0x00001946,0x00001950, 14940x000200f9,0x0000173c,0x000200f8,0x0000173c,
19310x000300f7,0x00001cc1,0x00000000,0x000400fa, 14950x000700f5,0x0000004b,0x0000313c,0x00001683,
19320x00001cba,0x00001cbb,0x00001cc1,0x000200f8, 14960x0000170c,0x0000173b,0x0000173a,0x00050041,
19330x00001cbb,0x000500bc,0x0000002f,0x00001cc0, 14970x0000004c,0x00001555,0x0000151a,0x0000312e,
19340x00001949,0x00001953,0x000200f9,0x00001cc1, 14980x0003003e,0x00001555,0x0000313c,0x000200f9,
19350x000200f8,0x00001cc1,0x000700f5,0x0000002f, 14990x00001556,0x000200f8,0x00001556,0x00050080,
19360x00001cc2,0x00001cba,0x0000193d,0x00001cc0, 15000x00000006,0x00001558,0x0000312e,0x00000154,
19370x00001cbb,0x000300f7,0x00001cc9,0x00000000, 15010x000200f9,0x00001548,0x000200f8,0x00001559,
19380x000400fa,0x00001cc2,0x00001cc3,0x00001cc9, 15020x00050041,0x000000fe,0x0000155a,0x000000fc,
19390x000200f8,0x00001cc3,0x000500bc,0x0000002f, 15030x00000308,0x0004003d,0x00000006,0x0000155b,
19400x00001cc8,0x0000194c,0x00001956,0x000200f9, 15040x0000155a,0x00050080,0x00000006,0x0000155d,
19410x00001cc9,0x000200f8,0x00001cc9,0x000700f5, 15050x0000155b,0x00000b11,0x00050041,0x000000fe,
19420x0000002f,0x00001cca,0x00001cc2,0x00001cc1, 15060x0000155e,0x000000fc,0x0000022c,0x0004003d,
19430x00001cc8,0x00001cc3,0x000300f7,0x00001960, 15070x00000006,0x0000155f,0x0000155e,0x00050084,
19440x00000000,0x000400fa,0x00001cca,0x0000195c, 15080x00000006,0x00001561,0x00000107,0x0000155d,
19450x00001960,0x000200f8,0x0000195c,0x000500c2, 15090x00050080,0x00000006,0x00001562,0x0000155f,
19460x00000006,0x0000195e,0x00001ac9,0x0000047b, 15100x00001561,0x000200f9,0x00001563,0x000200f8,
19470x000500ab,0x0000002f,0x0000195f,0x0000195e, 15110x00001563,0x000700f5,0x00000006,0x0000312f,
19480x000000a3,0x000200f9,0x00001960,0x000200f8, 15120x000000a6,0x00001559,0x0000158a,0x00001567,
19490x00001960,0x000700f5,0x0000002f,0x00001961, 15130x000500b0,0x0000002f,0x00001566,0x0000312f,
19500x00001cca,0x00001cc9,0x0000195f,0x0000195c, 15140x000002b7,0x000400f6,0x0000158b,0x00001567,
19510x000300f7,0x000019d1,0x00000000,0x000400fa, 15150x00000000,0x000400fa,0x00001566,0x00001567,
19520x00001961,0x00001962,0x000019d1,0x000200f8, 15160x0000158b,0x000200f8,0x00001567,0x00050084,
19530x00001962,0x000200f9,0x00001963,0x000200f8, 15170x00000006,0x0000156a,0x00000118,0x0000312f,
19540x00001963,0x000700f5,0x0000004b,0x00002b0b, 15180x00050080,0x00000006,0x0000156b,0x00001562,
19550x00002b66,0x00001962,0x000019cc,0x00001967, 15190x0000156a,0x00050041,0x00000156,0x0000156d,
19560x000700f5,0x0000004b,0x00002af9,0x00002b64, 15200x000000fc,0x000000da,0x0004003d,0x00000007,
19570x00001962,0x000019c9,0x00001967,0x000700f5, 15210x0000156e,0x0000156d,0x00060041,0x00000028,
19580x00000006,0x00002ad6,0x000000a3,0x00001962, 15220x0000156f,0x0000151a,0x0000312f,0x000000a6,
19590x000019cf,0x00001967,0x000500b0,0x0000002f, 15230x0004003d,0x00000027,0x00001570,0x0000156f,
19600x00001966,0x00002ad6,0x0000010e,0x000400f6, 15240x0004007c,0x00000006,0x000017d2,0x00001570,
19610x000019d0,0x00001967,0x00000000,0x000400fa, 15250x00050051,0x00000006,0x000017eb,0x0000156e,
19620x00001966,0x00001967,0x000019d0,0x000200f8, 15260x00000000,0x00050095,0x000000ab,0x000017ed,
19630x00001967,0x000500c7,0x00000006,0x00001969, 15270x000017eb,0x0000156b,0x00050051,0x00000006,
19640x00002ad6,0x000000ad,0x000500ab,0x0000002f, 15280x000017ee,0x000017ed,0x00000001,0x00050051,
19650x0000196a,0x00001969,0x000000a3,0x000600a9, 15290x00000006,0x000017ef,0x000017ed,0x00000000,
19660x00000027,0x00002b6c,0x0000196a,0x00001950, 15300x00050051,0x00000006,0x000017f2,0x0000156e,
19670x00001946,0x000500c7,0x00000006,0x00001974, 15310x00000001,0x00050080,0x00000006,0x000017f4,
19680x00002ad6,0x0000016d,0x000500ab,0x0000002f, 15320x000017f2,0x000017ee,0x00050050,0x00000007,
19690x00001975,0x00001974,0x000000a3,0x000600a9, 15330x000017f5,0x000017ef,0x000017f4,0x0004007c,
19700x00000027,0x00002b6d,0x00001975,0x00001953, 15340x00000014,0x000017e5,0x000017f5,0x00060041,
19710x00001949,0x000500c7,0x00000006,0x0000197f, 15350x000000db,0x000017dd,0x000017e5,0x000000da,
19720x00002ad6,0x00000107,0x000500ab,0x0000002f, 15360x000000da,0x0005003e,0x000017dd,0x000017d2,
19730x00001980,0x0000197f,0x000000a3,0x000600a9,
19740x00000027,0x00002b6e,0x00001980,0x00001956,
19750x0000194c,0x00050041,0x00000028,0x0000198a,
19760x00001884,0x000000d7,0x0004003d,0x00000027,
19770x0000198b,0x0000198a,0x00050085,0x00000027,
19780x0000198e,0x0000198b,0x00002b6c,0x00050041,
19790x00000028,0x0000198f,0x00001884,0x00000151,
19800x0004003d,0x00000027,0x00001990,0x0000198f,
19810x00050085,0x00000027,0x00001993,0x00001990,
19820x00002b6d,0x00050081,0x00000027,0x00001994,
19830x0000198e,0x00001993,0x00050041,0x00000028,
19840x00001995,0x00001884,0x00000202,0x0004003d,
19850x00000027,0x00001996,0x00001995,0x00050085,
19860x00000027,0x00001999,0x00001996,0x00002b6e,
19870x00050081,0x00000027,0x0000199a,0x00001994,
19880x00001999,0x00050041,0x00000028,0x0000199b,
19890x00001884,0x0000020a,0x0004003d,0x00000027,
19900x0000199c,0x0000199b,0x00050081,0x00000027,
19910x0000199d,0x0000199a,0x0000199c,0x00050041,
19920x00000028,0x0000199e,0x00001884,0x00000212,
19930x0004003d,0x00000027,0x0000199f,0x0000199e,
19940x00050085,0x00000027,0x000019a2,0x0000199f,
19950x00002b6c,0x00050041,0x00000028,0x000019a3,
19960x00001884,0x0000021a,0x0004003d,0x00000027,
19970x000019a4,0x000019a3,0x00050085,0x00000027,
19980x000019a7,0x000019a4,0x00002b6d,0x00050081,
19990x00000027,0x000019a8,0x000019a2,0x000019a7,
20000x00050041,0x00000028,0x000019a9,0x00001884,
20010x00000230,0x0004003d,0x00000027,0x000019aa,
20020x000019a9,0x00050085,0x00000027,0x000019ad,
20030x000019aa,0x00002b6e,0x00050081,0x00000027,
20040x000019ae,0x000019a8,0x000019ad,0x00050041,
20050x00000028,0x000019af,0x00001884,0x000004d5,
20060x0004003d,0x00000027,0x000019b0,0x000019af,
20070x00050081,0x00000027,0x000019b1,0x000019ae,
20080x000019b0,0x00050041,0x00000028,0x000019b2,
20090x00001884,0x00000305,0x0004003d,0x00000027,
20100x000019b3,0x000019b2,0x00050085,0x00000027,
20110x000019b6,0x000019b3,0x00002b6c,0x00050041,
20120x00000028,0x000019b7,0x00001884,0x0000024d,
20130x0004003d,0x00000027,0x000019b8,0x000019b7,
20140x00050085,0x00000027,0x000019bb,0x000019b8,
20150x00002b6d,0x00050081,0x00000027,0x000019bc,
20160x000019b6,0x000019bb,0x00050041,0x00000028,
20170x000019bd,0x00001884,0x00000263,0x0004003d,
20180x00000027,0x000019be,0x000019bd,0x00050085,
20190x00000027,0x000019c1,0x000019be,0x00002b6e,
20200x00050081,0x00000027,0x000019c2,0x000019bc,
20210x000019c1,0x00050041,0x00000028,0x000019c3,
20220x00001884,0x00000278,0x0004003d,0x00000027,
20230x000019c4,0x000019c3,0x00050081,0x00000027,
20240x000019c5,0x000019c2,0x000019c4,0x00060050,
20250x0000004b,0x000019c6,0x0000199d,0x000019b1,
20260x000019c5,0x0007000c,0x0000004b,0x000019c9,
20270x00000001,0x00000025,0x00002af9,0x000019c6,
20280x0007000c,0x0000004b,0x000019cc,0x00000001,
20290x00000028,0x00002b0b,0x000019c6,0x00050080,
20300x00000006,0x000019cf,0x00002ad6,0x00000151,
20310x000200f9,0x00001963,0x000200f8,0x000019d0,
20320x000200f9,0x000019d1,0x000200f8,0x000019d1,
20330x000700f5,0x0000004b,0x00002b07,0x00002b66,
20340x00001960,0x00002b0b,0x000019d0,0x000700f5,
20350x0000004b,0x00002af5,0x00002b64,0x00001960,
20360x00002af9,0x000019d0,0x000200f9,0x000019d2,
20370x000200f8,0x000019d2,0x000700f5,0x0000004b,
20380x00002b05,0x00002b66,0x00001bb7,0x00002b07,
20390x000019d1,0x000700f5,0x0000004b,0x00002af3,
20400x00002b64,0x00001bb7,0x00002af5,0x000019d1,
20410x000700f5,0x00000006,0x00002adf,0x0000037d,
20420x00001bb7,0x00001bd5,0x000019d1,0x00050041,
20430x00000028,0x000019d3,0x00001884,0x000000d7,
20440x0004003d,0x00000027,0x000019d4,0x000019d3,
20450x000500b4,0x0000002f,0x000019d5,0x000019d4,
20460x000004f9,0x000300f7,0x000019da,0x00000000,
20470x000400fa,0x000019d5,0x000019d6,0x000019da,
20480x000200f8,0x000019d6,0x00050041,0x00000028,
20490x000019d7,0x00001884,0x00000151,0x0004003d,
20500x00000027,0x000019d8,0x000019d7,0x000500b4,
20510x0000002f,0x000019d9,0x000019d8,0x0000026a,
20520x000200f9,0x000019da,0x000200f8,0x000019da,
20530x000700f5,0x0000002f,0x000019db,0x000019d5,
20540x000019d2,0x000019d9,0x000019d6,0x000300f7,
20550x000019e0,0x00000000,0x000400fa,0x000019db,
20560x000019dc,0x000019e0,0x000200f8,0x000019dc,
20570x00050041,0x00000028,0x000019dd,0x00001884,
20580x00000202,0x0004003d,0x00000027,0x000019de,
20590x000019dd,0x000500b4,0x0000002f,0x000019df,
20600x000019de,0x0000026a,0x000200f9,0x000019e0,
20610x000200f8,0x000019e0,0x000700f5,0x0000002f,
20620x000019e1,0x000019db,0x000019da,0x000019df,
20630x000019dc,0x000300f7,0x000019e6,0x00000000,
20640x000400fa,0x000019e1,0x000019e2,0x000019e6,
20650x000200f8,0x000019e2,0x00050041,0x00000028,
20660x000019e3,0x00001884,0x00000212,0x0004003d,
20670x00000027,0x000019e4,0x000019e3,0x000500b4,
20680x0000002f,0x000019e5,0x000019e4,0x0000026a,
20690x000200f9,0x000019e6,0x000200f8,0x000019e6,
20700x000700f5,0x0000002f,0x000019e7,0x000019e1,
20710x000019e0,0x000019e5,0x000019e2,0x000300f7,
20720x000019ec,0x00000000,0x000400fa,0x000019e7,
20730x000019e8,0x000019ec,0x000200f8,0x000019e8,
20740x00050041,0x00000028,0x000019e9,0x00001884,
20750x0000021a,0x0004003d,0x00000027,0x000019ea,
20760x000019e9,0x000500b4,0x0000002f,0x000019eb,
20770x000019ea,0x000004f9,0x000200f9,0x000019ec,
20780x000200f8,0x000019ec,0x000700f5,0x0000002f,
20790x000019ed,0x000019e7,0x000019e6,0x000019eb,
20800x000019e8,0x000300f7,0x000019f2,0x00000000,
20810x000400fa,0x000019ed,0x000019ee,0x000019f2,
20820x000200f8,0x000019ee,0x00050041,0x00000028,
20830x000019ef,0x00001884,0x00000230,0x0004003d,
20840x00000027,0x000019f0,0x000019ef,0x000500b4,
20850x0000002f,0x000019f1,0x000019f0,0x0000026a,
20860x000200f9,0x000019f2,0x000200f8,0x000019f2,
20870x000700f5,0x0000002f,0x000019f3,0x000019ed,
20880x000019ec,0x000019f1,0x000019ee,0x000300f7,
20890x000019f8,0x00000000,0x000400fa,0x000019f3,
20900x000019f4,0x000019f8,0x000200f8,0x000019f4,
20910x00050041,0x00000028,0x000019f5,0x00001884,
20920x00000305,0x0004003d,0x00000027,0x000019f6,
20930x000019f5,0x000500b4,0x0000002f,0x000019f7,
20940x000019f6,0x0000026a,0x000200f9,0x000019f8,
20950x000200f8,0x000019f8,0x000700f5,0x0000002f,
20960x000019f9,0x000019f3,0x000019f2,0x000019f7,
20970x000019f4,0x000300f7,0x000019fe,0x00000000,
20980x000400fa,0x000019f9,0x000019fa,0x000019fe,
20990x000200f8,0x000019fa,0x00050041,0x00000028,
21000x000019fb,0x00001884,0x0000024d,0x0004003d,
21010x00000027,0x000019fc,0x000019fb,0x000500b4,
21020x0000002f,0x000019fd,0x000019fc,0x0000026a,
21030x000200f9,0x000019fe,0x000200f8,0x000019fe,
21040x000700f5,0x0000002f,0x000019ff,0x000019f9,
21050x000019f8,0x000019fd,0x000019fa,0x000300f7,
21060x00001a04,0x00000000,0x000400fa,0x000019ff,
21070x00001a00,0x00001a04,0x000200f8,0x00001a00,
21080x00050041,0x00000028,0x00001a01,0x00001884,
21090x00000263,0x0004003d,0x00000027,0x00001a02,
21100x00001a01,0x000500b4,0x0000002f,0x00001a03,
21110x00001a02,0x000004f9,0x000200f9,0x00001a04,
21120x000200f8,0x00001a04,0x000700f5,0x0000002f,
21130x00001a05,0x000019ff,0x000019fe,0x00001a03,
21140x00001a00,0x00050080,0x00000006,0x00001a07,
21150x00001916,0x0000037b,0x000500c7,0x00000006,
21160x00001a09,0x00002adf,0x0000052e,0x000600a9,
21170x00000006,0x00001a0b,0x00001a05,0x0000012d,
21180x000000a3,0x000500c5,0x00000006,0x00001a0c,
21190x00001a09,0x00001a0b,0x00050095,0x000000a8,
21200x00001ce3,0x00001b83,0x00001a07,0x00050051,
21210x00000006,0x00001ce4,0x00001ce3,0x00000001,
21220x00050051,0x00000006,0x00001ce5,0x00001ce3,
21230x00000000,0x00050080,0x00000006,0x00001cea,
21240x00001b8a,0x00001ce4,0x00050050,0x00000007,
21250x00001ceb,0x00001ce5,0x00001cea,0x0004007c,
21260x00000014,0x00001cdb,0x00001ceb,0x00060041,
21270x000000d8,0x00001cd3,0x00001cdb,0x000000d7,
21280x000000d7,0x0005003e,0x00001cd3,0x00001a0c,
21290x00000002,0x00000004,0x00050080,0x00000006, 15370x00000002,0x00000004,0x00050080,0x00000006,
21300x00001a11,0x00001916,0x00000385,0x000500c2, 15380x00001576,0x0000156b,0x0000010a,0x00060041,
21310x00000006,0x00001a14,0x00001b0b,0x00000305, 15390x00000028,0x0000157a,0x0000151a,0x0000312f,
21320x000500c4,0x00000006,0x00001a17,0x00001b2c, 15400x000000b0,0x0004003d,0x00000027,0x0000157b,
21330x0000047b,0x000500c5,0x00000006,0x00001a18, 15410x0000157a,0x0004007c,0x00000006,0x000017fb,
21340x00001a14,0x00001a17,0x00050095,0x000000a8, 15420x0000157b,0x00050095,0x000000ab,0x00001816,
21350x00001d03,0x00001b83,0x00001a11,0x00050051, 15430x000017eb,0x00001576,0x00050051,0x00000006,
21360x00000006,0x00001d04,0x00001d03,0x00000001, 15440x00001817,0x00001816,0x00000001,0x00050051,
21370x00050051,0x00000006,0x00001d05,0x00001d03, 15450x00000006,0x00001818,0x00001816,0x00000000,
21380x00000000,0x00050080,0x00000006,0x00001d0a, 15460x00050080,0x00000006,0x0000181d,0x000017f2,
21390x00001b8a,0x00001d04,0x00050050,0x00000007, 15470x00001817,0x00050050,0x00000007,0x0000181e,
21400x00001d0b,0x00001d05,0x00001d0a,0x0004007c, 15480x00001818,0x0000181d,0x0004007c,0x00000014,
21410x00000014,0x00001cfb,0x00001d0b,0x00060041, 15490x0000180e,0x0000181e,0x00060041,0x000000db,
21420x000000d8,0x00001cf3,0x00001cfb,0x000000d7, 15500x00001806,0x0000180e,0x000000da,0x000000da,
21430x000000d7,0x0005003e,0x00001cf3,0x00001a18, 15510x0005003e,0x00001806,0x000017fb,0x00000002,
21440x00000002,0x00000004,0x0004003d,0x00000027, 15520x00000004,0x00050080,0x00000006,0x00001581,
21450x00001a1d,0x000019d3,0x00050041,0x00000028, 15530x0000156b,0x00000111,0x00060041,0x00000028,
21460x00001a1e,0x00001884,0x00000212,0x0004003d, 15540x00001585,0x0000151a,0x0000312f,0x00000170,
21470x00000027,0x00001a1f,0x00001a1e,0x00050041, 15550x0004003d,0x00000027,0x00001586,0x00001585,
21480x00000028,0x00001a20,0x00001884,0x00000305, 15560x0004007c,0x00000006,0x00001824,0x00001586,
21490x0004003d,0x00000027,0x00001a21,0x00001a20, 15570x00050095,0x000000ab,0x0000183f,0x000017eb,
21500x00050041,0x00000028,0x00001a22,0x00001884, 15580x00001581,0x00050051,0x00000006,0x00001840,
21510x00000151,0x0004003d,0x00000027,0x00001a23, 15590x0000183f,0x00000001,0x00050051,0x00000006,
21520x00001a22,0x00050041,0x00000028,0x00001a24, 15600x00001841,0x0000183f,0x00000000,0x00050080,
21530x00001884,0x0000021a,0x0004003d,0x00000027, 15610x00000006,0x00001846,0x000017f2,0x00001840,
21540x00001a25,0x00001a24,0x00050041,0x00000028, 15620x00050050,0x00000007,0x00001847,0x00001841,
21550x00001a26,0x00001884,0x0000024d,0x0004003d, 15630x00001846,0x0004007c,0x00000014,0x00001837,
21560x00000027,0x00001a27,0x00001a26,0x00050041, 15640x00001847,0x00060041,0x000000db,0x0000182f,
21570x00000028,0x00001a28,0x00001884,0x00000202, 15650x00001837,0x000000da,0x000000da,0x0005003e,
21580x0004003d,0x00000027,0x00001a29,0x00001a28, 15660x0000182f,0x00001824,0x00000002,0x00000004,
21590x00050041,0x00000028,0x00001a2a,0x00001884, 15670x00050080,0x00000006,0x0000158a,0x0000312f,
21600x00000230,0x0004003d,0x00000027,0x00001a2b, 15680x00000154,0x000200f9,0x00001563,0x000200f8,
21610x00001a2a,0x00050041,0x00000028,0x00001a2c, 15690x0000158b,0x00050080,0x00000006,0x0000158d,
21620x00001884,0x00000263,0x0004003d,0x00000027, 15700x00001562,0x00000347,0x00050041,0x00000156,
21630x00001a2d,0x00001a2c,0x00060050,0x0000004b, 15710x0000158e,0x000000fc,0x000000da,0x0004003d,
21640x00001a2e,0x00001a1d,0x00001a1f,0x00001a21, 15720x00000007,0x0000158f,0x0000158e,0x00060041,
21650x00060050,0x0000004b,0x00001a2f,0x00001a23, 15730x00000028,0x00001590,0x0000151a,0x00000205,
21660x00001a25,0x00001a27,0x00060050,0x0000004b, 15740x000000a6,0x0004003d,0x00000027,0x00001591,
21670x00001a30,0x00001a29,0x00001a2b,0x00001a2d, 15750x00001590,0x0004007c,0x00000006,0x0000184d,
21680x00060050,0x00000548,0x00001a31,0x00001a2e, 15760x00001591,0x00050051,0x00000006,0x00001866,
21690x00001a2f,0x00001a30,0x0006000c,0x00000027, 15770x0000158f,0x00000000,0x00050095,0x000000ab,
21700x00001a33,0x00000001,0x00000021,0x00001a31, 15780x00001868,0x00001866,0x0000158d,0x00050051,
21710x000500b7,0x0000002f,0x00001a35,0x00001a33, 15790x00000006,0x00001869,0x00001868,0x00000001,
21720x0000026a,0x000300f7,0x00001a3a,0x00000000, 15800x00050051,0x00000006,0x0000186a,0x00001868,
21730x000400fa,0x00001a35,0x00001a36,0x00001a39, 15810x00000000,0x00050051,0x00000006,0x0000186d,
21740x000200f8,0x00001a36,0x0006000c,0x00000548, 15820x0000158f,0x00000001,0x00050080,0x00000006,
21750x00001a38,0x00000001,0x00000022,0x00001a31, 15830x0000186f,0x0000186d,0x00001869,0x00050050,
21760x000200f9,0x00001a3a,0x000200f8,0x00001a39, 15840x00000007,0x00001870,0x0000186a,0x0000186f,
21770x000200f9,0x00001a3a,0x000200f8,0x00001a3a, 15850x0004007c,0x00000014,0x00001860,0x00001870,
21780x000700f5,0x00000548,0x00002ae6,0x00001a38, 15860x00060041,0x000000db,0x00001858,0x00001860,
21790x00001a36,0x0000056e,0x00001a39,0x0003003e, 15870x000000da,0x000000da,0x0005003e,0x00001858,
21800x000018c5,0x00002ae6,0x00050041,0x00000028, 15880x0000184d,0x00000002,0x00000004,0x00050080,
21810x00001a3c,0x00001884,0x0000020a,0x0004003d, 15890x00000006,0x00001594,0x00001562,0x00000352,
21820x00000027,0x00001a3d,0x00001a3c,0x00050041, 15900x00060041,0x00000028,0x00001597,0x0000151a,
21830x00000028,0x00001a3e,0x00001884,0x000004d5, 15910x00000205,0x000000b0,0x0004003d,0x00000027,
21840x0004003d,0x00000027,0x00001a3f,0x00001a3e, 15920x00001598,0x00001597,0x0004007c,0x00000006,
21850x00050041,0x00000028,0x00001a40,0x00001884, 15930x00001876,0x00001598,0x00050095,0x000000ab,
21860x00000278,0x0004003d,0x00000027,0x00001a41, 15940x00001891,0x00001866,0x00001594,0x00050051,
21870x00001a40,0x00060050,0x0000004b,0x00001a42, 15950x00000006,0x00001892,0x00001891,0x00000001,
21880x00001a3d,0x00001a3f,0x00001a41,0x00050091, 15960x00050051,0x00000006,0x00001893,0x00001891,
21890x0000004b,0x00001a45,0x00002ae6,0x00001a42, 15970x00000000,0x00050080,0x00000006,0x00001898,
21900x0004007f,0x0000004b,0x00001a46,0x00001a45, 15980x0000186d,0x00001892,0x00050050,0x00000007,
21910x0003003e,0x000018c8,0x00001a46,0x000200f9, 15990x00001899,0x00001893,0x00001898,0x0004007c,
21920x00001a47,0x000200f8,0x00001a47,0x000700f5, 16000x00000014,0x00001889,0x00001899,0x00060041,
21930x00000006,0x00002ae7,0x000000a3,0x00001a3a, 16010x000000db,0x00001881,0x00001889,0x000000da,
21940x00001a7a,0x00001a4b,0x000500b0,0x0000002f, 16020x000000da,0x0005003e,0x00001881,0x00001876,
21950x00001a4a,0x00002ae7,0x000002b4,0x000400f6,
21960x00001a7b,0x00001a4b,0x00000000,0x000400fa,
21970x00001a4a,0x00001a4b,0x00001a7b,0x000200f8,
21980x00001a4b,0x00050080,0x00000006,0x00001a4d,
21990x00001916,0x00000104,0x00050084,0x00000006,
22000x00001a4f,0x0000011c,0x00002ae7,0x00050080,
22010x00000006,0x00001a50,0x00001a4d,0x00001a4f,
22020x00060041,0x00000028,0x00001a54,0x000018c5,
22030x000000d7,0x00002ae7,0x0004003d,0x00000027,
22040x00001a55,0x00001a54,0x0004007c,0x00000006,
22050x00001d11,0x00001a55,0x00050095,0x000000a8,
22060x00001d2c,0x00001b83,0x00001a50,0x00050051,
22070x00000006,0x00001d2d,0x00001d2c,0x00000001,
22080x00050051,0x00000006,0x00001d2e,0x00001d2c,
22090x00000000,0x00050080,0x00000006,0x00001d33,
22100x00001b8a,0x00001d2d,0x00050050,0x00000007,
22110x00001d34,0x00001d2e,0x00001d33,0x0004007c,
22120x00000014,0x00001d24,0x00001d34,0x00060041,
22130x000000d8,0x00001d1c,0x00001d24,0x000000d7,
22140x000000d7,0x0005003e,0x00001d1c,0x00001d11,
22150x00000002,0x00000004,0x00050080,0x00000006, 16030x00000002,0x00000004,0x00050080,0x00000006,
22160x00001a58,0x00001916,0x00000594,0x00050080, 16040x0000159b,0x00001562,0x0000035d,0x00060041,
22170x00000006,0x00001a5b,0x00001a58,0x00001a4f, 16050x00000028,0x0000159e,0x0000151a,0x00000205,
22180x00060041,0x00000028,0x00001a5f,0x000018c5, 16060x00000170,0x0004003d,0x00000027,0x0000159f,
22190x00000151,0x00002ae7,0x0004003d,0x00000027, 16070x0000159e,0x0004007c,0x00000006,0x0000189f,
22200x00001a60,0x00001a5f,0x0004007c,0x00000006, 16080x0000159f,0x00050095,0x000000ab,0x000018ba,
22210x00001d3a,0x00001a60,0x00050095,0x000000a8, 16090x00001866,0x0000159b,0x00050051,0x00000006,
22220x00001d55,0x00001b83,0x00001a5b,0x00050051, 16100x000018bb,0x000018ba,0x00000001,0x00050051,
22230x00000006,0x00001d56,0x00001d55,0x00000001, 16110x00000006,0x000018bc,0x000018ba,0x00000000,
22240x00050051,0x00000006,0x00001d57,0x00001d55, 16120x00050080,0x00000006,0x000018c1,0x0000186d,
22250x00000000,0x00050080,0x00000006,0x00001d5c, 16130x000018bb,0x00050050,0x00000007,0x000018c2,
22260x00001b8a,0x00001d56,0x00050050,0x00000007, 16140x000018bc,0x000018c1,0x0004007c,0x00000014,
22270x00001d5d,0x00001d57,0x00001d5c,0x0004007c, 16150x000018b2,0x000018c2,0x00060041,0x000000db,
22280x00000014,0x00001d4d,0x00001d5d,0x00060041, 16160x000018aa,0x000018b2,0x000000da,0x000000da,
22290x000000d8,0x00001d45,0x00001d4d,0x000000d7, 16170x0005003e,0x000018aa,0x0000189f,0x00000002,
22300x000000d7,0x0005003e,0x00001d45,0x00001d3a, 16180x00000004,0x00050080,0x00000006,0x000015a2,
16190x00001562,0x00000368,0x00050041,0x000000fe,
16200x000015a5,0x000000fc,0x0000036a,0x0004003d,
16210x00000006,0x000015a6,0x000015a5,0x00050095,
16220x000000ab,0x000018da,0x00001866,0x000015a2,
16230x00050051,0x00000006,0x000018db,0x000018da,
16240x00000001,0x00050051,0x00000006,0x000018dc,
16250x000018da,0x00000000,0x00050080,0x00000006,
16260x000018e1,0x0000186d,0x000018db,0x00050050,
16270x00000007,0x000018e2,0x000018dc,0x000018e1,
16280x0004007c,0x00000014,0x000018d2,0x000018e2,
16290x00060041,0x000000db,0x000018ca,0x000018d2,
16300x000000da,0x000000da,0x0005003e,0x000018ca,
16310x000015a6,0x00000002,0x00000004,0x00050080,
16320x00000006,0x000015a9,0x00001562,0x00000374,
16330x00050095,0x000000ab,0x000018fa,0x00001866,
16340x000015a9,0x00050051,0x00000006,0x000018fb,
16350x000018fa,0x00000001,0x00050051,0x00000006,
16360x000018fc,0x000018fa,0x00000000,0x00050080,
16370x00000006,0x00001901,0x0000186d,0x000018fb,
16380x00050050,0x00000007,0x00001902,0x000018fc,
16390x00001901,0x0004007c,0x00000014,0x000018f2,
16400x00001902,0x00060041,0x000000db,0x000018ea,
16410x000018f2,0x000000da,0x000000da,0x0005003e,
16420x000018ea,0x00000b11,0x00000002,0x00000004,
16430x00050080,0x00000006,0x000015af,0x00001562,
16440x0000037e,0x00050095,0x000000ab,0x0000191a,
16450x00001866,0x000015af,0x00050051,0x00000006,
16460x0000191b,0x0000191a,0x00000001,0x00050051,
16470x00000006,0x0000191c,0x0000191a,0x00000000,
16480x00050080,0x00000006,0x00001921,0x0000186d,
16490x0000191b,0x00050050,0x00000007,0x00001922,
16500x0000191c,0x00001921,0x0004007c,0x00000014,
16510x00001912,0x00001922,0x00060041,0x000000db,
16520x0000190a,0x00001912,0x000000da,0x000000da,
16530x0005003e,0x0000190a,0x00000380,0x00000002,
16540x00000004,0x00050080,0x00000006,0x000015b4,
16550x00001562,0x00000388,0x00050095,0x000000ab,
16560x0000193a,0x00001866,0x000015b4,0x00050051,
16570x00000006,0x0000193b,0x0000193a,0x00000001,
16580x00050051,0x00000006,0x0000193c,0x0000193a,
16590x00000000,0x00050080,0x00000006,0x00001941,
16600x0000186d,0x0000193b,0x00050050,0x00000007,
16610x00001942,0x0000193c,0x00001941,0x0004007c,
16620x00000014,0x00001932,0x00001942,0x00060041,
16630x000000db,0x0000192a,0x00001932,0x000000da,
16640x000000da,0x0005003e,0x0000192a,0x0000038a,
16650x00000002,0x00000004,0x00050041,0x0000004c,
16660x000015b8,0x0000151a,0x000000da,0x0004003d,
16670x0000004b,0x000015b9,0x000015b8,0x0004009c,
16680x00000395,0x000015ba,0x000015b9,0x0004009a,
16690x0000002f,0x000015bb,0x000015ba,0x000400a8,
16700x0000002f,0x000015bc,0x000015bb,0x000300f7,
16710x000015c2,0x00000000,0x000400fa,0x000015bc,
16720x000015bd,0x000015c2,0x000200f8,0x000015bd,
16730x00050041,0x0000004c,0x000015be,0x0000151a,
16740x00000154,0x0004003d,0x0000004b,0x000015bf,
16750x000015be,0x0004009c,0x00000395,0x000015c0,
16760x000015bf,0x0004009a,0x0000002f,0x000015c1,
16770x000015c0,0x000200f9,0x000015c2,0x000200f8,
16780x000015c2,0x000700f5,0x0000002f,0x000015c3,
16790x000015bb,0x0000158b,0x000015c1,0x000015bd,
16800x000400a8,0x0000002f,0x000015c4,0x000015c3,
16810x000300f7,0x000015ca,0x00000000,0x000400fa,
16820x000015c4,0x000015c5,0x000015ca,0x000200f8,
16830x000015c5,0x00050041,0x0000004c,0x000015c6,
16840x0000151a,0x00000205,0x0004003d,0x0000004b,
16850x000015c7,0x000015c6,0x0004009c,0x00000395,
16860x000015c8,0x000015c7,0x0004009a,0x0000002f,
16870x000015c9,0x000015c8,0x000200f9,0x000015ca,
16880x000200f8,0x000015ca,0x000700f5,0x0000002f,
16890x000015cb,0x000015c3,0x000015c2,0x000015c9,
16900x000015c5,0x0004003d,0x0000004b,0x000015cd,
16910x000015b8,0x00050041,0x0000004c,0x000015ce,
16920x0000151a,0x00000154,0x0004003d,0x0000004b,
16930x000015cf,0x000015ce,0x0007000c,0x0000004b,
16940x000015d0,0x00000001,0x00000025,0x000015cd,
16950x000015cf,0x00050041,0x0000004c,0x000015d1,
16960x0000151a,0x00000205,0x0004003d,0x0000004b,
16970x000015d2,0x000015d1,0x0007000c,0x0000004b,
16980x000015d3,0x00000001,0x00000025,0x000015d0,
16990x000015d2,0x0004003d,0x0000004b,0x000015d5,
17000x000015b8,0x0004003d,0x0000004b,0x000015d7,
17010x000015ce,0x0007000c,0x0000004b,0x000015d8,
17020x00000001,0x00000028,0x000015d5,0x000015d7,
17030x0004003d,0x0000004b,0x000015da,0x000015d1,
17040x0007000c,0x0000004b,0x000015db,0x00000001,
17050x00000028,0x000015d8,0x000015da,0x00060050,
17060x00000395,0x0000319d,0x000015cb,0x000015cb,
17070x000015cb,0x000600a9,0x0000004b,0x0000319e,
17080x0000319d,0x0000319b,0x000015db,0x000600a9,
17090x0000004b,0x000031a0,0x0000319d,0x00003199,
17100x000015d3,0x00050041,0x000000fe,0x0000198c,
17110x000000fc,0x000000fd,0x0004003d,0x00000006,
17120x0000198d,0x0000198c,0x00050084,0x00000006,
17130x0000198e,0x0000011f,0x0000198d,0x00050080,
17140x00000006,0x0000198f,0x00000107,0x0000198e,
17150x00050080,0x00000006,0x00001995,0x0000198d,
17160x0000319c,0x00050086,0x00000006,0x00001996,
17170x00001995,0x00000101,0x00050084,0x00000006,
17180x00001988,0x00000107,0x00001996,0x00050080,
17190x00000006,0x00001989,0x0000198f,0x00001988,
17200x00050084,0x00000006,0x00001959,0x00000150,
17210x0000155d,0x00050080,0x00000006,0x0000195a,
17220x00001989,0x00001959,0x00050041,0x00000156,
17230x0000195b,0x000000fc,0x00000154,0x0004003d,
17240x00000007,0x0000195c,0x0000195b,0x00050051,
17250x00000027,0x0000195f,0x000031a0,0x00000000,
17260x0004007c,0x00000006,0x0000199c,0x0000195f,
17270x00050051,0x00000006,0x000019b5,0x0000195c,
17280x00000000,0x00050095,0x000000ab,0x000019b7,
17290x000019b5,0x0000195a,0x00050051,0x00000006,
17300x000019b8,0x000019b7,0x00000001,0x00050051,
17310x00000006,0x000019b9,0x000019b7,0x00000000,
17320x00050051,0x00000006,0x000019bc,0x0000195c,
17330x00000001,0x00050080,0x00000006,0x000019be,
17340x000019bc,0x000019b8,0x00050050,0x00000007,
17350x000019bf,0x000019b9,0x000019be,0x0004007c,
17360x00000014,0x000019af,0x000019bf,0x00060041,
17370x000000db,0x000019a7,0x000019af,0x000000da,
17380x000000da,0x0005003e,0x000019a7,0x0000199c,
22310x00000002,0x00000004,0x00050080,0x00000006, 17390x00000002,0x00000004,0x00050080,0x00000006,
22320x00001a63,0x00001916,0x000005a3,0x00050080, 17400x00001962,0x0000195a,0x0000010a,0x00050051,
22330x00000006,0x00001a66,0x00001a63,0x00001a4f, 17410x00000027,0x00001966,0x000031a0,0x00000001,
22340x00060041,0x00000028,0x00001a6a,0x000018c5, 17420x0004007c,0x00000006,0x000019c5,0x00001966,
22350x00000202,0x00002ae7,0x0004003d,0x00000027, 17430x00050095,0x000000ab,0x000019e0,0x000019b5,
22360x00001a6b,0x00001a6a,0x0004007c,0x00000006, 17440x00001962,0x00050051,0x00000006,0x000019e1,
22370x00001d63,0x00001a6b,0x00050095,0x000000a8, 17450x000019e0,0x00000001,0x00050051,0x00000006,
22380x00001d7e,0x00001b83,0x00001a66,0x00050051, 17460x000019e2,0x000019e0,0x00000000,0x00050080,
22390x00000006,0x00001d7f,0x00001d7e,0x00000001, 17470x00000006,0x000019e7,0x000019bc,0x000019e1,
22400x00050051,0x00000006,0x00001d80,0x00001d7e, 17480x00050050,0x00000007,0x000019e8,0x000019e2,
22410x00000000,0x00050080,0x00000006,0x00001d85, 17490x000019e7,0x0004007c,0x00000014,0x000019d8,
22420x00001b8a,0x00001d7f,0x00050050,0x00000007, 17500x000019e8,0x00060041,0x000000db,0x000019d0,
22430x00001d86,0x00001d80,0x00001d85,0x0004007c, 17510x000019d8,0x000000da,0x000000da,0x0005003e,
22440x00000014,0x00001d76,0x00001d86,0x00060041, 17520x000019d0,0x000019c5,0x00000002,0x00000004,
22450x000000d8,0x00001d6e,0x00001d76,0x000000d7, 17530x00050080,0x00000006,0x00001969,0x0000195a,
22460x000000d7,0x0005003e,0x00001d6e,0x00001d63, 17540x00000111,0x00050051,0x00000027,0x0000196d,
17550x000031a0,0x00000002,0x0004007c,0x00000006,
17560x000019ee,0x0000196d,0x00050095,0x000000ab,
17570x00001a09,0x000019b5,0x00001969,0x00050051,
17580x00000006,0x00001a0a,0x00001a09,0x00000001,
17590x00050051,0x00000006,0x00001a0b,0x00001a09,
17600x00000000,0x00050080,0x00000006,0x00001a10,
17610x000019bc,0x00001a0a,0x00050050,0x00000007,
17620x00001a11,0x00001a0b,0x00001a10,0x0004007c,
17630x00000014,0x00001a01,0x00001a11,0x00060041,
17640x000000db,0x000019f9,0x00001a01,0x000000da,
17650x000000da,0x0005003e,0x000019f9,0x000019ee,
22470x00000002,0x00000004,0x00050080,0x00000006, 17660x00000002,0x00000004,0x00050080,0x00000006,
22480x00001a6e,0x00001916,0x000005b2,0x00050080, 17670x00001970,0x0000195a,0x00000118,0x00050051,
22490x00000006,0x00001a71,0x00001a6e,0x00001a4f, 17680x00000027,0x00001974,0x0000319e,0x00000000,
22500x00050041,0x00000028,0x00001a75,0x000018c8, 17690x0004007c,0x00000006,0x00001a17,0x00001974,
22510x00002ae7,0x0004003d,0x00000027,0x00001a76, 17700x00050095,0x000000ab,0x00001a32,0x000019b5,
22520x00001a75,0x0004007c,0x00000006,0x00001d8c, 17710x00001970,0x00050051,0x00000006,0x00001a33,
22530x00001a76,0x00050095,0x000000a8,0x00001da7, 17720x00001a32,0x00000001,0x00050051,0x00000006,
22540x00001b83,0x00001a71,0x00050051,0x00000006, 17730x00001a34,0x00001a32,0x00000000,0x00050080,
22550x00001da8,0x00001da7,0x00000001,0x00050051, 17740x00000006,0x00001a39,0x000019bc,0x00001a33,
22560x00000006,0x00001da9,0x00001da7,0x00000000, 17750x00050050,0x00000007,0x00001a3a,0x00001a34,
22570x00050080,0x00000006,0x00001dae,0x00001b8a, 17760x00001a39,0x0004007c,0x00000014,0x00001a2a,
22580x00001da8,0x00050050,0x00000007,0x00001daf, 17770x00001a3a,0x00060041,0x000000db,0x00001a22,
22590x00001da9,0x00001dae,0x0004007c,0x00000014, 17780x00001a2a,0x000000da,0x000000da,0x0005003e,
22600x00001d9f,0x00001daf,0x00060041,0x000000d8, 17790x00001a22,0x00001a17,0x00000002,0x00000004,
22610x00001d97,0x00001d9f,0x000000d7,0x000000d7, 17800x00050080,0x00000006,0x00001977,0x0000195a,
22620x0005003e,0x00001d97,0x00001d8c,0x00000002, 17810x0000011f,0x00050051,0x00000027,0x0000197b,
22630x00000004,0x00050080,0x00000006,0x00001a7a, 17820x0000319e,0x00000001,0x0004007c,0x00000006,
22640x00002ae7,0x00000151,0x000200f9,0x00001a47, 17830x00001a40,0x0000197b,0x00050095,0x000000ab,
22650x000200f8,0x00001a7b,0x00050080,0x00000006, 17840x00001a5b,0x000019b5,0x00001977,0x00050051,
22660x00001a7d,0x00001916,0x000005c3,0x00050095, 17850x00000006,0x00001a5c,0x00001a5b,0x00000001,
22670x000000a8,0x00001dc7,0x00001b83,0x00001a7d, 17860x00050051,0x00000006,0x00001a5d,0x00001a5b,
22680x00050051,0x00000006,0x00001dc8,0x00001dc7, 17870x00000000,0x00050080,0x00000006,0x00001a62,
22690x00000001,0x00050051,0x00000006,0x00001dc9, 17880x000019bc,0x00001a5c,0x00050050,0x00000007,
22700x00001dc7,0x00000000,0x00050080,0x00000006, 17890x00001a63,0x00001a5d,0x00001a62,0x0004007c,
22710x00001dce,0x00001b8a,0x00001dc8,0x00050050, 17900x00000014,0x00001a53,0x00001a63,0x00060041,
22720x00000007,0x00001dcf,0x00001dc9,0x00001dce, 17910x000000db,0x00001a4b,0x00001a53,0x000000da,
22730x0004007c,0x00000014,0x00001dbf,0x00001dcf, 17920x000000da,0x0005003e,0x00001a4b,0x00001a40,
22740x00060041,0x000000d8,0x00001db7,0x00001dbf,
22750x000000d7,0x000000d7,0x0005003e,0x00001db7,
22760x000009e9,0x00000002,0x00000004,0x00050080,
22770x00000006,0x00001a83,0x00001916,0x000005cd,
22780x00050095,0x000000a8,0x00001de7,0x00001b83,
22790x00001a83,0x00050051,0x00000006,0x00001de8,
22800x00001de7,0x00000001,0x00050051,0x00000006,
22810x00001de9,0x00001de7,0x00000000,0x00050080,
22820x00000006,0x00001dee,0x00001b8a,0x00001de8,
22830x00050050,0x00000007,0x00001def,0x00001de9,
22840x00001dee,0x0004007c,0x00000014,0x00001ddf,
22850x00001def,0x00060041,0x000000d8,0x00001dd7,
22860x00001ddf,0x000000d7,0x000000d7,0x0005003e,
22870x00001dd7,0x0000037d,0x00000002,0x00000004,
22880x00050080,0x00000006,0x00001a88,0x00001916,
22890x000005d6,0x00050095,0x000000a8,0x00001e07,
22900x00001b83,0x00001a88,0x00050051,0x00000006,
22910x00001e08,0x00001e07,0x00000001,0x00050051,
22920x00000006,0x00001e09,0x00001e07,0x00000000,
22930x00050080,0x00000006,0x00001e0e,0x00001b8a,
22940x00001e08,0x00050050,0x00000007,0x00001e0f,
22950x00001e09,0x00001e0e,0x0004007c,0x00000014,
22960x00001dff,0x00001e0f,0x00060041,0x000000d8,
22970x00001df7,0x00001dff,0x000000d7,0x000000d7,
22980x0005003e,0x00001df7,0x000000a3,0x00000002,
22990x00000004,0x00050080,0x00000006,0x00001a8d,
23000x00001916,0x000005df,0x00050095,0x000000a8,
23010x00001e27,0x00001b83,0x00001a8d,0x00050051,
23020x00000006,0x00001e28,0x00001e27,0x00000001,
23030x00050051,0x00000006,0x00001e29,0x00001e27,
23040x00000000,0x00050080,0x00000006,0x00001e2e,
23050x00001b8a,0x00001e28,0x00050050,0x00000007,
23060x00001e2f,0x00001e29,0x00001e2e,0x0004007c,
23070x00000014,0x00001e1f,0x00001e2f,0x00060041,
23080x000000d8,0x00001e17,0x00001e1f,0x000000d7,
23090x000000d7,0x0005003e,0x00001e17,0x000000a3,
23100x00000002,0x00000004,0x000500b4,0x0000002f,
23110x00001a92,0x00001a33,0x0000026a,0x00060050,
23120x00000392,0x00002b6f,0x00001a92,0x00001a92,
23130x00001a92,0x000600a9,0x0000004b,0x00002b70,
23140x00002b6f,0x00002b66,0x00002b05,0x000600a9,
23150x0000004b,0x00002b72,0x00002b6f,0x00002b64,
23160x00002af3,0x00050041,0x000000fb,0x00001e79,
23170x000000f9,0x000000fa,0x0004003d,0x00000006,
23180x00001e7a,0x00001e79,0x00050084,0x00000006,
23190x00001e7b,0x0000011c,0x00001e7a,0x00050080,
23200x00000006,0x00001e7c,0x00000104,0x00001e7b,
23210x00050080,0x00000006,0x00001e82,0x00001e7a,
23220x00002b67,0x00050086,0x00000006,0x00001e83,
23230x00001e82,0x000000fe,0x00050084,0x00000006,
23240x00001e75,0x00000104,0x00001e83,0x00050080,
23250x00000006,0x00001e76,0x00001e7c,0x00001e75,
23260x00050084,0x00000006,0x00001e46,0x0000014d,
23270x000009e9,0x00050080,0x00000006,0x00001e47,
23280x00001e76,0x00001e46,0x00050041,0x00000153,
23290x00001e48,0x000000f9,0x00000151,0x0004003d,
23300x00000007,0x00001e49,0x00001e48,0x00050051,
23310x00000027,0x00001e4c,0x00002b72,0x00000000,
23320x0004007c,0x00000006,0x00001e89,0x00001e4c,
23330x00050051,0x00000006,0x00001ea2,0x00001e49,
23340x00000000,0x00050095,0x000000a8,0x00001ea4,
23350x00001ea2,0x00001e47,0x00050051,0x00000006,
23360x00001ea5,0x00001ea4,0x00000001,0x00050051,
23370x00000006,0x00001ea6,0x00001ea4,0x00000000,
23380x00050051,0x00000006,0x00001ea9,0x00001e49,
23390x00000001,0x00050080,0x00000006,0x00001eab,
23400x00001ea9,0x00001ea5,0x00050050,0x00000007,
23410x00001eac,0x00001ea6,0x00001eab,0x0004007c,
23420x00000014,0x00001e9c,0x00001eac,0x00060041,
23430x000000d8,0x00001e94,0x00001e9c,0x000000d7,
23440x000000d7,0x0005003e,0x00001e94,0x00001e89,
23450x00000002,0x00000004,0x00050080,0x00000006, 17930x00000002,0x00000004,0x00050080,0x00000006,
23460x00001e4f,0x00001e47,0x00000107,0x00050051, 17940x0000197e,0x0000195a,0x00000189,0x00050051,
23470x00000027,0x00001e53,0x00002b72,0x00000001, 17950x00000027,0x00001982,0x0000319e,0x00000002,
23480x0004007c,0x00000006,0x00001eb2,0x00001e53, 17960x0004007c,0x00000006,0x00001a69,0x00001982,
23490x00050095,0x000000a8,0x00001ecd,0x00001ea2, 17970x00050095,0x000000ab,0x00001a84,0x000019b5,
23500x00001e4f,0x00050051,0x00000006,0x00001ece, 17980x0000197e,0x00050051,0x00000006,0x00001a85,
23510x00001ecd,0x00000001,0x00050051,0x00000006, 17990x00001a84,0x00000001,0x00050051,0x00000006,
23520x00001ecf,0x00001ecd,0x00000000,0x00050080, 18000x00001a86,0x00001a84,0x00000000,0x00050080,
23530x00000006,0x00001ed4,0x00001ea9,0x00001ece, 18010x00000006,0x00001a8b,0x000019bc,0x00001a85,
23540x00050050,0x00000007,0x00001ed5,0x00001ecf, 18020x00050050,0x00000007,0x00001a8c,0x00001a86,
23550x00001ed4,0x0004007c,0x00000014,0x00001ec5, 18030x00001a8b,0x0004007c,0x00000014,0x00001a7c,
23560x00001ed5,0x00060041,0x000000d8,0x00001ebd, 18040x00001a8c,0x00060041,0x000000db,0x00001a74,
23570x00001ec5,0x000000d7,0x000000d7,0x0005003e, 18050x00001a7c,0x000000da,0x000000da,0x0005003e,
23580x00001ebd,0x00001eb2,0x00000002,0x00000004, 18060x00001a74,0x00001a69,0x00000002,0x00000004,
23590x00050080,0x00000006,0x00001e56,0x00001e47, 18070x000300f7,0x00001acc,0x00000000,0x000300fb,
23600x0000010e,0x00050051,0x00000027,0x00001e5a, 18080x000000a6,0x00001a9b,0x000200f8,0x00001a9b,
23610x00002b72,0x00000002,0x0004007c,0x00000006, 18090x000500bc,0x0000002f,0x00001ad3,0x0000195f,
23620x00001edb,0x00001e5a,0x00050095,0x000000a8, 18100x00001974,0x000300f7,0x00001ada,0x00000000,
23630x00001ef6,0x00001ea2,0x00001e56,0x00050051, 18110x000400fa,0x00001ad3,0x00001ad4,0x00001ada,
23640x00000006,0x00001ef7,0x00001ef6,0x00000001, 18120x000200f8,0x00001ad4,0x000500bc,0x0000002f,
23650x00050051,0x00000006,0x00001ef8,0x00001ef6, 18130x00001ad9,0x00001966,0x0000197b,0x000200f9,
23660x00000000,0x00050080,0x00000006,0x00001efd, 18140x00001ada,0x000200f8,0x00001ada,0x000700f5,
23670x00001ea9,0x00001ef7,0x00050050,0x00000007, 18150x0000002f,0x00001adb,0x00001ad3,0x00001a9b,
23680x00001efe,0x00001ef8,0x00001efd,0x0004007c, 18160x00001ad9,0x00001ad4,0x000300f7,0x00001ae2,
23690x00000014,0x00001eee,0x00001efe,0x00060041, 18170x00000000,0x000400fa,0x00001adb,0x00001adc,
23700x000000d8,0x00001ee6,0x00001eee,0x000000d7, 18180x00001ae2,0x000200f8,0x00001adc,0x000500bc,
23710x000000d7,0x0005003e,0x00001ee6,0x00001edb, 18190x0000002f,0x00001ae1,0x0000196d,0x00001982,
18200x000200f9,0x00001ae2,0x000200f8,0x00001ae2,
18210x000700f5,0x0000002f,0x00001ae3,0x00001adb,
18220x00001ada,0x00001ae1,0x00001adc,0x000400a8,
18230x0000002f,0x00001ae4,0x00001ae3,0x000300f7,
18240x00001aa0,0x00000000,0x000400fa,0x00001ae4,
18250x00001a9f,0x00001aa0,0x000200f8,0x00001a9f,
18260x000200f9,0x00001acc,0x000200f8,0x00001aa0,
18270x00050081,0x0000004b,0x00001aa3,0x000031a0,
18280x0000319e,0x0005008e,0x0000004b,0x00001aa4,
18290x00001aa3,0x000001ed,0x00050095,0x000000ab,
18300x00001af4,0x000019b5,0x000000a6,0x00050051,
18310x00000006,0x00001af5,0x00001af4,0x00000001,
18320x00050051,0x00000006,0x00001af6,0x00001af4,
18330x00000000,0x00050080,0x00000006,0x00001afb,
18340x000019bc,0x00001af5,0x00050050,0x00000007,
18350x00001afc,0x00001af6,0x00001afb,0x0004007c,
18360x00000014,0x00001aec,0x00001afc,0x00060041,
18370x000000db,0x00001aa9,0x00001aec,0x000000da,
18380x000000da,0x00050051,0x00000027,0x00001aab,
18390x00001aa4,0x00000000,0x0004007c,0x00000006,
18400x00001b02,0x00001aab,0x000500c7,0x00000006,
18410x00001b04,0x00001b02,0x00000130,0x000500ab,
18420x0000002f,0x00001b05,0x00001b04,0x000000a6,
18430x000300f7,0x00001b0c,0x00000000,0x000400fa,
18440x00001b05,0x00001b06,0x00001b09,0x000200f8,
18450x00001b06,0x000400c8,0x00000006,0x00001b08,
18460x00001b02,0x000200f9,0x00001b0c,0x000200f8,
18470x00001b09,0x000500c5,0x00000006,0x00001b0b,
18480x00001b02,0x00000130,0x000200f9,0x00001b0c,
18490x000200f8,0x00001b0c,0x000700f5,0x00000006,
18500x00003132,0x00001b08,0x00001b06,0x00001b0b,
18510x00001b09,0x000700ed,0x00000006,0x00001aad,
18520x00001aa9,0x000000b0,0x000000a6,0x00003132,
18530x00060041,0x000000db,0x00001aaf,0x00001aec,
18540x000000da,0x00000154,0x00050051,0x00000027,
18550x00001ab1,0x00001aa4,0x00000001,0x0004007c,
18560x00000006,0x00001b13,0x00001ab1,0x000500c7,
18570x00000006,0x00001b15,0x00001b13,0x00000130,
18580x000500ab,0x0000002f,0x00001b16,0x00001b15,
18590x000000a6,0x000300f7,0x00001b1d,0x00000000,
18600x000400fa,0x00001b16,0x00001b17,0x00001b1a,
18610x000200f8,0x00001b17,0x000400c8,0x00000006,
18620x00001b19,0x00001b13,0x000200f9,0x00001b1d,
18630x000200f8,0x00001b1a,0x000500c5,0x00000006,
18640x00001b1c,0x00001b13,0x00000130,0x000200f9,
18650x00001b1d,0x000200f8,0x00001b1d,0x000700f5,
18660x00000006,0x00003133,0x00001b19,0x00001b17,
18670x00001b1c,0x00001b1a,0x000700ed,0x00000006,
18680x00001ab3,0x00001aaf,0x000000b0,0x000000a6,
18690x00003133,0x00060041,0x000000db,0x00001ab5,
18700x00001aec,0x000000da,0x00000205,0x00050051,
18710x00000027,0x00001ab7,0x00001aa4,0x00000002,
18720x0004007c,0x00000006,0x00001b24,0x00001ab7,
18730x000500c7,0x00000006,0x00001b26,0x00001b24,
18740x00000130,0x000500ab,0x0000002f,0x00001b27,
18750x00001b26,0x000000a6,0x000300f7,0x00001b2e,
18760x00000000,0x000400fa,0x00001b27,0x00001b28,
18770x00001b2b,0x000200f8,0x00001b28,0x000400c8,
18780x00000006,0x00001b2a,0x00001b24,0x000200f9,
18790x00001b2e,0x000200f8,0x00001b2b,0x000500c5,
18800x00000006,0x00001b2d,0x00001b24,0x00000130,
18810x000200f9,0x00001b2e,0x000200f8,0x00001b2e,
18820x000700f5,0x00000006,0x00003134,0x00001b2a,
18830x00001b28,0x00001b2d,0x00001b2b,0x000700ed,
18840x00000006,0x00001ab9,0x00001ab5,0x000000b0,
18850x000000a6,0x00003134,0x00060041,0x000000db,
18860x00001abb,0x00001aec,0x000000da,0x0000020d,
18870x000300f7,0x00001b3f,0x00000000,0x000400fa,
18880x00001b05,0x00001b39,0x00001b3c,0x000200f8,
18890x00001b39,0x000400c8,0x00000006,0x00001b3b,
18900x00001b02,0x000200f9,0x00001b3f,0x000200f8,
18910x00001b3c,0x000500c5,0x00000006,0x00001b3e,
18920x00001b02,0x00000130,0x000200f9,0x00001b3f,
18930x000200f8,0x00001b3f,0x000700f5,0x00000006,
18940x00003135,0x00001b3b,0x00001b39,0x00001b3e,
18950x00001b3c,0x000700ef,0x00000006,0x00001abf,
18960x00001abb,0x000000b0,0x000000a6,0x00003135,
18970x00060041,0x000000db,0x00001ac1,0x00001aec,
18980x000000da,0x00000215,0x000300f7,0x00001b50,
18990x00000000,0x000400fa,0x00001b16,0x00001b4a,
19000x00001b4d,0x000200f8,0x00001b4a,0x000400c8,
19010x00000006,0x00001b4c,0x00001b13,0x000200f9,
19020x00001b50,0x000200f8,0x00001b4d,0x000500c5,
19030x00000006,0x00001b4f,0x00001b13,0x00000130,
19040x000200f9,0x00001b50,0x000200f8,0x00001b50,
19050x000700f5,0x00000006,0x00003136,0x00001b4c,
19060x00001b4a,0x00001b4f,0x00001b4d,0x000700ef,
19070x00000006,0x00001ac5,0x00001ac1,0x000000b0,
19080x000000a6,0x00003136,0x00060041,0x000000db,
19090x00001ac7,0x00001aec,0x000000da,0x0000021d,
19100x000300f7,0x00001b61,0x00000000,0x000400fa,
19110x00001b27,0x00001b5b,0x00001b5e,0x000200f8,
19120x00001b5b,0x000400c8,0x00000006,0x00001b5d,
19130x00001b24,0x000200f9,0x00001b61,0x000200f8,
19140x00001b5e,0x000500c5,0x00000006,0x00001b60,
19150x00001b24,0x00000130,0x000200f9,0x00001b61,
19160x000200f8,0x00001b61,0x000700f5,0x00000006,
19170x00003137,0x00001b5d,0x00001b5b,0x00001b60,
19180x00001b5e,0x000700ef,0x00000006,0x00001acb,
19190x00001ac7,0x000000b0,0x000000a6,0x00003137,
19200x000200f9,0x00001acc,0x000200f8,0x00001acc,
19210x000200f9,0x00000b95,0x000200f8,0x00000b99,
19220x000500aa,0x0000002f,0x00000b9c,0x00000b13,
19230x00000170,0x000300f7,0x00000b9e,0x00000000,
19240x000400fa,0x00000b9c,0x00000b9d,0x00000ba2,
19250x000200f8,0x00000b9d,0x00050084,0x00000006,
19260x00001bca,0x00000107,0x00000b11,0x000200f9,
19270x00001bcb,0x000200f8,0x00001bcb,0x000700f5,
19280x00000006,0x000030e4,0x000000a6,0x00000b9d,
19290x00001bdc,0x00001bcf,0x000500b0,0x0000002f,
19300x00001bce,0x000030e4,0x00000118,0x000400f6,
19310x00001bdd,0x00001bcf,0x00000000,0x000400fa,
19320x00001bce,0x00001bcf,0x00001bdd,0x000200f8,
19330x00001bcf,0x00050084,0x00000006,0x00001bd3,
19340x0000010a,0x000030e4,0x00050080,0x00000006,
19350x00001bd4,0x00001bca,0x00001bd3,0x00050041,
19360x00000156,0x00001bd5,0x000000fc,0x00000205,
19370x0004003d,0x00000007,0x00001bd6,0x00001bd5,
19380x00050051,0x00000006,0x00001d97,0x00001bd6,
19390x00000000,0x00050095,0x000000ab,0x00001d99,
19400x00001d97,0x00001bd4,0x00050051,0x00000006,
19410x00001d9a,0x00001d99,0x00000001,0x00050051,
19420x00000006,0x00001d9b,0x00001d99,0x00000000,
19430x00050051,0x00000006,0x00001d9e,0x00001bd6,
19440x00000001,0x00050080,0x00000006,0x00001da0,
19450x00001d9e,0x00001d9a,0x00050050,0x00000007,
19460x00001da1,0x00001d9b,0x00001da0,0x0004007c,
19470x00000014,0x00001d91,0x00001da1,0x00060041,
19480x000000db,0x00001d88,0x00001d91,0x000000da,
19490x000000da,0x0006003d,0x00000006,0x00001d89,
19500x00001d88,0x00000002,0x00000004,0x0004007c,
19510x00000027,0x00001bd8,0x00001d89,0x00050041,
19520x00000028,0x00001bd9,0x00001b65,0x000030e4,
19530x0003003e,0x00001bd9,0x00001bd8,0x00050080,
19540x00000006,0x00001bdc,0x000030e4,0x00000154,
19550x000200f9,0x00001bcb,0x000200f8,0x00001bdd,
19560x00050080,0x00000006,0x00001bdf,0x00001bca,
19570x00000368,0x00050041,0x00000156,0x00001be0,
19580x000000fc,0x00000205,0x0004003d,0x00000007,
19590x00001be1,0x00001be0,0x00050051,0x00000006,
19600x00001db8,0x00001be1,0x00000000,0x00050095,
19610x000000ab,0x00001dba,0x00001db8,0x00001bdf,
19620x00050051,0x00000006,0x00001dbb,0x00001dba,
19630x00000001,0x00050051,0x00000006,0x00001dbc,
19640x00001dba,0x00000000,0x00050051,0x00000006,
19650x00001dbf,0x00001be1,0x00000001,0x00050080,
19660x00000006,0x00001dc1,0x00001dbf,0x00001dbb,
19670x00050050,0x00000007,0x00001dc2,0x00001dbc,
19680x00001dc1,0x0004007c,0x00000014,0x00001db2,
19690x00001dc2,0x00060041,0x000000db,0x00001da9,
19700x00001db2,0x000000da,0x000000da,0x0006003d,
19710x00000006,0x00001daa,0x00001da9,0x00000002,
19720x00000004,0x00050080,0x00000006,0x00001be4,
19730x00001bca,0x00000374,0x00050095,0x000000ab,
19740x00001ddb,0x00001db8,0x00001be4,0x00050051,
19750x00000006,0x00001ddc,0x00001ddb,0x00000001,
19760x00050051,0x00000006,0x00001ddd,0x00001ddb,
19770x00000000,0x00050080,0x00000006,0x00001de2,
19780x00001dbf,0x00001ddc,0x00050050,0x00000007,
19790x00001de3,0x00001ddd,0x00001de2,0x0004007c,
19800x00000014,0x00001dd3,0x00001de3,0x00060041,
19810x000000db,0x00001dca,0x00001dd3,0x000000da,
19820x000000da,0x0006003d,0x00000006,0x00001dcb,
19830x00001dca,0x00000002,0x00000004,0x00050080,
19840x00000006,0x00001be9,0x00001bca,0x0000037e,
19850x00050095,0x000000ab,0x00001dfc,0x00001db8,
19860x00001be9,0x00050051,0x00000006,0x00001dfd,
19870x00001dfc,0x00000001,0x00050051,0x00000006,
19880x00001dfe,0x00001dfc,0x00000000,0x00050080,
19890x00000006,0x00001e03,0x00001dbf,0x00001dfd,
19900x00050050,0x00000007,0x00001e04,0x00001dfe,
19910x00001e03,0x0004007c,0x00000014,0x00001df4,
19920x00001e04,0x00060041,0x000000db,0x00001deb,
19930x00001df4,0x000000da,0x000000da,0x0006003d,
19940x00000006,0x00001dec,0x00001deb,0x00000002,
19950x00000004,0x00050080,0x00000006,0x00001bee,
19960x00001bca,0x00000388,0x00050095,0x000000ab,
19970x00001e1d,0x00001db8,0x00001bee,0x00050051,
19980x00000006,0x00001e1e,0x00001e1d,0x00000001,
19990x00050051,0x00000006,0x00001e1f,0x00001e1d,
20000x00000000,0x00050080,0x00000006,0x00001e24,
20010x00001dbf,0x00001e1e,0x00050050,0x00000007,
20020x00001e25,0x00001e1f,0x00001e24,0x0004007c,
20030x00000014,0x00001e15,0x00001e25,0x00060041,
20040x000000db,0x00001e0c,0x00001e15,0x000000da,
20050x000000da,0x0006003d,0x00000006,0x00001e0d,
20060x00001e0c,0x00000002,0x00000004,0x00050041,
20070x000000fe,0x00001bf3,0x000000fc,0x0000022c,
20080x0004003d,0x00000006,0x00001bf4,0x00001bf3,
20090x00050084,0x00000006,0x00001bf6,0x00000228,
20100x00000b11,0x00050080,0x00000006,0x00001bf7,
20110x00001bf4,0x00001bf6,0x000200f9,0x00001bf8,
20120x000200f8,0x00001bf8,0x000700f5,0x00000006,
20130x000030e5,0x000000a6,0x00001bdd,0x00001c09,
20140x00001bfc,0x000500b0,0x0000002f,0x00001bfb,
20150x000030e5,0x00000118,0x000400f6,0x00001c0a,
20160x00001bfc,0x00000000,0x000400fa,0x00001bfb,
20170x00001bfc,0x00001c0a,0x000200f8,0x00001bfc,
20180x00050084,0x00000006,0x00001bff,0x0000010a,
20190x000030e5,0x00050080,0x00000006,0x00001c00,
20200x00001bf7,0x00001bff,0x00050041,0x00000156,
20210x00001c02,0x000000fc,0x000000da,0x0004003d,
20220x00000007,0x00001c03,0x00001c02,0x00050041,
20230x00000028,0x00001c04,0x00001b65,0x000030e5,
20240x0004003d,0x00000027,0x00001c05,0x00001c04,
20250x0004007c,0x00000006,0x00001e2b,0x00001c05,
20260x00050051,0x00000006,0x00001e44,0x00001c03,
20270x00000000,0x00050095,0x000000ab,0x00001e46,
20280x00001e44,0x00001c00,0x00050051,0x00000006,
20290x00001e47,0x00001e46,0x00000001,0x00050051,
20300x00000006,0x00001e48,0x00001e46,0x00000000,
20310x00050051,0x00000006,0x00001e4b,0x00001c03,
20320x00000001,0x00050080,0x00000006,0x00001e4d,
20330x00001e4b,0x00001e47,0x00050050,0x00000007,
20340x00001e4e,0x00001e48,0x00001e4d,0x0004007c,
20350x00000014,0x00001e3e,0x00001e4e,0x00060041,
20360x000000db,0x00001e36,0x00001e3e,0x000000da,
20370x000000da,0x0005003e,0x00001e36,0x00001e2b,
23720x00000002,0x00000004,0x00050080,0x00000006, 20380x00000002,0x00000004,0x00050080,0x00000006,
23730x00001e5d,0x00001e47,0x00000115,0x00050051, 20390x00001c09,0x000030e5,0x00000154,0x000200f9,
23740x00000027,0x00001e61,0x00002b70,0x00000000, 20400x00001bf8,0x000200f8,0x00001c0a,0x00050080,
23750x0004007c,0x00000006,0x00001f04,0x00001e61, 20410x00000006,0x00001c0c,0x00001bf7,0x00000368,
23760x00050095,0x000000a8,0x00001f1f,0x00001ea2, 20420x00050041,0x00000156,0x00001c0d,0x000000fc,
23770x00001e5d,0x00050051,0x00000006,0x00001f20, 20430x000000da,0x0004003d,0x00000007,0x00001c0e,
23780x00001f1f,0x00000001,0x00050051,0x00000006, 20440x00001c0d,0x00050051,0x00000006,0x00001e64,
23790x00001f21,0x00001f1f,0x00000000,0x00050080, 20450x00001c0e,0x00000000,0x00050095,0x000000ab,
23800x00000006,0x00001f26,0x00001ea9,0x00001f20, 20460x00001e66,0x00001e64,0x00001c0c,0x00050051,
23810x00050050,0x00000007,0x00001f27,0x00001f21, 20470x00000006,0x00001e67,0x00001e66,0x00000001,
23820x00001f26,0x0004007c,0x00000014,0x00001f17, 20480x00050051,0x00000006,0x00001e68,0x00001e66,
23830x00001f27,0x00060041,0x000000d8,0x00001f0f, 20490x00000000,0x00050051,0x00000006,0x00001e6b,
23840x00001f17,0x000000d7,0x000000d7,0x0005003e, 20500x00001c0e,0x00000001,0x00050080,0x00000006,
23850x00001f0f,0x00001f04,0x00000002,0x00000004, 20510x00001e6d,0x00001e6b,0x00001e67,0x00050050,
23860x00050080,0x00000006,0x00001e64,0x00001e47, 20520x00000007,0x00001e6e,0x00001e68,0x00001e6d,
23870x0000011c,0x00050051,0x00000027,0x00001e68, 20530x0004007c,0x00000014,0x00001e5e,0x00001e6e,
23880x00002b70,0x00000001,0x0004007c,0x00000006, 20540x00060041,0x000000db,0x00001e56,0x00001e5e,
23890x00001f2d,0x00001e68,0x00050095,0x000000a8, 20550x000000da,0x000000da,0x0005003e,0x00001e56,
23900x00001f48,0x00001ea2,0x00001e64,0x00050051, 20560x00001daa,0x00000002,0x00000004,0x00050080,
23910x00000006,0x00001f49,0x00001f48,0x00000001, 20570x00000006,0x00001c12,0x00001bf7,0x00000374,
23920x00050051,0x00000006,0x00001f4a,0x00001f48, 20580x00050095,0x000000ab,0x00001e86,0x00001e64,
23930x00000000,0x00050080,0x00000006,0x00001f4f, 20590x00001c12,0x00050051,0x00000006,0x00001e87,
23940x00001ea9,0x00001f49,0x00050050,0x00000007, 20600x00001e86,0x00000001,0x00050051,0x00000006,
23950x00001f50,0x00001f4a,0x00001f4f,0x0004007c, 20610x00001e88,0x00001e86,0x00000000,0x00050080,
23960x00000014,0x00001f40,0x00001f50,0x00060041, 20620x00000006,0x00001e8d,0x00001e6b,0x00001e87,
23970x000000d8,0x00001f38,0x00001f40,0x000000d7, 20630x00050050,0x00000007,0x00001e8e,0x00001e88,
23980x000000d7,0x0005003e,0x00001f38,0x00001f2d, 20640x00001e8d,0x0004007c,0x00000014,0x00001e7e,
20650x00001e8e,0x00060041,0x000000db,0x00001e76,
20660x00001e7e,0x000000da,0x000000da,0x0005003e,
20670x00001e76,0x00001dcb,0x00000002,0x00000004,
20680x000500aa,0x0000002f,0x00001e93,0x00001dec,
20690x000000a6,0x000300f7,0x00001e98,0x00000000,
20700x000400fa,0x00001e93,0x00001e94,0x00001e98,
20710x000200f8,0x00001e94,0x000500aa,0x0000002f,
20720x00001e97,0x00001e0d,0x000000a6,0x000200f9,
20730x00001e98,0x000200f8,0x00001e98,0x000700f5,
20740x0000002f,0x00001e99,0x00001e93,0x00001c0a,
20750x00001e97,0x00001e94,0x000400a8,0x0000002f,
20760x00001c1d,0x00001e99,0x000300f7,0x00001cb3,
20770x00000000,0x000400fa,0x00001c1d,0x00001c1e,
20780x00001cb3,0x000200f8,0x00001c1e,0x00050041,
20790x00000156,0x00001c20,0x000000fc,0x0000021d,
20800x0004003d,0x00000007,0x00001c21,0x00001c20,
20810x00050051,0x00000006,0x00001ea1,0x00001c21,
20820x00000000,0x00050095,0x000000ab,0x00001ea2,
20830x00001dec,0x00001ea1,0x00050051,0x00000006,
20840x00001ea3,0x00001ea2,0x00000001,0x00050051,
20850x00000006,0x00001ea4,0x00001ea2,0x00000000,
20860x00050051,0x00000006,0x00001ea9,0x00001c21,
20870x00000001,0x00050080,0x00000006,0x00001eaa,
20880x00001e0d,0x00001ea9,0x00050080,0x00000006,
20890x00001eac,0x00001eaa,0x00001ea3,0x00050095,
20900x000000ab,0x00001ec6,0x00001ea4,0x00000368,
20910x00050051,0x00000006,0x00001ec7,0x00001ec6,
20920x00000001,0x00050051,0x00000006,0x00001ec8,
20930x00001ec6,0x00000000,0x00050080,0x00000006,
20940x00001ecd,0x00001eac,0x00001ec7,0x00050050,
20950x00000007,0x00001ece,0x00001ec8,0x00001ecd,
20960x0004007c,0x00000014,0x00001ebe,0x00001ece,
20970x00060041,0x000000db,0x00001eb5,0x00001ebe,
20980x000000da,0x000000da,0x0006003d,0x00000006,
20990x00001eb6,0x00001eb5,0x00000002,0x00000004,
21000x00050095,0x000000ab,0x00001ee7,0x00001ea4,
21010x0000011f,0x00050051,0x00000006,0x00001ee8,
21020x00001ee7,0x00000001,0x00050051,0x00000006,
21030x00001ee9,0x00001ee7,0x00000000,0x00050080,
21040x00000006,0x00001eee,0x00001eac,0x00001ee8,
21050x00050050,0x00000007,0x00001eef,0x00001ee9,
21060x00001eee,0x0004007c,0x00000014,0x00001edf,
21070x00001eef,0x00060041,0x000000db,0x00001ed6,
21080x00001edf,0x000000da,0x000000da,0x0006003d,
21090x00000006,0x00001ed7,0x00001ed6,0x00000002,
21100x00000004,0x0004007c,0x00000027,0x00001c27,
21110x00001ed7,0x00050095,0x000000ab,0x00001f08,
21120x00001ea4,0x00000189,0x00050051,0x00000006,
21130x00001f09,0x00001f08,0x00000001,0x00050051,
21140x00000006,0x00001f0a,0x00001f08,0x00000000,
21150x00050080,0x00000006,0x00001f0f,0x00001eac,
21160x00001f09,0x00050050,0x00000007,0x00001f10,
21170x00001f0a,0x00001f0f,0x0004007c,0x00000014,
21180x00001f00,0x00001f10,0x00060041,0x000000db,
21190x00001ef7,0x00001f00,0x000000da,0x000000da,
21200x0006003d,0x00000006,0x00001ef8,0x00001ef7,
21210x00000002,0x00000004,0x0004007c,0x00000027,
21220x00001c2a,0x00001ef8,0x00050095,0x000000ab,
21230x00001f29,0x00001ea4,0x00000150,0x00050051,
21240x00000006,0x00001f2a,0x00001f29,0x00000001,
21250x00050051,0x00000006,0x00001f2b,0x00001f29,
21260x00000000,0x00050080,0x00000006,0x00001f30,
21270x00001eac,0x00001f2a,0x00050050,0x00000007,
21280x00001f31,0x00001f2b,0x00001f30,0x0004007c,
21290x00000014,0x00001f21,0x00001f31,0x00060041,
21300x000000db,0x00001f18,0x00001f21,0x000000da,
21310x000000da,0x0006003d,0x00000006,0x00001f19,
21320x00001f18,0x00000002,0x00000004,0x0004007c,
21330x00000027,0x00001c2d,0x00001f19,0x00050095,
21340x000000ab,0x00001f4a,0x00001ea4,0x00000463,
21350x00050051,0x00000006,0x00001f4b,0x00001f4a,
21360x00000001,0x00050051,0x00000006,0x00001f4c,
21370x00001f4a,0x00000000,0x00050080,0x00000006,
21380x00001f51,0x00001eac,0x00001f4b,0x00050050,
21390x00000007,0x00001f52,0x00001f4c,0x00001f51,
21400x0004007c,0x00000014,0x00001f42,0x00001f52,
21410x00060041,0x000000db,0x00001f39,0x00001f42,
21420x000000da,0x000000da,0x0006003d,0x00000006,
21430x00001f3a,0x00001f39,0x00000002,0x00000004,
21440x0004007c,0x00000027,0x00001c31,0x00001f3a,
21450x00050095,0x000000ab,0x00001f6b,0x00001ea4,
21460x00000469,0x00050051,0x00000006,0x00001f6c,
21470x00001f6b,0x00000001,0x00050051,0x00000006,
21480x00001f6d,0x00001f6b,0x00000000,0x00050080,
21490x00000006,0x00001f72,0x00001eac,0x00001f6c,
21500x00050050,0x00000007,0x00001f73,0x00001f6d,
21510x00001f72,0x0004007c,0x00000014,0x00001f63,
21520x00001f73,0x00060041,0x000000db,0x00001f5a,
21530x00001f63,0x000000da,0x000000da,0x0006003d,
21540x00000006,0x00001f5b,0x00001f5a,0x00000002,
21550x00000004,0x0004007c,0x00000027,0x00001c34,
21560x00001f5b,0x00050095,0x000000ab,0x00001f8c,
21570x00001ea4,0x00000347,0x00050051,0x00000006,
21580x00001f8d,0x00001f8c,0x00000001,0x00050051,
21590x00000006,0x00001f8e,0x00001f8c,0x00000000,
21600x00050080,0x00000006,0x00001f93,0x00001eac,
21610x00001f8d,0x00050050,0x00000007,0x00001f94,
21620x00001f8e,0x00001f93,0x0004007c,0x00000014,
21630x00001f84,0x00001f94,0x00060041,0x000000db,
21640x00001f7b,0x00001f84,0x000000da,0x000000da,
21650x0006003d,0x00000006,0x00001f7c,0x00001f7b,
21660x00000002,0x00000004,0x0004007c,0x00000027,
21670x00001c37,0x00001f7c,0x000500bc,0x0000002f,
21680x00001f9b,0x00001c27,0x00001c31,0x000300f7,
21690x00001fa2,0x00000000,0x000400fa,0x00001f9b,
21700x00001f9c,0x00001fa2,0x000200f8,0x00001f9c,
21710x000500bc,0x0000002f,0x00001fa1,0x00001c2a,
21720x00001c34,0x000200f9,0x00001fa2,0x000200f8,
21730x00001fa2,0x000700f5,0x0000002f,0x00001fa3,
21740x00001f9b,0x00001c1e,0x00001fa1,0x00001f9c,
21750x000300f7,0x00001faa,0x00000000,0x000400fa,
21760x00001fa3,0x00001fa4,0x00001faa,0x000200f8,
21770x00001fa4,0x000500bc,0x0000002f,0x00001fa9,
21780x00001c2d,0x00001c37,0x000200f9,0x00001faa,
21790x000200f8,0x00001faa,0x000700f5,0x0000002f,
21800x00001fab,0x00001fa3,0x00001fa2,0x00001fa9,
21810x00001fa4,0x000300f7,0x00001c41,0x00000000,
21820x000400fa,0x00001fab,0x00001c3d,0x00001c41,
21830x000200f8,0x00001c3d,0x000500c2,0x00000006,
21840x00001c3f,0x00001daa,0x0000047e,0x000500ab,
21850x0000002f,0x00001c40,0x00001c3f,0x000000a6,
21860x000200f9,0x00001c41,0x000200f8,0x00001c41,
21870x000700f5,0x0000002f,0x00001c42,0x00001fab,
21880x00001faa,0x00001c40,0x00001c3d,0x000300f7,
21890x00001cb2,0x00000000,0x000400fa,0x00001c42,
21900x00001c43,0x00001cb2,0x000200f8,0x00001c43,
21910x000200f9,0x00001c44,0x000200f8,0x00001c44,
21920x000700f5,0x0000004b,0x0000311b,0x0000319b,
21930x00001c43,0x00001cad,0x00001c48,0x000700f5,
21940x0000004b,0x00003109,0x00003199,0x00001c43,
21950x00001caa,0x00001c48,0x000700f5,0x00000006,
21960x000030e6,0x000000a6,0x00001c43,0x00001cb0,
21970x00001c48,0x000500b0,0x0000002f,0x00001c47,
21980x000030e6,0x00000111,0x000400f6,0x00001cb1,
21990x00001c48,0x00000000,0x000400fa,0x00001c47,
22000x00001c48,0x00001cb1,0x000200f8,0x00001c48,
22010x000500c7,0x00000006,0x00001c4a,0x000030e6,
22020x000000b0,0x000500ab,0x0000002f,0x00001c4b,
22030x00001c4a,0x000000a6,0x000600a9,0x00000027,
22040x000031a1,0x00001c4b,0x00001c31,0x00001c27,
22050x000500c7,0x00000006,0x00001c55,0x000030e6,
22060x00000170,0x000500ab,0x0000002f,0x00001c56,
22070x00001c55,0x000000a6,0x000600a9,0x00000027,
22080x000031a2,0x00001c56,0x00001c34,0x00001c2a,
22090x000500c7,0x00000006,0x00001c60,0x000030e6,
22100x0000010a,0x000500ab,0x0000002f,0x00001c61,
22110x00001c60,0x000000a6,0x000600a9,0x00000027,
22120x000031a3,0x00001c61,0x00001c37,0x00001c2d,
22130x00050041,0x00000028,0x00001c6b,0x00001b65,
22140x000000da,0x0004003d,0x00000027,0x00001c6c,
22150x00001c6b,0x00050085,0x00000027,0x00001c6f,
22160x00001c6c,0x000031a1,0x00050041,0x00000028,
22170x00001c70,0x00001b65,0x00000154,0x0004003d,
22180x00000027,0x00001c71,0x00001c70,0x00050085,
22190x00000027,0x00001c74,0x00001c71,0x000031a2,
22200x00050081,0x00000027,0x00001c75,0x00001c6f,
22210x00001c74,0x00050041,0x00000028,0x00001c76,
22220x00001b65,0x00000205,0x0004003d,0x00000027,
22230x00001c77,0x00001c76,0x00050085,0x00000027,
22240x00001c7a,0x00001c77,0x000031a3,0x00050081,
22250x00000027,0x00001c7b,0x00001c75,0x00001c7a,
22260x00050041,0x00000028,0x00001c7c,0x00001b65,
22270x0000020d,0x0004003d,0x00000027,0x00001c7d,
22280x00001c7c,0x00050081,0x00000027,0x00001c7e,
22290x00001c7b,0x00001c7d,0x00050041,0x00000028,
22300x00001c7f,0x00001b65,0x00000215,0x0004003d,
22310x00000027,0x00001c80,0x00001c7f,0x00050085,
22320x00000027,0x00001c83,0x00001c80,0x000031a1,
22330x00050041,0x00000028,0x00001c84,0x00001b65,
22340x0000021d,0x0004003d,0x00000027,0x00001c85,
22350x00001c84,0x00050085,0x00000027,0x00001c88,
22360x00001c85,0x000031a2,0x00050081,0x00000027,
22370x00001c89,0x00001c83,0x00001c88,0x00050041,
22380x00000028,0x00001c8a,0x00001b65,0x00000233,
22390x0004003d,0x00000027,0x00001c8b,0x00001c8a,
22400x00050085,0x00000027,0x00001c8e,0x00001c8b,
22410x000031a3,0x00050081,0x00000027,0x00001c8f,
22420x00001c89,0x00001c8e,0x00050041,0x00000028,
22430x00001c90,0x00001b65,0x000004d8,0x0004003d,
22440x00000027,0x00001c91,0x00001c90,0x00050081,
22450x00000027,0x00001c92,0x00001c8f,0x00001c91,
22460x00050041,0x00000028,0x00001c93,0x00001b65,
22470x00000308,0x0004003d,0x00000027,0x00001c94,
22480x00001c93,0x00050085,0x00000027,0x00001c97,
22490x00001c94,0x000031a1,0x00050041,0x00000028,
22500x00001c98,0x00001b65,0x00000250,0x0004003d,
22510x00000027,0x00001c99,0x00001c98,0x00050085,
22520x00000027,0x00001c9c,0x00001c99,0x000031a2,
22530x00050081,0x00000027,0x00001c9d,0x00001c97,
22540x00001c9c,0x00050041,0x00000028,0x00001c9e,
22550x00001b65,0x00000266,0x0004003d,0x00000027,
22560x00001c9f,0x00001c9e,0x00050085,0x00000027,
22570x00001ca2,0x00001c9f,0x000031a3,0x00050081,
22580x00000027,0x00001ca3,0x00001c9d,0x00001ca2,
22590x00050041,0x00000028,0x00001ca4,0x00001b65,
22600x0000027b,0x0004003d,0x00000027,0x00001ca5,
22610x00001ca4,0x00050081,0x00000027,0x00001ca6,
22620x00001ca3,0x00001ca5,0x00060050,0x0000004b,
22630x00001ca7,0x00001c7e,0x00001c92,0x00001ca6,
22640x0007000c,0x0000004b,0x00001caa,0x00000001,
22650x00000025,0x00003109,0x00001ca7,0x0007000c,
22660x0000004b,0x00001cad,0x00000001,0x00000028,
22670x0000311b,0x00001ca7,0x00050080,0x00000006,
22680x00001cb0,0x000030e6,0x00000154,0x000200f9,
22690x00001c44,0x000200f8,0x00001cb1,0x000200f9,
22700x00001cb2,0x000200f8,0x00001cb2,0x000700f5,
22710x0000004b,0x00003117,0x0000319b,0x00001c41,
22720x0000311b,0x00001cb1,0x000700f5,0x0000004b,
22730x00003105,0x00003199,0x00001c41,0x00003109,
22740x00001cb1,0x000200f9,0x00001cb3,0x000200f8,
22750x00001cb3,0x000700f5,0x0000004b,0x00003115,
22760x0000319b,0x00001e98,0x00003117,0x00001cb2,
22770x000700f5,0x0000004b,0x00003103,0x00003199,
22780x00001e98,0x00003105,0x00001cb2,0x000700f5,
22790x00000006,0x000030ef,0x00000380,0x00001e98,
22800x00001eb6,0x00001cb2,0x00050041,0x00000028,
22810x00001cb4,0x00001b65,0x000000da,0x0004003d,
22820x00000027,0x00001cb5,0x00001cb4,0x000500b4,
22830x0000002f,0x00001cb6,0x00001cb5,0x000004fc,
22840x000300f7,0x00001cbb,0x00000000,0x000400fa,
22850x00001cb6,0x00001cb7,0x00001cbb,0x000200f8,
22860x00001cb7,0x00050041,0x00000028,0x00001cb8,
22870x00001b65,0x00000154,0x0004003d,0x00000027,
22880x00001cb9,0x00001cb8,0x000500b4,0x0000002f,
22890x00001cba,0x00001cb9,0x0000026d,0x000200f9,
22900x00001cbb,0x000200f8,0x00001cbb,0x000700f5,
22910x0000002f,0x00001cbc,0x00001cb6,0x00001cb3,
22920x00001cba,0x00001cb7,0x000300f7,0x00001cc1,
22930x00000000,0x000400fa,0x00001cbc,0x00001cbd,
22940x00001cc1,0x000200f8,0x00001cbd,0x00050041,
22950x00000028,0x00001cbe,0x00001b65,0x00000205,
22960x0004003d,0x00000027,0x00001cbf,0x00001cbe,
22970x000500b4,0x0000002f,0x00001cc0,0x00001cbf,
22980x0000026d,0x000200f9,0x00001cc1,0x000200f8,
22990x00001cc1,0x000700f5,0x0000002f,0x00001cc2,
23000x00001cbc,0x00001cbb,0x00001cc0,0x00001cbd,
23010x000300f7,0x00001cc7,0x00000000,0x000400fa,
23020x00001cc2,0x00001cc3,0x00001cc7,0x000200f8,
23030x00001cc3,0x00050041,0x00000028,0x00001cc4,
23040x00001b65,0x00000215,0x0004003d,0x00000027,
23050x00001cc5,0x00001cc4,0x000500b4,0x0000002f,
23060x00001cc6,0x00001cc5,0x0000026d,0x000200f9,
23070x00001cc7,0x000200f8,0x00001cc7,0x000700f5,
23080x0000002f,0x00001cc8,0x00001cc2,0x00001cc1,
23090x00001cc6,0x00001cc3,0x000300f7,0x00001ccd,
23100x00000000,0x000400fa,0x00001cc8,0x00001cc9,
23110x00001ccd,0x000200f8,0x00001cc9,0x00050041,
23120x00000028,0x00001cca,0x00001b65,0x0000021d,
23130x0004003d,0x00000027,0x00001ccb,0x00001cca,
23140x000500b4,0x0000002f,0x00001ccc,0x00001ccb,
23150x000004fc,0x000200f9,0x00001ccd,0x000200f8,
23160x00001ccd,0x000700f5,0x0000002f,0x00001cce,
23170x00001cc8,0x00001cc7,0x00001ccc,0x00001cc9,
23180x000300f7,0x00001cd3,0x00000000,0x000400fa,
23190x00001cce,0x00001ccf,0x00001cd3,0x000200f8,
23200x00001ccf,0x00050041,0x00000028,0x00001cd0,
23210x00001b65,0x00000233,0x0004003d,0x00000027,
23220x00001cd1,0x00001cd0,0x000500b4,0x0000002f,
23230x00001cd2,0x00001cd1,0x0000026d,0x000200f9,
23240x00001cd3,0x000200f8,0x00001cd3,0x000700f5,
23250x0000002f,0x00001cd4,0x00001cce,0x00001ccd,
23260x00001cd2,0x00001ccf,0x000300f7,0x00001cd9,
23270x00000000,0x000400fa,0x00001cd4,0x00001cd5,
23280x00001cd9,0x000200f8,0x00001cd5,0x00050041,
23290x00000028,0x00001cd6,0x00001b65,0x00000308,
23300x0004003d,0x00000027,0x00001cd7,0x00001cd6,
23310x000500b4,0x0000002f,0x00001cd8,0x00001cd7,
23320x0000026d,0x000200f9,0x00001cd9,0x000200f8,
23330x00001cd9,0x000700f5,0x0000002f,0x00001cda,
23340x00001cd4,0x00001cd3,0x00001cd8,0x00001cd5,
23350x000300f7,0x00001cdf,0x00000000,0x000400fa,
23360x00001cda,0x00001cdb,0x00001cdf,0x000200f8,
23370x00001cdb,0x00050041,0x00000028,0x00001cdc,
23380x00001b65,0x00000250,0x0004003d,0x00000027,
23390x00001cdd,0x00001cdc,0x000500b4,0x0000002f,
23400x00001cde,0x00001cdd,0x0000026d,0x000200f9,
23410x00001cdf,0x000200f8,0x00001cdf,0x000700f5,
23420x0000002f,0x00001ce0,0x00001cda,0x00001cd9,
23430x00001cde,0x00001cdb,0x000300f7,0x00001ce5,
23440x00000000,0x000400fa,0x00001ce0,0x00001ce1,
23450x00001ce5,0x000200f8,0x00001ce1,0x00050041,
23460x00000028,0x00001ce2,0x00001b65,0x00000266,
23470x0004003d,0x00000027,0x00001ce3,0x00001ce2,
23480x000500b4,0x0000002f,0x00001ce4,0x00001ce3,
23490x000004fc,0x000200f9,0x00001ce5,0x000200f8,
23500x00001ce5,0x000700f5,0x0000002f,0x00001ce6,
23510x00001ce0,0x00001cdf,0x00001ce4,0x00001ce1,
23520x00050080,0x00000006,0x00001ce8,0x00001bf7,
23530x0000037e,0x000500c7,0x00000006,0x00001cea,
23540x000030ef,0x00000531,0x000600a9,0x00000006,
23550x00001cec,0x00001ce6,0x00000130,0x000000a6,
23560x000500c5,0x00000006,0x00001ced,0x00001cea,
23570x00001cec,0x00050095,0x000000ab,0x00001fc4,
23580x00001e64,0x00001ce8,0x00050051,0x00000006,
23590x00001fc5,0x00001fc4,0x00000001,0x00050051,
23600x00000006,0x00001fc6,0x00001fc4,0x00000000,
23610x00050080,0x00000006,0x00001fcb,0x00001e6b,
23620x00001fc5,0x00050050,0x00000007,0x00001fcc,
23630x00001fc6,0x00001fcb,0x0004007c,0x00000014,
23640x00001fbc,0x00001fcc,0x00060041,0x000000db,
23650x00001fb4,0x00001fbc,0x000000da,0x000000da,
23660x0005003e,0x00001fb4,0x00001ced,0x00000002,
23670x00000004,0x00050080,0x00000006,0x00001cf2,
23680x00001bf7,0x00000388,0x000500c2,0x00000006,
23690x00001cf5,0x00001dec,0x00000308,0x000500c4,
23700x00000006,0x00001cf8,0x00001e0d,0x0000047e,
23710x000500c5,0x00000006,0x00001cf9,0x00001cf5,
23720x00001cf8,0x00050095,0x000000ab,0x00001fe4,
23730x00001e64,0x00001cf2,0x00050051,0x00000006,
23740x00001fe5,0x00001fe4,0x00000001,0x00050051,
23750x00000006,0x00001fe6,0x00001fe4,0x00000000,
23760x00050080,0x00000006,0x00001feb,0x00001e6b,
23770x00001fe5,0x00050050,0x00000007,0x00001fec,
23780x00001fe6,0x00001feb,0x0004007c,0x00000014,
23790x00001fdc,0x00001fec,0x00060041,0x000000db,
23800x00001fd4,0x00001fdc,0x000000da,0x000000da,
23810x0005003e,0x00001fd4,0x00001cf9,0x00000002,
23820x00000004,0x0004003d,0x00000027,0x00001cfe,
23830x00001cb4,0x00050041,0x00000028,0x00001cff,
23840x00001b65,0x00000215,0x0004003d,0x00000027,
23850x00001d00,0x00001cff,0x00050041,0x00000028,
23860x00001d01,0x00001b65,0x00000308,0x0004003d,
23870x00000027,0x00001d02,0x00001d01,0x00050041,
23880x00000028,0x00001d03,0x00001b65,0x00000154,
23890x0004003d,0x00000027,0x00001d04,0x00001d03,
23900x00050041,0x00000028,0x00001d05,0x00001b65,
23910x0000021d,0x0004003d,0x00000027,0x00001d06,
23920x00001d05,0x00050041,0x00000028,0x00001d07,
23930x00001b65,0x00000250,0x0004003d,0x00000027,
23940x00001d08,0x00001d07,0x00050041,0x00000028,
23950x00001d09,0x00001b65,0x00000205,0x0004003d,
23960x00000027,0x00001d0a,0x00001d09,0x00050041,
23970x00000028,0x00001d0b,0x00001b65,0x00000233,
23980x0004003d,0x00000027,0x00001d0c,0x00001d0b,
23990x00050041,0x00000028,0x00001d0d,0x00001b65,
24000x00000266,0x0004003d,0x00000027,0x00001d0e,
24010x00001d0d,0x00060050,0x0000004b,0x00001d0f,
24020x00001cfe,0x00001d00,0x00001d02,0x00060050,
24030x0000004b,0x00001d10,0x00001d04,0x00001d06,
24040x00001d08,0x00060050,0x0000004b,0x00001d11,
24050x00001d0a,0x00001d0c,0x00001d0e,0x00060050,
24060x0000054b,0x00001d12,0x00001d0f,0x00001d10,
24070x00001d11,0x0006000c,0x00000027,0x00001d14,
24080x00000001,0x00000021,0x00001d12,0x000500b7,
24090x0000002f,0x00001d16,0x00001d14,0x0000026d,
24100x000300f7,0x00001d1b,0x00000000,0x000400fa,
24110x00001d16,0x00001d17,0x00001d1a,0x000200f8,
24120x00001d17,0x0006000c,0x0000054b,0x00001d19,
24130x00000001,0x00000022,0x00001d12,0x000200f9,
24140x00001d1b,0x000200f8,0x00001d1a,0x000200f9,
24150x00001d1b,0x000200f8,0x00001d1b,0x000700f5,
24160x0000054b,0x000030f6,0x00001d19,0x00001d17,
24170x00000571,0x00001d1a,0x0003003e,0x00001ba6,
24180x000030f6,0x00050041,0x00000028,0x00001d1d,
24190x00001b65,0x0000020d,0x0004003d,0x00000027,
24200x00001d1e,0x00001d1d,0x00050041,0x00000028,
24210x00001d1f,0x00001b65,0x000004d8,0x0004003d,
24220x00000027,0x00001d20,0x00001d1f,0x00050041,
24230x00000028,0x00001d21,0x00001b65,0x0000027b,
24240x0004003d,0x00000027,0x00001d22,0x00001d21,
24250x00060050,0x0000004b,0x00001d23,0x00001d1e,
24260x00001d20,0x00001d22,0x00050091,0x0000004b,
24270x00001d26,0x000030f6,0x00001d23,0x0004007f,
24280x0000004b,0x00001d27,0x00001d26,0x0003003e,
24290x00001ba9,0x00001d27,0x000200f9,0x00001d28,
24300x000200f8,0x00001d28,0x000700f5,0x00000006,
24310x000030f7,0x000000a6,0x00001d1b,0x00001d5b,
24320x00001d2c,0x000500b0,0x0000002f,0x00001d2b,
24330x000030f7,0x000002b7,0x000400f6,0x00001d5c,
24340x00001d2c,0x00000000,0x000400fa,0x00001d2b,
24350x00001d2c,0x00001d5c,0x000200f8,0x00001d2c,
24360x00050080,0x00000006,0x00001d2e,0x00001bf7,
24370x00000107,0x00050084,0x00000006,0x00001d30,
24380x0000011f,0x000030f7,0x00050080,0x00000006,
24390x00001d31,0x00001d2e,0x00001d30,0x00060041,
24400x00000028,0x00001d35,0x00001ba6,0x000000da,
24410x000030f7,0x0004003d,0x00000027,0x00001d36,
24420x00001d35,0x0004007c,0x00000006,0x00001ff2,
24430x00001d36,0x00050095,0x000000ab,0x0000200d,
24440x00001e64,0x00001d31,0x00050051,0x00000006,
24450x0000200e,0x0000200d,0x00000001,0x00050051,
24460x00000006,0x0000200f,0x0000200d,0x00000000,
24470x00050080,0x00000006,0x00002014,0x00001e6b,
24480x0000200e,0x00050050,0x00000007,0x00002015,
24490x0000200f,0x00002014,0x0004007c,0x00000014,
24500x00002005,0x00002015,0x00060041,0x000000db,
24510x00001ffd,0x00002005,0x000000da,0x000000da,
24520x0005003e,0x00001ffd,0x00001ff2,0x00000002,
24530x00000004,0x00050080,0x00000006,0x00001d39,
24540x00001bf7,0x00000597,0x00050080,0x00000006,
24550x00001d3c,0x00001d39,0x00001d30,0x00060041,
24560x00000028,0x00001d40,0x00001ba6,0x00000154,
24570x000030f7,0x0004003d,0x00000027,0x00001d41,
24580x00001d40,0x0004007c,0x00000006,0x0000201b,
24590x00001d41,0x00050095,0x000000ab,0x00002036,
24600x00001e64,0x00001d3c,0x00050051,0x00000006,
24610x00002037,0x00002036,0x00000001,0x00050051,
24620x00000006,0x00002038,0x00002036,0x00000000,
24630x00050080,0x00000006,0x0000203d,0x00001e6b,
24640x00002037,0x00050050,0x00000007,0x0000203e,
24650x00002038,0x0000203d,0x0004007c,0x00000014,
24660x0000202e,0x0000203e,0x00060041,0x000000db,
24670x00002026,0x0000202e,0x000000da,0x000000da,
24680x0005003e,0x00002026,0x0000201b,0x00000002,
24690x00000004,0x00050080,0x00000006,0x00001d44,
24700x00001bf7,0x000005a6,0x00050080,0x00000006,
24710x00001d47,0x00001d44,0x00001d30,0x00060041,
24720x00000028,0x00001d4b,0x00001ba6,0x00000205,
24730x000030f7,0x0004003d,0x00000027,0x00001d4c,
24740x00001d4b,0x0004007c,0x00000006,0x00002044,
24750x00001d4c,0x00050095,0x000000ab,0x0000205f,
24760x00001e64,0x00001d47,0x00050051,0x00000006,
24770x00002060,0x0000205f,0x00000001,0x00050051,
24780x00000006,0x00002061,0x0000205f,0x00000000,
24790x00050080,0x00000006,0x00002066,0x00001e6b,
24800x00002060,0x00050050,0x00000007,0x00002067,
24810x00002061,0x00002066,0x0004007c,0x00000014,
24820x00002057,0x00002067,0x00060041,0x000000db,
24830x0000204f,0x00002057,0x000000da,0x000000da,
24840x0005003e,0x0000204f,0x00002044,0x00000002,
24850x00000004,0x00050080,0x00000006,0x00001d4f,
24860x00001bf7,0x000005b5,0x00050080,0x00000006,
24870x00001d52,0x00001d4f,0x00001d30,0x00050041,
24880x00000028,0x00001d56,0x00001ba9,0x000030f7,
24890x0004003d,0x00000027,0x00001d57,0x00001d56,
24900x0004007c,0x00000006,0x0000206d,0x00001d57,
24910x00050095,0x000000ab,0x00002088,0x00001e64,
24920x00001d52,0x00050051,0x00000006,0x00002089,
24930x00002088,0x00000001,0x00050051,0x00000006,
24940x0000208a,0x00002088,0x00000000,0x00050080,
24950x00000006,0x0000208f,0x00001e6b,0x00002089,
24960x00050050,0x00000007,0x00002090,0x0000208a,
24970x0000208f,0x0004007c,0x00000014,0x00002080,
24980x00002090,0x00060041,0x000000db,0x00002078,
24990x00002080,0x000000da,0x000000da,0x0005003e,
25000x00002078,0x0000206d,0x00000002,0x00000004,
25010x00050080,0x00000006,0x00001d5b,0x000030f7,
25020x00000154,0x000200f9,0x00001d28,0x000200f8,
25030x00001d5c,0x00050080,0x00000006,0x00001d5e,
25040x00001bf7,0x000005c6,0x00050095,0x000000ab,
25050x000020a8,0x00001e64,0x00001d5e,0x00050051,
25060x00000006,0x000020a9,0x000020a8,0x00000001,
25070x00050051,0x00000006,0x000020aa,0x000020a8,
25080x00000000,0x00050080,0x00000006,0x000020af,
25090x00001e6b,0x000020a9,0x00050050,0x00000007,
25100x000020b0,0x000020aa,0x000020af,0x0004007c,
25110x00000014,0x000020a0,0x000020b0,0x00060041,
25120x000000db,0x00002098,0x000020a0,0x000000da,
25130x000000da,0x0005003e,0x00002098,0x00000b11,
23990x00000002,0x00000004,0x00050080,0x00000006, 25140x00000002,0x00000004,0x00050080,0x00000006,
24000x00001e6b,0x00001e47,0x00000186,0x00050051, 25150x00001d64,0x00001bf7,0x000005d0,0x00050095,
24010x00000027,0x00001e6f,0x00002b70,0x00000002, 25160x000000ab,0x000020c8,0x00001e64,0x00001d64,
24020x0004007c,0x00000006,0x00001f56,0x00001e6f, 25170x00050051,0x00000006,0x000020c9,0x000020c8,
24030x00050095,0x000000a8,0x00001f71,0x00001ea2, 25180x00000001,0x00050051,0x00000006,0x000020ca,
24040x00001e6b,0x00050051,0x00000006,0x00001f72, 25190x000020c8,0x00000000,0x00050080,0x00000006,
24050x00001f71,0x00000001,0x00050051,0x00000006, 25200x000020cf,0x00001e6b,0x000020c9,0x00050050,
24060x00001f73,0x00001f71,0x00000000,0x00050080, 25210x00000007,0x000020d0,0x000020ca,0x000020cf,
24070x00000006,0x00001f78,0x00001ea9,0x00001f72, 25220x0004007c,0x00000014,0x000020c0,0x000020d0,
24080x00050050,0x00000007,0x00001f79,0x00001f73, 25230x00060041,0x000000db,0x000020b8,0x000020c0,
24090x00001f78,0x0004007c,0x00000014,0x00001f69, 25240x000000da,0x000000da,0x0005003e,0x000020b8,
24100x00001f79,0x00060041,0x000000d8,0x00001f61, 25250x00000380,0x00000002,0x00000004,0x00050080,
24110x00001f69,0x000000d7,0x000000d7,0x0005003e, 25260x00000006,0x00001d69,0x00001bf7,0x000005d9,
24120x00001f61,0x00001f56,0x00000002,0x00000004, 25270x00050095,0x000000ab,0x000020e8,0x00001e64,
24130x000300f7,0x00001fb9,0x00000000,0x000300fb, 25280x00001d69,0x00050051,0x00000006,0x000020e9,
24140x000000a3,0x00001f88,0x000200f8,0x00001f88, 25290x000020e8,0x00000001,0x00050051,0x00000006,
24150x000500bc,0x0000002f,0x00001fc0,0x00001e4c, 25300x000020ea,0x000020e8,0x00000000,0x00050080,
24160x00001e61,0x000300f7,0x00001fc7,0x00000000, 25310x00000006,0x000020ef,0x00001e6b,0x000020e9,
24170x000400fa,0x00001fc0,0x00001fc1,0x00001fc7, 25320x00050050,0x00000007,0x000020f0,0x000020ea,
24180x000200f8,0x00001fc1,0x000500bc,0x0000002f, 25330x000020ef,0x0004007c,0x00000014,0x000020e0,
24190x00001fc6,0x00001e53,0x00001e68,0x000200f9, 25340x000020f0,0x00060041,0x000000db,0x000020d8,
24200x00001fc7,0x000200f8,0x00001fc7,0x000700f5, 25350x000020e0,0x000000da,0x000000da,0x0005003e,
24210x0000002f,0x00001fc8,0x00001fc0,0x00001f88, 25360x000020d8,0x000000a6,0x00000002,0x00000004,
24220x00001fc6,0x00001fc1,0x000300f7,0x00001fcf, 25370x00050080,0x00000006,0x00001d6e,0x00001bf7,
24230x00000000,0x000400fa,0x00001fc8,0x00001fc9, 25380x000005e2,0x00050095,0x000000ab,0x00002108,
24240x00001fcf,0x000200f8,0x00001fc9,0x000500bc, 25390x00001e64,0x00001d6e,0x00050051,0x00000006,
24250x0000002f,0x00001fce,0x00001e5a,0x00001e6f, 25400x00002109,0x00002108,0x00000001,0x00050051,
24260x000200f9,0x00001fcf,0x000200f8,0x00001fcf, 25410x00000006,0x0000210a,0x00002108,0x00000000,
24270x000700f5,0x0000002f,0x00001fd0,0x00001fc8, 25420x00050080,0x00000006,0x0000210f,0x00001e6b,
24280x00001fc7,0x00001fce,0x00001fc9,0x000400a8, 25430x00002109,0x00050050,0x00000007,0x00002110,
24290x0000002f,0x00001fd1,0x00001fd0,0x000300f7, 25440x0000210a,0x0000210f,0x0004007c,0x00000014,
24300x00001f8d,0x00000000,0x000400fa,0x00001fd1, 25450x00002100,0x00002110,0x00060041,0x000000db,
24310x00001f8c,0x00001f8d,0x000200f8,0x00001f8c, 25460x000020f8,0x00002100,0x000000da,0x000000da,
24320x000200f9,0x00001fb9,0x000200f8,0x00001f8d, 25470x0005003e,0x000020f8,0x000000a6,0x00000002,
24330x00050081,0x0000004b,0x00001f90,0x00002b72, 25480x00000004,0x000500b4,0x0000002f,0x00001d73,
24340x00002b70,0x0005008e,0x0000004b,0x00001f91, 25490x00001d14,0x0000026d,0x00060050,0x00000395,
24350x00001f90,0x000001ea,0x00050095,0x000000a8, 25500x000031a4,0x00001d73,0x00001d73,0x00001d73,
24360x00001fe1,0x00001ea2,0x000000a3,0x00050051, 25510x000600a9,0x0000004b,0x000031a5,0x000031a4,
24370x00000006,0x00001fe2,0x00001fe1,0x00000001, 25520x0000319b,0x00003115,0x000600a9,0x0000004b,
24380x00050051,0x00000006,0x00001fe3,0x00001fe1, 25530x000031a7,0x000031a4,0x00003199,0x00003103,
24390x00000000,0x00050080,0x00000006,0x00001fe8, 25540x00050041,0x000000fe,0x0000215a,0x000000fc,
24400x00001ea9,0x00001fe2,0x00050050,0x00000007, 25550x000000fd,0x0004003d,0x00000006,0x0000215b,
24410x00001fe9,0x00001fe3,0x00001fe8,0x0004007c, 25560x0000215a,0x00050084,0x00000006,0x0000215c,
24420x00000014,0x00001fd9,0x00001fe9,0x00060041, 25570x0000011f,0x0000215b,0x00050080,0x00000006,
24430x000000d8,0x00001f96,0x00001fd9,0x000000d7, 25580x0000215d,0x00000107,0x0000215c,0x00050080,
24440x000000d7,0x00050051,0x00000027,0x00001f98, 25590x00000006,0x00002163,0x0000215b,0x0000319c,
24450x00001f91,0x00000000,0x0004007c,0x00000006, 25600x00050086,0x00000006,0x00002164,0x00002163,
24460x00001fef,0x00001f98,0x000500c7,0x00000006, 25610x00000101,0x00050084,0x00000006,0x00002156,
24470x00001ff1,0x00001fef,0x0000012d,0x000500ab, 25620x00000107,0x00002164,0x00050080,0x00000006,
24480x0000002f,0x00001ff2,0x00001ff1,0x000000a3, 25630x00002157,0x0000215d,0x00002156,0x00050084,
24490x000300f7,0x00001ff9,0x00000000,0x000400fa, 25640x00000006,0x00002127,0x00000150,0x00000b11,
24500x00001ff2,0x00001ff3,0x00001ff6,0x000200f8, 25650x00050080,0x00000006,0x00002128,0x00002157,
24510x00001ff3,0x000400c8,0x00000006,0x00001ff5, 25660x00002127,0x00050041,0x00000156,0x00002129,
24520x00001fef,0x000200f9,0x00001ff9,0x000200f8, 25670x000000fc,0x00000154,0x0004003d,0x00000007,
24530x00001ff6,0x000500c5,0x00000006,0x00001ff8, 25680x0000212a,0x00002129,0x00050051,0x00000027,
24540x00001fef,0x0000012d,0x000200f9,0x00001ff9, 25690x0000212d,0x000031a7,0x00000000,0x0004007c,
24550x000200f8,0x00001ff9,0x000700f5,0x00000006, 25700x00000006,0x0000216a,0x0000212d,0x00050051,
24560x00002b0c,0x00001ff5,0x00001ff3,0x00001ff8, 25710x00000006,0x00002183,0x0000212a,0x00000000,
24570x00001ff6,0x000700ed,0x00000006,0x00001f9a, 25720x00050095,0x000000ab,0x00002185,0x00002183,
24580x00001f96,0x000000ad,0x000000a3,0x00002b0c, 25730x00002128,0x00050051,0x00000006,0x00002186,
24590x00060041,0x000000d8,0x00001f9c,0x00001fd9, 25740x00002185,0x00000001,0x00050051,0x00000006,
24600x000000d7,0x00000151,0x00050051,0x00000027, 25750x00002187,0x00002185,0x00000000,0x00050051,
24610x00001f9e,0x00001f91,0x00000001,0x0004007c, 25760x00000006,0x0000218a,0x0000212a,0x00000001,
24620x00000006,0x00002000,0x00001f9e,0x000500c7, 25770x00050080,0x00000006,0x0000218c,0x0000218a,
24630x00000006,0x00002002,0x00002000,0x0000012d, 25780x00002186,0x00050050,0x00000007,0x0000218d,
24640x000500ab,0x0000002f,0x00002003,0x00002002, 25790x00002187,0x0000218c,0x0004007c,0x00000014,
24650x000000a3,0x000300f7,0x0000200a,0x00000000, 25800x0000217d,0x0000218d,0x00060041,0x000000db,
24660x000400fa,0x00002003,0x00002004,0x00002007, 25810x00002175,0x0000217d,0x000000da,0x000000da,
24670x000200f8,0x00002004,0x000400c8,0x00000006, 25820x0005003e,0x00002175,0x0000216a,0x00000002,
24680x00002006,0x00002000,0x000200f9,0x0000200a, 25830x00000004,0x00050080,0x00000006,0x00002130,
24690x000200f8,0x00002007,0x000500c5,0x00000006, 25840x00002128,0x0000010a,0x00050051,0x00000027,
24700x00002009,0x00002000,0x0000012d,0x000200f9, 25850x00002134,0x000031a7,0x00000001,0x0004007c,
24710x0000200a,0x000200f8,0x0000200a,0x000700f5, 25860x00000006,0x00002193,0x00002134,0x00050095,
24720x00000006,0x00002b0d,0x00002006,0x00002004, 25870x000000ab,0x000021ae,0x00002183,0x00002130,
24730x00002009,0x00002007,0x000700ed,0x00000006, 25880x00050051,0x00000006,0x000021af,0x000021ae,
24740x00001fa0,0x00001f9c,0x000000ad,0x000000a3, 25890x00000001,0x00050051,0x00000006,0x000021b0,
24750x00002b0d,0x00060041,0x000000d8,0x00001fa2, 25900x000021ae,0x00000000,0x00050080,0x00000006,
24760x00001fd9,0x000000d7,0x00000202,0x00050051, 25910x000021b5,0x0000218a,0x000021af,0x00050050,
24770x00000027,0x00001fa4,0x00001f91,0x00000002, 25920x00000007,0x000021b6,0x000021b0,0x000021b5,
24780x0004007c,0x00000006,0x00002011,0x00001fa4, 25930x0004007c,0x00000014,0x000021a6,0x000021b6,
24790x000500c7,0x00000006,0x00002013,0x00002011, 25940x00060041,0x000000db,0x0000219e,0x000021a6,
24800x0000012d,0x000500ab,0x0000002f,0x00002014, 25950x000000da,0x000000da,0x0005003e,0x0000219e,
24810x00002013,0x000000a3,0x000300f7,0x0000201b, 25960x00002193,0x00000002,0x00000004,0x00050080,
24820x00000000,0x000400fa,0x00002014,0x00002015, 25970x00000006,0x00002137,0x00002128,0x00000111,
24830x00002018,0x000200f8,0x00002015,0x000400c8, 25980x00050051,0x00000027,0x0000213b,0x000031a7,
24840x00000006,0x00002017,0x00002011,0x000200f9, 25990x00000002,0x0004007c,0x00000006,0x000021bc,
24850x0000201b,0x000200f8,0x00002018,0x000500c5, 26000x0000213b,0x00050095,0x000000ab,0x000021d7,
24860x00000006,0x0000201a,0x00002011,0x0000012d, 26010x00002183,0x00002137,0x00050051,0x00000006,
24870x000200f9,0x0000201b,0x000200f8,0x0000201b, 26020x000021d8,0x000021d7,0x00000001,0x00050051,
24880x000700f5,0x00000006,0x00002b0e,0x00002017, 26030x00000006,0x000021d9,0x000021d7,0x00000000,
24890x00002015,0x0000201a,0x00002018,0x000700ed, 26040x00050080,0x00000006,0x000021de,0x0000218a,
24900x00000006,0x00001fa6,0x00001fa2,0x000000ad, 26050x000021d8,0x00050050,0x00000007,0x000021df,
24910x000000a3,0x00002b0e,0x00060041,0x000000d8, 26060x000021d9,0x000021de,0x0004007c,0x00000014,
24920x00001fa8,0x00001fd9,0x000000d7,0x0000020a, 26070x000021cf,0x000021df,0x00060041,0x000000db,
24930x000300f7,0x0000202c,0x00000000,0x000400fa, 26080x000021c7,0x000021cf,0x000000da,0x000000da,
24940x00001ff2,0x00002026,0x00002029,0x000200f8, 26090x0005003e,0x000021c7,0x000021bc,0x00000002,
24950x00002026,0x000400c8,0x00000006,0x00002028, 26100x00000004,0x00050080,0x00000006,0x0000213e,
24960x00001fef,0x000200f9,0x0000202c,0x000200f8, 26110x00002128,0x00000118,0x00050051,0x00000027,
24970x00002029,0x000500c5,0x00000006,0x0000202b, 26120x00002142,0x000031a5,0x00000000,0x0004007c,
24980x00001fef,0x0000012d,0x000200f9,0x0000202c, 26130x00000006,0x000021e5,0x00002142,0x00050095,
24990x000200f8,0x0000202c,0x000700f5,0x00000006, 26140x000000ab,0x00002200,0x00002183,0x0000213e,
25000x00002b0f,0x00002028,0x00002026,0x0000202b, 26150x00050051,0x00000006,0x00002201,0x00002200,
25010x00002029,0x000700ef,0x00000006,0x00001fac, 26160x00000001,0x00050051,0x00000006,0x00002202,
25020x00001fa8,0x000000ad,0x000000a3,0x00002b0f, 26170x00002200,0x00000000,0x00050080,0x00000006,
25030x00060041,0x000000d8,0x00001fae,0x00001fd9, 26180x00002207,0x0000218a,0x00002201,0x00050050,
25040x000000d7,0x00000212,0x000300f7,0x0000203d, 26190x00000007,0x00002208,0x00002202,0x00002207,
25050x00000000,0x000400fa,0x00002003,0x00002037, 26200x0004007c,0x00000014,0x000021f8,0x00002208,
25060x0000203a,0x000200f8,0x00002037,0x000400c8, 26210x00060041,0x000000db,0x000021f0,0x000021f8,
25070x00000006,0x00002039,0x00002000,0x000200f9, 26220x000000da,0x000000da,0x0005003e,0x000021f0,
25080x0000203d,0x000200f8,0x0000203a,0x000500c5, 26230x000021e5,0x00000002,0x00000004,0x00050080,
25090x00000006,0x0000203c,0x00002000,0x0000012d, 26240x00000006,0x00002145,0x00002128,0x0000011f,
25100x000200f9,0x0000203d,0x000200f8,0x0000203d, 26250x00050051,0x00000027,0x00002149,0x000031a5,
25110x000700f5,0x00000006,0x00002b10,0x00002039, 26260x00000001,0x0004007c,0x00000006,0x0000220e,
25120x00002037,0x0000203c,0x0000203a,0x000700ef, 26270x00002149,0x00050095,0x000000ab,0x00002229,
25130x00000006,0x00001fb2,0x00001fae,0x000000ad, 26280x00002183,0x00002145,0x00050051,0x00000006,
25140x000000a3,0x00002b10,0x00060041,0x000000d8, 26290x0000222a,0x00002229,0x00000001,0x00050051,
25150x00001fb4,0x00001fd9,0x000000d7,0x0000021a, 26300x00000006,0x0000222b,0x00002229,0x00000000,
25160x000300f7,0x0000204e,0x00000000,0x000400fa, 26310x00050080,0x00000006,0x00002230,0x0000218a,
25170x00002014,0x00002048,0x0000204b,0x000200f8, 26320x0000222a,0x00050050,0x00000007,0x00002231,
25180x00002048,0x000400c8,0x00000006,0x0000204a, 26330x0000222b,0x00002230,0x0004007c,0x00000014,
25190x00002011,0x000200f9,0x0000204e,0x000200f8, 26340x00002221,0x00002231,0x00060041,0x000000db,
25200x0000204b,0x000500c5,0x00000006,0x0000204d, 26350x00002219,0x00002221,0x000000da,0x000000da,
25210x00002011,0x0000012d,0x000200f9,0x0000204e, 26360x0005003e,0x00002219,0x0000220e,0x00000002,
25220x000200f8,0x0000204e,0x000700f5,0x00000006, 26370x00000004,0x00050080,0x00000006,0x0000214c,
25230x00002b11,0x0000204a,0x00002048,0x0000204d, 26380x00002128,0x00000189,0x00050051,0x00000027,
25240x0000204b,0x000700ef,0x00000006,0x00001fb8, 26390x00002150,0x000031a5,0x00000002,0x0004007c,
25250x00001fb4,0x000000ad,0x000000a3,0x00002b11, 26400x00000006,0x00002237,0x00002150,0x00050095,
25260x000200f9,0x00001fb9,0x000200f8,0x00001fb9, 26410x000000ab,0x00002252,0x00002183,0x0000214c,
25270x000200f9,0x00000a56,0x000200f8,0x00000a5a, 26420x00050051,0x00000006,0x00002253,0x00002252,
25280x000500aa,0x0000002f,0x00000a5d,0x000009eb, 26430x00000001,0x00050051,0x00000006,0x00002254,
25290x000002b4,0x000300f7,0x00000a5f,0x00000000, 26440x00002252,0x00000000,0x00050080,0x00000006,
25300x000400fa,0x00000a5d,0x00000a5e,0x00000a63, 26450x00002259,0x0000218a,0x00002253,0x00050050,
25310x000200f8,0x00000a5e,0x00050041,0x000000fb, 26460x00000007,0x0000225a,0x00002254,0x00002259,
25320x00002103,0x000000f9,0x000000fa,0x0004003d, 26470x0004007c,0x00000014,0x0000224a,0x0000225a,
25330x00000006,0x00002104,0x00002103,0x00050084, 26480x00060041,0x000000db,0x00002242,0x0000224a,
25340x00000006,0x00002105,0x0000011c,0x00002104, 26490x000000da,0x000000da,0x0005003e,0x00002242,
25350x00050080,0x00000006,0x00002106,0x00000104, 26500x00002237,0x00000002,0x00000004,0x000300f7,
25360x00002105,0x00050080,0x00000006,0x0000210c, 26510x0000229a,0x00000000,0x000300fb,0x000000a6,
25370x00002104,0x00002b67,0x00050086,0x00000006, 26520x00002269,0x000200f8,0x00002269,0x000500bc,
25380x0000210d,0x0000210c,0x000000fe,0x00050084, 26530x0000002f,0x000022a1,0x0000212d,0x00002142,
25390x00000006,0x000020ff,0x00000104,0x0000210d, 26540x000300f7,0x000022a8,0x00000000,0x000400fa,
25400x00050080,0x00000006,0x00002100,0x00002106, 26550x000022a1,0x000022a2,0x000022a8,0x000200f8,
25410x000020ff,0x00050084,0x00000006,0x000020d4, 26560x000022a2,0x000500bc,0x0000002f,0x000022a7,
25420x0000014d,0x000009e9,0x00050080,0x00000006, 26570x00002134,0x00002149,0x000200f9,0x000022a8,
25430x000020d5,0x00002100,0x000020d4,0x00050041, 26580x000200f8,0x000022a8,0x000700f5,0x0000002f,
25440x00000153,0x000020d6,0x000000f9,0x00000151, 26590x000022a9,0x000022a1,0x00002269,0x000022a7,
25450x0004003d,0x00000007,0x000020d7,0x000020d6, 26600x000022a2,0x000300f7,0x000022b0,0x00000000,
25460x00050051,0x00000006,0x00002124,0x000020d7, 26610x000400fa,0x000022a9,0x000022aa,0x000022b0,
25470x00000000,0x00050095,0x000000a8,0x00002126, 26620x000200f8,0x000022aa,0x000500bc,0x0000002f,
25480x00002124,0x000020d5,0x00050051,0x00000006, 26630x000022af,0x0000213b,0x00002150,0x000200f9,
25490x00002127,0x00002126,0x00000001,0x00050051, 26640x000022b0,0x000200f8,0x000022b0,0x000700f5,
25500x00000006,0x00002128,0x00002126,0x00000000, 26650x0000002f,0x000022b1,0x000022a9,0x000022a8,
25510x00050051,0x00000006,0x0000212b,0x000020d7, 26660x000022af,0x000022aa,0x000400a8,0x0000002f,
25520x00000001,0x00050080,0x00000006,0x0000212d, 26670x000022b2,0x000022b1,0x000300f7,0x0000226e,
25530x0000212b,0x00002127,0x00050050,0x00000007, 26680x00000000,0x000400fa,0x000022b2,0x0000226d,
25540x0000212e,0x00002128,0x0000212d,0x0004007c, 26690x0000226e,0x000200f8,0x0000226d,0x000200f9,
25550x00000014,0x0000211e,0x0000212e,0x00060041, 26700x0000229a,0x000200f8,0x0000226e,0x00050081,
25560x000000d8,0x00002115,0x0000211e,0x000000d7, 26710x0000004b,0x00002271,0x000031a7,0x000031a5,
25570x000000d7,0x0006003d,0x00000006,0x00002116, 26720x0005008e,0x0000004b,0x00002272,0x00002271,
25580x00002115,0x00000002,0x00000004,0x0004007c, 26730x000001ed,0x00050095,0x000000ab,0x000022c2,
25590x00000027,0x000020da,0x00002116,0x00050080, 26740x00002183,0x000000a6,0x00050051,0x00000006,
25600x00000006,0x000020dc,0x000020d5,0x00000107, 26750x000022c3,0x000022c2,0x00000001,0x00050051,
25610x00050095,0x000000a8,0x00002147,0x00002124, 26760x00000006,0x000022c4,0x000022c2,0x00000000,
25620x000020dc,0x00050051,0x00000006,0x00002148, 26770x00050080,0x00000006,0x000022c9,0x0000218a,
25630x00002147,0x00000001,0x00050051,0x00000006, 26780x000022c3,0x00050050,0x00000007,0x000022ca,
25640x00002149,0x00002147,0x00000000,0x00050080, 26790x000022c4,0x000022c9,0x0004007c,0x00000014,
25650x00000006,0x0000214e,0x0000212b,0x00002148, 26800x000022ba,0x000022ca,0x00060041,0x000000db,
25660x00050050,0x00000007,0x0000214f,0x00002149, 26810x00002277,0x000022ba,0x000000da,0x000000da,
25670x0000214e,0x0004007c,0x00000014,0x0000213f, 26820x00050051,0x00000027,0x00002279,0x00002272,
25680x0000214f,0x00060041,0x000000d8,0x00002136, 26830x00000000,0x0004007c,0x00000006,0x000022d0,
25690x0000213f,0x000000d7,0x000000d7,0x0006003d, 26840x00002279,0x000500c7,0x00000006,0x000022d2,
25700x00000006,0x00002137,0x00002136,0x00000002, 26850x000022d0,0x00000130,0x000500ab,0x0000002f,
25710x00000004,0x0004007c,0x00000027,0x000020e0, 26860x000022d3,0x000022d2,0x000000a6,0x000300f7,
25720x00002137,0x00050080,0x00000006,0x000020e2, 26870x000022da,0x00000000,0x000400fa,0x000022d3,
25730x000020d5,0x0000010e,0x00050095,0x000000a8, 26880x000022d4,0x000022d7,0x000200f8,0x000022d4,
25740x00002168,0x00002124,0x000020e2,0x00050051, 26890x000400c8,0x00000006,0x000022d6,0x000022d0,
25750x00000006,0x00002169,0x00002168,0x00000001, 26900x000200f9,0x000022da,0x000200f8,0x000022d7,
25760x00050051,0x00000006,0x0000216a,0x00002168, 26910x000500c5,0x00000006,0x000022d9,0x000022d0,
25770x00000000,0x00050080,0x00000006,0x0000216f, 26920x00000130,0x000200f9,0x000022da,0x000200f8,
25780x0000212b,0x00002169,0x00050050,0x00000007, 26930x000022da,0x000700f5,0x00000006,0x0000311c,
25790x00002170,0x0000216a,0x0000216f,0x0004007c, 26940x000022d6,0x000022d4,0x000022d9,0x000022d7,
25800x00000014,0x00002160,0x00002170,0x00060041, 26950x000700ed,0x00000006,0x0000227b,0x00002277,
25810x000000d8,0x00002157,0x00002160,0x000000d7, 26960x000000b0,0x000000a6,0x0000311c,0x00060041,
25820x000000d7,0x0006003d,0x00000006,0x00002158, 26970x000000db,0x0000227d,0x000022ba,0x000000da,
25830x00002157,0x00000002,0x00000004,0x0004007c, 26980x00000154,0x00050051,0x00000027,0x0000227f,
25840x00000027,0x000020e6,0x00002158,0x00060050, 26990x00002272,0x00000001,0x0004007c,0x00000006,
25850x0000004b,0x000020e7,0x000020da,0x000020e0, 27000x000022e1,0x0000227f,0x000500c7,0x00000006,
25860x000020e6,0x00050080,0x00000006,0x000020e9, 27010x000022e3,0x000022e1,0x00000130,0x000500ab,
25870x000020d5,0x00000115,0x00050095,0x000000a8, 27020x0000002f,0x000022e4,0x000022e3,0x000000a6,
25880x00002189,0x00002124,0x000020e9,0x00050051, 27030x000300f7,0x000022eb,0x00000000,0x000400fa,
25890x00000006,0x0000218a,0x00002189,0x00000001, 27040x000022e4,0x000022e5,0x000022e8,0x000200f8,
25900x00050051,0x00000006,0x0000218b,0x00002189, 27050x000022e5,0x000400c8,0x00000006,0x000022e7,
25910x00000000,0x00050080,0x00000006,0x00002190, 27060x000022e1,0x000200f9,0x000022eb,0x000200f8,
25920x0000212b,0x0000218a,0x00050050,0x00000007, 27070x000022e8,0x000500c5,0x00000006,0x000022ea,
25930x00002191,0x0000218b,0x00002190,0x0004007c, 27080x000022e1,0x00000130,0x000200f9,0x000022eb,
25940x00000014,0x00002181,0x00002191,0x00060041, 27090x000200f8,0x000022eb,0x000700f5,0x00000006,
25950x000000d8,0x00002178,0x00002181,0x000000d7, 27100x0000311d,0x000022e7,0x000022e5,0x000022ea,
25960x000000d7,0x0006003d,0x00000006,0x00002179, 27110x000022e8,0x000700ed,0x00000006,0x00002281,
25970x00002178,0x00000002,0x00000004,0x0004007c, 27120x0000227d,0x000000b0,0x000000a6,0x0000311d,
25980x00000027,0x000020ed,0x00002179,0x00050080, 27130x00060041,0x000000db,0x00002283,0x000022ba,
25990x00000006,0x000020ef,0x000020d5,0x0000011c, 27140x000000da,0x00000205,0x00050051,0x00000027,
26000x00050095,0x000000a8,0x000021aa,0x00002124, 27150x00002285,0x00002272,0x00000002,0x0004007c,
26010x000020ef,0x00050051,0x00000006,0x000021ab, 27160x00000006,0x000022f2,0x00002285,0x000500c7,
26020x000021aa,0x00000001,0x00050051,0x00000006, 27170x00000006,0x000022f4,0x000022f2,0x00000130,
26030x000021ac,0x000021aa,0x00000000,0x00050080, 27180x000500ab,0x0000002f,0x000022f5,0x000022f4,
26040x00000006,0x000021b1,0x0000212b,0x000021ab, 27190x000000a6,0x000300f7,0x000022fc,0x00000000,
26050x00050050,0x00000007,0x000021b2,0x000021ac, 27200x000400fa,0x000022f5,0x000022f6,0x000022f9,
26060x000021b1,0x0004007c,0x00000014,0x000021a2, 27210x000200f8,0x000022f6,0x000400c8,0x00000006,
26070x000021b2,0x00060041,0x000000d8,0x00002199, 27220x000022f8,0x000022f2,0x000200f9,0x000022fc,
26080x000021a2,0x000000d7,0x000000d7,0x0006003d, 27230x000200f8,0x000022f9,0x000500c5,0x00000006,
26090x00000006,0x0000219a,0x00002199,0x00000002, 27240x000022fb,0x000022f2,0x00000130,0x000200f9,
26100x00000004,0x0004007c,0x00000027,0x000020f3, 27250x000022fc,0x000200f8,0x000022fc,0x000700f5,
26110x0000219a,0x00050080,0x00000006,0x000020f5, 27260x00000006,0x0000311e,0x000022f8,0x000022f6,
26120x000020d5,0x00000186,0x00050095,0x000000a8, 27270x000022fb,0x000022f9,0x000700ed,0x00000006,
26130x000021cb,0x00002124,0x000020f5,0x00050051, 27280x00002287,0x00002283,0x000000b0,0x000000a6,
26140x00000006,0x000021cc,0x000021cb,0x00000001, 27290x0000311e,0x00060041,0x000000db,0x00002289,
26150x00050051,0x00000006,0x000021cd,0x000021cb, 27300x000022ba,0x000000da,0x0000020d,0x000300f7,
26160x00000000,0x00050080,0x00000006,0x000021d2, 27310x0000230d,0x00000000,0x000400fa,0x000022d3,
26170x0000212b,0x000021cc,0x00050050,0x00000007, 27320x00002307,0x0000230a,0x000200f8,0x00002307,
26180x000021d3,0x000021cd,0x000021d2,0x0004007c, 27330x000400c8,0x00000006,0x00002309,0x000022d0,
26190x00000014,0x000021c3,0x000021d3,0x00060041, 27340x000200f9,0x0000230d,0x000200f8,0x0000230a,
26200x000000d8,0x000021ba,0x000021c3,0x000000d7, 27350x000500c5,0x00000006,0x0000230c,0x000022d0,
26210x000000d7,0x0006003d,0x00000006,0x000021bb, 27360x00000130,0x000200f9,0x0000230d,0x000200f8,
26220x000021ba,0x00000002,0x00000004,0x0004007c, 27370x0000230d,0x000700f5,0x00000006,0x0000311f,
26230x00000027,0x000020f9,0x000021bb,0x00060050, 27380x00002309,0x00002307,0x0000230c,0x0000230a,
26240x0000004b,0x000020fa,0x000020ed,0x000020f3, 27390x000700ef,0x00000006,0x0000228d,0x00002289,
26250x000020f9,0x000500bc,0x0000002f,0x000021da, 27400x000000b0,0x000000a6,0x0000311f,0x00060041,
26260x000020da,0x000020ed,0x000300f7,0x000021e1, 27410x000000db,0x0000228f,0x000022ba,0x000000da,
26270x00000000,0x000400fa,0x000021da,0x000021db, 27420x00000215,0x000300f7,0x0000231e,0x00000000,
26280x000021e1,0x000200f8,0x000021db,0x000500bc, 27430x000400fa,0x000022e4,0x00002318,0x0000231b,
26290x0000002f,0x000021e0,0x000020e0,0x000020f3, 27440x000200f8,0x00002318,0x000400c8,0x00000006,
26300x000200f9,0x000021e1,0x000200f8,0x000021e1, 27450x0000231a,0x000022e1,0x000200f9,0x0000231e,
26310x000700f5,0x0000002f,0x000021e2,0x000021da, 27460x000200f8,0x0000231b,0x000500c5,0x00000006,
26320x00000a5e,0x000021e0,0x000021db,0x000300f7, 27470x0000231d,0x000022e1,0x00000130,0x000200f9,
26330x000021e9,0x00000000,0x000400fa,0x000021e2, 27480x0000231e,0x000200f8,0x0000231e,0x000700f5,
26340x000021e3,0x000021e9,0x000200f8,0x000021e3, 27490x00000006,0x00003120,0x0000231a,0x00002318,
26350x000500bc,0x0000002f,0x000021e8,0x000020e6, 27500x0000231d,0x0000231b,0x000700ef,0x00000006,
26360x000020f9,0x000200f9,0x000021e9,0x000200f8, 27510x00002293,0x0000228f,0x000000b0,0x000000a6,
26370x000021e9,0x000700f5,0x0000002f,0x000021ea, 27520x00003120,0x00060041,0x000000db,0x00002295,
26380x000021e2,0x000021e1,0x000021e8,0x000021e3, 27530x000022ba,0x000000da,0x0000021d,0x000300f7,
26390x000300f7,0x000020b3,0x00000000,0x000400fa, 27540x0000232f,0x00000000,0x000400fa,0x000022f5,
26400x000021ea,0x00002077,0x000020b3,0x000200f8, 27550x00002329,0x0000232c,0x000200f8,0x00002329,
26410x00002077,0x00050095,0x000000a8,0x000021fb, 27560x000400c8,0x00000006,0x0000232b,0x000022f2,
26420x00002124,0x000000a3,0x00050051,0x00000006, 27570x000200f9,0x0000232f,0x000200f8,0x0000232c,
26430x000021fc,0x000021fb,0x00000001,0x00050051, 27580x000500c5,0x00000006,0x0000232e,0x000022f2,
26440x00000006,0x000021fd,0x000021fb,0x00000000, 27590x00000130,0x000200f9,0x0000232f,0x000200f8,
26450x00050080,0x00000006,0x00002202,0x0000212b, 27600x0000232f,0x000700f5,0x00000006,0x00003121,
26460x000021fc,0x00050050,0x00000007,0x00002203, 27610x0000232b,0x00002329,0x0000232e,0x0000232c,
26470x000021fd,0x00002202,0x0004007c,0x00000014, 27620x000700ef,0x00000006,0x00002299,0x00002295,
26480x000021f3,0x00002203,0x00060041,0x000000d8, 27630x000000b0,0x000000a6,0x00003121,0x000200f9,
26490x0000207c,0x000021f3,0x000000d7,0x000000d7, 27640x0000229a,0x000200f8,0x0000229a,0x000200f9,
26500x0006003d,0x00000006,0x0000207d,0x0000207c, 27650x00000b9e,0x000200f8,0x00000ba2,0x000500aa,
27660x0000002f,0x00000ba5,0x00000b13,0x000002b7,
27670x000300f7,0x00000ba7,0x00000000,0x000400fa,
27680x00000ba5,0x00000ba6,0x00000bab,0x000200f8,
27690x00000ba6,0x00050041,0x000000fe,0x000023e4,
27700x000000fc,0x000000fd,0x0004003d,0x00000006,
27710x000023e5,0x000023e4,0x00050084,0x00000006,
27720x000023e6,0x0000011f,0x000023e5,0x00050080,
27730x00000006,0x000023e7,0x00000107,0x000023e6,
27740x00050080,0x00000006,0x000023ed,0x000023e5,
27750x0000319c,0x00050086,0x00000006,0x000023ee,
27760x000023ed,0x00000101,0x00050084,0x00000006,
27770x000023e0,0x00000107,0x000023ee,0x00050080,
27780x00000006,0x000023e1,0x000023e7,0x000023e0,
27790x00050084,0x00000006,0x000023b5,0x00000150,
27800x00000b11,0x00050080,0x00000006,0x000023b6,
27810x000023e1,0x000023b5,0x00050041,0x00000156,
27820x000023b7,0x000000fc,0x00000154,0x0004003d,
27830x00000007,0x000023b8,0x000023b7,0x00050051,
27840x00000006,0x00002405,0x000023b8,0x00000000,
27850x00050095,0x000000ab,0x00002407,0x00002405,
27860x000023b6,0x00050051,0x00000006,0x00002408,
27870x00002407,0x00000001,0x00050051,0x00000006,
27880x00002409,0x00002407,0x00000000,0x00050051,
27890x00000006,0x0000240c,0x000023b8,0x00000001,
27900x00050080,0x00000006,0x0000240e,0x0000240c,
27910x00002408,0x00050050,0x00000007,0x0000240f,
27920x00002409,0x0000240e,0x0004007c,0x00000014,
27930x000023ff,0x0000240f,0x00060041,0x000000db,
27940x000023f6,0x000023ff,0x000000da,0x000000da,
27950x0006003d,0x00000006,0x000023f7,0x000023f6,
27960x00000002,0x00000004,0x0004007c,0x00000027,
27970x000023bb,0x000023f7,0x00050080,0x00000006,
27980x000023bd,0x000023b6,0x0000010a,0x00050095,
27990x000000ab,0x00002428,0x00002405,0x000023bd,
28000x00050051,0x00000006,0x00002429,0x00002428,
28010x00000001,0x00050051,0x00000006,0x0000242a,
28020x00002428,0x00000000,0x00050080,0x00000006,
28030x0000242f,0x0000240c,0x00002429,0x00050050,
28040x00000007,0x00002430,0x0000242a,0x0000242f,
28050x0004007c,0x00000014,0x00002420,0x00002430,
28060x00060041,0x000000db,0x00002417,0x00002420,
28070x000000da,0x000000da,0x0006003d,0x00000006,
28080x00002418,0x00002417,0x00000002,0x00000004,
28090x0004007c,0x00000027,0x000023c1,0x00002418,
28100x00050080,0x00000006,0x000023c3,0x000023b6,
28110x00000111,0x00050095,0x000000ab,0x00002449,
28120x00002405,0x000023c3,0x00050051,0x00000006,
28130x0000244a,0x00002449,0x00000001,0x00050051,
28140x00000006,0x0000244b,0x00002449,0x00000000,
28150x00050080,0x00000006,0x00002450,0x0000240c,
28160x0000244a,0x00050050,0x00000007,0x00002451,
28170x0000244b,0x00002450,0x0004007c,0x00000014,
28180x00002441,0x00002451,0x00060041,0x000000db,
28190x00002438,0x00002441,0x000000da,0x000000da,
28200x0006003d,0x00000006,0x00002439,0x00002438,
28210x00000002,0x00000004,0x0004007c,0x00000027,
28220x000023c7,0x00002439,0x00060050,0x0000004b,
28230x000023c8,0x000023bb,0x000023c1,0x000023c7,
28240x00050080,0x00000006,0x000023ca,0x000023b6,
28250x00000118,0x00050095,0x000000ab,0x0000246a,
28260x00002405,0x000023ca,0x00050051,0x00000006,
28270x0000246b,0x0000246a,0x00000001,0x00050051,
28280x00000006,0x0000246c,0x0000246a,0x00000000,
28290x00050080,0x00000006,0x00002471,0x0000240c,
28300x0000246b,0x00050050,0x00000007,0x00002472,
28310x0000246c,0x00002471,0x0004007c,0x00000014,
28320x00002462,0x00002472,0x00060041,0x000000db,
28330x00002459,0x00002462,0x000000da,0x000000da,
28340x0006003d,0x00000006,0x0000245a,0x00002459,
28350x00000002,0x00000004,0x0004007c,0x00000027,
28360x000023ce,0x0000245a,0x00050080,0x00000006,
28370x000023d0,0x000023b6,0x0000011f,0x00050095,
28380x000000ab,0x0000248b,0x00002405,0x000023d0,
28390x00050051,0x00000006,0x0000248c,0x0000248b,
28400x00000001,0x00050051,0x00000006,0x0000248d,
28410x0000248b,0x00000000,0x00050080,0x00000006,
28420x00002492,0x0000240c,0x0000248c,0x00050050,
28430x00000007,0x00002493,0x0000248d,0x00002492,
28440x0004007c,0x00000014,0x00002483,0x00002493,
28450x00060041,0x000000db,0x0000247a,0x00002483,
28460x000000da,0x000000da,0x0006003d,0x00000006,
28470x0000247b,0x0000247a,0x00000002,0x00000004,
28480x0004007c,0x00000027,0x000023d4,0x0000247b,
28490x00050080,0x00000006,0x000023d6,0x000023b6,
28500x00000189,0x00050095,0x000000ab,0x000024ac,
28510x00002405,0x000023d6,0x00050051,0x00000006,
28520x000024ad,0x000024ac,0x00000001,0x00050051,
28530x00000006,0x000024ae,0x000024ac,0x00000000,
28540x00050080,0x00000006,0x000024b3,0x0000240c,
28550x000024ad,0x00050050,0x00000007,0x000024b4,
28560x000024ae,0x000024b3,0x0004007c,0x00000014,
28570x000024a4,0x000024b4,0x00060041,0x000000db,
28580x0000249b,0x000024a4,0x000000da,0x000000da,
28590x0006003d,0x00000006,0x0000249c,0x0000249b,
28600x00000002,0x00000004,0x0004007c,0x00000027,
28610x000023da,0x0000249c,0x00060050,0x0000004b,
28620x000023db,0x000023ce,0x000023d4,0x000023da,
28630x000500bc,0x0000002f,0x000024bb,0x000023bb,
28640x000023ce,0x000300f7,0x000024c2,0x00000000,
28650x000400fa,0x000024bb,0x000024bc,0x000024c2,
28660x000200f8,0x000024bc,0x000500bc,0x0000002f,
28670x000024c1,0x000023c1,0x000023d4,0x000200f9,
28680x000024c2,0x000200f8,0x000024c2,0x000700f5,
28690x0000002f,0x000024c3,0x000024bb,0x00000ba6,
28700x000024c1,0x000024bc,0x000300f7,0x000024ca,
28710x00000000,0x000400fa,0x000024c3,0x000024c4,
28720x000024ca,0x000200f8,0x000024c4,0x000500bc,
28730x0000002f,0x000024c9,0x000023c7,0x000023da,
28740x000200f9,0x000024ca,0x000200f8,0x000024ca,
28750x000700f5,0x0000002f,0x000024cb,0x000024c3,
28760x000024c2,0x000024c9,0x000024c4,0x000300f7,
28770x00002394,0x00000000,0x000400fa,0x000024cb,
28780x00002358,0x00002394,0x000200f8,0x00002358,
28790x00050095,0x000000ab,0x000024dc,0x00002405,
28800x000000a6,0x00050051,0x00000006,0x000024dd,
28810x000024dc,0x00000001,0x00050051,0x00000006,
28820x000024de,0x000024dc,0x00000000,0x00050080,
28830x00000006,0x000024e3,0x0000240c,0x000024dd,
28840x00050050,0x00000007,0x000024e4,0x000024de,
28850x000024e3,0x0004007c,0x00000014,0x000024d4,
28860x000024e4,0x00060041,0x000000db,0x0000235d,
28870x000024d4,0x000000da,0x000000da,0x0006003d,
28880x00000006,0x0000235e,0x0000235d,0x00000002,
28890x00000004,0x000500c7,0x00000006,0x000024e9,
28900x0000235e,0x00000130,0x000500ab,0x0000002f,
28910x000024ea,0x000024e9,0x000000a6,0x000300f7,
28920x000024f1,0x00000000,0x000400fa,0x000024ea,
28930x000024eb,0x000024ee,0x000200f8,0x000024eb,
28940x000500c7,0x00000006,0x000024ed,0x0000235e,
28950x00000145,0x000200f9,0x000024f1,0x000200f8,
28960x000024ee,0x000400c8,0x00000006,0x000024f0,
28970x0000235e,0x000200f9,0x000024f1,0x000200f8,
28980x000024f1,0x000700f5,0x00000006,0x000030db,
28990x000024ed,0x000024eb,0x000024f0,0x000024ee,
29000x0004007c,0x00000027,0x000024f3,0x000030db,
29010x00060041,0x000000db,0x00002361,0x000024d4,
29020x000000da,0x00000154,0x0006003d,0x00000006,
29030x00002362,0x00002361,0x00000002,0x00000004,
29040x000500c7,0x00000006,0x000024f8,0x00002362,
29050x00000130,0x000500ab,0x0000002f,0x000024f9,
29060x000024f8,0x000000a6,0x000300f7,0x00002500,
29070x00000000,0x000400fa,0x000024f9,0x000024fa,
29080x000024fd,0x000200f8,0x000024fa,0x000500c7,
29090x00000006,0x000024fc,0x00002362,0x00000145,
29100x000200f9,0x00002500,0x000200f8,0x000024fd,
29110x000400c8,0x00000006,0x000024ff,0x00002362,
29120x000200f9,0x00002500,0x000200f8,0x00002500,
29130x000700f5,0x00000006,0x000030dc,0x000024fc,
29140x000024fa,0x000024ff,0x000024fd,0x0004007c,
29150x00000027,0x00002502,0x000030dc,0x00060041,
29160x000000db,0x00002365,0x000024d4,0x000000da,
29170x00000205,0x0006003d,0x00000006,0x00002366,
29180x00002365,0x00000002,0x00000004,0x000500c7,
29190x00000006,0x00002507,0x00002366,0x00000130,
29200x000500ab,0x0000002f,0x00002508,0x00002507,
29210x000000a6,0x000300f7,0x0000250f,0x00000000,
29220x000400fa,0x00002508,0x00002509,0x0000250c,
29230x000200f8,0x00002509,0x000500c7,0x00000006,
29240x0000250b,0x00002366,0x00000145,0x000200f9,
29250x0000250f,0x000200f8,0x0000250c,0x000400c8,
29260x00000006,0x0000250e,0x00002366,0x000200f9,
29270x0000250f,0x000200f8,0x0000250f,0x000700f5,
29280x00000006,0x000030dd,0x0000250b,0x00002509,
29290x0000250e,0x0000250c,0x0004007c,0x00000027,
29300x00002511,0x000030dd,0x00060050,0x0000004b,
29310x00002368,0x000024f3,0x00002502,0x00002511,
29320x00060041,0x000000db,0x0000236a,0x000024d4,
29330x000000da,0x0000020d,0x0006003d,0x00000006,
29340x0000236b,0x0000236a,0x00000002,0x00000004,
29350x000500c7,0x00000006,0x00002516,0x0000236b,
29360x00000130,0x000500ab,0x0000002f,0x00002517,
29370x00002516,0x000000a6,0x000300f7,0x0000251e,
29380x00000000,0x000400fa,0x00002517,0x00002518,
29390x0000251b,0x000200f8,0x00002518,0x000500c7,
29400x00000006,0x0000251a,0x0000236b,0x00000145,
29410x000200f9,0x0000251e,0x000200f8,0x0000251b,
29420x000400c8,0x00000006,0x0000251d,0x0000236b,
29430x000200f9,0x0000251e,0x000200f8,0x0000251e,
29440x000700f5,0x00000006,0x000030de,0x0000251a,
29450x00002518,0x0000251d,0x0000251b,0x0004007c,
29460x00000027,0x00002520,0x000030de,0x00060041,
29470x000000db,0x0000236e,0x000024d4,0x000000da,
29480x00000215,0x0006003d,0x00000006,0x0000236f,
29490x0000236e,0x00000002,0x00000004,0x000500c7,
29500x00000006,0x00002525,0x0000236f,0x00000130,
29510x000500ab,0x0000002f,0x00002526,0x00002525,
29520x000000a6,0x000300f7,0x0000252d,0x00000000,
29530x000400fa,0x00002526,0x00002527,0x0000252a,
29540x000200f8,0x00002527,0x000500c7,0x00000006,
29550x00002529,0x0000236f,0x00000145,0x000200f9,
29560x0000252d,0x000200f8,0x0000252a,0x000400c8,
29570x00000006,0x0000252c,0x0000236f,0x000200f9,
29580x0000252d,0x000200f8,0x0000252d,0x000700f5,
29590x00000006,0x000030df,0x00002529,0x00002527,
29600x0000252c,0x0000252a,0x0004007c,0x00000027,
29610x0000252f,0x000030df,0x00060041,0x000000db,
29620x00002372,0x000024d4,0x000000da,0x0000021d,
29630x0006003d,0x00000006,0x00002373,0x00002372,
26510x00000002,0x00000004,0x000500c7,0x00000006, 29640x00000002,0x00000004,0x000500c7,0x00000006,
26520x00002208,0x0000207d,0x0000012d,0x000500ab, 29650x00002534,0x00002373,0x00000130,0x000500ab,
26530x0000002f,0x00002209,0x00002208,0x000000a3, 29660x0000002f,0x00002535,0x00002534,0x000000a6,
26540x000300f7,0x00002210,0x00000000,0x000400fa, 29670x000300f7,0x0000253c,0x00000000,0x000400fa,
26550x00002209,0x0000220a,0x0000220d,0x000200f8, 29680x00002535,0x00002536,0x00002539,0x000200f8,
26560x0000220a,0x000500c7,0x00000006,0x0000220c, 29690x00002536,0x000500c7,0x00000006,0x00002538,
26570x0000207d,0x00000142,0x000200f9,0x00002210, 29700x00002373,0x00000145,0x000200f9,0x0000253c,
26580x000200f8,0x0000220d,0x000400c8,0x00000006, 29710x000200f8,0x00002539,0x000400c8,0x00000006,
26590x0000220f,0x0000207d,0x000200f9,0x00002210, 29720x0000253b,0x00002373,0x000200f9,0x0000253c,
26600x000200f8,0x00002210,0x000700f5,0x00000006, 29730x000200f8,0x0000253c,0x000700f5,0x00000006,
26610x00002acb,0x0000220c,0x0000220a,0x0000220f, 29740x000030e0,0x00002538,0x00002536,0x0000253b,
26620x0000220d,0x0004007c,0x00000027,0x00002212, 29750x00002539,0x0004007c,0x00000027,0x0000253e,
26630x00002acb,0x00060041,0x000000d8,0x00002080, 29760x000030e0,0x00060050,0x0000004b,0x00002375,
26640x000021f3,0x000000d7,0x00000151,0x0006003d, 29770x00002520,0x0000252f,0x0000253e,0x00050083,
26650x00000006,0x00002081,0x00002080,0x00000002, 29780x0000004b,0x00002378,0x00002375,0x00002368,
26660x00000004,0x000500c7,0x00000006,0x00002217, 29790x0007000c,0x0000004b,0x00002379,0x00000001,
26670x00002081,0x0000012d,0x000500ab,0x0000002f, 29800x00000028,0x00002378,0x0000065b,0x00050081,
26680x00002218,0x00002217,0x000000a3,0x000300f7, 29810x0000004b,0x0000237c,0x000023c8,0x000023db,
26690x0000221f,0x00000000,0x000400fa,0x00002218, 29820x0005008e,0x0000004b,0x0000237d,0x0000237c,
26700x00002219,0x0000221c,0x000200f8,0x00002219, 29830x000001ed,0x00050083,0x0000004b,0x0000237f,
26710x000500c7,0x00000006,0x0000221b,0x00002081, 29840x0000237d,0x00002368,0x00050088,0x0000004b,
26720x00000142,0x000200f9,0x0000221f,0x000200f8, 29850x00002381,0x0000237f,0x00002379,0x0008000c,
26730x0000221c,0x000400c8,0x00000006,0x0000221e, 29860x0000004b,0x00002384,0x00000001,0x0000002b,
26740x00002081,0x000200f9,0x0000221f,0x000200f8, 29870x00002381,0x00000570,0x00003196,0x0005008e,
26750x0000221f,0x000700f5,0x00000006,0x00002acc, 29880x0000004b,0x00002385,0x00002384,0x0000066b,
26760x0000221b,0x00002219,0x0000221e,0x0000221c, 29890x0004006d,0x0000065d,0x00002386,0x00002385,
26770x0004007c,0x00000027,0x00002221,0x00002acc, 29900x00050051,0x00000006,0x00002388,0x00002386,
26780x00060041,0x000000d8,0x00002084,0x000021f3, 29910x00000000,0x000500c7,0x00000006,0x00002542,
26790x000000d7,0x00000202,0x0006003d,0x00000006, 29920x00002388,0x000005fe,0x000500c4,0x00000006,
26800x00002085,0x00002084,0x00000002,0x00000004, 29930x00002545,0x00002542,0x0000023e,0x000500c5,
26810x000500c7,0x00000006,0x00002226,0x00002085, 29940x00000006,0x00002546,0x00002542,0x00002545,
26820x0000012d,0x000500ab,0x0000002f,0x00002227, 29950x000500c7,0x00000006,0x00002547,0x00002546,
26830x00002226,0x000000a3,0x000300f7,0x0000222e, 29960x00000605,0x000500c4,0x00000006,0x0000254a,
26840x00000000,0x000400fa,0x00002227,0x00002228, 29970x00002547,0x00000308,0x000500c5,0x00000006,
26850x0000222b,0x000200f8,0x00002228,0x000500c7, 29980x0000254b,0x00002547,0x0000254a,0x000500c7,
26860x00000006,0x0000222a,0x00002085,0x00000142, 29990x00000006,0x0000254c,0x0000254b,0x0000060b,
26870x000200f9,0x0000222e,0x000200f8,0x0000222b, 30000x000500c4,0x00000006,0x0000254f,0x0000254c,
26880x000400c8,0x00000006,0x0000222d,0x00002085, 30010x00000215,0x000500c5,0x00000006,0x00002550,
26890x000200f9,0x0000222e,0x000200f8,0x0000222e, 30020x0000254c,0x0000254f,0x000500c7,0x00000006,
26900x000700f5,0x00000006,0x00002acd,0x0000222a, 30030x00002551,0x00002550,0x00000611,0x000500c4,
26910x00002228,0x0000222d,0x0000222b,0x0004007c, 30040x00000006,0x00002554,0x00002551,0x00000205,
26920x00000027,0x00002230,0x00002acd,0x00060050, 30050x000500c5,0x00000006,0x00002555,0x00002551,
26930x0000004b,0x00002087,0x00002212,0x00002221, 30060x00002554,0x000500c7,0x00000006,0x00002556,
26940x00002230,0x00060041,0x000000d8,0x00002089, 30070x00002555,0x00000617,0x000500c4,0x00000006,
26950x000021f3,0x000000d7,0x0000020a,0x0006003d, 30080x0000238a,0x00002556,0x00000205,0x00050051,
26960x00000006,0x0000208a,0x00002089,0x00000002, 30090x00000006,0x0000238c,0x00002386,0x00000001,
26970x00000004,0x000500c7,0x00000006,0x00002235, 30100x000500c7,0x00000006,0x0000255b,0x0000238c,
26980x0000208a,0x0000012d,0x000500ab,0x0000002f, 30110x000005fe,0x000500c4,0x00000006,0x0000255e,
26990x00002236,0x00002235,0x000000a3,0x000300f7, 30120x0000255b,0x0000023e,0x000500c5,0x00000006,
27000x0000223d,0x00000000,0x000400fa,0x00002236, 30130x0000255f,0x0000255b,0x0000255e,0x000500c7,
27010x00002237,0x0000223a,0x000200f8,0x00002237, 30140x00000006,0x00002560,0x0000255f,0x00000605,
27020x000500c7,0x00000006,0x00002239,0x0000208a, 30150x000500c4,0x00000006,0x00002563,0x00002560,
27030x00000142,0x000200f9,0x0000223d,0x000200f8, 30160x00000308,0x000500c5,0x00000006,0x00002564,
27040x0000223a,0x000400c8,0x00000006,0x0000223c, 30170x00002560,0x00002563,0x000500c7,0x00000006,
27050x0000208a,0x000200f9,0x0000223d,0x000200f8, 30180x00002565,0x00002564,0x0000060b,0x000500c4,
27060x0000223d,0x000700f5,0x00000006,0x00002ace, 30190x00000006,0x00002568,0x00002565,0x00000215,
27070x00002239,0x00002237,0x0000223c,0x0000223a, 30200x000500c5,0x00000006,0x00002569,0x00002565,
27080x0004007c,0x00000027,0x0000223f,0x00002ace, 30210x00002568,0x000500c7,0x00000006,0x0000256a,
27090x00060041,0x000000d8,0x0000208d,0x000021f3, 30220x00002569,0x00000611,0x000500c4,0x00000006,
27100x000000d7,0x00000212,0x0006003d,0x00000006, 30230x0000256d,0x0000256a,0x00000205,0x000500c5,
27110x0000208e,0x0000208d,0x00000002,0x00000004, 30240x00000006,0x0000256e,0x0000256a,0x0000256d,
27120x000500c7,0x00000006,0x00002244,0x0000208e, 30250x000500c7,0x00000006,0x0000256f,0x0000256e,
27130x0000012d,0x000500ab,0x0000002f,0x00002245, 30260x00000617,0x000500c4,0x00000006,0x0000238e,
27140x00002244,0x000000a3,0x000300f7,0x0000224c, 30270x0000256f,0x00000154,0x000500c5,0x00000006,
27150x00000000,0x000400fa,0x00002245,0x00002246, 30280x0000238f,0x0000238a,0x0000238e,0x00050051,
27160x00002249,0x000200f8,0x00002246,0x000500c7, 30290x00000006,0x00002391,0x00002386,0x00000002,
27170x00000006,0x00002248,0x0000208e,0x00000142, 30300x000500c7,0x00000006,0x00002574,0x00002391,
27180x000200f9,0x0000224c,0x000200f8,0x00002249, 30310x000005fe,0x000500c4,0x00000006,0x00002577,
27190x000400c8,0x00000006,0x0000224b,0x0000208e, 30320x00002574,0x0000023e,0x000500c5,0x00000006,
27200x000200f9,0x0000224c,0x000200f8,0x0000224c, 30330x00002578,0x00002574,0x00002577,0x000500c7,
27210x000700f5,0x00000006,0x00002acf,0x00002248, 30340x00000006,0x00002579,0x00002578,0x00000605,
27220x00002246,0x0000224b,0x00002249,0x0004007c, 30350x000500c4,0x00000006,0x0000257c,0x00002579,
27230x00000027,0x0000224e,0x00002acf,0x00060041, 30360x00000308,0x000500c5,0x00000006,0x0000257d,
27240x000000d8,0x00002091,0x000021f3,0x000000d7, 30370x00002579,0x0000257c,0x000500c7,0x00000006,
27250x0000021a,0x0006003d,0x00000006,0x00002092, 30380x0000257e,0x0000257d,0x0000060b,0x000500c4,
27260x00002091,0x00000002,0x00000004,0x000500c7, 30390x00000006,0x00002581,0x0000257e,0x00000215,
27270x00000006,0x00002253,0x00002092,0x0000012d, 30400x000500c5,0x00000006,0x00002582,0x0000257e,
27280x000500ab,0x0000002f,0x00002254,0x00002253, 30410x00002581,0x000500c7,0x00000006,0x00002583,
27290x000000a3,0x000300f7,0x0000225b,0x00000000, 30420x00002582,0x00000611,0x000500c4,0x00000006,
27300x000400fa,0x00002254,0x00002255,0x00002258, 30430x00002586,0x00002583,0x00000205,0x000500c5,
27310x000200f8,0x00002255,0x000500c7,0x00000006, 30440x00000006,0x00002587,0x00002583,0x00002586,
27320x00002257,0x00002092,0x00000142,0x000200f9, 30450x000500c7,0x00000006,0x00002588,0x00002587,
27330x0000225b,0x000200f8,0x00002258,0x000400c8, 30460x00000617,0x000500c5,0x00000006,0x00002393,
27340x00000006,0x0000225a,0x00002092,0x000200f9, 30470x0000238f,0x00002588,0x000200f9,0x00002394,
27350x0000225b,0x000200f8,0x0000225b,0x000700f5, 30480x000200f8,0x00002394,0x000700f5,0x00000006,
27360x00000006,0x00002ad0,0x00002257,0x00002255, 30490x000030e1,0x00000531,0x000024ca,0x00002393,
27370x0000225a,0x00002258,0x0004007c,0x00000027, 30500x0000253c,0x00050084,0x00000006,0x00002397,
27380x0000225d,0x00002ad0,0x00060050,0x0000004b, 30510x0000010a,0x00000b11,0x00050080,0x00000006,
27390x00002094,0x0000223f,0x0000224e,0x0000225d, 30520x00002398,0x00000107,0x00002397,0x00050095,
27400x00050083,0x0000004b,0x00002097,0x00002094, 30530x000000ab,0x000025a3,0x00002405,0x00002398,
27410x00002087,0x0007000c,0x0000004b,0x00002098, 30540x00050051,0x00000006,0x000025a4,0x000025a3,
27420x00000001,0x00000028,0x00002097,0x00000658, 30550x00000001,0x00050051,0x00000006,0x000025a5,
27430x00050081,0x0000004b,0x0000209b,0x000020e7, 30560x000025a3,0x00000000,0x00050080,0x00000006,
27440x000020fa,0x0005008e,0x0000004b,0x0000209c, 30570x000025aa,0x0000240c,0x000025a4,0x00050050,
27450x0000209b,0x000001ea,0x00050083,0x0000004b, 30580x00000007,0x000025ab,0x000025a5,0x000025aa,
27460x0000209e,0x0000209c,0x00002087,0x00050088, 30590x0004007c,0x00000014,0x0000259b,0x000025ab,
27470x0000004b,0x000020a0,0x0000209e,0x00002098, 30600x00060041,0x000000db,0x00002593,0x0000259b,
27480x0008000c,0x0000004b,0x000020a3,0x00000001, 30610x000000da,0x000000da,0x0005003e,0x00002593,
27490x0000002b,0x000020a0,0x0000056d,0x00002b61, 30620x000030e1,0x00000002,0x00000004,0x00050084,
27500x0005008e,0x0000004b,0x000020a4,0x000020a3, 30630x00000006,0x000025b0,0x0000010a,0x000023e5,
27510x00000668,0x0004006d,0x0000065a,0x000020a5, 30640x00050080,0x00000006,0x000025b1,0x00000107,
27520x000020a4,0x00050051,0x00000006,0x000020a7, 30650x000025b0,0x00050080,0x00000006,0x000023a0,
27530x000020a5,0x00000000,0x000500c7,0x00000006, 30660x000025b1,0x00002397,0x00050095,0x000000ab,
27540x00002261,0x000020a7,0x000005fb,0x000500c4, 30670x000025c9,0x00002405,0x000023a0,0x00050051,
27550x00000006,0x00002264,0x00002261,0x0000023b, 30680x00000006,0x000025ca,0x000025c9,0x00000001,
27560x000500c5,0x00000006,0x00002265,0x00002261, 30690x00050051,0x00000006,0x000025cb,0x000025c9,
27570x00002264,0x000500c7,0x00000006,0x00002266, 30700x00000000,0x00050080,0x00000006,0x000025d0,
27580x00002265,0x00000602,0x000500c4,0x00000006, 30710x0000240c,0x000025ca,0x00050050,0x00000007,
27590x00002269,0x00002266,0x00000305,0x000500c5, 30720x000025d1,0x000025cb,0x000025d0,0x0004007c,
27600x00000006,0x0000226a,0x00002266,0x00002269, 30730x00000014,0x000025c1,0x000025d1,0x00060041,
27610x000500c7,0x00000006,0x0000226b,0x0000226a, 30740x000000db,0x000025b9,0x000025c1,0x000000da,
27620x00000608,0x000500c4,0x00000006,0x0000226e, 30750x000000da,0x0005003e,0x000025b9,0x00000b11,
27630x0000226b,0x00000212,0x000500c5,0x00000006, 30760x00000002,0x00000004,0x000200f9,0x00000ba7,
27640x0000226f,0x0000226b,0x0000226e,0x000500c7, 30770x000200f8,0x00000bab,0x000500aa,0x0000002f,
27650x00000006,0x00002270,0x0000226f,0x0000060e, 30780x00000bae,0x00000b13,0x00000246,0x000300f7,
27660x000500c4,0x00000006,0x00002273,0x00002270, 30790x00000bb0,0x00000000,0x000400fa,0x00000bae,
27670x00000202,0x000500c5,0x00000006,0x00002274, 30800x00000baf,0x00000bb0,0x000200f8,0x00000baf,
27680x00002270,0x00002273,0x000500c7,0x00000006, 30810x00050041,0x000000fe,0x00002620,0x000000fc,
27690x00002275,0x00002274,0x00000614,0x000500c4, 30820x00000308,0x0004003d,0x00000006,0x00002621,
27700x00000006,0x000020a9,0x00002275,0x00000202, 30830x00002620,0x00050080,0x00000006,0x00002623,
27710x00050051,0x00000006,0x000020ab,0x000020a5, 30840x00002621,0x00000b11,0x00050041,0x000000fe,
27720x00000001,0x000500c7,0x00000006,0x0000227a, 30850x00002729,0x000000fc,0x0000023e,0x0004003d,
27730x000020ab,0x000005fb,0x000500c4,0x00000006, 30860x00000006,0x0000272a,0x00002729,0x00050084,
27740x0000227d,0x0000227a,0x0000023b,0x000500c5, 30870x00000006,0x0000272c,0x00002623,0x00000228,
27750x00000006,0x0000227e,0x0000227a,0x0000227d, 30880x00050080,0x00000006,0x0000272d,0x0000272a,
27760x000500c7,0x00000006,0x0000227f,0x0000227e, 30890x0000272c,0x000500c2,0x00000006,0x0000272e,
27770x00000602,0x000500c4,0x00000006,0x00002282, 30900x0000272d,0x00000233,0x000500c4,0x00000006,
27780x0000227f,0x00000305,0x000500c5,0x00000006, 30910x0000272f,0x0000272e,0x0000020d,0x000500c5,
27790x00002283,0x0000227f,0x00002282,0x000500c7, 30920x00000006,0x00002730,0x0000272f,0x00000246,
27800x00000006,0x00002284,0x00002283,0x00000608, 30930x000200f9,0x0000262f,0x000200f8,0x0000262f,
27810x000500c4,0x00000006,0x00002287,0x00002284, 30940x000700f5,0x0000004b,0x00003096,0x0000319b,
27820x00000212,0x000500c5,0x00000006,0x00002288, 30950x00000baf,0x0000317f,0x0000270b,0x000700f5,
27830x00002284,0x00002287,0x000500c7,0x00000006, 30960x0000004b,0x00003094,0x00003199,0x00000baf,
27840x00002289,0x00002288,0x0000060e,0x000500c4, 30970x0000317a,0x0000270b,0x000700f5,0x00000006,
27850x00000006,0x0000228c,0x00002289,0x00000202, 30980x00003091,0x000000a6,0x00000baf,0x0000270d,
27860x000500c5,0x00000006,0x0000228d,0x00002289, 30990x0000270b,0x000500b0,0x0000002f,0x00002632,
27870x0000228c,0x000500c7,0x00000006,0x0000228e, 31000x00003091,0x0000010a,0x000400f6,0x0000270e,
27880x0000228d,0x00000614,0x000500c4,0x00000006, 31010x0000270b,0x00000000,0x000400fa,0x00002632,
27890x000020ad,0x0000228e,0x00000151,0x000500c5, 31020x00002633,0x0000270e,0x000200f8,0x00002633,
27900x00000006,0x000020ae,0x000020a9,0x000020ad, 31030x00050084,0x00000006,0x00002635,0x0000010a,
27910x00050051,0x00000006,0x000020b0,0x000020a5, 31040x00000b11,0x00050080,0x00000006,0x00002637,
27920x00000002,0x000500c7,0x00000006,0x00002293, 31050x00002635,0x00003091,0x00050041,0x000000fe,
27930x000020b0,0x000005fb,0x000500c4,0x00000006, 31060x0000263c,0x000000fc,0x0000027b,0x0004003d,
27940x00002296,0x00002293,0x0000023b,0x000500c5, 31070x00000006,0x0000263d,0x0000263c,0x000500aa,
27950x00000006,0x00002297,0x00002293,0x00002296, 31080x0000002f,0x0000263e,0x0000263d,0x000000b0,
27960x000500c7,0x00000006,0x00002298,0x00002297, 31090x000300f7,0x000026d4,0x00000000,0x000400fa,
27970x00000602,0x000500c4,0x00000006,0x0000229b, 31100x0000263e,0x0000263f,0x00002684,0x000200f8,
27980x00002298,0x00000305,0x000500c5,0x00000006, 31110x0000263f,0x00050084,0x00000006,0x00002642,
27990x0000229c,0x00002298,0x0000229b,0x000500c7, 31120x0000010a,0x00003091,0x00050080,0x00000006,
28000x00000006,0x0000229d,0x0000229c,0x00000608, 31130x00002643,0x0000272d,0x00002642,0x00050041,
28010x000500c4,0x00000006,0x000022a0,0x0000229d, 31140x00000156,0x00002644,0x000000fc,0x000000da,
28020x00000212,0x000500c5,0x00000006,0x000022a1, 31150x0004003d,0x00000007,0x00002645,0x00002644,
28030x0000229d,0x000022a0,0x000500c7,0x00000006, 31160x00050051,0x00000006,0x00002747,0x00002645,
28040x000022a2,0x000022a1,0x0000060e,0x000500c4, 31170x00000000,0x00050095,0x000000ab,0x00002749,
28050x00000006,0x000022a5,0x000022a2,0x00000202, 31180x00002747,0x00002643,0x00050051,0x00000006,
28060x000500c5,0x00000006,0x000022a6,0x000022a2, 31190x0000274a,0x00002749,0x00000001,0x00050051,
28070x000022a5,0x000500c7,0x00000006,0x000022a7, 31200x00000006,0x0000274b,0x00002749,0x00000000,
28080x000022a6,0x00000614,0x000500c5,0x00000006, 31210x00050051,0x00000006,0x0000274e,0x00002645,
28090x000020b2,0x000020ae,0x000022a7,0x000200f9, 31220x00000001,0x00050080,0x00000006,0x00002750,
28100x000020b3,0x000200f8,0x000020b3,0x000700f5, 31230x0000274e,0x0000274a,0x00050050,0x00000007,
28110x00000006,0x00002ad1,0x0000052e,0x000021e9, 31240x00002751,0x0000274b,0x00002750,0x0004007c,
28120x000020b2,0x0000225b,0x00050084,0x00000006, 31250x00000014,0x00002741,0x00002751,0x00060041,
28130x000020b6,0x00000107,0x000009e9,0x00050080, 31260x000000db,0x00002738,0x00002741,0x000000da,
28140x00000006,0x000020b7,0x00000104,0x000020b6, 31270x000000da,0x0006003d,0x00000006,0x00002739,
28150x00050095,0x000000a8,0x000022c2,0x00002124, 31280x00002738,0x00000002,0x00000004,0x000500ab,
28160x000020b7,0x00050051,0x00000006,0x000022c3, 31290x0000002f,0x00002648,0x00002739,0x00000380,
28170x000022c2,0x00000001,0x00050051,0x00000006, 31300x000300f7,0x00002683,0x00000000,0x000400fa,
28180x000022c4,0x000022c2,0x00000000,0x00050080, 31310x00002648,0x00002649,0x00002683,0x000200f8,
28190x00000006,0x000022c9,0x0000212b,0x000022c3, 31320x00002649,0x000500c2,0x00000006,0x00002755,
28200x00050050,0x00000007,0x000022ca,0x000022c4, 31330x00002739,0x0000020d,0x00050084,0x00000006,
28210x000022c9,0x0004007c,0x00000014,0x000022ba, 31340x0000264c,0x00002755,0x00000107,0x000500c7,
28220x000022ca,0x00060041,0x000000d8,0x000022b2, 31350x00000006,0x0000264e,0x00002739,0x00000967,
28230x000022ba,0x000000d7,0x000000d7,0x0005003e, 31360x000500aa,0x0000002f,0x0000264f,0x0000264e,
28240x000022b2,0x00002ad1,0x00000002,0x00000004, 31370x00000246,0x000300f7,0x00002676,0x00000000,
28250x00050084,0x00000006,0x000022cf,0x00000107, 31380x000400fa,0x0000264f,0x00002650,0x0000265c,
28260x00002104,0x00050080,0x00000006,0x000022d0, 31390x000200f8,0x00002650,0x00050041,0x000000fe,
28270x00000104,0x000022cf,0x00050080,0x00000006, 31400x00002651,0x000000fc,0x0000096c,0x0004003d,
28280x000020bf,0x000022d0,0x000020b6,0x00050095, 31410x00000006,0x00002652,0x00002651,0x00050082,
28290x000000a8,0x000022e8,0x00002124,0x000020bf, 31420x00000006,0x00002656,0x0000264c,0x0000272a,
28300x00050051,0x00000006,0x000022e9,0x000022e8, 31430x00050086,0x00000006,0x00002657,0x00002656,
28310x00000001,0x00050051,0x00000006,0x000022ea, 31440x00000228,0x00050080,0x00000006,0x00002658,
28320x000022e8,0x00000000,0x00050080,0x00000006, 31450x00002652,0x00002657,0x00050041,0x000000fe,
28330x000022ef,0x0000212b,0x000022e9,0x00050050, 31460x00002795,0x000000fc,0x000000fd,0x0004003d,
28340x00000007,0x000022f0,0x000022ea,0x000022ef, 31470x00000006,0x00002796,0x00002795,0x00050084,
28350x0004007c,0x00000014,0x000022e0,0x000022f0, 31480x00000006,0x00002797,0x0000011f,0x00002796,
28360x00060041,0x000000d8,0x000022d8,0x000022e0, 31490x00050080,0x00000006,0x00002798,0x00000107,
28370x000000d7,0x000000d7,0x0005003e,0x000022d8, 31500x00002797,0x00050080,0x00000006,0x0000279e,
28380x000009e9,0x00000002,0x00000004,0x000200f9, 31510x00002796,0x0000319c,0x00050086,0x00000006,
28390x00000a5f,0x000200f8,0x00000a63,0x000500aa, 31520x0000279f,0x0000279e,0x00000101,0x00050084,
28400x0000002f,0x00000a66,0x000009eb,0x00000243, 31530x00000006,0x00002791,0x00000107,0x0000279f,
28410x000300f7,0x00000a68,0x00000000,0x000400fa, 31540x00050080,0x00000006,0x00002792,0x00002798,
28420x00000a66,0x00000a67,0x00000a68,0x000200f8, 31550x00002791,0x00050084,0x00000006,0x00002766,
28430x00000a67,0x00050041,0x000000fb,0x0000232f, 31560x00000150,0x00002658,0x00050080,0x00000006,
28440x000000f9,0x00000305,0x0004003d,0x00000006, 31570x00002767,0x00002792,0x00002766,0x00050041,
28450x00002330,0x0000232f,0x00050080,0x00000006, 31580x00000156,0x00002768,0x000000fc,0x00000154,
28460x00002332,0x00002330,0x000009e9,0x00050041, 31590x0004003d,0x00000007,0x00002769,0x00002768,
28470x000000fb,0x000023ee,0x000000f9,0x0000023b, 31600x00050051,0x00000006,0x000027b6,0x00002769,
28480x0004003d,0x00000006,0x000023ef,0x000023ee, 31610x00000000,0x00050095,0x000000ab,0x000027b8,
28490x00050084,0x00000006,0x000023f1,0x00002332, 31620x000027b6,0x00002767,0x00050051,0x00000006,
28500x00000225,0x00050080,0x00000006,0x000023f2, 31630x000027b9,0x000027b8,0x00000001,0x00050051,
28510x000023ef,0x000023f1,0x000500c2,0x00000006, 31640x00000006,0x000027ba,0x000027b8,0x00000000,
28520x000023f3,0x000023f2,0x00000230,0x000500c4, 31650x00050051,0x00000006,0x000027bd,0x00002769,
28530x00000006,0x000023f4,0x000023f3,0x0000020a, 31660x00000001,0x00050080,0x00000006,0x000027bf,
28540x000500c5,0x00000006,0x000023f5,0x000023f4, 31670x000027bd,0x000027b9,0x00050050,0x00000007,
28550x00000243,0x000200f9,0x0000233e,0x000200f8, 31680x000027c0,0x000027ba,0x000027bf,0x0004007c,
28560x0000233e,0x000700f5,0x0000004b,0x00002aaa, 31690x00000014,0x000027b0,0x000027c0,0x00060041,
28570x00002b66,0x00000a67,0x00002b57,0x000023d0, 31700x000000db,0x000027a7,0x000027b0,0x000000da,
28580x000700f5,0x0000004b,0x00002aa8,0x00002b64, 31710x000000da,0x0006003d,0x00000006,0x000027a8,
28590x00000a67,0x00002b55,0x000023d0,0x000700f5, 31720x000027a7,0x00000002,0x00000004,0x0004007c,
28600x00000006,0x00002aa5,0x000000a3,0x00000a67, 31730x00000027,0x0000276c,0x000027a8,0x00050080,
28610x000023d2,0x000023d0,0x000500b0,0x0000002f, 31740x00000006,0x0000276e,0x00002767,0x0000010a,
28620x00002341,0x00002aa5,0x00000107,0x000400f6, 31750x00050095,0x000000ab,0x000027d9,0x000027b6,
28630x000023d3,0x000023d0,0x00000000,0x000400fa, 31760x0000276e,0x00050051,0x00000006,0x000027da,
28640x00002341,0x00002342,0x000023d3,0x000200f8, 31770x000027d9,0x00000001,0x00050051,0x00000006,
28650x00002342,0x00050084,0x00000006,0x00002344, 31780x000027db,0x000027d9,0x00000000,0x00050080,
28660x00000107,0x000009e9,0x00050080,0x00000006, 31790x00000006,0x000027e0,0x000027bd,0x000027da,
28670x00002346,0x00002344,0x00002aa5,0x00050041, 31800x00050050,0x00000007,0x000027e1,0x000027db,
28680x000000fb,0x0000234c,0x000000f9,0x0000024d, 31810x000027e0,0x0004007c,0x00000014,0x000027d1,
28690x0004003d,0x00000006,0x0000234d,0x0000234c, 31820x000027e1,0x00060041,0x000000db,0x000027c8,
28700x000500b0,0x0000002f,0x0000234e,0x00002346, 31830x000027d1,0x000000da,0x000000da,0x0006003d,
28710x0000234d,0x000300f7,0x00002399,0x00000000, 31840x00000006,0x000027c9,0x000027c8,0x00000002,
28720x000400fa,0x0000234e,0x0000234f,0x00002399, 31850x00000004,0x0004007c,0x00000027,0x00002772,
28730x000200f8,0x0000234f,0x00050041,0x000000fb, 31860x000027c9,0x00050080,0x00000006,0x00002774,
28740x00002350,0x000000f9,0x00000263,0x0004003d, 31870x00002767,0x00000111,0x00050095,0x000000ab,
28750x00000006,0x00002351,0x00002350,0x000500aa, 31880x000027fa,0x000027b6,0x00002774,0x00050051,
28760x0000002f,0x00002352,0x00002351,0x0000037d, 31890x00000006,0x000027fb,0x000027fa,0x00000001,
28770x000300f7,0x0000237e,0x00000000,0x000400fa, 31900x00050051,0x00000006,0x000027fc,0x000027fa,
28780x00002352,0x00002353,0x00002370,0x000200f8, 31910x00000000,0x00050080,0x00000006,0x00002801,
28790x00002353,0x00050041,0x000000fb,0x000023f8, 31920x000027bd,0x000027fb,0x00050050,0x00000007,
28800x000000f9,0x000000fa,0x0004003d,0x00000006, 31930x00002802,0x000027fc,0x00002801,0x0004007c,
28810x000023f9,0x000023f8,0x00050084,0x00000006, 31940x00000014,0x000027f2,0x00002802,0x00060041,
28820x000023fa,0x00000107,0x000023f9,0x00050080, 31950x000000db,0x000027e9,0x000027f2,0x000000da,
28830x00000006,0x000023fb,0x00000104,0x000023fa, 31960x000000da,0x0006003d,0x00000006,0x000027ea,
28840x00050084,0x00000006,0x00002356,0x00000107, 31970x000027e9,0x00000002,0x00000004,0x0004007c,
28850x00002346,0x00050080,0x00000006,0x00002357, 31980x00000027,0x00002778,0x000027ea,0x00060050,
28860x000023fb,0x00002356,0x00050041,0x00000153, 31990x0000004b,0x00002779,0x0000276c,0x00002772,
28870x00002358,0x000000f9,0x00000151,0x0004003d, 32000x00002778,0x00050080,0x00000006,0x0000277b,
28880x00000007,0x00002359,0x00002358,0x00050051, 32010x00002767,0x00000118,0x00050095,0x000000ab,
28890x00000006,0x00002412,0x00002359,0x00000000, 32020x0000281b,0x000027b6,0x0000277b,0x00050051,
28900x00050095,0x000000a8,0x00002414,0x00002412, 32030x00000006,0x0000281c,0x0000281b,0x00000001,
28910x00002357,0x00050051,0x00000006,0x00002415, 32040x00050051,0x00000006,0x0000281d,0x0000281b,
28920x00002414,0x00000001,0x00050051,0x00000006, 32050x00000000,0x00050080,0x00000006,0x00002822,
28930x00002416,0x00002414,0x00000000,0x00050051, 32060x000027bd,0x0000281c,0x00050050,0x00000007,
28940x00000006,0x00002419,0x00002359,0x00000001, 32070x00002823,0x0000281d,0x00002822,0x0004007c,
28950x00050080,0x00000006,0x0000241b,0x00002419, 32080x00000014,0x00002813,0x00002823,0x00060041,
28960x00002415,0x00050050,0x00000007,0x0000241c, 32090x000000db,0x0000280a,0x00002813,0x000000da,
28970x00002416,0x0000241b,0x0004007c,0x00000014, 32100x000000da,0x0006003d,0x00000006,0x0000280b,
28980x0000240c,0x0000241c,0x00060041,0x000000d8, 32110x0000280a,0x00000002,0x00000004,0x0004007c,
28990x00002403,0x0000240c,0x000000d7,0x000000d7, 32120x00000027,0x0000277f,0x0000280b,0x00050080,
29000x0006003d,0x00000006,0x00002404,0x00002403, 32130x00000006,0x00002781,0x00002767,0x0000011f,
29010x00000002,0x00000004,0x00050041,0x000000fb, 32140x00050095,0x000000ab,0x0000283c,0x000027b6,
29020x0000241f,0x000000f9,0x00000229,0x0004003d, 32150x00002781,0x00050051,0x00000006,0x0000283d,
29030x00000006,0x00002420,0x0000241f,0x00050041, 32160x0000283c,0x00000001,0x00050051,0x00000006,
29040x000000fb,0x0000242e,0x000000f9,0x00000221, 32170x0000283e,0x0000283c,0x00000000,0x00050080,
29050x0004003d,0x00000006,0x0000242f,0x0000242e, 32180x00000006,0x00002843,0x000027bd,0x0000283d,
29060x000500ab,0x0000002f,0x00002430,0x0000242f, 32190x00050050,0x00000007,0x00002844,0x0000283e,
29070x000000a3,0x000600a9,0x00000006,0x00002431, 32200x00002843,0x0004007c,0x00000014,0x00002834,
29080x00002430,0x00000225,0x00000104,0x00050084, 32210x00002844,0x00060041,0x000000db,0x0000282b,
29090x00000006,0x00002423,0x00002404,0x00002431, 32220x00002834,0x000000da,0x000000da,0x0006003d,
29100x00050080,0x00000006,0x00002424,0x00002420, 32230x00000006,0x0000282c,0x0000282b,0x00000002,
29110x00002423,0x000500c2,0x00000006,0x00002425, 32240x00000004,0x0004007c,0x00000027,0x00002785,
29120x00002424,0x00000230,0x000500c4,0x00000006, 32250x0000282c,0x00050080,0x00000006,0x00002787,
29130x00002426,0x00002425,0x0000020a,0x000600a9, 32260x00002767,0x00000189,0x00050095,0x000000ab,
29140x00000006,0x0000242a,0x00002430,0x00000236, 32270x0000285d,0x000027b6,0x00002787,0x00050051,
29150x000000a3,0x000500c5,0x00000006,0x0000242b, 32280x00000006,0x0000285e,0x0000285d,0x00000001,
29160x00002426,0x0000242a,0x00050084,0x00000006, 32290x00050051,0x00000006,0x0000285f,0x0000285d,
29170x00002473,0x0000011c,0x000023f9,0x00050080, 32300x00000000,0x00050080,0x00000006,0x00002864,
29180x00000006,0x00002474,0x00000104,0x00002473, 32310x000027bd,0x0000285e,0x00050050,0x00000007,
29190x00050080,0x00000006,0x0000247a,0x000023f9, 32320x00002865,0x0000285f,0x00002864,0x0004007c,
29200x00002b67,0x00050086,0x00000006,0x0000247b, 32330x00000014,0x00002855,0x00002865,0x00060041,
29210x0000247a,0x000000fe,0x00050084,0x00000006, 32340x000000db,0x0000284c,0x00002855,0x000000da,
29220x0000246d,0x00000104,0x0000247b,0x00050080, 32350x000000da,0x0006003d,0x00000006,0x0000284d,
29230x00000006,0x0000246e,0x00002474,0x0000246d, 32360x0000284c,0x00000002,0x00000004,0x0004007c,
29240x00050084,0x00000006,0x00002442,0x0000014d, 32370x00000027,0x0000278b,0x0000284d,0x00060050,
29250x00002404,0x00050080,0x00000006,0x00002443, 32380x0000004b,0x0000278c,0x0000277f,0x00002785,
29260x0000246e,0x00002442,0x00050095,0x000000a8, 32390x0000278b,0x000200f9,0x00002676,0x000200f8,
29270x00002494,0x00002412,0x00002443,0x00050051, 32400x0000265c,0x00050041,0x000000fe,0x0000265e,
29280x00000006,0x00002495,0x00002494,0x00000001, 32410x000000fc,0x0000022c,0x0004003d,0x00000006,
29290x00050051,0x00000006,0x00002496,0x00002494, 32420x0000265f,0x0000265e,0x00050082,0x00000006,
29300x00000000,0x00050080,0x00000006,0x0000249b, 32430x00002660,0x0000264c,0x0000265f,0x00050041,
29310x00002419,0x00002495,0x00050050,0x00000007, 32440x000000fe,0x00002868,0x000000fc,0x00000224,
29320x0000249c,0x00002496,0x0000249b,0x0004007c, 32450x0004003d,0x00000006,0x00002869,0x00002868,
29330x00000014,0x0000248c,0x0000249c,0x00060041, 32460x000500ab,0x0000002f,0x0000286a,0x00002869,
29340x000000d8,0x00002483,0x0000248c,0x000000d7, 32470x000000a6,0x000600a9,0x00000006,0x0000286b,
29350x000000d7,0x0006003d,0x00000006,0x00002484, 32480x0000286a,0x00000228,0x00000107,0x00050086,
29360x00002483,0x00000002,0x00000004,0x0004007c, 32490x00000006,0x00002662,0x00002660,0x0000286b,
29370x00000027,0x00002448,0x00002484,0x00050080, 32500x00050041,0x000000fe,0x000028ab,0x000000fc,
29380x00000006,0x0000244a,0x00002443,0x00000107, 32510x000000fd,0x0004003d,0x00000006,0x000028ac,
29390x00050095,0x000000a8,0x000024b5,0x00002412, 32520x000028ab,0x00050084,0x00000006,0x000028ad,
29400x0000244a,0x00050051,0x00000006,0x000024b6, 32530x0000011f,0x000028ac,0x00050080,0x00000006,
29410x000024b5,0x00000001,0x00050051,0x00000006, 32540x000028ae,0x00000107,0x000028ad,0x00050080,
29420x000024b7,0x000024b5,0x00000000,0x00050080, 32550x00000006,0x000028b4,0x000028ac,0x0000319c,
29430x00000006,0x000024bc,0x00002419,0x000024b6, 32560x00050086,0x00000006,0x000028b5,0x000028b4,
29440x00050050,0x00000007,0x000024bd,0x000024b7, 32570x00000101,0x00050084,0x00000006,0x000028a7,
29450x000024bc,0x0004007c,0x00000014,0x000024ad, 32580x00000107,0x000028b5,0x00050080,0x00000006,
29460x000024bd,0x00060041,0x000000d8,0x000024a4, 32590x000028a8,0x000028ae,0x000028a7,0x00050084,
29470x000024ad,0x000000d7,0x000000d7,0x0006003d, 32600x00000006,0x0000287c,0x00000150,0x00002662,
29480x00000006,0x000024a5,0x000024a4,0x00000002, 32610x00050080,0x00000006,0x0000287d,0x000028a8,
29490x00000004,0x0004007c,0x00000027,0x0000244e, 32620x0000287c,0x00050041,0x00000156,0x0000287e,
29500x000024a5,0x00050080,0x00000006,0x00002450, 32630x000000fc,0x00000154,0x0004003d,0x00000007,
29510x00002443,0x0000010e,0x00050095,0x000000a8, 32640x0000287f,0x0000287e,0x00050051,0x00000006,
29520x000024d6,0x00002412,0x00002450,0x00050051, 32650x000028cc,0x0000287f,0x00000000,0x00050095,
29530x00000006,0x000024d7,0x000024d6,0x00000001, 32660x000000ab,0x000028ce,0x000028cc,0x0000287d,
29540x00050051,0x00000006,0x000024d8,0x000024d6, 32670x00050051,0x00000006,0x000028cf,0x000028ce,
29550x00000000,0x00050080,0x00000006,0x000024dd, 32680x00000001,0x00050051,0x00000006,0x000028d0,
29560x00002419,0x000024d7,0x00050050,0x00000007, 32690x000028ce,0x00000000,0x00050051,0x00000006,
29570x000024de,0x000024d8,0x000024dd,0x0004007c, 32700x000028d3,0x0000287f,0x00000001,0x00050080,
29580x00000014,0x000024ce,0x000024de,0x00060041, 32710x00000006,0x000028d5,0x000028d3,0x000028cf,
29590x000000d8,0x000024c5,0x000024ce,0x000000d7, 32720x00050050,0x00000007,0x000028d6,0x000028d0,
29600x000000d7,0x0006003d,0x00000006,0x000024c6, 32730x000028d5,0x0004007c,0x00000014,0x000028c6,
29610x000024c5,0x00000002,0x00000004,0x0004007c, 32740x000028d6,0x00060041,0x000000db,0x000028bd,
29620x00000027,0x00002454,0x000024c6,0x00060050, 32750x000028c6,0x000000da,0x000000da,0x0006003d,
29630x0000004b,0x00002455,0x00002448,0x0000244e, 32760x00000006,0x000028be,0x000028bd,0x00000002,
29640x00002454,0x00050080,0x00000006,0x00002457, 32770x00000004,0x0004007c,0x00000027,0x00002882,
29650x00002443,0x00000115,0x00050095,0x000000a8, 32780x000028be,0x00050080,0x00000006,0x00002884,
29660x000024f7,0x00002412,0x00002457,0x00050051, 32790x0000287d,0x0000010a,0x00050095,0x000000ab,
29670x00000006,0x000024f8,0x000024f7,0x00000001, 32800x000028ef,0x000028cc,0x00002884,0x00050051,
29680x00050051,0x00000006,0x000024f9,0x000024f7, 32810x00000006,0x000028f0,0x000028ef,0x00000001,
29690x00000000,0x00050080,0x00000006,0x000024fe, 32820x00050051,0x00000006,0x000028f1,0x000028ef,
29700x00002419,0x000024f8,0x00050050,0x00000007, 32830x00000000,0x00050080,0x00000006,0x000028f6,
29710x000024ff,0x000024f9,0x000024fe,0x0004007c, 32840x000028d3,0x000028f0,0x00050050,0x00000007,
29720x00000014,0x000024ef,0x000024ff,0x00060041, 32850x000028f7,0x000028f1,0x000028f6,0x0004007c,
29730x000000d8,0x000024e6,0x000024ef,0x000000d7, 32860x00000014,0x000028e7,0x000028f7,0x00060041,
29740x000000d7,0x0006003d,0x00000006,0x000024e7, 32870x000000db,0x000028de,0x000028e7,0x000000da,
29750x000024e6,0x00000002,0x00000004,0x0004007c, 32880x000000da,0x0006003d,0x00000006,0x000028df,
29760x00000027,0x0000245b,0x000024e7,0x00050080, 32890x000028de,0x00000002,0x00000004,0x0004007c,
29770x00000006,0x0000245d,0x00002443,0x0000011c, 32900x00000027,0x00002888,0x000028df,0x00050080,
29780x00050095,0x000000a8,0x00002518,0x00002412, 32910x00000006,0x0000288a,0x0000287d,0x00000111,
29790x0000245d,0x00050051,0x00000006,0x00002519, 32920x00050095,0x000000ab,0x00002910,0x000028cc,
29800x00002518,0x00000001,0x00050051,0x00000006, 32930x0000288a,0x00050051,0x00000006,0x00002911,
29810x0000251a,0x00002518,0x00000000,0x00050080, 32940x00002910,0x00000001,0x00050051,0x00000006,
29820x00000006,0x0000251f,0x00002419,0x00002519, 32950x00002912,0x00002910,0x00000000,0x00050080,
29830x00050050,0x00000007,0x00002520,0x0000251a, 32960x00000006,0x00002917,0x000028d3,0x00002911,
29840x0000251f,0x0004007c,0x00000014,0x00002510, 32970x00050050,0x00000007,0x00002918,0x00002912,
29850x00002520,0x00060041,0x000000d8,0x00002507, 32980x00002917,0x0004007c,0x00000014,0x00002908,
29860x00002510,0x000000d7,0x000000d7,0x0006003d, 32990x00002918,0x00060041,0x000000db,0x000028ff,
29870x00000006,0x00002508,0x00002507,0x00000002, 33000x00002908,0x000000da,0x000000da,0x0006003d,
29880x00000004,0x0004007c,0x00000027,0x00002461, 33010x00000006,0x00002900,0x000028ff,0x00000002,
29890x00002508,0x00050080,0x00000006,0x00002463, 33020x00000004,0x0004007c,0x00000027,0x0000288e,
29900x00002443,0x00000186,0x00050095,0x000000a8, 33030x00002900,0x00060050,0x0000004b,0x0000288f,
29910x00002539,0x00002412,0x00002463,0x00050051, 33040x00002882,0x00002888,0x0000288e,0x00050080,
29920x00000006,0x0000253a,0x00002539,0x00000001, 33050x00000006,0x00002891,0x0000287d,0x00000118,
29930x00050051,0x00000006,0x0000253b,0x00002539, 33060x00050095,0x000000ab,0x00002931,0x000028cc,
29940x00000000,0x00050080,0x00000006,0x00002540, 33070x00002891,0x00050051,0x00000006,0x00002932,
29950x00002419,0x0000253a,0x00050050,0x00000007, 33080x00002931,0x00000001,0x00050051,0x00000006,
29960x00002541,0x0000253b,0x00002540,0x0004007c, 33090x00002933,0x00002931,0x00000000,0x00050080,
29970x00000014,0x00002531,0x00002541,0x00060041, 33100x00000006,0x00002938,0x000028d3,0x00002932,
29980x000000d8,0x00002528,0x00002531,0x000000d7, 33110x00050050,0x00000007,0x00002939,0x00002933,
29990x000000d7,0x0006003d,0x00000006,0x00002529, 33120x00002938,0x0004007c,0x00000014,0x00002929,
30000x00002528,0x00000002,0x00000004,0x0004007c, 33130x00002939,0x00060041,0x000000db,0x00002920,
30010x00000027,0x00002467,0x00002529,0x00060050, 33140x00002929,0x000000da,0x000000da,0x0006003d,
30020x0000004b,0x00002468,0x0000245b,0x00002461, 33150x00000006,0x00002921,0x00002920,0x00000002,
30030x00002467,0x000300f7,0x0000236f,0x00000000, 33160x00000004,0x0004007c,0x00000027,0x00002895,
30040x000400fa,0x00002430,0x00002364,0x0000236f, 33170x00002921,0x00050080,0x00000006,0x00002897,
30050x000200f8,0x00002364,0x00050084,0x00000006, 33180x0000287d,0x0000011f,0x00050095,0x000000ab,
30060x00002368,0x00000225,0x00002404,0x00050080, 33190x00002952,0x000028cc,0x00002897,0x00050051,
30070x00000006,0x00002369,0x00002420,0x00002368, 33200x00000006,0x00002953,0x00002952,0x00000001,
30080x00050080,0x00000006,0x0000236a,0x00002369, 33210x00050051,0x00000006,0x00002954,0x00002952,
30090x000005cd,0x00050041,0x00000153,0x0000236b, 33220x00000000,0x00050080,0x00000006,0x00002959,
30100x000000f9,0x000000d7,0x0004003d,0x00000007, 33230x000028d3,0x00002953,0x00050050,0x00000007,
30110x0000236c,0x0000236b,0x00050051,0x00000006, 33240x0000295a,0x00002954,0x00002959,0x0004007c,
30120x00002557,0x0000236c,0x00000000,0x00050095, 33250x00000014,0x0000294a,0x0000295a,0x00060041,
30130x000000a8,0x00002559,0x00002557,0x0000236a, 33260x000000db,0x00002941,0x0000294a,0x000000da,
30140x00050051,0x00000006,0x0000255a,0x00002559, 33270x000000da,0x0006003d,0x00000006,0x00002942,
30150x00000001,0x00050051,0x00000006,0x0000255b, 33280x00002941,0x00000002,0x00000004,0x0004007c,
30160x00002559,0x00000000,0x00050051,0x00000006, 33290x00000027,0x0000289b,0x00002942,0x00050080,
30170x0000255e,0x0000236c,0x00000001,0x00050080, 33300x00000006,0x0000289d,0x0000287d,0x00000189,
30180x00000006,0x00002560,0x0000255e,0x0000255a, 33310x00050095,0x000000ab,0x00002973,0x000028cc,
30190x00050050,0x00000007,0x00002561,0x0000255b, 33320x0000289d,0x00050051,0x00000006,0x00002974,
30200x00002560,0x0004007c,0x00000014,0x00002551, 33330x00002973,0x00000001,0x00050051,0x00000006,
30210x00002561,0x00060041,0x000000d8,0x00002549, 33340x00002975,0x00002973,0x00000000,0x00050080,
30220x00002551,0x000000d7,0x000000d7,0x0005003e, 33350x00000006,0x0000297a,0x000028d3,0x00002974,
30230x00002549,0x000023f5,0x00000002,0x00000004, 33360x00050050,0x00000007,0x0000297b,0x00002975,
30240x000200f9,0x0000236f,0x000200f8,0x0000236f, 33370x0000297a,0x0004007c,0x00000014,0x0000296b,
30250x000200f9,0x0000237e,0x000200f8,0x00002370, 33380x0000297b,0x00060041,0x000000db,0x00002962,
30260x00050080,0x00000006,0x00002374,0x00002351, 33390x0000296b,0x000000da,0x000000da,0x0006003d,
30270x00002346,0x00050084,0x00000006,0x00002567, 33400x00000006,0x00002963,0x00002962,0x00000002,
30280x00002374,0x00000225,0x00050080,0x00000006, 33410x00000004,0x0004007c,0x00000027,0x000028a1,
30290x00002568,0x000023ef,0x00002567,0x000500c2, 33420x00002963,0x00060050,0x0000004b,0x000028a2,
30300x00000006,0x00002569,0x00002568,0x00000230, 33430x00002895,0x0000289b,0x000028a1,0x000300f7,
30310x000500c4,0x00000006,0x0000256a,0x00002569, 33440x00002675,0x00000000,0x000400fa,0x0000286a,
30320x0000020a,0x000500c5,0x00000006,0x0000256b, 33450x0000266a,0x00002675,0x000200f8,0x0000266a,
30330x0000256a,0x00000243,0x00050041,0x000000fb, 33460x00050084,0x00000006,0x0000266e,0x00000228,
30340x00002377,0x000000f9,0x000008bc,0x0004003d, 33470x00002662,0x00050080,0x00000006,0x0000266f,
30350x00000006,0x00002378,0x00002377,0x00050080, 33480x0000265f,0x0000266e,0x00050080,0x00000006,
30360x00000006,0x0000237a,0x00002378,0x00002374, 33490x00002670,0x0000266f,0x000005d0,0x00050095,
30370x00050041,0x000000fb,0x000025ab,0x000000f9, 33500x000000ab,0x00002993,0x00002747,0x00002670,
30380x000000fa,0x0004003d,0x00000006,0x000025ac, 33510x00050051,0x00000006,0x00002994,0x00002993,
30390x000025ab,0x00050084,0x00000006,0x000025ad, 33520x00000001,0x00050051,0x00000006,0x00002995,
30400x0000011c,0x000025ac,0x00050080,0x00000006, 33530x00002993,0x00000000,0x00050080,0x00000006,
30410x000025ae,0x00000104,0x000025ad,0x00050080, 33540x0000299a,0x0000274e,0x00002994,0x00050050,
30420x00000006,0x000025b4,0x000025ac,0x00002b67, 33550x00000007,0x0000299b,0x00002995,0x0000299a,
30430x00050086,0x00000006,0x000025b5,0x000025b4, 33560x0004007c,0x00000014,0x0000298b,0x0000299b,
30440x000000fe,0x00050084,0x00000006,0x000025a7, 33570x00060041,0x000000db,0x00002983,0x0000298b,
30450x00000104,0x000025b5,0x00050080,0x00000006, 33580x000000da,0x000000da,0x0005003e,0x00002983,
30460x000025a8,0x000025ae,0x000025a7,0x00050084, 33590x00002730,0x00000002,0x00000004,0x000200f9,
30470x00000006,0x0000257c,0x0000014d,0x0000237a, 33600x00002675,0x000200f8,0x00002675,0x000200f9,
30480x00050080,0x00000006,0x0000257d,0x000025a8, 33610x00002676,0x000200f8,0x00002676,0x000700f5,
30490x0000257c,0x00050041,0x00000153,0x0000257e, 33620x0000004b,0x000030ab,0x0000278c,0x00002650,
30500x000000f9,0x00000151,0x0004003d,0x00000007, 33630x000028a2,0x00002675,0x000700f5,0x0000004b,
30510x0000257f,0x0000257e,0x00050051,0x00000006, 33640x000030a9,0x00002779,0x00002650,0x0000288f,
30520x000025cc,0x0000257f,0x00000000,0x00050095, 33650x00002675,0x00050051,0x00000027,0x0000299f,
30530x000000a8,0x000025ce,0x000025cc,0x0000257d, 33660x000030a9,0x00000000,0x00050051,0x00000027,
30540x00050051,0x00000006,0x000025cf,0x000025ce, 33670x000029a1,0x000030ab,0x00000000,0x000500bc,
30550x00000001,0x00050051,0x00000006,0x000025d0, 33680x0000002f,0x000029a2,0x0000299f,0x000029a1,
30560x000025ce,0x00000000,0x00050051,0x00000006, 33690x000300f7,0x000029a9,0x00000000,0x000400fa,
30570x000025d3,0x0000257f,0x00000001,0x00050080, 33700x000029a2,0x000029a3,0x000029a9,0x000200f8,
30580x00000006,0x000025d5,0x000025d3,0x000025cf, 33710x000029a3,0x00050051,0x00000027,0x000029a5,
30590x00050050,0x00000007,0x000025d6,0x000025d0, 33720x000030a9,0x00000001,0x00050051,0x00000027,
30600x000025d5,0x0004007c,0x00000014,0x000025c6, 33730x000029a7,0x000030ab,0x00000001,0x000500bc,
30610x000025d6,0x00060041,0x000000d8,0x000025bd, 33740x0000002f,0x000029a8,0x000029a5,0x000029a7,
30620x000025c6,0x000000d7,0x000000d7,0x0006003d, 33750x000200f9,0x000029a9,0x000200f8,0x000029a9,
30630x00000006,0x000025be,0x000025bd,0x00000002, 33760x000700f5,0x0000002f,0x000029aa,0x000029a2,
30640x00000004,0x0004007c,0x00000027,0x00002582, 33770x00002676,0x000029a8,0x000029a3,0x000300f7,
30650x000025be,0x00050080,0x00000006,0x00002584, 33780x000029b1,0x00000000,0x000400fa,0x000029aa,
30660x0000257d,0x00000107,0x00050095,0x000000a8, 33790x000029ab,0x000029b1,0x000200f8,0x000029ab,
30670x000025ef,0x000025cc,0x00002584,0x00050051, 33800x00050051,0x00000027,0x000029ad,0x000030a9,
30680x00000006,0x000025f0,0x000025ef,0x00000001, 33810x00000002,0x00050051,0x00000027,0x000029af,
30690x00050051,0x00000006,0x000025f1,0x000025ef, 33820x000030ab,0x00000002,0x000500bc,0x0000002f,
30700x00000000,0x00050080,0x00000006,0x000025f6, 33830x000029b0,0x000029ad,0x000029af,0x000200f9,
30710x000025d3,0x000025f0,0x00050050,0x00000007, 33840x000029b1,0x000200f8,0x000029b1,0x000700f5,
30720x000025f7,0x000025f1,0x000025f6,0x0004007c, 33850x0000002f,0x000029b2,0x000029aa,0x000029a9,
30730x00000014,0x000025e7,0x000025f7,0x00060041, 33860x000029b0,0x000029ab,0x000300f7,0x00002682,
30740x000000d8,0x000025de,0x000025e7,0x000000d7, 33870x00000000,0x000400fa,0x000029b2,0x0000267b,
30750x000000d7,0x0006003d,0x00000006,0x000025df, 33880x00002682,0x000200f8,0x0000267b,0x0007000c,
30760x000025de,0x00000002,0x00000004,0x0004007c, 33890x0000004b,0x0000267e,0x00000001,0x00000025,
30770x00000027,0x00002588,0x000025df,0x00050080, 33900x00003094,0x000030a9,0x0007000c,0x0000004b,
30780x00000006,0x0000258a,0x0000257d,0x0000010e, 33910x00002681,0x00000001,0x00000028,0x00003096,
30790x00050095,0x000000a8,0x00002610,0x000025cc, 33920x000030ab,0x000200f9,0x00002682,0x000200f8,
30800x0000258a,0x00050051,0x00000006,0x00002611, 33930x00002682,0x000700f5,0x0000004b,0x00003181,
30810x00002610,0x00000001,0x00050051,0x00000006, 33940x00003096,0x000029b1,0x00002681,0x0000267b,
30820x00002612,0x00002610,0x00000000,0x00050080, 33950x000700f5,0x0000004b,0x0000317c,0x00003094,
30830x00000006,0x00002617,0x000025d3,0x00002611, 33960x000029b1,0x0000267e,0x0000267b,0x000200f9,
30840x00050050,0x00000007,0x00002618,0x00002612, 33970x00002683,0x000200f8,0x00002683,0x000700f5,
30850x00002617,0x0004007c,0x00000014,0x00002608, 33980x0000004b,0x00003180,0x00003096,0x0000263f,
30860x00002618,0x00060041,0x000000d8,0x000025ff, 33990x00003181,0x00002682,0x000700f5,0x0000004b,
30870x00002608,0x000000d7,0x000000d7,0x0006003d, 34000x0000317b,0x00003094,0x0000263f,0x0000317c,
30880x00000006,0x00002600,0x000025ff,0x00000002, 34010x00002682,0x000700f5,0x0000004b,0x000030d7,
30890x00000004,0x0004007c,0x00000027,0x0000258e, 34020x0000319b,0x0000263f,0x000030ab,0x00002682,
30900x00002600,0x00060050,0x0000004b,0x0000258f, 34030x000700f5,0x0000004b,0x000030d2,0x00003199,
30910x00002582,0x00002588,0x0000258e,0x00050080, 34040x0000263f,0x000030a9,0x00002682,0x000200f9,
30920x00000006,0x00002591,0x0000257d,0x00000115, 34050x000026d4,0x000200f8,0x00002684,0x00050041,
30930x00050095,0x000000a8,0x00002631,0x000025cc, 34060x000000fe,0x00002686,0x000000fc,0x00000250,
30940x00002591,0x00050051,0x00000006,0x00002632, 34070x0004003d,0x00000006,0x00002687,0x00002686,
30950x00002631,0x00000001,0x00050051,0x00000006, 34080x000500b0,0x0000002f,0x00002688,0x00002637,
30960x00002633,0x00002631,0x00000000,0x00050080, 34090x00002687,0x000300f7,0x000026d3,0x00000000,
30970x00000006,0x00002638,0x000025d3,0x00002632, 34100x000400fa,0x00002688,0x00002689,0x000026d3,
30980x00050050,0x00000007,0x00002639,0x00002633, 34110x000200f8,0x00002689,0x00050041,0x000000fe,
30990x00002638,0x0004007c,0x00000014,0x00002629, 34120x0000268a,0x000000fc,0x00000266,0x0004003d,
31000x00002639,0x00060041,0x000000d8,0x00002620, 34130x00000006,0x0000268b,0x0000268a,0x000500aa,
31010x00002629,0x000000d7,0x000000d7,0x0006003d, 34140x0000002f,0x0000268c,0x0000268b,0x00000380,
31020x00000006,0x00002621,0x00002620,0x00000002, 34150x000300f7,0x000026b8,0x00000000,0x000400fa,
31030x00000004,0x0004007c,0x00000027,0x00002595, 34160x0000268c,0x0000268d,0x000026aa,0x000200f8,
31040x00002621,0x00050080,0x00000006,0x00002597, 34170x0000268d,0x00050041,0x000000fe,0x000029b6,
31050x0000257d,0x0000011c,0x00050095,0x000000a8, 34180x000000fc,0x000000fd,0x0004003d,0x00000006,
31060x00002652,0x000025cc,0x00002597,0x00050051, 34190x000029b7,0x000029b6,0x00050084,0x00000006,
31070x00000006,0x00002653,0x00002652,0x00000001, 34200x000029b8,0x0000010a,0x000029b7,0x00050080,
31080x00050051,0x00000006,0x00002654,0x00002652, 34210x00000006,0x000029b9,0x00000107,0x000029b8,
31090x00000000,0x00050080,0x00000006,0x00002659, 34220x00050084,0x00000006,0x00002690,0x0000010a,
31100x000025d3,0x00002653,0x00050050,0x00000007, 34230x00002637,0x00050080,0x00000006,0x00002691,
31110x0000265a,0x00002654,0x00002659,0x0004007c, 34240x000029b9,0x00002690,0x00050041,0x00000156,
31120x00000014,0x0000264a,0x0000265a,0x00060041, 34250x00002692,0x000000fc,0x00000154,0x0004003d,
31130x000000d8,0x00002641,0x0000264a,0x000000d7, 34260x00000007,0x00002693,0x00002692,0x00050051,
31140x000000d7,0x0006003d,0x00000006,0x00002642, 34270x00000006,0x000029d0,0x00002693,0x00000000,
31150x00002641,0x00000002,0x00000004,0x0004007c, 34280x00050095,0x000000ab,0x000029d2,0x000029d0,
31160x00000027,0x0000259b,0x00002642,0x00050080, 34290x00002691,0x00050051,0x00000006,0x000029d3,
31170x00000006,0x0000259d,0x0000257d,0x00000186, 34300x000029d2,0x00000001,0x00050051,0x00000006,
31180x00050095,0x000000a8,0x00002673,0x000025cc, 34310x000029d4,0x000029d2,0x00000000,0x00050051,
31190x0000259d,0x00050051,0x00000006,0x00002674, 34320x00000006,0x000029d7,0x00002693,0x00000001,
31200x00002673,0x00000001,0x00050051,0x00000006, 34330x00050080,0x00000006,0x000029d9,0x000029d7,
31210x00002675,0x00002673,0x00000000,0x00050080, 34340x000029d3,0x00050050,0x00000007,0x000029da,
31220x00000006,0x0000267a,0x000025d3,0x00002674, 34350x000029d4,0x000029d9,0x0004007c,0x00000014,
31230x00050050,0x00000007,0x0000267b,0x00002675, 34360x000029ca,0x000029da,0x00060041,0x000000db,
31240x0000267a,0x0004007c,0x00000014,0x0000266b, 34370x000029c1,0x000029ca,0x000000da,0x000000da,
31250x0000267b,0x00060041,0x000000d8,0x00002662, 34380x0006003d,0x00000006,0x000029c2,0x000029c1,
31260x0000266b,0x000000d7,0x000000d7,0x0006003d, 34390x00000002,0x00000004,0x00050041,0x000000fe,
31270x00000006,0x00002663,0x00002662,0x00000002, 34400x000029dd,0x000000fc,0x0000022c,0x0004003d,
31280x00000004,0x0004007c,0x00000027,0x000025a1, 34410x00000006,0x000029de,0x000029dd,0x00050041,
31290x00002663,0x00060050,0x0000004b,0x000025a2, 34420x000000fe,0x000029ec,0x000000fc,0x00000224,
31300x00002595,0x0000259b,0x000025a1,0x000200f9, 34430x0004003d,0x00000006,0x000029ed,0x000029ec,
31310x0000237e,0x000200f8,0x0000237e,0x000700f5, 34440x000500ab,0x0000002f,0x000029ee,0x000029ed,
31320x0000004b,0x00002aaf,0x00002468,0x0000236f, 34450x000000a6,0x000600a9,0x00000006,0x000029ef,
31330x000025a2,0x00002370,0x000700f5,0x0000004b, 34460x000029ee,0x00000228,0x00000107,0x00050084,
31340x00002aad,0x00002455,0x0000236f,0x0000258f, 34470x00000006,0x000029e1,0x000029c2,0x000029ef,
31350x00002370,0x000700f5,0x00000006,0x00002aab, 34480x00050080,0x00000006,0x000029e2,0x000029de,
31360x0000242b,0x0000236f,0x0000256b,0x00002370, 34490x000029e1,0x000500c2,0x00000006,0x000029e3,
31370x00050041,0x000000fb,0x0000237f,0x000000f9, 34500x000029e2,0x00000233,0x000500c4,0x00000006,
31380x000008c7,0x0004003d,0x00000006,0x00002380, 34510x000029e4,0x000029e3,0x0000020d,0x000600a9,
31390x0000237f,0x000500c2,0x00000006,0x0000267f, 34520x00000006,0x000029e8,0x000029ee,0x00000239,
31400x00002aab,0x0000020a,0x00050041,0x000000fb, 34530x000000a6,0x000500c5,0x00000006,0x000029e9,
31410x00002383,0x000000f9,0x00000229,0x0004003d, 34540x000029e4,0x000029e8,0x00050084,0x00000006,
31420x00000006,0x00002384,0x00002383,0x00050086, 34550x00002a31,0x0000011f,0x000029b7,0x00050080,
31430x00000006,0x00002385,0x00002384,0x00000104, 34560x00000006,0x00002a32,0x00000107,0x00002a31,
31440x00050082,0x00000006,0x00002386,0x0000267f, 34570x00050080,0x00000006,0x00002a38,0x000029b7,
31450x00002385,0x00050084,0x00000006,0x00002387, 34580x0000319c,0x00050086,0x00000006,0x00002a39,
31460x00000107,0x00002386,0x00050080,0x00000006, 34590x00002a38,0x00000101,0x00050084,0x00000006,
31470x00002388,0x00002380,0x00002387,0x00050041, 34600x00002a2b,0x00000107,0x00002a39,0x00050080,
31480x00000153,0x00002389,0x000000f9,0x000000d7, 34610x00000006,0x00002a2c,0x00002a32,0x00002a2b,
31490x0004003d,0x00000007,0x0000238a,0x00002389, 34620x00050084,0x00000006,0x00002a00,0x00000150,
31500x00050051,0x00000006,0x00002695,0x0000238a, 34630x000029c2,0x00050080,0x00000006,0x00002a01,
31510x00000000,0x00050095,0x000000a8,0x00002697, 34640x00002a2c,0x00002a00,0x00050095,0x000000ab,
31520x00002695,0x00002388,0x00050051,0x00000006, 34650x00002a52,0x000029d0,0x00002a01,0x00050051,
31530x00002698,0x00002697,0x00000001,0x00050051, 34660x00000006,0x00002a53,0x00002a52,0x00000001,
31540x00000006,0x00002699,0x00002697,0x00000000, 34670x00050051,0x00000006,0x00002a54,0x00002a52,
31550x00050051,0x00000006,0x0000269c,0x0000238a, 34680x00000000,0x00050080,0x00000006,0x00002a59,
31560x00000001,0x00050080,0x00000006,0x0000269e, 34690x000029d7,0x00002a53,0x00050050,0x00000007,
31570x0000269c,0x00002698,0x00050050,0x00000007, 34700x00002a5a,0x00002a54,0x00002a59,0x0004007c,
31580x0000269f,0x00002699,0x0000269e,0x0004007c, 34710x00000014,0x00002a4a,0x00002a5a,0x00060041,
31590x00000014,0x0000268f,0x0000269f,0x00060041, 34720x000000db,0x00002a41,0x00002a4a,0x000000da,
31600x000000d8,0x00002687,0x0000268f,0x000000d7, 34730x000000da,0x0006003d,0x00000006,0x00002a42,
31610x000000d7,0x0005003e,0x00002687,0x000023f5, 34740x00002a41,0x00000002,0x00000004,0x0004007c,
34750x00000027,0x00002a06,0x00002a42,0x00050080,
34760x00000006,0x00002a08,0x00002a01,0x0000010a,
34770x00050095,0x000000ab,0x00002a73,0x000029d0,
34780x00002a08,0x00050051,0x00000006,0x00002a74,
34790x00002a73,0x00000001,0x00050051,0x00000006,
34800x00002a75,0x00002a73,0x00000000,0x00050080,
34810x00000006,0x00002a7a,0x000029d7,0x00002a74,
34820x00050050,0x00000007,0x00002a7b,0x00002a75,
34830x00002a7a,0x0004007c,0x00000014,0x00002a6b,
34840x00002a7b,0x00060041,0x000000db,0x00002a62,
34850x00002a6b,0x000000da,0x000000da,0x0006003d,
34860x00000006,0x00002a63,0x00002a62,0x00000002,
34870x00000004,0x0004007c,0x00000027,0x00002a0c,
34880x00002a63,0x00050080,0x00000006,0x00002a0e,
34890x00002a01,0x00000111,0x00050095,0x000000ab,
34900x00002a94,0x000029d0,0x00002a0e,0x00050051,
34910x00000006,0x00002a95,0x00002a94,0x00000001,
34920x00050051,0x00000006,0x00002a96,0x00002a94,
34930x00000000,0x00050080,0x00000006,0x00002a9b,
34940x000029d7,0x00002a95,0x00050050,0x00000007,
34950x00002a9c,0x00002a96,0x00002a9b,0x0004007c,
34960x00000014,0x00002a8c,0x00002a9c,0x00060041,
34970x000000db,0x00002a83,0x00002a8c,0x000000da,
34980x000000da,0x0006003d,0x00000006,0x00002a84,
34990x00002a83,0x00000002,0x00000004,0x0004007c,
35000x00000027,0x00002a12,0x00002a84,0x00060050,
35010x0000004b,0x00002a13,0x00002a06,0x00002a0c,
35020x00002a12,0x00050080,0x00000006,0x00002a15,
35030x00002a01,0x00000118,0x00050095,0x000000ab,
35040x00002ab5,0x000029d0,0x00002a15,0x00050051,
35050x00000006,0x00002ab6,0x00002ab5,0x00000001,
35060x00050051,0x00000006,0x00002ab7,0x00002ab5,
35070x00000000,0x00050080,0x00000006,0x00002abc,
35080x000029d7,0x00002ab6,0x00050050,0x00000007,
35090x00002abd,0x00002ab7,0x00002abc,0x0004007c,
35100x00000014,0x00002aad,0x00002abd,0x00060041,
35110x000000db,0x00002aa4,0x00002aad,0x000000da,
35120x000000da,0x0006003d,0x00000006,0x00002aa5,
35130x00002aa4,0x00000002,0x00000004,0x0004007c,
35140x00000027,0x00002a19,0x00002aa5,0x00050080,
35150x00000006,0x00002a1b,0x00002a01,0x0000011f,
35160x00050095,0x000000ab,0x00002ad6,0x000029d0,
35170x00002a1b,0x00050051,0x00000006,0x00002ad7,
35180x00002ad6,0x00000001,0x00050051,0x00000006,
35190x00002ad8,0x00002ad6,0x00000000,0x00050080,
35200x00000006,0x00002add,0x000029d7,0x00002ad7,
35210x00050050,0x00000007,0x00002ade,0x00002ad8,
35220x00002add,0x0004007c,0x00000014,0x00002ace,
35230x00002ade,0x00060041,0x000000db,0x00002ac5,
35240x00002ace,0x000000da,0x000000da,0x0006003d,
35250x00000006,0x00002ac6,0x00002ac5,0x00000002,
35260x00000004,0x0004007c,0x00000027,0x00002a1f,
35270x00002ac6,0x00050080,0x00000006,0x00002a21,
35280x00002a01,0x00000189,0x00050095,0x000000ab,
35290x00002af7,0x000029d0,0x00002a21,0x00050051,
35300x00000006,0x00002af8,0x00002af7,0x00000001,
35310x00050051,0x00000006,0x00002af9,0x00002af7,
35320x00000000,0x00050080,0x00000006,0x00002afe,
35330x000029d7,0x00002af8,0x00050050,0x00000007,
35340x00002aff,0x00002af9,0x00002afe,0x0004007c,
35350x00000014,0x00002aef,0x00002aff,0x00060041,
35360x000000db,0x00002ae6,0x00002aef,0x000000da,
35370x000000da,0x0006003d,0x00000006,0x00002ae7,
35380x00002ae6,0x00000002,0x00000004,0x0004007c,
35390x00000027,0x00002a25,0x00002ae7,0x00060050,
35400x0000004b,0x00002a26,0x00002a19,0x00002a1f,
35410x00002a25,0x000300f7,0x000026a9,0x00000000,
35420x000400fa,0x000029ee,0x0000269e,0x000026a9,
35430x000200f8,0x0000269e,0x00050084,0x00000006,
35440x000026a2,0x00000228,0x000029c2,0x00050080,
35450x00000006,0x000026a3,0x000029de,0x000026a2,
35460x00050080,0x00000006,0x000026a4,0x000026a3,
35470x000005d0,0x00050041,0x00000156,0x000026a5,
35480x000000fc,0x000000da,0x0004003d,0x00000007,
35490x000026a6,0x000026a5,0x00050051,0x00000006,
35500x00002b15,0x000026a6,0x00000000,0x00050095,
35510x000000ab,0x00002b17,0x00002b15,0x000026a4,
35520x00050051,0x00000006,0x00002b18,0x00002b17,
35530x00000001,0x00050051,0x00000006,0x00002b19,
35540x00002b17,0x00000000,0x00050051,0x00000006,
35550x00002b1c,0x000026a6,0x00000001,0x00050080,
35560x00000006,0x00002b1e,0x00002b1c,0x00002b18,
35570x00050050,0x00000007,0x00002b1f,0x00002b19,
35580x00002b1e,0x0004007c,0x00000014,0x00002b0f,
35590x00002b1f,0x00060041,0x000000db,0x00002b07,
35600x00002b0f,0x000000da,0x000000da,0x0005003e,
35610x00002b07,0x00002730,0x00000002,0x00000004,
35620x000200f9,0x000026a9,0x000200f8,0x000026a9,
35630x000200f9,0x000026b8,0x000200f8,0x000026aa,
35640x00050080,0x00000006,0x000026ae,0x0000268b,
35650x00002637,0x00050084,0x00000006,0x00002b25,
35660x000026ae,0x00000228,0x00050080,0x00000006,
35670x00002b26,0x0000272a,0x00002b25,0x000500c2,
35680x00000006,0x00002b27,0x00002b26,0x00000233,
35690x000500c4,0x00000006,0x00002b28,0x00002b27,
35700x0000020d,0x000500c5,0x00000006,0x00002b29,
35710x00002b28,0x00000246,0x00050041,0x000000fe,
35720x000026b1,0x000000fc,0x0000096c,0x0004003d,
35730x00000006,0x000026b2,0x000026b1,0x00050080,
35740x00000006,0x000026b4,0x000026b2,0x000026ae,
35750x00050041,0x000000fe,0x00002b69,0x000000fc,
35760x000000fd,0x0004003d,0x00000006,0x00002b6a,
35770x00002b69,0x00050084,0x00000006,0x00002b6b,
35780x0000011f,0x00002b6a,0x00050080,0x00000006,
35790x00002b6c,0x00000107,0x00002b6b,0x00050080,
35800x00000006,0x00002b72,0x00002b6a,0x0000319c,
35810x00050086,0x00000006,0x00002b73,0x00002b72,
35820x00000101,0x00050084,0x00000006,0x00002b65,
35830x00000107,0x00002b73,0x00050080,0x00000006,
35840x00002b66,0x00002b6c,0x00002b65,0x00050084,
35850x00000006,0x00002b3a,0x00000150,0x000026b4,
35860x00050080,0x00000006,0x00002b3b,0x00002b66,
35870x00002b3a,0x00050041,0x00000156,0x00002b3c,
35880x000000fc,0x00000154,0x0004003d,0x00000007,
35890x00002b3d,0x00002b3c,0x00050051,0x00000006,
35900x00002b8a,0x00002b3d,0x00000000,0x00050095,
35910x000000ab,0x00002b8c,0x00002b8a,0x00002b3b,
35920x00050051,0x00000006,0x00002b8d,0x00002b8c,
35930x00000001,0x00050051,0x00000006,0x00002b8e,
35940x00002b8c,0x00000000,0x00050051,0x00000006,
35950x00002b91,0x00002b3d,0x00000001,0x00050080,
35960x00000006,0x00002b93,0x00002b91,0x00002b8d,
35970x00050050,0x00000007,0x00002b94,0x00002b8e,
35980x00002b93,0x0004007c,0x00000014,0x00002b84,
35990x00002b94,0x00060041,0x000000db,0x00002b7b,
36000x00002b84,0x000000da,0x000000da,0x0006003d,
36010x00000006,0x00002b7c,0x00002b7b,0x00000002,
36020x00000004,0x0004007c,0x00000027,0x00002b40,
36030x00002b7c,0x00050080,0x00000006,0x00002b42,
36040x00002b3b,0x0000010a,0x00050095,0x000000ab,
36050x00002bad,0x00002b8a,0x00002b42,0x00050051,
36060x00000006,0x00002bae,0x00002bad,0x00000001,
36070x00050051,0x00000006,0x00002baf,0x00002bad,
36080x00000000,0x00050080,0x00000006,0x00002bb4,
36090x00002b91,0x00002bae,0x00050050,0x00000007,
36100x00002bb5,0x00002baf,0x00002bb4,0x0004007c,
36110x00000014,0x00002ba5,0x00002bb5,0x00060041,
36120x000000db,0x00002b9c,0x00002ba5,0x000000da,
36130x000000da,0x0006003d,0x00000006,0x00002b9d,
36140x00002b9c,0x00000002,0x00000004,0x0004007c,
36150x00000027,0x00002b46,0x00002b9d,0x00050080,
36160x00000006,0x00002b48,0x00002b3b,0x00000111,
36170x00050095,0x000000ab,0x00002bce,0x00002b8a,
36180x00002b48,0x00050051,0x00000006,0x00002bcf,
36190x00002bce,0x00000001,0x00050051,0x00000006,
36200x00002bd0,0x00002bce,0x00000000,0x00050080,
36210x00000006,0x00002bd5,0x00002b91,0x00002bcf,
36220x00050050,0x00000007,0x00002bd6,0x00002bd0,
36230x00002bd5,0x0004007c,0x00000014,0x00002bc6,
36240x00002bd6,0x00060041,0x000000db,0x00002bbd,
36250x00002bc6,0x000000da,0x000000da,0x0006003d,
36260x00000006,0x00002bbe,0x00002bbd,0x00000002,
36270x00000004,0x0004007c,0x00000027,0x00002b4c,
36280x00002bbe,0x00060050,0x0000004b,0x00002b4d,
36290x00002b40,0x00002b46,0x00002b4c,0x00050080,
36300x00000006,0x00002b4f,0x00002b3b,0x00000118,
36310x00050095,0x000000ab,0x00002bef,0x00002b8a,
36320x00002b4f,0x00050051,0x00000006,0x00002bf0,
36330x00002bef,0x00000001,0x00050051,0x00000006,
36340x00002bf1,0x00002bef,0x00000000,0x00050080,
36350x00000006,0x00002bf6,0x00002b91,0x00002bf0,
36360x00050050,0x00000007,0x00002bf7,0x00002bf1,
36370x00002bf6,0x0004007c,0x00000014,0x00002be7,
36380x00002bf7,0x00060041,0x000000db,0x00002bde,
36390x00002be7,0x000000da,0x000000da,0x0006003d,
36400x00000006,0x00002bdf,0x00002bde,0x00000002,
36410x00000004,0x0004007c,0x00000027,0x00002b53,
36420x00002bdf,0x00050080,0x00000006,0x00002b55,
36430x00002b3b,0x0000011f,0x00050095,0x000000ab,
36440x00002c10,0x00002b8a,0x00002b55,0x00050051,
36450x00000006,0x00002c11,0x00002c10,0x00000001,
36460x00050051,0x00000006,0x00002c12,0x00002c10,
36470x00000000,0x00050080,0x00000006,0x00002c17,
36480x00002b91,0x00002c11,0x00050050,0x00000007,
36490x00002c18,0x00002c12,0x00002c17,0x0004007c,
36500x00000014,0x00002c08,0x00002c18,0x00060041,
36510x000000db,0x00002bff,0x00002c08,0x000000da,
36520x000000da,0x0006003d,0x00000006,0x00002c00,
36530x00002bff,0x00000002,0x00000004,0x0004007c,
36540x00000027,0x00002b59,0x00002c00,0x00050080,
36550x00000006,0x00002b5b,0x00002b3b,0x00000189,
36560x00050095,0x000000ab,0x00002c31,0x00002b8a,
36570x00002b5b,0x00050051,0x00000006,0x00002c32,
36580x00002c31,0x00000001,0x00050051,0x00000006,
36590x00002c33,0x00002c31,0x00000000,0x00050080,
36600x00000006,0x00002c38,0x00002b91,0x00002c32,
36610x00050050,0x00000007,0x00002c39,0x00002c33,
36620x00002c38,0x0004007c,0x00000014,0x00002c29,
36630x00002c39,0x00060041,0x000000db,0x00002c20,
36640x00002c29,0x000000da,0x000000da,0x0006003d,
36650x00000006,0x00002c21,0x00002c20,0x00000002,
36660x00000004,0x0004007c,0x00000027,0x00002b5f,
36670x00002c21,0x00060050,0x0000004b,0x00002b60,
36680x00002b53,0x00002b59,0x00002b5f,0x000200f9,
36690x000026b8,0x000200f8,0x000026b8,0x000700f5,
36700x0000004b,0x0000309b,0x00002a26,0x000026a9,
36710x00002b60,0x000026aa,0x000700f5,0x0000004b,
36720x00003099,0x00002a13,0x000026a9,0x00002b4d,
36730x000026aa,0x000700f5,0x00000006,0x00003097,
36740x000029e9,0x000026a9,0x00002b29,0x000026aa,
36750x00050041,0x000000fe,0x000026b9,0x000000fc,
36760x000009ef,0x0004003d,0x00000006,0x000026ba,
36770x000026b9,0x000500c2,0x00000006,0x00002c3d,
36780x00003097,0x0000020d,0x00050041,0x000000fe,
36790x000026bd,0x000000fc,0x0000022c,0x0004003d,
36800x00000006,0x000026be,0x000026bd,0x00050086,
36810x00000006,0x000026bf,0x000026be,0x00000107,
36820x00050082,0x00000006,0x000026c0,0x00002c3d,
36830x000026bf,0x00050084,0x00000006,0x000026c1,
36840x0000010a,0x000026c0,0x00050080,0x00000006,
36850x000026c2,0x000026ba,0x000026c1,0x00050041,
36860x00000156,0x000026c3,0x000000fc,0x000000da,
36870x0004003d,0x00000007,0x000026c4,0x000026c3,
36880x00050051,0x00000006,0x00002c53,0x000026c4,
36890x00000000,0x00050095,0x000000ab,0x00002c55,
36900x00002c53,0x000026c2,0x00050051,0x00000006,
36910x00002c56,0x00002c55,0x00000001,0x00050051,
36920x00000006,0x00002c57,0x00002c55,0x00000000,
36930x00050051,0x00000006,0x00002c5a,0x000026c4,
36940x00000001,0x00050080,0x00000006,0x00002c5c,
36950x00002c5a,0x00002c56,0x00050050,0x00000007,
36960x00002c5d,0x00002c57,0x00002c5c,0x0004007c,
36970x00000014,0x00002c4d,0x00002c5d,0x00060041,
36980x000000db,0x00002c45,0x00002c4d,0x000000da,
36990x000000da,0x0005003e,0x00002c45,0x00002730,
31620x00000002,0x00000004,0x00050051,0x00000027, 37000x00000002,0x00000004,0x00050051,0x00000027,
31630x000026a3,0x00002aad,0x00000000,0x00050051, 37010x00002c61,0x00003099,0x00000000,0x00050051,
31640x00000027,0x000026a5,0x00002aaf,0x00000000, 37020x00000027,0x00002c63,0x0000309b,0x00000000,
31650x000500bc,0x0000002f,0x000026a6,0x000026a3, 37030x000500bc,0x0000002f,0x00002c64,0x00002c61,
31660x000026a5,0x000300f7,0x000026ad,0x00000000, 37040x00002c63,0x000300f7,0x00002c6b,0x00000000,
31670x000400fa,0x000026a6,0x000026a7,0x000026ad, 37050x000400fa,0x00002c64,0x00002c65,0x00002c6b,
31680x000200f8,0x000026a7,0x00050051,0x00000027, 37060x000200f8,0x00002c65,0x00050051,0x00000027,
31690x000026a9,0x00002aad,0x00000001,0x00050051, 37070x00002c67,0x00003099,0x00000001,0x00050051,
31700x00000027,0x000026ab,0x00002aaf,0x00000001, 37080x00000027,0x00002c69,0x0000309b,0x00000001,
31710x000500bc,0x0000002f,0x000026ac,0x000026a9, 37090x000500bc,0x0000002f,0x00002c6a,0x00002c67,
31720x000026ab,0x000200f9,0x000026ad,0x000200f8, 37100x00002c69,0x000200f9,0x00002c6b,0x000200f8,
31730x000026ad,0x000700f5,0x0000002f,0x000026ae, 37110x00002c6b,0x000700f5,0x0000002f,0x00002c6c,
31740x000026a6,0x0000237e,0x000026ac,0x000026a7, 37120x00002c64,0x000026b8,0x00002c6a,0x00002c65,
31750x000300f7,0x000026b5,0x00000000,0x000400fa, 37130x000300f7,0x00002c73,0x00000000,0x000400fa,
31760x000026ae,0x000026af,0x000026b5,0x000200f8, 37140x00002c6c,0x00002c6d,0x00002c73,0x000200f8,
31770x000026af,0x00050051,0x00000027,0x000026b1, 37150x00002c6d,0x00050051,0x00000027,0x00002c6f,
31780x00002aad,0x00000002,0x00050051,0x00000027, 37160x00003099,0x00000002,0x00050051,0x00000027,
31790x000026b3,0x00002aaf,0x00000002,0x000500bc, 37170x00002c71,0x0000309b,0x00000002,0x000500bc,
31800x0000002f,0x000026b4,0x000026b1,0x000026b3, 37180x0000002f,0x00002c72,0x00002c6f,0x00002c71,
31810x000200f9,0x000026b5,0x000200f8,0x000026b5, 37190x000200f9,0x00002c73,0x000200f8,0x00002c73,
31820x000700f5,0x0000002f,0x000026b6,0x000026ae, 37200x000700f5,0x0000002f,0x00002c74,0x00002c6c,
31830x000026ad,0x000026b4,0x000026af,0x000300f7, 37210x00002c6b,0x00002c72,0x00002c6d,0x000300f7,
31840x00002398,0x00000000,0x000400fa,0x000026b6, 37220x000026d2,0x00000000,0x000400fa,0x00002c74,
31850x00002391,0x00002398,0x000200f8,0x00002391, 37230x000026cb,0x000026d2,0x000200f8,0x000026cb,
31860x0007000c,0x0000004b,0x00002394,0x00000001, 37240x0007000c,0x0000004b,0x000026ce,0x00000001,
31870x00000025,0x00002aa8,0x00002aad,0x0007000c, 37250x00000025,0x00003094,0x00003099,0x0007000c,
31880x0000004b,0x00002397,0x00000001,0x00000028, 37260x0000004b,0x000026d1,0x00000001,0x00000028,
31890x00002aaa,0x00002aaf,0x000200f9,0x00002398, 37270x00003096,0x0000309b,0x000200f9,0x000026d2,
31900x000200f8,0x00002398,0x000700f5,0x0000004b, 37280x000200f8,0x000026d2,0x000700f5,0x0000004b,
31910x00002b58,0x00002aaa,0x000026b5,0x00002397, 37290x00003183,0x00003096,0x00002c73,0x000026d1,
31920x00002391,0x000700f5,0x0000004b,0x00002b56, 37300x000026cb,0x000700f5,0x0000004b,0x0000317e,
31930x00002aa8,0x000026b5,0x00002394,0x00002391, 37310x00003094,0x00002c73,0x000026ce,0x000026cb,
31940x000200f9,0x00002399,0x000200f8,0x00002399, 37320x000200f9,0x000026d3,0x000200f8,0x000026d3,
31950x000700f5,0x0000004b,0x00002b57,0x00002aaa, 37330x000700f5,0x0000004b,0x00003182,0x00003096,
31960x00002342,0x00002b58,0x00002398,0x000700f5, 37340x00002684,0x00003183,0x000026d2,0x000700f5,
31970x0000004b,0x00002b55,0x00002aa8,0x00002342, 37350x0000004b,0x0000317d,0x00003094,0x00002684,
31980x00002b56,0x00002398,0x000700f5,0x0000004b, 37360x0000317e,0x000026d2,0x000700f5,0x0000004b,
31990x00002ac9,0x00002b66,0x00002342,0x00002aaf, 37370x000030d9,0x0000319b,0x00002684,0x0000309b,
32000x00002398,0x000700f5,0x0000004b,0x00002ac7, 37380x000026d2,0x000700f5,0x0000004b,0x000030d4,
32010x00002b64,0x00002342,0x00002aad,0x00002398, 37390x00003199,0x00002684,0x00003099,0x000026d2,
32020x000700f5,0x00000006,0x00002ac3,0x0000037d, 37400x000700f5,0x00000006,0x000030cd,0x00000380,
32030x00002342,0x00002aab,0x00002398,0x00050084, 37410x00002684,0x00003097,0x000026d2,0x000200f9,
32040x00000006,0x0000239c,0x00000107,0x00002aa5, 37420x000026d4,0x000200f8,0x000026d4,0x000700f5,
32050x00050080,0x00000006,0x0000239d,0x000023f2, 37430x0000004b,0x0000317f,0x00003180,0x00002683,
32060x0000239c,0x00050041,0x00000153,0x0000239e, 37440x00003182,0x000026d3,0x000700f5,0x0000004b,
32070x000000f9,0x000000d7,0x0004003d,0x00000007, 37450x0000317a,0x0000317b,0x00002683,0x0000317d,
32080x0000239f,0x0000239e,0x00050051,0x00000006, 37460x000026d3,0x000700f5,0x0000004b,0x000030d6,
32090x000026cd,0x0000239f,0x00000000,0x00050095, 37470x000030d7,0x00002683,0x000030d9,0x000026d3,
32100x000000a8,0x000026cf,0x000026cd,0x0000239d, 37480x000700f5,0x0000004b,0x000030d1,0x000030d2,
32110x00050051,0x00000006,0x000026d0,0x000026cf, 37490x00002683,0x000030d4,0x000026d3,0x000700f5,
32120x00000001,0x00050051,0x00000006,0x000026d1, 37500x00000006,0x000030c6,0x00002739,0x00002683,
32130x000026cf,0x00000000,0x00050051,0x00000006, 37510x000030cd,0x000026d3,0x00050084,0x00000006,
32140x000026d4,0x0000239f,0x00000001,0x00050080, 37520x000026d7,0x0000010a,0x00003091,0x00050080,
32150x00000006,0x000026d6,0x000026d4,0x000026d0, 37530x00000006,0x000026d8,0x0000272d,0x000026d7,
32160x00050050,0x00000007,0x000026d7,0x000026d1, 37540x00050041,0x00000156,0x000026d9,0x000000fc,
32170x000026d6,0x0004007c,0x00000014,0x000026c7, 37550x000000da,0x0004003d,0x00000007,0x000026da,
32180x000026d7,0x00060041,0x000000d8,0x000026bf, 37560x000026d9,0x00050051,0x00000006,0x00002c8b,
32190x000026c7,0x000000d7,0x000000d7,0x0005003e, 37570x000026da,0x00000000,0x00050095,0x000000ab,
32200x000026bf,0x00002ac3,0x00000002,0x00000004, 37580x00002c8d,0x00002c8b,0x000026d8,0x00050051,
32210x00050080,0x00000006,0x000023a3,0x000023f2, 37590x00000006,0x00002c8e,0x00002c8d,0x00000001,
32220x0000011c,0x00050084,0x00000006,0x000023a5, 37600x00050051,0x00000006,0x00002c8f,0x00002c8d,
32230x0000014d,0x00002aa5,0x00050080,0x00000006, 37610x00000000,0x00050051,0x00000006,0x00002c92,
32240x000023a6,0x000023a3,0x000023a5,0x00050051, 37620x000026da,0x00000001,0x00050080,0x00000006,
32250x00000027,0x000023ab,0x00002ac7,0x00000000, 37630x00002c94,0x00002c92,0x00002c8e,0x00050050,
32260x0004007c,0x00000006,0x000026dd,0x000023ab, 37640x00000007,0x00002c95,0x00002c8f,0x00002c94,
32270x00050095,0x000000a8,0x000026f8,0x000026cd, 37650x0004007c,0x00000014,0x00002c85,0x00002c95,
32280x000023a6,0x00050051,0x00000006,0x000026f9, 37660x00060041,0x000000db,0x00002c7d,0x00002c85,
32290x000026f8,0x00000001,0x00050051,0x00000006, 37670x000000da,0x000000da,0x0005003e,0x00002c7d,
32300x000026fa,0x000026f8,0x00000000,0x00050080, 37680x000030c6,0x00000002,0x00000004,0x00050080,
32310x00000006,0x000026ff,0x000026d4,0x000026f9, 37690x00000006,0x000026de,0x0000272d,0x0000011f,
32320x00050050,0x00000007,0x00002700,0x000026fa, 37700x00050084,0x00000006,0x000026e0,0x00000150,
32330x000026ff,0x0004007c,0x00000014,0x000026f0, 37710x00003091,0x00050080,0x00000006,0x000026e1,
32340x00002700,0x00060041,0x000000d8,0x000026e8, 37720x000026de,0x000026e0,0x00050051,0x00000027,
32350x000026f0,0x000000d7,0x000000d7,0x0005003e, 37730x000026e6,0x000030d1,0x00000000,0x0004007c,
32360x000026e8,0x000026dd,0x00000002,0x00000004, 37740x00000006,0x00002c9b,0x000026e6,0x00050095,
32370x00050080,0x00000006,0x000023ae,0x000023a6, 37750x000000ab,0x00002cb6,0x00002c8b,0x000026e1,
32380x00000107,0x00050051,0x00000027,0x000023b2, 37760x00050051,0x00000006,0x00002cb7,0x00002cb6,
32390x00002ac7,0x00000001,0x0004007c,0x00000006, 37770x00000001,0x00050051,0x00000006,0x00002cb8,
32400x00002706,0x000023b2,0x00050095,0x000000a8, 37780x00002cb6,0x00000000,0x00050080,0x00000006,
32410x00002721,0x000026cd,0x000023ae,0x00050051, 37790x00002cbd,0x00002c92,0x00002cb7,0x00050050,
32420x00000006,0x00002722,0x00002721,0x00000001, 37800x00000007,0x00002cbe,0x00002cb8,0x00002cbd,
32430x00050051,0x00000006,0x00002723,0x00002721, 37810x0004007c,0x00000014,0x00002cae,0x00002cbe,
32440x00000000,0x00050080,0x00000006,0x00002728, 37820x00060041,0x000000db,0x00002ca6,0x00002cae,
32450x000026d4,0x00002722,0x00050050,0x00000007, 37830x000000da,0x000000da,0x0005003e,0x00002ca6,
32460x00002729,0x00002723,0x00002728,0x0004007c, 37840x00002c9b,0x00000002,0x00000004,0x00050080,
32470x00000014,0x00002719,0x00002729,0x00060041, 37850x00000006,0x000026e9,0x000026e1,0x0000010a,
32480x000000d8,0x00002711,0x00002719,0x000000d7, 37860x00050051,0x00000027,0x000026ed,0x000030d1,
32490x000000d7,0x0005003e,0x00002711,0x00002706, 37870x00000001,0x0004007c,0x00000006,0x00002cc4,
37880x000026ed,0x00050095,0x000000ab,0x00002cdf,
37890x00002c8b,0x000026e9,0x00050051,0x00000006,
37900x00002ce0,0x00002cdf,0x00000001,0x00050051,
37910x00000006,0x00002ce1,0x00002cdf,0x00000000,
37920x00050080,0x00000006,0x00002ce6,0x00002c92,
37930x00002ce0,0x00050050,0x00000007,0x00002ce7,
37940x00002ce1,0x00002ce6,0x0004007c,0x00000014,
37950x00002cd7,0x00002ce7,0x00060041,0x000000db,
37960x00002ccf,0x00002cd7,0x000000da,0x000000da,
37970x0005003e,0x00002ccf,0x00002cc4,0x00000002,
37980x00000004,0x00050080,0x00000006,0x000026f0,
37990x000026e1,0x00000111,0x00050051,0x00000027,
38000x000026f4,0x000030d1,0x00000002,0x0004007c,
38010x00000006,0x00002ced,0x000026f4,0x00050095,
38020x000000ab,0x00002d08,0x00002c8b,0x000026f0,
38030x00050051,0x00000006,0x00002d09,0x00002d08,
38040x00000001,0x00050051,0x00000006,0x00002d0a,
38050x00002d08,0x00000000,0x00050080,0x00000006,
38060x00002d0f,0x00002c92,0x00002d09,0x00050050,
38070x00000007,0x00002d10,0x00002d0a,0x00002d0f,
38080x0004007c,0x00000014,0x00002d00,0x00002d10,
38090x00060041,0x000000db,0x00002cf8,0x00002d00,
38100x000000da,0x000000da,0x0005003e,0x00002cf8,
38110x00002ced,0x00000002,0x00000004,0x00050080,
38120x00000006,0x000026f7,0x000026e1,0x00000118,
38130x00050051,0x00000027,0x000026fb,0x000030d6,
38140x00000000,0x0004007c,0x00000006,0x00002d16,
38150x000026fb,0x00050095,0x000000ab,0x00002d31,
38160x00002c8b,0x000026f7,0x00050051,0x00000006,
38170x00002d32,0x00002d31,0x00000001,0x00050051,
38180x00000006,0x00002d33,0x00002d31,0x00000000,
38190x00050080,0x00000006,0x00002d38,0x00002c92,
38200x00002d32,0x00050050,0x00000007,0x00002d39,
38210x00002d33,0x00002d38,0x0004007c,0x00000014,
38220x00002d29,0x00002d39,0x00060041,0x000000db,
38230x00002d21,0x00002d29,0x000000da,0x000000da,
38240x0005003e,0x00002d21,0x00002d16,0x00000002,
38250x00000004,0x00050080,0x00000006,0x000026fe,
38260x000026e1,0x0000011f,0x00050051,0x00000027,
38270x00002702,0x000030d6,0x00000001,0x0004007c,
38280x00000006,0x00002d3f,0x00002702,0x00050095,
38290x000000ab,0x00002d5a,0x00002c8b,0x000026fe,
38300x00050051,0x00000006,0x00002d5b,0x00002d5a,
38310x00000001,0x00050051,0x00000006,0x00002d5c,
38320x00002d5a,0x00000000,0x00050080,0x00000006,
38330x00002d61,0x00002c92,0x00002d5b,0x00050050,
38340x00000007,0x00002d62,0x00002d5c,0x00002d61,
38350x0004007c,0x00000014,0x00002d52,0x00002d62,
38360x00060041,0x000000db,0x00002d4a,0x00002d52,
38370x000000da,0x000000da,0x0005003e,0x00002d4a,
38380x00002d3f,0x00000002,0x00000004,0x00050080,
38390x00000006,0x00002705,0x000026e1,0x00000189,
38400x00050051,0x00000027,0x00002709,0x000030d6,
38410x00000002,0x0004007c,0x00000006,0x00002d68,
38420x00002709,0x00050095,0x000000ab,0x00002d83,
38430x00002c8b,0x00002705,0x00050051,0x00000006,
38440x00002d84,0x00002d83,0x00000001,0x00050051,
38450x00000006,0x00002d85,0x00002d83,0x00000000,
38460x00050080,0x00000006,0x00002d8a,0x00002c92,
38470x00002d84,0x00050050,0x00000007,0x00002d8b,
38480x00002d85,0x00002d8a,0x0004007c,0x00000014,
38490x00002d7b,0x00002d8b,0x00060041,0x000000db,
38500x00002d73,0x00002d7b,0x000000da,0x000000da,
38510x0005003e,0x00002d73,0x00002d68,0x00000002,
38520x00000004,0x000200f9,0x0000270b,0x000200f8,
38530x0000270b,0x00050080,0x00000006,0x0000270d,
38540x00003091,0x00000154,0x000200f9,0x0000262f,
38550x000200f8,0x0000270e,0x000200f9,0x0000270f,
38560x000200f8,0x0000270f,0x000700f5,0x00000006,
38570x00003092,0x000000a6,0x0000270e,0x0000271e,
38580x00002713,0x000500b0,0x0000002f,0x00002712,
38590x00003092,0x0000010a,0x000400f6,0x0000271f,
38600x00002713,0x00000000,0x000400fa,0x00002712,
38610x00002713,0x0000271f,0x000200f8,0x00002713,
38620x00050080,0x00000006,0x00002715,0x0000272d,
38630x000005c6,0x00050084,0x00000006,0x00002717,
38640x0000010a,0x00003092,0x00050080,0x00000006,
38650x00002718,0x00002715,0x00002717,0x00050041,
38660x00000156,0x00002719,0x000000fc,0x000000da,
38670x0004003d,0x00000007,0x0000271a,0x00002719,
38680x00050051,0x00000006,0x00002da1,0x0000271a,
38690x00000000,0x00050095,0x000000ab,0x00002da3,
38700x00002da1,0x00002718,0x00050051,0x00000006,
38710x00002da4,0x00002da3,0x00000001,0x00050051,
38720x00000006,0x00002da5,0x00002da3,0x00000000,
38730x00050051,0x00000006,0x00002da8,0x0000271a,
38740x00000001,0x00050080,0x00000006,0x00002daa,
38750x00002da8,0x00002da4,0x00050050,0x00000007,
38760x00002dab,0x00002da5,0x00002daa,0x0004007c,
38770x00000014,0x00002d9b,0x00002dab,0x00060041,
38780x000000db,0x00002d93,0x00002d9b,0x000000da,
38790x000000da,0x0005003e,0x00002d93,0x000000a6,
38800x00000002,0x00000004,0x00050080,0x00000006,
38810x0000271e,0x00003092,0x00000154,0x000200f9,
38820x0000270f,0x000200f8,0x0000271f,0x00050041,
38830x000000fe,0x00002720,0x000000fc,0x0000096c,
38840x0004003d,0x00000006,0x00002721,0x00002720,
38850x00050080,0x00000006,0x00002723,0x00002721,
38860x00002623,0x00050041,0x000000fe,0x00002df5,
38870x000000fc,0x000000fd,0x0004003d,0x00000006,
38880x00002df6,0x00002df5,0x00050084,0x00000006,
38890x00002df7,0x0000011f,0x00002df6,0x00050080,
38900x00000006,0x00002df8,0x00000107,0x00002df7,
38910x00050080,0x00000006,0x00002dfe,0x00002df6,
38920x0000319c,0x00050086,0x00000006,0x00002dff,
38930x00002dfe,0x00000101,0x00050084,0x00000006,
38940x00002df1,0x00000107,0x00002dff,0x00050080,
38950x00000006,0x00002df2,0x00002df8,0x00002df1,
38960x00050084,0x00000006,0x00002dc2,0x00000150,
38970x00002723,0x00050080,0x00000006,0x00002dc3,
38980x00002df2,0x00002dc2,0x00050041,0x00000156,
38990x00002dc4,0x000000fc,0x00000154,0x0004003d,
39000x00000007,0x00002dc5,0x00002dc4,0x00050051,
39010x00000027,0x00002dc8,0x00003094,0x00000000,
39020x0004007c,0x00000006,0x00002e05,0x00002dc8,
39030x00050051,0x00000006,0x00002e1e,0x00002dc5,
39040x00000000,0x00050095,0x000000ab,0x00002e20,
39050x00002e1e,0x00002dc3,0x00050051,0x00000006,
39060x00002e21,0x00002e20,0x00000001,0x00050051,
39070x00000006,0x00002e22,0x00002e20,0x00000000,
39080x00050051,0x00000006,0x00002e25,0x00002dc5,
39090x00000001,0x00050080,0x00000006,0x00002e27,
39100x00002e25,0x00002e21,0x00050050,0x00000007,
39110x00002e28,0x00002e22,0x00002e27,0x0004007c,
39120x00000014,0x00002e18,0x00002e28,0x00060041,
39130x000000db,0x00002e10,0x00002e18,0x000000da,
39140x000000da,0x0005003e,0x00002e10,0x00002e05,
39150x00000002,0x00000004,0x00050080,0x00000006,
39160x00002dcb,0x00002dc3,0x0000010a,0x00050051,
39170x00000027,0x00002dcf,0x00003094,0x00000001,
39180x0004007c,0x00000006,0x00002e2e,0x00002dcf,
39190x00050095,0x000000ab,0x00002e49,0x00002e1e,
39200x00002dcb,0x00050051,0x00000006,0x00002e4a,
39210x00002e49,0x00000001,0x00050051,0x00000006,
39220x00002e4b,0x00002e49,0x00000000,0x00050080,
39230x00000006,0x00002e50,0x00002e25,0x00002e4a,
39240x00050050,0x00000007,0x00002e51,0x00002e4b,
39250x00002e50,0x0004007c,0x00000014,0x00002e41,
39260x00002e51,0x00060041,0x000000db,0x00002e39,
39270x00002e41,0x000000da,0x000000da,0x0005003e,
39280x00002e39,0x00002e2e,0x00000002,0x00000004,
39290x00050080,0x00000006,0x00002dd2,0x00002dc3,
39300x00000111,0x00050051,0x00000027,0x00002dd6,
39310x00003094,0x00000002,0x0004007c,0x00000006,
39320x00002e57,0x00002dd6,0x00050095,0x000000ab,
39330x00002e72,0x00002e1e,0x00002dd2,0x00050051,
39340x00000006,0x00002e73,0x00002e72,0x00000001,
39350x00050051,0x00000006,0x00002e74,0x00002e72,
39360x00000000,0x00050080,0x00000006,0x00002e79,
39370x00002e25,0x00002e73,0x00050050,0x00000007,
39380x00002e7a,0x00002e74,0x00002e79,0x0004007c,
39390x00000014,0x00002e6a,0x00002e7a,0x00060041,
39400x000000db,0x00002e62,0x00002e6a,0x000000da,
39410x000000da,0x0005003e,0x00002e62,0x00002e57,
32500x00000002,0x00000004,0x00050080,0x00000006, 39420x00000002,0x00000004,0x00050080,0x00000006,
32510x000023b5,0x000023a6,0x0000010e,0x00050051, 39430x00002dd9,0x00002dc3,0x00000118,0x00050051,
32520x00000027,0x000023b9,0x00002ac7,0x00000002, 39440x00000027,0x00002ddd,0x00003096,0x00000000,
32530x0004007c,0x00000006,0x0000272f,0x000023b9, 39450x0004007c,0x00000006,0x00002e80,0x00002ddd,
32540x00050095,0x000000a8,0x0000274a,0x000026cd, 39460x00050095,0x000000ab,0x00002e9b,0x00002e1e,
32550x000023b5,0x00050051,0x00000006,0x0000274b, 39470x00002dd9,0x00050051,0x00000006,0x00002e9c,
32560x0000274a,0x00000001,0x00050051,0x00000006, 39480x00002e9b,0x00000001,0x00050051,0x00000006,
32570x0000274c,0x0000274a,0x00000000,0x00050080, 39490x00002e9d,0x00002e9b,0x00000000,0x00050080,
32580x00000006,0x00002751,0x000026d4,0x0000274b, 39500x00000006,0x00002ea2,0x00002e25,0x00002e9c,
32590x00050050,0x00000007,0x00002752,0x0000274c, 39510x00050050,0x00000007,0x00002ea3,0x00002e9d,
32600x00002751,0x0004007c,0x00000014,0x00002742, 39520x00002ea2,0x0004007c,0x00000014,0x00002e93,
32610x00002752,0x00060041,0x000000d8,0x0000273a, 39530x00002ea3,0x00060041,0x000000db,0x00002e8b,
32620x00002742,0x000000d7,0x000000d7,0x0005003e, 39540x00002e93,0x000000da,0x000000da,0x0005003e,
32630x0000273a,0x0000272f,0x00000002,0x00000004, 39550x00002e8b,0x00002e80,0x00000002,0x00000004,
32640x00050080,0x00000006,0x000023bc,0x000023a6, 39560x00050080,0x00000006,0x00002de0,0x00002dc3,
32650x00000115,0x00050051,0x00000027,0x000023c0, 39570x0000011f,0x00050051,0x00000027,0x00002de4,
32660x00002ac9,0x00000000,0x0004007c,0x00000006, 39580x00003096,0x00000001,0x0004007c,0x00000006,
32670x00002758,0x000023c0,0x00050095,0x000000a8, 39590x00002ea9,0x00002de4,0x00050095,0x000000ab,
32680x00002773,0x000026cd,0x000023bc,0x00050051, 39600x00002ec4,0x00002e1e,0x00002de0,0x00050051,
32690x00000006,0x00002774,0x00002773,0x00000001, 39610x00000006,0x00002ec5,0x00002ec4,0x00000001,
32700x00050051,0x00000006,0x00002775,0x00002773, 39620x00050051,0x00000006,0x00002ec6,0x00002ec4,
32710x00000000,0x00050080,0x00000006,0x0000277a, 39630x00000000,0x00050080,0x00000006,0x00002ecb,
32720x000026d4,0x00002774,0x00050050,0x00000007, 39640x00002e25,0x00002ec5,0x00050050,0x00000007,
32730x0000277b,0x00002775,0x0000277a,0x0004007c, 39650x00002ecc,0x00002ec6,0x00002ecb,0x0004007c,
32740x00000014,0x0000276b,0x0000277b,0x00060041, 39660x00000014,0x00002ebc,0x00002ecc,0x00060041,
32750x000000d8,0x00002763,0x0000276b,0x000000d7, 39670x000000db,0x00002eb4,0x00002ebc,0x000000da,
32760x000000d7,0x0005003e,0x00002763,0x00002758, 39680x000000da,0x0005003e,0x00002eb4,0x00002ea9,
32770x00000002,0x00000004,0x00050080,0x00000006, 39690x00000002,0x00000004,0x00050080,0x00000006,
32780x000023c3,0x000023a6,0x0000011c,0x00050051, 39700x00002de7,0x00002dc3,0x00000189,0x00050051,
32790x00000027,0x000023c7,0x00002ac9,0x00000001, 39710x00000027,0x00002deb,0x00003096,0x00000002,
32800x0004007c,0x00000006,0x00002781,0x000023c7, 39720x0004007c,0x00000006,0x00002ed2,0x00002deb,
32810x00050095,0x000000a8,0x0000279c,0x000026cd, 39730x00050095,0x000000ab,0x00002eed,0x00002e1e,
32820x000023c3,0x00050051,0x00000006,0x0000279d, 39740x00002de7,0x00050051,0x00000006,0x00002eee,
32830x0000279c,0x00000001,0x00050051,0x00000006, 39750x00002eed,0x00000001,0x00050051,0x00000006,
32840x0000279e,0x0000279c,0x00000000,0x00050080, 39760x00002eef,0x00002eed,0x00000000,0x00050080,
32850x00000006,0x000027a3,0x000026d4,0x0000279d, 39770x00000006,0x00002ef4,0x00002e25,0x00002eee,
32860x00050050,0x00000007,0x000027a4,0x0000279e, 39780x00050050,0x00000007,0x00002ef5,0x00002eef,
32870x000027a3,0x0004007c,0x00000014,0x00002794, 39790x00002ef4,0x0004007c,0x00000014,0x00002ee5,
32880x000027a4,0x00060041,0x000000d8,0x0000278c, 39800x00002ef5,0x00060041,0x000000db,0x00002edd,
32890x00002794,0x000000d7,0x000000d7,0x0005003e, 39810x00002ee5,0x000000da,0x000000da,0x0005003e,
32900x0000278c,0x00002781,0x00000002,0x00000004, 39820x00002edd,0x00002ed2,0x00000002,0x00000004,
32910x00050080,0x00000006,0x000023ca,0x000023a6, 39830x000200f9,0x00000bb0,0x000200f8,0x00000bb0,
32920x00000186,0x00050051,0x00000027,0x000023ce, 39840x000200f9,0x00000ba7,0x000200f8,0x00000ba7,
32930x00002ac9,0x00000002,0x0004007c,0x00000006, 39850x000200f9,0x00000b9e,0x000200f8,0x00000b9e,
32940x000027aa,0x000023ce,0x00050095,0x000000a8, 39860x000200f9,0x00000b95,0x000200f8,0x00000b95,
32950x000027c5,0x000026cd,0x000023ca,0x00050051, 39870x000200f9,0x00000b6f,0x000200f8,0x00000b6f,
32960x00000006,0x000027c6,0x000027c5,0x00000001, 39880x000200f9,0x00000b5a,0x000200f8,0x00000b5a,
32970x00050051,0x00000006,0x000027c7,0x000027c5, 39890x000200f9,0x00000bb6,0x000200f8,0x00000bb6,
32980x00000000,0x00050080,0x00000006,0x000027cc, 39900x000100fd,0x00010038}
32990x000026d4,0x000027c6,0x00050050,0x00000007,
33000x000027cd,0x000027c7,0x000027cc,0x0004007c,
33010x00000014,0x000027bd,0x000027cd,0x00060041,
33020x000000d8,0x000027b5,0x000027bd,0x000000d7,
33030x000000d7,0x0005003e,0x000027b5,0x000027aa,
33040x00000002,0x00000004,0x000200f9,0x000023d0,
33050x000200f8,0x000023d0,0x00050080,0x00000006,
33060x000023d2,0x00002aa5,0x00000151,0x000200f9,
33070x0000233e,0x000200f8,0x000023d3,0x000200f9,
33080x000023d4,0x000200f8,0x000023d4,0x000700f5,
33090x00000006,0x00002aa6,0x000000a3,0x000023d3,
33100x000023e3,0x000023d8,0x000500b0,0x0000002f,
33110x000023d7,0x00002aa6,0x00000107,0x000400f6,
33120x000023e4,0x000023d8,0x00000000,0x000400fa,
33130x000023d7,0x000023d8,0x000023e4,0x000200f8,
33140x000023d8,0x00050080,0x00000006,0x000023da,
33150x000023f2,0x000005c3,0x00050084,0x00000006,
33160x000023dc,0x00000107,0x00002aa6,0x00050080,
33170x00000006,0x000023dd,0x000023da,0x000023dc,
33180x00050041,0x00000153,0x000023de,0x000000f9,
33190x000000d7,0x0004003d,0x00000007,0x000023df,
33200x000023de,0x00050051,0x00000006,0x000027e3,
33210x000023df,0x00000000,0x00050095,0x000000a8,
33220x000027e5,0x000027e3,0x000023dd,0x00050051,
33230x00000006,0x000027e6,0x000027e5,0x00000001,
33240x00050051,0x00000006,0x000027e7,0x000027e5,
33250x00000000,0x00050051,0x00000006,0x000027ea,
33260x000023df,0x00000001,0x00050080,0x00000006,
33270x000027ec,0x000027ea,0x000027e6,0x00050050,
33280x00000007,0x000027ed,0x000027e7,0x000027ec,
33290x0004007c,0x00000014,0x000027dd,0x000027ed,
33300x00060041,0x000000d8,0x000027d5,0x000027dd,
33310x000000d7,0x000000d7,0x0005003e,0x000027d5,
33320x000000a3,0x00000002,0x00000004,0x00050080,
33330x00000006,0x000023e3,0x00002aa6,0x00000151,
33340x000200f9,0x000023d4,0x000200f8,0x000023e4,
33350x00050041,0x000000fb,0x000023e5,0x000000f9,
33360x000008bc,0x0004003d,0x00000006,0x000023e6,
33370x000023e5,0x00050080,0x00000006,0x000023e8,
33380x000023e6,0x00002332,0x00050041,0x000000fb,
33390x00002837,0x000000f9,0x000000fa,0x0004003d,
33400x00000006,0x00002838,0x00002837,0x00050084,
33410x00000006,0x00002839,0x0000011c,0x00002838,
33420x00050080,0x00000006,0x0000283a,0x00000104,
33430x00002839,0x00050080,0x00000006,0x00002840,
33440x00002838,0x00002b67,0x00050086,0x00000006,
33450x00002841,0x00002840,0x000000fe,0x00050084,
33460x00000006,0x00002833,0x00000104,0x00002841,
33470x00050080,0x00000006,0x00002834,0x0000283a,
33480x00002833,0x00050084,0x00000006,0x00002804,
33490x0000014d,0x000023e8,0x00050080,0x00000006,
33500x00002805,0x00002834,0x00002804,0x00050041,
33510x00000153,0x00002806,0x000000f9,0x00000151,
33520x0004003d,0x00000007,0x00002807,0x00002806,
33530x00050051,0x00000027,0x0000280a,0x00002aa8,
33540x00000000,0x0004007c,0x00000006,0x00002847,
33550x0000280a,0x00050051,0x00000006,0x00002860,
33560x00002807,0x00000000,0x00050095,0x000000a8,
33570x00002862,0x00002860,0x00002805,0x00050051,
33580x00000006,0x00002863,0x00002862,0x00000001,
33590x00050051,0x00000006,0x00002864,0x00002862,
33600x00000000,0x00050051,0x00000006,0x00002867,
33610x00002807,0x00000001,0x00050080,0x00000006,
33620x00002869,0x00002867,0x00002863,0x00050050,
33630x00000007,0x0000286a,0x00002864,0x00002869,
33640x0004007c,0x00000014,0x0000285a,0x0000286a,
33650x00060041,0x000000d8,0x00002852,0x0000285a,
33660x000000d7,0x000000d7,0x0005003e,0x00002852,
33670x00002847,0x00000002,0x00000004,0x00050080,
33680x00000006,0x0000280d,0x00002805,0x00000107,
33690x00050051,0x00000027,0x00002811,0x00002aa8,
33700x00000001,0x0004007c,0x00000006,0x00002870,
33710x00002811,0x00050095,0x000000a8,0x0000288b,
33720x00002860,0x0000280d,0x00050051,0x00000006,
33730x0000288c,0x0000288b,0x00000001,0x00050051,
33740x00000006,0x0000288d,0x0000288b,0x00000000,
33750x00050080,0x00000006,0x00002892,0x00002867,
33760x0000288c,0x00050050,0x00000007,0x00002893,
33770x0000288d,0x00002892,0x0004007c,0x00000014,
33780x00002883,0x00002893,0x00060041,0x000000d8,
33790x0000287b,0x00002883,0x000000d7,0x000000d7,
33800x0005003e,0x0000287b,0x00002870,0x00000002,
33810x00000004,0x00050080,0x00000006,0x00002814,
33820x00002805,0x0000010e,0x00050051,0x00000027,
33830x00002818,0x00002aa8,0x00000002,0x0004007c,
33840x00000006,0x00002899,0x00002818,0x00050095,
33850x000000a8,0x000028b4,0x00002860,0x00002814,
33860x00050051,0x00000006,0x000028b5,0x000028b4,
33870x00000001,0x00050051,0x00000006,0x000028b6,
33880x000028b4,0x00000000,0x00050080,0x00000006,
33890x000028bb,0x00002867,0x000028b5,0x00050050,
33900x00000007,0x000028bc,0x000028b6,0x000028bb,
33910x0004007c,0x00000014,0x000028ac,0x000028bc,
33920x00060041,0x000000d8,0x000028a4,0x000028ac,
33930x000000d7,0x000000d7,0x0005003e,0x000028a4,
33940x00002899,0x00000002,0x00000004,0x00050080,
33950x00000006,0x0000281b,0x00002805,0x00000115,
33960x00050051,0x00000027,0x0000281f,0x00002aaa,
33970x00000000,0x0004007c,0x00000006,0x000028c2,
33980x0000281f,0x00050095,0x000000a8,0x000028dd,
33990x00002860,0x0000281b,0x00050051,0x00000006,
34000x000028de,0x000028dd,0x00000001,0x00050051,
34010x00000006,0x000028df,0x000028dd,0x00000000,
34020x00050080,0x00000006,0x000028e4,0x00002867,
34030x000028de,0x00050050,0x00000007,0x000028e5,
34040x000028df,0x000028e4,0x0004007c,0x00000014,
34050x000028d5,0x000028e5,0x00060041,0x000000d8,
34060x000028cd,0x000028d5,0x000000d7,0x000000d7,
34070x0005003e,0x000028cd,0x000028c2,0x00000002,
34080x00000004,0x00050080,0x00000006,0x00002822,
34090x00002805,0x0000011c,0x00050051,0x00000027,
34100x00002826,0x00002aaa,0x00000001,0x0004007c,
34110x00000006,0x000028eb,0x00002826,0x00050095,
34120x000000a8,0x00002906,0x00002860,0x00002822,
34130x00050051,0x00000006,0x00002907,0x00002906,
34140x00000001,0x00050051,0x00000006,0x00002908,
34150x00002906,0x00000000,0x00050080,0x00000006,
34160x0000290d,0x00002867,0x00002907,0x00050050,
34170x00000007,0x0000290e,0x00002908,0x0000290d,
34180x0004007c,0x00000014,0x000028fe,0x0000290e,
34190x00060041,0x000000d8,0x000028f6,0x000028fe,
34200x000000d7,0x000000d7,0x0005003e,0x000028f6,
34210x000028eb,0x00000002,0x00000004,0x00050080,
34220x00000006,0x00002829,0x00002805,0x00000186,
34230x00050051,0x00000027,0x0000282d,0x00002aaa,
34240x00000002,0x0004007c,0x00000006,0x00002914,
34250x0000282d,0x00050095,0x000000a8,0x0000292f,
34260x00002860,0x00002829,0x00050051,0x00000006,
34270x00002930,0x0000292f,0x00000001,0x00050051,
34280x00000006,0x00002931,0x0000292f,0x00000000,
34290x00050080,0x00000006,0x00002936,0x00002867,
34300x00002930,0x00050050,0x00000007,0x00002937,
34310x00002931,0x00002936,0x0004007c,0x00000014,
34320x00002927,0x00002937,0x00060041,0x000000d8,
34330x0000291f,0x00002927,0x000000d7,0x000000d7,
34340x0005003e,0x0000291f,0x00002914,0x00000002,
34350x00000004,0x000200f9,0x00000a68,0x000200f8,
34360x00000a68,0x000200f9,0x00000a5f,0x000200f8,
34370x00000a5f,0x000200f9,0x00000a56,0x000200f8,
34380x00000a56,0x000200f9,0x00000a4d,0x000200f8,
34390x00000a4d,0x000200f9,0x00000a27,0x000200f8,
34400x00000a27,0x000200f9,0x00000a6e,0x000200f8,
34410x00000a6e,0x000100fd,0x00010038}
diff --git a/runtime/test/allocator_proxy_test.cpp b/runtime/test/allocator_proxy_test.cpp
new file mode 100644
index 000000000..733e37cac
--- /dev/null
+++ b/runtime/test/allocator_proxy_test.cpp
@@ -0,0 +1,382 @@
1// Xbox-ABI command allocator proxies (d3d12_xs_device.h, device slot 9) behind the device proxy, on the Vulkan-backed
2// device and on the host PC runtime (WARP, and the first hardware adapter when there is one):
3// - Vulkan device: slot 9 wraps the allocator; the public chain (9 slots) is forwarded with the real allocator's
4// answers, every slot past it up to the end of the table is refused (E_NOTIMPL), and a read past the table faults
5// in the guard region and is counted;
6// - QueryInterface identity, GetDevice -> the device proxy, references and release orders;
7// - a command list created on the proxy and Reset on it (the Vulkan layer resolves the proxy), recording a buffer
8// copy that runs through the queue and fence proxies and is read back, twice, with the allocator Reset between;
9// and D3D12's allocator rules through the proxy (Reset while a list records: E_FAIL; a second list on a busy
10// allocator: E_INVALIDARG);
11// - MakeResident/Evict with an allocator proxy give the real allocator's HRESULT;
12// - host runtime: slot 9 hands out the PC allocator unwrapped (its lists could not resolve a proxy), and the same
13// copy works.
14// LEONIDA_VK_VALIDATION=1 runs the Vulkan device under VK_LAYER_KHRONOS_validation with synchronization validation;
15// any validation error fails the test. Exits 77 when neither a host D3D12 device nor a Vulkan device can be made.
16// No shaders, game data or Xbox DLLs.
17#include "vk_test_device.h"
18#include "../shims/d3d12_com.h"
19#include "../shims/d3d12_xs_device.h"
20
21#include <d3d12.h>
22#include <dxgi1_4.h>
23
24#include <cstdint>
25#include <cstdio>
26#include <cstring>
27
28#define EXPECT(condition) do { \
29 if (!(condition)) { std::fprintf(stderr, "%s line %d: %s\n", label, __LINE__, #condition); return 1; } \
30} while (0)
31
32namespace {
33
34namespace xs = rt::d3d12_xs;
35
36template <class T>
37struct Ref {
38 T* p = nullptr;
39 Ref() = default;
40 Ref(const Ref&) = delete;
41 Ref& operator=(const Ref&) = delete;
42 ~Ref() { reset(); }
43 void reset() {
44 if (p) p->Release();
45 p = nullptr;
46 }
47 T* operator->() const { return p; }
48};
49
50struct Backend {
51 const char* label;
52 ID3D12Device* device; // the device proxy
53 ID3D12Device* real; // the device behind it (PC runtime or Vulkan layer)
54 bool vulkan;
55};
56
57using SlotFn = std::uint64_t(WINAPI*)(void*, std::uint64_t, std::uint64_t, std::uint64_t, std::uint64_t,
58 std::uint64_t, std::uint64_t, std::uint64_t, std::uint64_t, std::uint64_t,
59 std::uint64_t, std::uint64_t, std::uint64_t, std::uint64_t, std::uint64_t);
60
61// A call through slot `slot` with all words zero, the way a title calls a console method the PC interface lacks.
62HRESULT call_slot(void* object, unsigned slot) {
63 void** vtable = *reinterpret_cast<void***>(object);
64 return static_cast<HRESULT>(static_cast<std::uint32_t>(
65 reinterpret_cast<SlotFn>(vtable[slot])(object, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)));
66}
67
68ULONG_PTR g_fault_address = 0;
69
70int record_fault(EXCEPTION_POINTERS* info) {
71 g_fault_address = info->ExceptionRecord->NumberParameters >= 2 ? info->ExceptionRecord->ExceptionInformation[1] : 0;
72 return EXCEPTION_EXECUTE_HANDLER;
73}
74
75// The read in a function of its own: clang-cl's __try only catches a fault raised inside a call.
76__declspec(noinline) void* read_entry(void* const* vtable, unsigned slot) {
77 return *static_cast<void* const volatile*>(&vtable[slot]);
78}
79
80// Reads vtable[slot] the way a call through it does. The exception code, or 0 when the read worked.
81DWORD read_slot_guarded(void* const* vtable, unsigned slot) {
82 g_fault_address = 0;
83 __try {
84 void* volatile entry = read_entry(vtable, slot);
85 (void)entry;
86 return 0;
87 } __except (record_fault(GetExceptionInformation())) {
88 return GetExceptionCode();
89 }
90}
91
92int wait_for(const char* label, ID3D12Fence* fence, UINT64 value) {
93 HANDLE event = CreateEventW(nullptr, FALSE, FALSE, nullptr);
94 EXPECT(event != nullptr);
95 const bool set = SUCCEEDED(fence->SetEventOnCompletion(value, event)) && WaitForSingleObject(event, 5000) == 0;
96 CloseHandle(event);
97 EXPECT(set && fence->GetCompletedValue() >= value);
98 return 0;
99}
100
101int make_buffer(const char* label, ID3D12Device* device, D3D12_HEAP_TYPE heap_type, D3D12_RESOURCE_STATES state,
102 Ref<ID3D12Resource>& out) {
103 D3D12_HEAP_PROPERTIES heap{};
104 heap.Type = heap_type;
105 D3D12_RESOURCE_DESC desc{};
106 desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;
107 desc.Width = 256;
108 desc.Height = desc.DepthOrArraySize = desc.MipLevels = 1;
109 desc.SampleDesc.Count = 1;
110 desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
111 EXPECT(SUCCEEDED(device->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, state, nullptr,
112 IID_PPV_ARGS(&out.p))));
113 return 0;
114}
115
116// One recording on `list` (open, recording into the allocator): 256 bytes of `byte` copied from an upload buffer to a
117// readback buffer, executed through the queue proxy, finished through the fence proxy at `value`, then compared.
118int copy_round(const char* label, ID3D12Device* device, ID3D12CommandQueue* queue, ID3D12Fence* fence,
119 ID3D12GraphicsCommandList* list, std::uint8_t byte, UINT64 value) {
120 Ref<ID3D12Resource> upload, readback;
121 if (make_buffer(label, device, D3D12_HEAP_TYPE_UPLOAD, D3D12_RESOURCE_STATE_GENERIC_READ, upload)) return 1;
122 if (make_buffer(label, device, D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_STATE_COPY_DEST, readback)) return 1;
123 void* mapped = nullptr;
124 EXPECT(SUCCEEDED(upload->Map(0, nullptr, &mapped)) && mapped);
125 std::memset(mapped, byte, 256);
126 upload->Unmap(0, nullptr);
127 list->CopyBufferRegion(readback.p, 0, upload.p, 0, 256);
128 EXPECT(SUCCEEDED(list->Close()));
129 ID3D12CommandList* lists[] = {list};
130 queue->ExecuteCommandLists(1, lists);
131 EXPECT(SUCCEEDED(queue->Signal(fence, value)));
132 if (wait_for(label, fence, value)) return 1;
133 const D3D12_RANGE read{0, 256};
134 EXPECT(SUCCEEDED(readback->Map(0, &read, &mapped)) && mapped);
135 const auto* bytes = static_cast<const std::uint8_t*>(mapped);
136 int wrong = 0;
137 for (int i = 0; i < 256; ++i) wrong += bytes[i] != byte;
138 const D3D12_RANGE none{0, 0};
139 readback->Unmap(0, &none);
140 EXPECT(wrong == 0);
141 return 0;
142}
143
144// ---- 1. The proxy itself: slots, identity, guard (Vulkan device) ----
145
146int check_proxy(const Backend& b, ID3D12CommandAllocator* allocator) {
147 const char* label = b.label;
148 ID3D12CommandAllocator* real = xs::allocator_proxy_real_allocator(allocator);
149 EXPECT(real && static_cast<void*>(real) != static_cast<void*>(allocator));
150 EXPECT(xs::allocator_proxy_slot_count(allocator) == 9);
151 EXPECT(xs::command_object_proxy_ref_count(allocator) == 1);
152
153 // QueryInterface: the base chain and the allocator itself answer with the proxy; anything else is refused.
154 const IID modelled[] = {__uuidof(IUnknown), __uuidof(ID3D12Object), __uuidof(ID3D12DeviceChild),
155 __uuidof(ID3D12Pageable), __uuidof(ID3D12CommandAllocator)};
156 for (const IID& iid : modelled) {
157 void* same = nullptr;
158 EXPECT(SUCCEEDED(allocator->QueryInterface(iid, &same)) && same == allocator);
159 static_cast<IUnknown*>(same)->Release();
160 }
161 void* other = reinterpret_cast<void*>(1);
162 EXPECT(allocator->QueryInterface(__uuidof(ID3D12Fence), &other) == E_NOINTERFACE && !other);
163 other = reinterpret_cast<void*>(1); // the Vulkan layer's private tag: not modelled, the real object stays hidden
164 EXPECT(allocator->QueryInterface(xs::kLeonidaCommandAllocatorTag, &other) == E_NOINTERFACE && !other);
165 EXPECT(xs::command_object_proxy_ref_count(allocator) == 1);
166
167 ID3D12Device* owner = nullptr;
168 EXPECT(SUCCEEDED(allocator->GetDevice(IID_PPV_ARGS(&owner))) && owner == b.device);
169 owner->Release();
170 // Private data and SetName go to the real allocator; the proxy pointer round-trips as an interface.
171 EXPECT(SUCCEEDED(allocator->SetName(L"leonida allocator proxy")));
172 constexpr GUID key{0x2a6b8c41, 0x77d2, 0x4e19, {0x9c, 0x3a, 0x51, 0xe0, 0x8f, 0x24, 0x6d, 0x0b}};
173 EXPECT(SUCCEEDED(allocator->SetPrivateDataInterface(key, allocator)));
174 IUnknown* back = nullptr;
175 UINT size = sizeof(back);
176 EXPECT(SUCCEEDED(allocator->GetPrivateData(key, &size, &back)) && back == allocator);
177 back->Release();
178 EXPECT(SUCCEEDED(allocator->SetPrivateDataInterface(key, nullptr)));
179
180 // The refused tail: every slot past the public chain, up to the table end, is E_NOTIMPL and counted.
181 const unsigned table = xs::allocator_proxy_table_size();
182 EXPECT(table == 64);
183 for (unsigned slot = 9; slot < table; ++slot) {
184 const std::uint64_t before = xs::allocator_slot_hits(slot);
185 EXPECT(call_slot(allocator, slot) == E_NOTIMPL);
186 EXPECT(xs::allocator_slot_hits(slot) == before + 1 && xs::allocator_slot_first_call_seen(slot));
187 }
188
189 // Past the table: the vtable read itself faults in the guard region, at the slot's address, and is counted.
190 EXPECT(xs::command_object_tables_guarded());
191 void* const* vtable = *reinterpret_cast<void* const* const*>(allocator);
192 EXPECT(read_slot_guarded(vtable, table - 1) == 0);
193 for (unsigned slot : {table, table + 512, table + 7000}) {
194 const std::uint64_t before = xs::allocator_table_overruns();
195 EXPECT(read_slot_guarded(vtable, slot) == EXCEPTION_ACCESS_VIOLATION);
196 EXPECT(g_fault_address == reinterpret_cast<ULONG_PTR>(&vtable[slot]));
197 EXPECT(xs::allocator_table_overruns() == before + 1);
198 }
199 std::printf("%s: allocator proxy: 9 public slots forwarded, slots 9-%u refused, the guard region names a read "
200 "past the table; QueryInterface/GetDevice/private data keep the proxy identity\n", label, table - 1);
201 return 0;
202}
203
204// ---- 2. Lists on the allocator, GPU work, D3D12's allocator rules, residency ----
205
206int check_backend(const Backend& b) {
207 const char* label = b.label;
208 const unsigned long device_refs = xs::device_proxy_ref_count(b.device);
209 {
210 Ref<ID3D12CommandAllocator> allocator;
211 EXPECT(SUCCEEDED(b.device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT,
212 IID_PPV_ARGS(&allocator.p))));
213 // Vulkan layer: wrapped. Host runtime: its lists could not resolve a proxy, so the PC allocator comes back.
214 EXPECT(xs::is_allocator_proxy(allocator.p) == b.vulkan);
215 if (b.vulkan && check_proxy(b, allocator.p)) return 1;
216 // As IUnknown, and without an output (the device's own answer), as slot 8 does for queues.
217 Ref<IUnknown> as_unknown;
218 EXPECT(SUCCEEDED(b.device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, __uuidof(IUnknown),
219 reinterpret_cast<void**>(&as_unknown.p))));
220 EXPECT(xs::is_allocator_proxy(as_unknown.p) == b.vulkan);
221#pragma warning(suppress : 6387) // the null output on purpose
222 EXPECT(b.device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, __uuidof(ID3D12CommandAllocator),
223 nullptr) ==
224 b.real->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, __uuidof(ID3D12CommandAllocator),
225 nullptr));
226 Ref<ID3D12Fence> not_an_allocator; // asked for an interface the allocator does not have
227 not_an_allocator.p = reinterpret_cast<ID3D12Fence*>(1);
228 const HRESULT wrong_iid = b.device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT,
229 IID_PPV_ARGS(&not_an_allocator.p));
230 const bool cleared = !not_an_allocator.p;
231 not_an_allocator.p = nullptr;
232 EXPECT(FAILED(wrong_iid) && cleared);
233
234 D3D12_COMMAND_QUEUE_DESC queue_desc{};
235 Ref<ID3D12CommandQueue> queue;
236 Ref<ID3D12Fence> fence;
237 EXPECT(SUCCEEDED(b.device->CreateCommandQueue(&queue_desc, IID_PPV_ARGS(&queue.p))));
238 EXPECT(SUCCEEDED(b.device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence.p))));
239 EXPECT(xs::is_queue_proxy(queue.p) && xs::is_fence_proxy(fence.p));
240
241 // A list on the allocator: the Vulkan layer resolves the proxy in CreateCommandList.
242 Ref<ID3D12GraphicsCommandList> list;
243 EXPECT(SUCCEEDED(b.device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocator.p, nullptr,
244 IID_PPV_ARGS(&list.p))));
245 // D3D12's rules, through the proxy: a recording list holds the allocator.
246 const std::uint64_t resets_before = xs::allocator_slot_hits(8);
247 EXPECT(allocator->Reset() == E_FAIL);
248 Ref<ID3D12GraphicsCommandList> second;
249 EXPECT(b.device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocator.p, nullptr,
250 IID_PPV_ARGS(&second.p)) == E_INVALIDARG && !second.p);
251 if (copy_round(label, b.device, queue.p, fence.p, list.p, 0x5a, 1)) return 1;
252
253 // Done on the GPU: the allocator resets through the proxy, and the list resets onto it (Reset resolves it).
254 EXPECT(SUCCEEDED(allocator->Reset()));
255 EXPECT(SUCCEEDED(list->Reset(allocator.p, nullptr)));
256 if (copy_round(label, b.device, queue.p, fence.p, list.p, 0xa5, 2)) return 1;
257 // The two allocator Reset calls above went through slot 8 (list->Reset is the list's method, not this one).
258 if (b.vulkan) EXPECT(xs::allocator_slot_hits(8) == resets_before + 2);
259
260 // Residency: the real runtime gets the real allocator (an allocator is a pageable).
261 ID3D12Pageable* pageable = allocator.p;
262 ID3D12CommandAllocator* real_allocator =
263 b.vulkan ? xs::allocator_proxy_real_allocator(allocator.p) : allocator.p;
264 ID3D12Pageable* real_pageable = real_allocator;
265 EXPECT(b.device->MakeResident(1, &pageable) == b.real->MakeResident(1, &real_pageable));
266 EXPECT(b.device->Evict(1, &pageable) == b.real->Evict(1, &real_pageable));
267
268 // Release orders: the allocator first while its (closed) list still exists, then the list.
269 if (b.vulkan) EXPECT(xs::command_object_proxy_ref_count(allocator.p) == 1);
270 allocator.reset();
271 list.reset();
272 }
273 EXPECT(xs::device_proxy_ref_count(b.device) == device_refs); // nothing the proxies made kept the device
274 std::printf("%s: CreateCommandAllocator %s; a list created and Reset on it, two GPU copies through the queue and "
275 "fence proxies read back exactly; allocator rules and residency as on the real allocator\n", label,
276 b.vulkan ? "returns an allocator proxy" : "returns the PC allocator unwrapped");
277 return 0;
278}
279
280int run_host(IDXGIAdapter1* adapter, const char* label) {
281 ID3D12Device* real = nullptr;
282 if (FAILED(D3D12CreateDevice(adapter, D3D_FEATURE_LEVEL_11_0, IID_PPV_ARGS(&real)))) {
283 std::printf("%s: no D3D12 device, skipped\n", label);
284 return 77;
285 }
286 real->AddRef(); // the backend's own reference; the proxy takes the other
287 Ref<ID3D12Device> device;
288 if (FAILED(xs::create_device_proxy(real, __uuidof(ID3D12Device), reinterpret_cast<void**>(&device.p)))) {
289 real->Release();
290 real->Release();
291 std::fprintf(stderr, "%s: device proxy creation failed\n", label);
292 return 1;
293 }
294 const int result = check_backend(Backend{label, device.p, real, false});
295 device.reset();
296 if (result) return 1;
297 if (real->Release() != 0) {
298 std::fprintf(stderr, "%s: the PC device outlives its proxies\n", label);
299 return 1;
300 }
301 return 0;
302}
303
304} // namespace
305
306// A failure ends the process with a message on stderr, never in a dialog a test run would wait on.
307static void no_dialogs() {
308 _set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT);
309 SetErrorMode(GetErrorMode() | SEM_FAILCRITICALERRORS | SEM_NOGPFAULTERRORBOX);
310}
311
312int main() {
313 no_dialogs();
314 std::setvbuf(stdout, nullptr, _IONBF, 0);
315 const char* label = "allocator_proxy_test";
316 int ran = 0;
317
318 // Host PC runtime: WARP, then the first hardware adapter. Under Wine the host d3d12.dll is Wine's own, not the
319 // PC runtime the proxy is written against, so only Vulkan runs there.
320 const bool wine = GetProcAddress(GetModuleHandleW(L"ntdll.dll"), "wine_get_version") != nullptr;
321 Ref<IDXGIFactory4> factory;
322 if (wine) std::printf("host D3D12: under Wine, skipped\n");
323 if (!wine && SUCCEEDED(CreateDXGIFactory1(IID_PPV_ARGS(&factory.p)))) {
324 Ref<IDXGIAdapter1> warp;
325 if (SUCCEEDED(factory->EnumWarpAdapter(IID_PPV_ARGS(&warp.p)))) {
326 const int r = run_host(warp.p, "host WARP");
327 if (r == 1) return 1;
328 ran += r == 0;
329 }
330 for (UINT i = 0;; ++i) {
331 Ref<IDXGIAdapter1> adapter;
332 if (factory->EnumAdapters1(i, &adapter.p) == DXGI_ERROR_NOT_FOUND) break;
333 DXGI_ADAPTER_DESC1 desc{};
334 if (FAILED(adapter->GetDesc1(&desc)) || (desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE)) continue;
335 char name[128] = {};
336 WideCharToMultiByte(CP_UTF8, 0, desc.Description, -1, name, sizeof(name) - 1, nullptr, nullptr);
337 char host_label[160];
338 std::snprintf(host_label, sizeof(host_label), "host %s", name);
339 const int r = run_host(adapter.p, host_label);
340 if (r == 1) return 1;
341 ran += r == 0;
342 break;
343 }
344 }
345
346 // The Vulkan-backed device, the way D3D12XboxCreateDevice hands it out with LEONIDA_D3D12=vulkan.
347 vktest::Device d;
348 if (d.create()) {
349 label = "Vulkan";
350 rt::d3d12::VulkanDeviceInfo info{};
351 info.get_instance_proc = d.instance_proc;
352 info.instance = d.instance;
353 info.physical = d.physical;
354 info.device = d.device;
355 info.queue = d.queue;
356 info.queue_family = d.family;
357 ID3D12Device* inner = nullptr;
358 EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&inner))));
359 inner->AddRef(); // the backend's own reference; the proxy takes the other
360 ID3D12Device* device = nullptr;
361 EXPECT(SUCCEEDED(xs::create_device_proxy(inner, __uuidof(ID3D12Device), reinterpret_cast<void**>(&device))));
362 rt::d3d12::set_device_outer(inner, device);
363 const int result = check_backend(Backend{label, device, inner, true});
364 device->Release();
365 if (result) return 1;
366 EXPECT(inner->Release() == 0); // nothing the proxies made kept the layer's device alive
367 ++ran;
368 if (d.validation_errors()) {
369 std::fprintf(stderr, "%u validation errors\n", d.validation_errors());
370 return 1;
371 }
372 } else {
373 std::printf("Vulkan: no device, skipped\n");
374 }
375
376 if (!ran) {
377 std::printf("SKIP allocator_proxy_test: neither a host D3D12 device nor a Vulkan device\n");
378 return 77;
379 }
380 std::printf("allocator_proxy_test: %d backend(s) passed\n", ran);
381 return 0;
382}
diff --git a/runtime/test/bindless_sizing_test.cpp b/runtime/test/bindless_sizing_test.cpp
index 469274d56..07715f01e 100644
--- a/runtime/test/bindless_sizing_test.cpp
+++ b/runtime/test/bindless_sizing_test.cpp
@@ -172,6 +172,37 @@ int main() {
172 EXPECT(totals(f).all <= 30000 && count(f, D::dim_2d) > 4096); 172 EXPECT(totals(f).all <= 30000 && count(f, D::dim_2d) > 4096);
173 } 173 }
174 174
175 // D3D-219: past maxPerSetDescriptors, growth follows layout_supported (vkGetDescriptorSetLayoutSupport), which
176 // is asked only above that limit. Intel's Xe-LP reports 6159 and supports the full sizes.
177 {
178 Device d = uniform(1048576, 1048576);
179 d.v11.maxPerSetDescriptors = 6159;
180 d.limits.maxSamplerAllocationCount = 4000;
181 unsigned asked = 0, asked_within = 0;
182 const auto all_supported = [&](const BindlessFeatures& candidate) {
183 ++asked;
184 asked_within += totals(candidate).all <= 6159;
185 return true;
186 };
187 BindlessFeatures f = with_ms(true);
188 EXPECT(bindless::size_bindings(f, d.limits, d.v11, d.v12, all_supported));
189 EXPECT(asked > 0 && asked_within == 0);
190 EXPECT(count(f, D::dim_2d) == bindless::max_2d_images &&
191 f.counts[bindless::sampler_binding] == 4000 - bindless::reserved_samplers);
192 EXPECT(storage(f, D::dim_2d) == bindless::max_storage_indices && storage_consistent(f));
193
194 // A driver that supports less: growth stops where it says no.
195 const auto up_to_20000 = [&](const BindlessFeatures& candidate) { return totals(candidate).all <= 20000; };
196 f = with_ms(true);
197 EXPECT(bindless::size_bindings(f, d.limits, d.v11, d.v12, up_to_20000));
198 EXPECT(totals(f).all <= 20000 && totals(f).all > 6159 && count(f, D::dim_2d) > 4096);
199
200 // Without the callback, maxPerSetDescriptors still caps growth as before.
201 f = with_ms(true);
202 EXPECT(bindless::size_bindings(f, d.limits, d.v11, d.v12));
203 EXPECT(totals(f).all <= 6159 || (count(f, D::dim_2d) == 4096 && f.counts[bindless::sampler_binding] == 1024));
204 }
205
175 // The default features are today's counts, which the device-less users (vk_image_fuzz) still get. 206 // The default features are today's counts, which the device-less users (vk_image_fuzz) still get.
176 EXPECT(BindlessFeatures{}.counts == defaults); 207 EXPECT(BindlessFeatures{}.counts == defaults);
177 std::printf("bindless sizing: synthetic limits gave the expected counts\n"); 208 std::printf("bindless sizing: synthetic limits gave the expected counts\n");
diff --git a/runtime/test/check_d3d12_trace.py b/runtime/test/check_d3d12_trace.py
index a95f01b35..d24e02058 100644
--- a/runtime/test/check_d3d12_trace.py
+++ b/runtime/test/check_d3d12_trace.py
@@ -50,12 +50,17 @@ def main():
50 ] 50 ]
51 else: 51 else:
52 expected = [ 52 expected = [
53 "ID3D12GraphicsCommandList::SetPipelineState called",
54 "ID3D12GraphicsCommandList::SetGraphicsRootSignature called",
53 "ID3D12GraphicsCommandList::SetMarker called", 55 "ID3D12GraphicsCommandList::SetMarker called",
54 "ID3D12GraphicsCommandList3::SetProtectedResourceSession unsupported", 56 "ID3D12GraphicsCommandList3::SetProtectedResourceSession unsupported",
55 "ID3D12GraphicsCommandList3::SetProtectedResourceSession unsupported", 57 "ID3D12GraphicsCommandList3::SetProtectedResourceSession unsupported",
56 "ID3D12GraphicsCommandList::Close ok", 58 "ID3D12GraphicsCommandList::Close ok",
57 "ID3D12GraphicsCommandList::Close failed", 59 "ID3D12GraphicsCommandList::Close failed",
58 "ID3D12GraphicsCommandList::Reset ok", 60 "ID3D12GraphicsCommandList::Reset ok",
61 "ID3D12GraphicsCommandList::DrawInstanced called",
62 "ID3D12GraphicsCommandList::DrawIndexedInstanced called",
63 "ID3D12GraphicsCommandList::Close failed",
59 ] 64 ]
60 65
61 observed = iter(entries) 66 observed = iter(entries)
diff --git a/runtime/test/check_vk_pipeline_cli.cmake b/runtime/test/check_vk_pipeline_cli.cmake
new file mode 100644
index 000000000..4800d2605
--- /dev/null
+++ b/runtime/test/check_vk_pipeline_cli.cmake
@@ -0,0 +1,33 @@
1file(MAKE_DIRECTORY "${TEST_DIR}")
2file(WRITE "${TEST_DIR}/index.json" "not JSON\n")
3
4# ${RUNNER} is CMAKE_CROSSCOMPILING_EMULATOR: CTest does not apply it to a script
5# test (the command is the host CMake), so the script runs the tool through it itself.
6function(check_invalid option)
7 execute_process(COMMAND ${RUNNER} "${TOOL}" "${TEST_DIR}" "${option}" ${ARGN}
8 RESULT_VARIABLE code OUTPUT_VARIABLE log ERROR_VARIABLE log TIMEOUT 5)
9 if(NOT code STREQUAL "2" OR NOT log MATCHES "${option} requires a valid value")
10 message(FATAL_ERROR "${option} ${ARGN}: expected usage error, got ${code}\n${log}")
11 endif()
12endfunction()
13
14check_invalid(--count)
15check_invalid(--count --compute-only)
16check_invalid(--count 18446744073709551616)
17check_invalid(--jobs 4294967296)
18check_invalid(--start -1)
19check_invalid(--max-bytes 1MiB)
20check_invalid(--large-module-bytes -1)
21check_invalid(--slow nonsense)
22check_invalid(--slow nan)
23check_invalid(--slow -0.5)
24check_invalid(--stage --graphics-only)
25check_invalid(--stats)
26
27execute_process(COMMAND ${RUNNER} "${TOOL}" "${TEST_DIR}"
28 --jobs 2 --start 3 --count 0 --max-bytes 0 --large-module-bytes 0
29 --slow 0.5 --stage cs --stats report.csv
30 RESULT_VARIABLE code OUTPUT_VARIABLE log ERROR_VARIABLE log TIMEOUT 5)
31if(NOT code STREQUAL "2" OR NOT log MATCHES "malformed JSON")
32 message(FATAL_ERROR "Expected valid arguments to reach the malformed index, got ${code}\n${log}")
33endif()
diff --git a/runtime/test/d3d12_clear_test.cpp b/runtime/test/d3d12_clear_test.cpp
index 53103a31f..3d2cd3944 100644
--- a/runtime/test/d3d12_clear_test.cpp
+++ b/runtime/test/d3d12_clear_test.cpp
@@ -350,6 +350,9 @@ int main(int argc, char** argv) {
350 const ColorFormat color_formats[] = { 350 const ColorFormat color_formats[] = {
351 {DXGI_FORMAT_R8G8B8A8_UNORM, "R8G8B8A8_UNORM", 4, float_values, nf}, 351 {DXGI_FORMAT_R8G8B8A8_UNORM, "R8G8B8A8_UNORM", 4, float_values, nf},
352 {DXGI_FORMAT_R8G8B8A8_SNORM, "R8G8B8A8_SNORM", 4, float_values, nf}, 352 {DXGI_FORMAT_R8G8B8A8_SNORM, "R8G8B8A8_SNORM", 4, float_values, nf},
353 // B8G8R8X8 is stored in a BGRA8 image; B8G8R8A8 next to it shows what the X byte changes.
354 {DXGI_FORMAT_B8G8R8A8_UNORM, "B8G8R8A8_UNORM", 4, float_values, nf},
355 {DXGI_FORMAT_B8G8R8X8_UNORM, "B8G8R8X8_UNORM", 4, float_values, nf},
353 {DXGI_FORMAT_R32G32B32A32_FLOAT, "R32G32B32A32_FLOAT", 16, float_values, nf}, 356 {DXGI_FORMAT_R32G32B32A32_FLOAT, "R32G32B32A32_FLOAT", 16, float_values, nf},
354 {DXGI_FORMAT_R8G8_UINT, "R8G8_UINT", 2, int_values, ni}, 357 {DXGI_FORMAT_R8G8_UINT, "R8G8_UINT", 2, int_values, ni},
355 {DXGI_FORMAT_R8G8B8A8_UINT, "R8G8B8A8_UINT", 4, int_values, ni}, 358 {DXGI_FORMAT_R8G8B8A8_UINT, "R8G8B8A8_UINT", 4, int_values, ni},
diff --git a/runtime/test/d3d12_compute_test.cpp b/runtime/test/d3d12_compute_test.cpp
index 2ac216bcb..e53f9ab4b 100644
--- a/runtime/test/d3d12_compute_test.cpp
+++ b/runtime/test/d3d12_compute_test.cpp
@@ -10,6 +10,7 @@
10// No game data. Set LEONIDA_VK_VALIDATION=1 to run under VK_LAYER_KHRONOS_validation. 10// No game data. Set LEONIDA_VK_VALIDATION=1 to run under VK_LAYER_KHRONOS_validation.
11#include "vk_test_device.h" 11#include "vk_test_device.h"
12#include "../shims/d3d12_com.h" 12#include "../shims/d3d12_com.h"
13#include "../src/gfx10_descriptors.h"
13#include "../src/shader_library.h" 14#include "../src/shader_library.h"
14#include "../shims/d3d12_xs_device.h" 15#include "../shims/d3d12_xs_device.h"
15 16
@@ -33,6 +34,8 @@ using XboxHeapHandleFn = std::uint64_t(WINAPI*)(void* heap); // heap slots 9/10
33// Device slot 62 as XboxBvhBuilder.dll calls it on 1.0.2.1: (desc, 0, 0, riid, out) (main's 28cf235). 34// Device slot 62 as XboxBvhBuilder.dll calls it on 1.0.2.1: (desc, 0, 0, riid, out) (main's 28cf235).
34using XboxComputePipelineFn = HRESULT(WINAPI*)(void* device, const D3D12_COMPUTE_PIPELINE_STATE_DESC*, std::uint64_t, 35using XboxComputePipelineFn = HRESULT(WINAPI*)(void* device, const D3D12_COMPUTE_PIPELINE_STATE_DESC*, std::uint64_t,
35 std::uint64_t, const IID*, void**); 36 std::uint64_t, const IID*, void**);
37// Device slot 67 as amd_fidelityfx_upscaler_xbox.dll calls it: (desc, riid, out).
38using XboxNativeComputePipelineFn = HRESULT(WINAPI*)(void* device, const void*, const IID*, void**);
36using SerializeFn = HRESULT(WINAPI*)(const D3D12_VERSIONED_ROOT_SIGNATURE_DESC*, ID3DBlob**, ID3DBlob**); 39using SerializeFn = HRESULT(WINAPI*)(const D3D12_VERSIONED_ROOT_SIGNATURE_DESC*, ID3DBlob**, ID3DBlob**);
37 40
38template<class T> 41template<class T>
@@ -169,6 +172,7 @@ int main() {
169 constexpr UINT elements = 64, bytes = elements * 4; 172 constexpr UINT elements = 64, bytes = elements * 4;
170 const std::uint32_t table_values[4] = {1000, 2000, 3000, 4000}; 173 const std::uint32_t table_values[4] = {1000, 2000, 3000, 4000};
171 std::vector<std::uint32_t> first(elements), second(elements); 174 std::vector<std::uint32_t> first(elements), second(elements);
175 std::vector<std::uint32_t> cbv_a_out(elements), cbv_oob_out(elements), cbv_b_out(elements), cbv_null_out(elements);
172 { 176 {
173 rt::d3d12::VulkanDeviceInfo info{}; 177 rt::d3d12::VulkanDeviceInfo info{};
174 info.get_instance_proc = d.instance_proc; 178 info.get_instance_proc = d.instance_proc;
@@ -178,6 +182,7 @@ int main() {
178 info.queue = d.queue; 182 info.queue = d.queue;
179 info.queue_family = d.family; 183 info.queue_family = d.family;
180 info.buffer_device_address = true; 184 info.buffer_device_address = true;
185 info.subgroup = d.subgroup;
181 info.shader_dir = library.string(); 186 info.shader_dir = library.string();
182 ID3D12Device* inner = nullptr; 187 ID3D12Device* inner = nullptr;
183 EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&inner)))); 188 EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&inner))));
@@ -220,6 +225,40 @@ int main() {
220 EXPECT(device->CreateComputePipelineState(&pso_desc, IID_PPV_ARGS(&unknown.p)) == E_INVALIDARG && !unknown.p); 225 EXPECT(device->CreateComputePipelineState(&pso_desc, IID_PPV_ARGS(&unknown.p)) == E_INVALIDARG && !unknown.p);
221 pso_desc.CS = {container.data(), container.size()}; 226 pso_desc.CS = {container.data(), container.size()};
222 227
228 // The PSO through slot 67, compute pipeline from native code; maps to CreateComputePipelineState.
229 struct XboxNativeComputeDesc {
230 ID3D12RootSignature* root_signature;
231 const void* kind0;
232 std::uint64_t kind0_size;
233 const void* kind1;
234 std::uint64_t kind1_size;
235 const void* kind6;
236 std::uint64_t kind6_size;
237 const void* kind7;
238 std::uint64_t kind7_size;
239 } native_desc{};
240 native_desc.root_signature = root.p;
241 native_desc.kind6 = fssm.data();
242 native_desc.kind6_size = fssm.size();
243 Ref<ID3D12PipelineState> pso67, unknown67;
244 EXPECT(SUCCEEDED(reinterpret_cast<XboxNativeComputePipelineFn>(slot(device.p, 67))(
245 device.p, &native_desc, &pso_iid, reinterpret_cast<void**>(&pso67.p))));
246 EXPECT(pso67.p != nullptr);
247 native_desc.kind6 = other.data();
248 native_desc.kind6_size = other.size();
249 EXPECT(reinterpret_cast<XboxNativeComputePipelineFn>(slot(device.p, 67))(
250 device.p, &native_desc, &pso_iid, reinterpret_cast<void**>(&unknown67.p)) == E_INVALIDARG && !unknown67.p);
251 void* out_null = reinterpret_cast<void*>(0x1111);
252 EXPECT(reinterpret_cast<XboxNativeComputePipelineFn>(slot(device.p, 67))(
253 device.p, nullptr, &pso_iid, &out_null) == E_INVALIDARG && !out_null);
254 out_null = reinterpret_cast<void*>(0x1111);
255 native_desc.kind6 = fssm.data();
256 native_desc.kind6_size = fssm.size();
257 EXPECT(reinterpret_cast<XboxNativeComputePipelineFn>(slot(device.p, 67))(
258 device.p, &native_desc, nullptr, &out_null) == E_POINTER && !out_null);
259 EXPECT(reinterpret_cast<XboxNativeComputePipelineFn>(slot(device.p, 67))(
260 device.p, &native_desc, &pso_iid, nullptr) == E_POINTER);
261
223 // A device whose maxPushConstantsSize is the Vulkan minimum (128 bytes) cannot hold the 144-byte block, so 262 // A device whose maxPushConstantsSize is the Vulkan minimum (128 bytes) cannot hold the 144-byte block, so
224 // its PSOs are refused instead of creating a pipeline layout the spec forbids (#224's fallback flag). 263 // its PSOs are refused instead of creating a pipeline layout the spec forbids (#224's fallback flag).
225 { 264 {
@@ -343,6 +382,128 @@ int main() {
343 std::memcpy(first.data(), results, bytes); 382 std::memcpy(first.data(), results, bytes);
344 std::memcpy(second.data(), static_cast<const std::uint8_t*>(results) + bytes, bytes); 383 std::memcpy(second.data(), static_cast<const std::uint8_t*>(results) + bytes, bytes);
345 384
385 // CreateConstantBufferView: populate shader-visible descriptor heap slots with GFX10 V# descriptors for a
386 // 512-byte arena constant buffer (two 256-byte CBVs: A at +0, B at +256) and null CBVs.
387 {
388 const UINT inc = device->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV);
389 EXPECT(inc == 32);
390 const auto cb_desc = buffer_desc(512, D3D12_RESOURCE_FLAG_NONE);
391 Ref<ID3D12Resource> cb_upload, cb_default, cb_readback;
392 EXPECT(SUCCEEDED(device->CreateCommittedResource(&upload_heap, D3D12_HEAP_FLAG_NONE, &cb_desc,
393 D3D12_RESOURCE_STATE_GENERIC_READ, nullptr,
394 IID_PPV_ARGS(&cb_upload.p))));
395 EXPECT(SUCCEEDED(device->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &cb_desc,
396 D3D12_RESOURCE_STATE_COPY_DEST, nullptr,
397 IID_PPV_ARGS(&cb_default.p))));
398 const auto cb_rb_desc = buffer_desc(4 * bytes, D3D12_RESOURCE_FLAG_NONE);
399 EXPECT(SUCCEEDED(device->CreateCommittedResource(&readback_heap, D3D12_HEAP_FLAG_NONE, &cb_rb_desc,
400 D3D12_RESOURCE_STATE_COPY_DEST, nullptr,
401 IID_PPV_ARGS(&cb_readback.p))));
402 void* cb_mapped = nullptr;
403 EXPECT(SUCCEEDED(cb_upload->Map(0, nullptr, &cb_mapped)));
404 auto* cb_words = static_cast<std::uint32_t*>(cb_mapped);
405 for (UINT i = 0; i < elements; ++i) {
406 cb_words[i] = 0x10000u + i;
407 cb_words[elements + i] = 0x20000u + i;
408 }
409 const D3D12_GPU_VIRTUAL_ADDRESS cb_va = cb_default->GetGPUVirtualAddress();
410 EXPECT(cb_va >= 0x10000 && cb_va < (1ull << 32));
411
412 const auto slot_cpu = [&](UINT idx) { return D3D12_CPU_DESCRIPTOR_HANDLE{SIZE_T(cpu + idx * inc)}; };
413 const auto slot_gpu = [&](UINT idx) { return D3D12_GPU_DESCRIPTOR_HANDLE{gpu + idx * inc}; };
414
415 // Pre-fill slot 3 with non-zero bytes to prove null CBV zeroes the entire 32-byte slot.
416 std::memset(reinterpret_cast<void*>(slot_cpu(3).ptr), 0xA5, inc);
417 device->CreateConstantBufferView(nullptr, slot_cpu(3));
418 std::uint8_t zeros[32] = {};
419 EXPECT(std::memcmp(reinterpret_cast<const void*>(slot_cpu(3).ptr), zeros, sizeof(zeros)) == 0);
420
421 // Zero BufferLocation or zero SizeInBytes also produces a zeroed null V#.
422 const D3D12_CONSTANT_BUFFER_VIEW_DESC zero_loc{0, 256};
423 std::memset(reinterpret_cast<void*>(slot_cpu(3).ptr), 0x5A, inc);
424 device->CreateConstantBufferView(&zero_loc, slot_cpu(3));
425 EXPECT(std::memcmp(reinterpret_cast<const void*>(slot_cpu(3).ptr), zeros, sizeof(zeros)) == 0);
426 const D3D12_CONSTANT_BUFFER_VIEW_DESC zero_size{cb_va, 0};
427 std::memset(reinterpret_cast<void*>(slot_cpu(3).ptr), 0x5A, inc);
428 device->CreateConstantBufferView(&zero_size, slot_cpu(3));
429 EXPECT(std::memcmp(reinterpret_cast<const void*>(slot_cpu(3).ptr), zeros, sizeof(zeros)) == 0);
430
431 const D3D12_CONSTANT_BUFFER_VIEW_DESC cbv_a{cb_va, 256};
432 const D3D12_CONSTANT_BUFFER_VIEW_DESC cbv_b{cb_va + 256, 256};
433 device->CreateConstantBufferView(&cbv_a, slot_cpu(1));
434 device->CreateConstantBufferView(&cbv_b, slot_cpu(2));
435
436 // Decode the written V# in slots 1 and 2 and verify every field + zeroed trailing 16 bytes.
437 for (const auto& [slot_idx, expected_va] :
438 {std::pair{1u, std::uint64_t(cb_va)}, std::pair{2u, std::uint64_t(cb_va + 256)}}) {
439 leonida::gfx10::BufferWords raw{};
440 std::memcpy(raw.data(), reinterpret_cast<const void*>(slot_cpu(slot_idx).ptr), sizeof(raw));
441 leonida::gfx10::Buffer decoded{};
442 EXPECT(leonida::gfx10::decode(raw, decoded));
443 EXPECT(decoded.address == expected_va);
444 EXPECT(decoded.stride == 0);
445 EXPECT(decoded.num_records == 256);
446 EXPECT(decoded.format == leonida::gfx10::format_from_vulkan(VK_FORMAT_R32_UINT));
447 EXPECT(decoded.swizzle == leonida::gfx10::identity_swizzle);
448 EXPECT(decoded.oob_select == leonida::gfx10::OobSelect::raw);
449 EXPECT(std::memcmp(reinterpret_cast<const std::uint8_t*>(slot_cpu(slot_idx).ptr) + 16, zeros, 16) == 0);
450 }
451
452 // Copy CBV data into the arena buffer, then run 4 dispatches:
453 // 1) CBV A at byte offset 0 (all 64 dwords in-bounds)
454 // 2) CBV A at byte offset 128 (dwords 0..31 in-bounds, dwords 32..63 OOB -> 0)
455 // 3) CBV B at byte offset 0 (negative control: all 64 dwords flip to 0x20000 + i)
456 // 4) Null CBV at byte offset 0 (negative control: all 64 dwords become 0)
457 EXPECT(SUCCEEDED(allocator->Reset()) && SUCCEEDED(list->Reset(allocator.p, pso.p)));
458 list->CopyBufferRegion(cb_default.p, 0, cb_upload.p, 0, 512);
459 const D3D12_RESOURCE_BARRIER cb_ready[] = {
460 transition(cb_default.p, D3D12_RESOURCE_STATE_COPY_DEST,
461 D3D12_RESOURCE_STATE_VERTEX_AND_CONSTANT_BUFFER),
462 transition(out_a.p, D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_UNORDERED_ACCESS),
463 };
464 list->ResourceBarrier(2, cb_ready);
465 list->SetDescriptorHeaps(1, heaps);
466 list->SetComputeRootSignature(root.p);
467 list->SetComputeRootUnorderedAccessView(1, va_a);
468
469 const struct CbvDispatch {
470 UINT byte_offset;
471 UINT slot_idx;
472 UINT readback_offset;
473 } cbv_dispatches[] = {
474 {0, 1, 0 * bytes},
475 {128, 1, 1 * bytes},
476 {0, 2, 2 * bytes},
477 {0, 3, 3 * bytes},
478 };
479 for (const auto& d_cfg : cbv_dispatches) {
480 const std::uint32_t rc[2] = {d_cfg.byte_offset, 0}; // s1 == 0 selects CBV V# mode
481 list->SetComputeRoot32BitConstants(0, 2, rc, 0);
482 list->SetComputeRootDescriptorTable(2, slot_gpu(d_cfg.slot_idx));
483 list->Dispatch(1, 1, 1);
484 const auto to_src =
485 transition(out_a.p, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE);
486 list->ResourceBarrier(1, &to_src);
487 list->CopyBufferRegion(cb_readback.p, d_cfg.readback_offset, out_a.p, 0, bytes);
488 const auto to_uav =
489 transition(out_a.p, D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_UNORDERED_ACCESS);
490 list->ResourceBarrier(1, &to_uav);
491 }
492 EXPECT(list->Close() == S_OK);
493 queue->ExecuteCommandLists(1, lists);
494 EXPECT(rt::d3d12::last_execute_result(queue.p) == leonida::ReplayResult::success);
495 EXPECT(SUCCEEDED(queue->Signal(fence.p, 2)));
496 EXPECT(SUCCEEDED(fence->SetEventOnCompletion(2, nullptr)));
497
498 void* cb_res = nullptr;
499 EXPECT(SUCCEEDED(cb_readback->Map(0, nullptr, &cb_res)));
500 const auto* src_bytes = static_cast<const std::uint8_t*>(cb_res);
501 std::memcpy(cbv_a_out.data(), src_bytes + 0 * bytes, bytes);
502 std::memcpy(cbv_oob_out.data(), src_bytes + 1 * bytes, bytes);
503 std::memcpy(cbv_b_out.data(), src_bytes + 2 * bytes, bytes);
504 std::memcpy(cbv_null_out.data(), src_bytes + 3 * bytes, bytes);
505 }
506
346 for (auto* r : {&out_a, &out_b, &constants, &readback}) r->reset(); 507 for (auto* r : {&out_a, &out_b, &constants, &readback}) r->reset();
347 pso.reset(); 508 pso.reset();
348 root.reset(); 509 root.reset();
@@ -363,6 +524,27 @@ int main() {
363 std::fprintf(stderr, "element %u: got %u and %u, want %u and %u\n", i, first[i], second[i], a, b); 524 std::fprintf(stderr, "element %u: got %u and %u, want %u and %u\n", i, first[i], second[i], a, b);
364 } 525 }
365 EXPECT(!mismatches); 526 EXPECT(!mismatches);
527 UINT cbv_b_diff = 0, cbv_null_diff = 0;
528 for (std::uint32_t i = 0; i < elements; ++i) {
529 const std::uint32_t want_a = 0x10000u + i;
530 const std::uint32_t want_oob = i < 32 ? (0x10000u + 32u + i) : 0u;
531 const std::uint32_t want_b = 0x20000u + i;
532 if (cbv_a_out[i] != want_a && mismatches++ < 4)
533 std::fprintf(stderr, "CBV A[%u]: got 0x%x want 0x%x\n", i, cbv_a_out[i], want_a);
534 if (cbv_oob_out[i] != want_oob && mismatches++ < 4)
535 std::fprintf(stderr, "CBV OOB[%u]: got 0x%x want 0x%x\n", i, cbv_oob_out[i], want_oob);
536 if (cbv_b_out[i] != want_b && mismatches++ < 4)
537 std::fprintf(stderr, "CBV B[%u]: got 0x%x want 0x%x\n", i, cbv_b_out[i], want_b);
538 if (cbv_null_out[i] != 0u && mismatches++ < 4)
539 std::fprintf(stderr, "CBV null[%u]: got 0x%x want 0\n", i, cbv_null_out[i]);
540 if (cbv_b_out[i] != cbv_a_out[i]) ++cbv_b_diff;
541 if (cbv_null_out[i] != cbv_a_out[i]) ++cbv_null_diff;
542 }
543 EXPECT(!mismatches);
544 EXPECT(cbv_b_diff == elements && cbv_null_diff == elements);
545 std::printf("CreateConstantBufferView: 64/64 dwords matched for CBV A, 32 in-bounds + 32 OOB-zero matched at "
546 "+128, negative controls flipped %u/%u (CBV B) and %u/%u (null CBV)\n",
547 cbv_b_diff, elements, cbv_null_diff, elements);
366 if (d.validation_errors()) { 548 if (d.validation_errors()) {
367 std::fprintf(stderr, "%u validation errors\n", d.validation_errors()); 549 std::fprintf(stderr, "%u validation errors\n", d.validation_errors());
368 return 1; 550 return 1;
diff --git a/runtime/test/d3d12_copy_compare.h b/runtime/test/d3d12_copy_compare.h
index 3679ab754..3d4281a17 100644
--- a/runtime/test/d3d12_copy_compare.h
+++ b/runtime/test/d3d12_copy_compare.h
@@ -5,7 +5,8 @@
5// into a readback buffer prefilled with 0xcd, and the bytes are compared. Only the texels a footprint row holds are 5// into a readback buffer prefilled with 0xcd, and the bytes are compared. Only the texels a footprint row holds are
6// compared (row padding is the driver's); everything else, including the 0xcd around a partial copy, must match. 6// compared (row padding is the driver's); everything else, including the 0xcd around a partial copy, must match.
7// Layouts come from the host's GetCopyableFootprints for both sides (those are compared separately). 7// Layouts come from the host's GetCopyableFootprints for both sides (those are compared separately).
8// LEONIDA_HOST_ADAPTER picks the host side: "warp", or part of an adapter name; unset is the default adapter. 8// LEONIDA_HOST_ADAPTER picks the host side: "warp", or part of an adapter name; unset is the layer's own adapter when
9// the test has set layer_adapter(), else the default adapter.
9#pragma once 10#pragma once
10#include <windows.h> 11#include <windows.h>
11#include <d3d12.h> 12#include <d3d12.h>
@@ -18,6 +19,7 @@
18#include <cstdio> 19#include <cstdio>
19#include <cstring> 20#include <cstring>
20#include <functional> 21#include <functional>
22#include <optional>
21#include <string> 23#include <string>
22#include <vector> 24#include <vector>
23 25
@@ -110,12 +112,25 @@ inline bool try_create_host(Ptr<ID3D12Device>& host, std::string& name, const LU
110 return true; 112 return true;
111} 113}
112 114
113// A host device, or false when there is none (the comparisons are then skipped). When LEONIDA_HOST_ADAPTER names an 115// The adapter behind the layer's Vulkan device (VkPhysicalDeviceIDProperties::deviceLUID), for a test that knows it.
114// adapter that cannot be had, the run fails: a typo must not turn the comparisons into a silent pass. 116// On a PC with two GPUs D3D12's default adapter can be the other one, whose driver accepts other formats (an AMD
117// layer device accepts an R9G9B9E5 render target that the NVIDIA host refuses), so the comparison would be between
118// two GPUs instead of between the layer and the host runtime.
119inline std::optional<LUID>& layer_adapter() {
120 static std::optional<LUID> luid;
121 return luid;
122}
123
124// A host device, or false when there is none (the comparisons are then skipped). Without LEONIDA_HOST_ADAPTER it is
125// on the layer's own adapter when that is set and has a D3D12 device, else on the default adapter. When
126// LEONIDA_HOST_ADAPTER names an adapter that cannot be had, the run fails: a typo must not turn the comparisons into a
127// silent pass.
115inline bool create_host(Ptr<ID3D12Device>& host, std::string& name) { 128inline bool create_host(Ptr<ID3D12Device>& host, std::string& name) {
116 if (try_create_host(host, name)) return true;
117 char want[128] = {}; 129 char want[128] = {};
118 if (GetEnvironmentVariableA("LEONIDA_HOST_ADAPTER", want, sizeof(want)) && want[0]) { 130 const bool named = GetEnvironmentVariableA("LEONIDA_HOST_ADAPTER", want, sizeof(want)) && want[0];
131 if (!named && layer_adapter() && try_create_host(host, name, &*layer_adapter())) return true;
132 if (try_create_host(host, name)) return true;
133 if (named) {
119 std::fprintf(stderr, "LEONIDA_HOST_ADAPTER=%s: no such adapter, or no D3D12 device on it\n", want); 134 std::fprintf(stderr, "LEONIDA_HOST_ADAPTER=%s: no such adapter, or no D3D12 device on it\n", want);
120 std::exit(1); 135 std::exit(1);
121 } 136 }
diff --git a/runtime/test/d3d12_descriptor_test.cpp b/runtime/test/d3d12_descriptor_test.cpp
index 4f587166b..2f6d059c3 100644
--- a/runtime/test/d3d12_descriptor_test.cpp
+++ b/runtime/test/d3d12_descriptor_test.cpp
@@ -13,6 +13,9 @@
13// CreateSampler2 samplers that clamp to a UINT (0,0,0,0) and (1,1,1,1) border, and a float white border on 13// CreateSampler2 samplers that clamp to a UINT (0,0,0,0) and (1,1,1,1) border, and a float white border on
14// the UNORM texture. Every texel is the border: 0, 1 and 255 in each channel. Both white borders are built in 14// the UNORM texture. Every texel is the border: 0, 1 and 255 in each channel. Both white borders are built in
15// at the same S# type, so this also checks that they are two samplers, not one. 15// at the same S# type, so this also checks that they are two samplers, not one.
16// - B8G8R8X8 (D3D-87): a B8G8R8X8_UNORM and a B8G8R8A8_UNORM texture uploaded with the same bytes, the fourth
17// never 255. Their default views read the same red, green and blue; B8G8R8X8 reads alpha 1, B8G8R8A8 the
18// stored byte. Views between the two typeless families give a null descriptor.
16// Multisample SRVs: four masked triangles seed different values per sample and array layer. A compute shader reads 19// Multisample SRVs: four masked triangles seed different values per sample and array layer. A compute shader reads
17// them back using the T#s for the 2D, full-array and sliced-array views. The test builds its pipelines in Vulkan 20// them back using the T#s for the 2D, full-array and sliced-array views. The test builds its pipelines in Vulkan
18// and binds the device's set (rt::d3d12::bindless_set). Without glslangValidator the GPU readbacks are skipped. 21// and binds the device's set (rt::d3d12::bindless_set). Without glslangValidator the GPU readbacks are skipped.
@@ -81,6 +84,13 @@ std::array<std::uint8_t, 4> texel(UINT x, UINT y) {
81 return {std::uint8_t(x * 32), std::uint8_t(y * 32), std::uint8_t(128 + x + 8 * y), 255}; 84 return {std::uint8_t(x * 32), std::uint8_t(y * 32), std::uint8_t(128 + x + 8 * y), 255};
82} 85}
83 86
87// The same texel in B, G, R memory order, with a fourth byte that is never 255: what a B8G8R8X8 texture and a
88// B8G8R8A8 one with the same bytes are uploaded with. Through a view the first reads alpha 1, the second this byte.
89std::array<std::uint8_t, 4> bgrx_texel(UINT x, UINT y) {
90 const auto t = texel(x, y);
91 return {t[2], t[1], t[0], std::uint8_t(3 * (y * 8 + x))};
92}
93
84#ifdef LEONIDA_TEST_CS_SAMPLE_SPV 94#ifdef LEONIDA_TEST_CS_SAMPLE_SPV
85// What cs_sample.comp is pushed: a T#, an S#, and where in the output buffer its 64 texels go. 95// What cs_sample.comp is pushed: a T#, an S#, and where in the output buffer its 64 texels go.
86struct SampleKeys { 96struct SampleKeys {
@@ -292,7 +302,7 @@ int main() {
292 if (device_status != vktest::DeviceStatus::ready) return 1; 302 if (device_status != vktest::DeviceStatus::ready) return 1;
293 303
294 constexpr UINT size = 8, texels = size * size, bytes = texels * 4; 304 constexpr UINT size = 8, texels = size * size, bytes = texels * 4;
295 std::vector<std::uint8_t> results(4 * bytes), after_destruction(bytes), borders(3 * bytes); 305 std::vector<std::uint8_t> results(4 * bytes), after_destruction(bytes), borders(3 * bytes), bgr_results(2 * bytes);
296 bool sampled_through_set = false; 306 bool sampled_through_set = false;
297 UINT lod_mismatches = 0; 307 UINT lod_mismatches = 0;
298 { 308 {
@@ -532,6 +542,32 @@ int main() {
532 for (UINT x = 0; x < fp.Width; ++x) std::memcpy(row + 4 * x, color.data(), 4); 542 for (UINT x = 0; x < fp.Width; ++x) std::memcpy(row + 4 * x, color.data(), 4);
533 } 543 }
534 } 544 }
545 // A B8G8R8X8_UNORM texture and a B8G8R8A8_UNORM one, uploaded with the same bgrx_texel bytes past the cube
546 // array's footprints.
547 constexpr DXGI_FORMAT bgr_formats[2] = {DXGI_FORMAT_B8G8R8X8_UNORM, DXGI_FORMAT_B8G8R8A8_UNORM};
548 Ref<ID3D12Resource> bgr_textures[2];
549 D3D12_PLACED_SUBRESOURCE_FOOTPRINT bgr_placed[2]{};
550 const auto& last_array = array_levels[std::size(array_levels) - 1];
551 constexpr UINT64 placement = D3D12_TEXTURE_DATA_PLACEMENT_ALIGNMENT;
552 const UINT64 bgr_start =
553 (last_array.Offset + UINT64(last_array.Footprint.RowPitch) * last_array.Footprint.Height + placement - 1) &
554 ~(placement - 1);
555 for (UINT f = 0; f < 2; ++f) {
556 D3D12_RESOURCE_DESC desc = texture_desc;
557 desc.Format = bgr_formats[f];
558 EXPECT(SUCCEEDED(device->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &desc,
559 D3D12_RESOURCE_STATE_COPY_DEST, nullptr,
560 IID_PPV_ARGS(&bgr_textures[f].p))));
561 device->GetCopyableFootprints(&desc, 0, 1, bgr_start + 8192 * f, &bgr_placed[f], nullptr, nullptr, nullptr);
562 EXPECT(bgr_placed[f].Footprint.Format == bgr_formats[f]);
563 EXPECT(bgr_placed[f].Offset + UINT64(bgr_placed[f].Footprint.RowPitch) * size <= upload_desc.Width);
564 for (UINT y = 0; y < size; ++y)
565 for (UINT x = 0; x < size; ++x)
566 std::memcpy(static_cast<std::uint8_t*>(mapped) + bgr_placed[f].Offset +
567 y * bgr_placed[f].Footprint.RowPitch + x * 4,
568 bgrx_texel(x, y).data(), 4);
569 }
570 EXPECT(bgr_placed[0].Footprint.RowPitch == bgr_placed[1].Footprint.RowPitch);
535 571
536 // Shader-visible heaps, start handles in the Xbox shape. 572 // Shader-visible heaps, start handles in the Xbox shape.
537 const UINT step = device->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); 573 const UINT step = device->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV);
@@ -562,7 +598,7 @@ int main() {
562 volume_lod_slot = cube_lod_slot + cube_lod_count, 598 volume_lod_slot = cube_lod_slot + cube_lod_count,
563 ms_slot = volume_lod_slot + volume_lod_count, ms_array_slot, ms_slice_slot, ms_first_layer_slot, 599 ms_slot = volume_lod_slot + volume_lod_count, ms_array_slot, ms_slice_slot, ms_first_layer_slot,
564 ms_uint_slot, ms_uint_array_slot, ms_sint_slot, ms_sint_array_slot, 600 ms_uint_slot, ms_uint_array_slot, ms_sint_slot, ms_sint_array_slot,
565 line_default, line_mip, line_clamped, view_slot_count 601 line_default, line_mip, line_clamped, bgrx_slot, bgra_slot, typed_bgrx_slot, view_slot_count
566 }; 602 };
567 D3D12_DESCRIPTOR_HEAP_DESC heap_desc{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, view_slot_count, 603 D3D12_DESCRIPTOR_HEAP_DESC heap_desc{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, view_slot_count,
568 D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, 0}; 604 D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, 0};
@@ -1099,6 +1135,51 @@ int main() {
1099 std::memset(view_bytes(null_slot), 0x77, step); 1135 std::memset(view_bytes(null_slot), 0x77, step);
1100 device->CreateShaderResourceView(texture.p, &colour_plane, view_slot(null_slot)); 1136 device->CreateShaderResourceView(texture.p, &colour_plane, view_slot(null_slot));
1101 EXPECT(null_at(null_slot)); 1137 EXPECT(null_at(null_slot));
1138
1139 // B8G8R8X8 is a BGRA8 image whose views read alpha as 1, so its T# selects one where B8G8R8A8's selects W.
1140 // B8G8R8X8 and B8G8R8A8 are different typeless families: a view never crosses from one to the other.
1141 device->CreateShaderResourceView(bgr_textures[0].p, nullptr, view_slot(bgrx_slot));
1142 device->CreateShaderResourceView(bgr_textures[1].p, nullptr, view_slot(bgra_slot));
1143 g::Image bgrx_image{}, bgra_image{};
1144 EXPECT(image_at(bgrx_slot, bgrx_image) && image_at(bgra_slot, bgra_image));
1145 EXPECT(bgrx_image.format == g::format_from_vulkan(VK_FORMAT_B8G8R8A8_UNORM) &&
1146 bgra_image.format == bgrx_image.format);
1147 EXPECT((bgrx_image.swizzle == g::Swizzle{g::select_z, g::select_y, g::select_x, g::select_one}));
1148 EXPECT((bgra_image.swizzle == g::Swizzle{g::select_z, g::select_y, g::select_x, g::select_w}));
1149 Ref<ID3D12Resource> bgrx_typeless;
1150 D3D12_RESOURCE_DESC bgrx_typeless_desc = texture_desc;
1151 bgrx_typeless_desc.Format = DXGI_FORMAT_B8G8R8X8_TYPELESS;
1152 bgrx_typeless_desc.Flags = D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; // allowed, but no format gives a UAV
1153 EXPECT(SUCCEEDED(device->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &bgrx_typeless_desc,
1154 D3D12_RESOURCE_STATE_COMMON, nullptr,
1155 IID_PPV_ARGS(&bgrx_typeless.p))));
1156 D3D12_SHADER_RESOURCE_VIEW_DESC bgr_view = flat_view;
1157 bgr_view.Format = DXGI_FORMAT_B8G8R8X8_UNORM_SRGB;
1158 device->CreateShaderResourceView(bgrx_typeless.p, &bgr_view, view_slot(typed_bgrx_slot));
1159 g::Image typed_bgrx_image{};
1160 EXPECT(image_at(typed_bgrx_slot, typed_bgrx_image));
1161 EXPECT(typed_bgrx_image.format == g::format_from_vulkan(VK_FORMAT_B8G8R8A8_SRGB));
1162 EXPECT(typed_bgrx_image.swizzle == bgrx_image.swizzle && typed_bgrx_image.address != bgrx_image.address);
1163 bgr_view.Format = DXGI_FORMAT_B8G8R8A8_UNORM;
1164 for (ID3D12Resource* x8 : {bgr_textures[0].p, bgrx_typeless.p}) {
1165 std::memset(view_bytes(null_slot), 0x77, step);
1166 device->CreateShaderResourceView(x8, &bgr_view, view_slot(null_slot));
1167 EXPECT(null_at(null_slot));
1168 }
1169 bgr_view.Format = DXGI_FORMAT_B8G8R8X8_UNORM;
1170 std::memset(view_bytes(null_slot), 0x77, step);
1171 device->CreateShaderResourceView(bgr_textures[1].p, &bgr_view, view_slot(null_slot));
1172 EXPECT(null_at(null_slot));
1173 D3D12_UNORDERED_ACCESS_VIEW_DESC bgrx_write{};
1174 bgrx_write.Format = DXGI_FORMAT_B8G8R8X8_UNORM;
1175 bgrx_write.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE2D;
1176 const D3D12_UNORDERED_ACCESS_VIEW_DESC* const bgrx_uavs[2] = {nullptr, &bgrx_write};
1177 for (const D3D12_UNORDERED_ACCESS_VIEW_DESC* uav : bgrx_uavs) {
1178 std::memset(view_bytes(null_slot), 0x77, step);
1179 device->CreateUnorderedAccessView(bgrx_typeless.p, nullptr, uav, view_slot(null_slot));
1180 EXPECT(null_at(null_slot));
1181 }
1182 bgrx_typeless.reset();
1102 cube.reset(); 1183 cube.reset();
1103 writable.reset(); 1184 writable.reset();
1104 1185
@@ -1205,6 +1286,11 @@ int main() {
1205 transition(bc.p, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE); 1286 transition(bc.p, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);
1206 list->ResourceBarrier(1, &barrier); 1287 list->ResourceBarrier(1, &barrier);
1207 } 1288 }
1289 for (UINT f = 0; f < 2; ++f) {
1290 to_texture.pResource = bgr_textures[f].p;
1291 from_upload.PlacedFootprint = bgr_placed[f];
1292 list->CopyTextureRegion(&to_texture, 0, 0, 0, &from_upload, nullptr);
1293 }
1208 to_texture.pResource = volume.p; 1294 to_texture.pResource = volume.p;
1209 for (UINT mip = 0; mip < 2; ++mip) { 1295 for (UINT mip = 0; mip < 2; ++mip) {
1210 to_texture.SubresourceIndex = mip; 1296 to_texture.SubresourceIndex = mip;
@@ -1221,7 +1307,11 @@ int main() {
1221 transition(line.p, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE), 1307 transition(line.p, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE),
1222 transition(packed.p, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE), 1308 transition(packed.p, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE),
1223 transition(uint_texture.p, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE), 1309 transition(uint_texture.p, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE),
1224 transition(volume.p, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE)}; 1310 transition(volume.p, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE),
1311 transition(bgr_textures[0].p, D3D12_RESOURCE_STATE_COPY_DEST,
1312 D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE),
1313 transition(bgr_textures[1].p, D3D12_RESOURCE_STATE_COPY_DEST,
1314 D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE)};
1225 list->ResourceBarrier(UINT(std::size(sampled)), sampled); 1315 list->ResourceBarrier(UINT(std::size(sampled)), sampled);
1226 to_texture.pResource = array_texture.p; 1316 to_texture.pResource = array_texture.p;
1227 for (UINT sub = 0; sub < std::size(array_levels); ++sub) { 1317 for (UINT sub = 0; sub < std::size(array_levels); ++sub) {
@@ -1854,6 +1944,15 @@ int main() {
1854 } 1944 }
1855 EXPECT(rgb96_differ == 0); 1945 EXPECT(rgb96_differ == 0);
1856 } 1946 }
1947 // The B8G8R8X8 and B8G8R8A8 textures through their default views.
1948 SampleKeys bgr_keys[2] = {};
1949 const UINT bgr_slots[2] = {bgrx_slot, bgra_slot};
1950 for (UINT k = 0; k < 2; ++k) {
1951 std::memcpy(bgr_keys[k].tsharp, view_bytes(bgr_slots[k]), sizeof(bgr_keys[k].tsharp));
1952 std::memcpy(bgr_keys[k].ssharp, sampler_bytes, sizeof(bgr_keys[k].ssharp));
1953 bgr_keys[k].first = k * texels;
1954 }
1955 EXPECT(sample_through_set(d, set0, set0_layout, bgr_keys, bgr_results.data()));
1857#endif 1956#endif
1858 1957
1859 // A destroyed texture takes its views out of the set: the next ExecuteCommandLists writes that, and nothing 1958 // A destroyed texture takes its views out of the set: the next ExecuteCommandLists writes that, and nothing
@@ -2067,6 +2166,47 @@ int main() {
2067#endif 2166#endif
2068 } 2167 }
2069 2168
2169 // Cross-family castable SRV: write_image_descriptor must pass resource.has_view_format_list() into a single
2170 // bind_image call so a listed R8G8B8A8_UINT -> R32_UINT view registers cleanly without a spurious first-pass
2171 // failure (and without double-binding every view).
2172 if (d.bindless) {
2173 Ref<ID3D12Device10> inner10;
2174 EXPECT(SUCCEEDED(inner->QueryInterface(IID_PPV_ARGS(&inner10.p))));
2175 D3D12_RESOURCE_DESC1 cast_desc{};
2176 cast_desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D;
2177 cast_desc.Width = 4;
2178 cast_desc.Height = 4;
2179 cast_desc.DepthOrArraySize = 1;
2180 cast_desc.MipLevels = 1;
2181 cast_desc.Format = DXGI_FORMAT_R8G8B8A8_UINT;
2182 cast_desc.SampleDesc = {1, 0};
2183 cast_desc.Layout = D3D12_TEXTURE_LAYOUT_UNKNOWN;
2184 const DXGI_FORMAT cast_formats[] = {DXGI_FORMAT_R8G8B8A8_UINT, DXGI_FORMAT_R32_UINT};
2185 Ref<ID3D12Resource> cast_tex;
2186 EXPECT(SUCCEEDED(inner10->CreateCommittedResource3(
2187 &default_heap, D3D12_HEAP_FLAG_NONE, &cast_desc, D3D12_BARRIER_LAYOUT_COMMON, nullptr, nullptr,
2188 2, cast_formats, IID_PPV_ARGS(&cast_tex.p))));
2189 const D3D12_DESCRIPTOR_HEAP_DESC cast_hd{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 1,
2190 D3D12_DESCRIPTOR_HEAP_FLAG_NONE, 0};
2191 Ref<ID3D12DescriptorHeap> cast_heap;
2192 EXPECT(SUCCEEDED(inner10->CreateDescriptorHeap(&cast_hd, IID_PPV_ARGS(&cast_heap.p))));
2193 const D3D12_CPU_DESCRIPTOR_HANDLE cast_slot = cast_heap->GetCPUDescriptorHandleForHeapStart();
2194 D3D12_SHADER_RESOURCE_VIEW_DESC cast_srv{};
2195 cast_srv.Format = DXGI_FORMAT_R32_UINT;
2196 cast_srv.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D;
2197 cast_srv.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING;
2198 cast_srv.Texture2D.MipLevels = 1;
2199 inner10->CreateShaderResourceView(cast_tex.p, &cast_srv, cast_slot);
2200 g::ImageWords cast_words{};
2201 std::memcpy(cast_words.data(), reinterpret_cast<const void*>(cast_slot.ptr), sizeof(cast_words));
2202 g::Image decoded{};
2203 EXPECT(g::decode(cast_words, decoded) && decoded.type == g::ImageType::image_2d);
2204 EXPECT(decoded.format == g::format_from_vulkan(VK_FORMAT_R32_UINT));
2205 std::uint32_t cast_key[8]{};
2206 std::memcpy(cast_key, cast_words.data(), sizeof(cast_key));
2207 EXPECT(rt::d3d12::bindless_hash_lookup(device.p, cast_key) != 0);
2208 }
2209
2070 upload.reset(); 2210 upload.reset();
2071 array_texture.reset(); 2211 array_texture.reset();
2072 line.reset(); 2212 line.reset();
@@ -2078,6 +2218,7 @@ int main() {
2078 byte_heap.reset(); 2218 byte_heap.reset();
2079 ms_texture.reset(); 2219 ms_texture.reset();
2080 ms_array.reset(); 2220 ms_array.reset();
2221 for (auto& resource : bgr_textures) resource.reset();
2081 view_heap.reset(); 2222 view_heap.reset();
2082 sampler_heap.reset(); 2223 sampler_heap.reset();
2083 list.reset(); 2224 list.reset();
@@ -2141,6 +2282,19 @@ int main() {
2141 } 2282 }
2142 EXPECT(!mismatches); 2283 EXPECT(!mismatches);
2143 EXPECT(lod_mismatches == 0); 2284 EXPECT(lod_mismatches == 0);
2285 // Both read red, green and blue from the same bytes; B8G8R8X8 reads alpha 1, B8G8R8A8 the stored byte.
2286 const char* bgr_names[2] = {"B8G8R8X8_UNORM", "B8G8R8A8_UNORM"};
2287 for (UINT k = 0; k < 2; ++k)
2288 for (UINT i = 0; i < texels; ++i) {
2289 auto want = texel(i % size, i / size);
2290 if (k == 1) want[3] = bgrx_texel(i % size, i / size)[3];
2291 const std::uint8_t* got = bgr_results.data() + k * bytes + i * 4;
2292 if (std::memcmp(got, want.data(), 4) != 0 && mismatches++ < 4)
2293 std::fprintf(stderr, "%s texel %u: got %u,%u,%u,%u, want %u,%u,%u,%u\n", bgr_names[k], i,
2294 unsigned(got[0]), unsigned(got[1]), unsigned(got[2]), unsigned(got[3]),
2295 unsigned(want[0]), unsigned(want[1]), unsigned(want[2]), unsigned(want[3]));
2296 }
2297 EXPECT(!mismatches);
2144 if (d.validation_errors()) { 2298 if (d.validation_errors()) {
2145 std::fprintf(stderr, "%u validation errors\n", d.validation_errors()); 2299 std::fprintf(stderr, "%u validation errors\n", d.validation_errors());
2146 return 1; 2300 return 1;
@@ -2148,6 +2302,7 @@ int main() {
2148 std::printf("descriptors: copies matched; a T# and an S# from CreateShaderResourceView and CreateSampler were " 2302 std::printf("descriptors: copies matched; a T# and an S# from CreateShaderResourceView and CreateSampler were "
2149 "found in the device's bindless set by a shader, %u RGBA8 and RGB9E5 texels matched, and an unknown descriptor " 2303 "found in the device's bindless set by a shader, %u RGBA8 and RGB9E5 texels matched, and an unknown descriptor "
2150 "and a destroyed texture's gave the fallback; UINT black, UINT white and float white borders read " 2304 "and a destroyed texture's gave the fallback; UINT black, UINT white and float white borders read "
2151 "0, 1 and 255\n", texels); 2305 "0, 1 and 255; B8G8R8X8 read alpha 1 where B8G8R8A8 read the same bytes' alpha (%u texels each)\n",
2306 texels, texels);
2152 return 0; 2307 return 0;
2153} 2308}
diff --git a/runtime/test/d3d12_draw_test.cpp b/runtime/test/d3d12_draw_test.cpp
index 574872b8a..12a1c71cf 100644
--- a/runtime/test/d3d12_draw_test.cpp
+++ b/runtime/test/d3d12_draw_test.cpp
@@ -84,6 +84,8 @@ int main() {
84 constexpr UINT size = 64; 84 constexpr UINT size = 64;
85 std::vector<std::uint8_t> pixels(size * 256), second_pixels(size * 256); 85 std::vector<std::uint8_t> pixels(size * 256), second_pixels(size * 256);
86 std::vector<std::uint8_t> strip16_pixels(size * 256), strip32_pixels(size * 256), strip_nocut_pixels(size * 256); 86 std::vector<std::uint8_t> strip16_pixels(size * 256), strip32_pixels(size * 256), strip_nocut_pixels(size * 256);
87 std::vector<std::uint8_t> msaa_full_pixels(size * 256), msaa_half_pixels(size * 256);
88 bool ran_msaa = false;
87 const bool logic_op = d.enabled.logicOp == VK_TRUE; 89 const bool logic_op = d.enabled.logicOp == VK_TRUE;
88 { 90 {
89 rt::d3d12::VulkanDeviceInfo info{}; 91 rt::d3d12::VulkanDeviceInfo info{};
@@ -94,6 +96,7 @@ int main() {
94 info.queue = d.queue; 96 info.queue = d.queue;
95 info.queue_family = d.family; 97 info.queue_family = d.family;
96 info.buffer_device_address = true; 98 info.buffer_device_address = true;
99 info.subgroup = d.subgroup;
97 info.shader_dir = library.string(); 100 info.shader_dir = library.string();
98 // Of the PSO features only logicOp is passed on, so the other feature refusals below still apply. 101 // Of the PSO features only logicOp is passed on, so the other feature refusals below still apply.
99 info.features.logicOp = d.enabled.logicOp; 102 info.features.logicOp = d.enabled.logicOp;
@@ -466,6 +469,102 @@ int main() {
466 } 469 }
467 } 470 }
468 471
472 // Multisampled graphics pipeline (4x MSAA): draw the top-left red quad into a 4x MSAA target and resolve.
473 // Full SampleMask (0xFFFFFFFF) writes all 4 samples red; half SampleMask (0x5) writes 2 of 4 samples so the
474 // resolved top-left quadrant shifts from (255, 0, 0, 255) to ~50/50 purple (128, 0, 128, 255).
475 {
476 // SampleDesc.Count == 0, non-power-of-two/out-of-range counts, and non-zero quality must all be rejected.
477 auto bad_desc = pso_desc;
478 Ref<ID3D12PipelineState> bad_pso;
479 for (const DXGI_SAMPLE_DESC sd : {DXGI_SAMPLE_DESC{0, 0}, DXGI_SAMPLE_DESC{3, 0}, DXGI_SAMPLE_DESC{64, 0},
480 DXGI_SAMPLE_DESC{4, 1}, DXGI_SAMPLE_DESC{1, 1}}) {
481 bad_desc.SampleDesc = sd;
482 EXPECT(device->CreateGraphicsPipelineState(&bad_desc, IID_PPV_ARGS(&bad_pso.p)) == E_INVALIDARG &&
483 !bad_pso.p);
484 }
485 // Any power-of-two sample count not supported by the attachment format must also be rejected.
486 D3D12_FEATURE_DATA_MULTISAMPLE_QUALITY_LEVELS ms32{DXGI_FORMAT_R8G8B8A8_UNORM, 32,
487 D3D12_MULTISAMPLE_QUALITY_LEVELS_FLAG_NONE, 0};
488 if (SUCCEEDED(device->CheckFeatureSupport(D3D12_FEATURE_MULTISAMPLE_QUALITY_LEVELS, &ms32, sizeof(ms32))) &&
489 ms32.NumQualityLevels == 0) {
490 bad_desc.SampleDesc = {32, 0};
491 EXPECT(device->CreateGraphicsPipelineState(&bad_desc, IID_PPV_ARGS(&bad_pso.p)) == E_INVALIDARG &&
492 !bad_pso.p);
493 }
494
495 D3D12_FEATURE_DATA_MULTISAMPLE_QUALITY_LEVELS ms_levels{DXGI_FORMAT_R8G8B8A8_UNORM, 4,
496 D3D12_MULTISAMPLE_QUALITY_LEVELS_FLAG_NONE, 0};
497 if (SUCCEEDED(device->CheckFeatureSupport(D3D12_FEATURE_MULTISAMPLE_QUALITY_LEVELS, &ms_levels,
498 sizeof(ms_levels))) &&
499 ms_levels.NumQualityLevels > 0) {
500 auto ms_rt_desc = rt_desc;
501 ms_rt_desc.SampleDesc.Count = 4;
502 Ref<ID3D12Resource> ms_target;
503 EXPECT(SUCCEEDED(device->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &ms_rt_desc,
504 D3D12_RESOURCE_STATE_RENDER_TARGET, nullptr,
505 IID_PPV_ARGS(&ms_target.p))));
506 D3D12_DESCRIPTOR_HEAP_DESC ms_heap_desc{D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 1,
507 D3D12_DESCRIPTOR_HEAP_FLAG_NONE, 0};
508 Ref<ID3D12DescriptorHeap> ms_rtv_heap;
509 EXPECT(SUCCEEDED(device->CreateDescriptorHeap(&ms_heap_desc, IID_PPV_ARGS(&ms_rtv_heap.p))));
510 const D3D12_CPU_DESCRIPTOR_HANDLE ms_rtv{
511 SIZE_T(reinterpret_cast<XboxHeapHandleFn>(slot(ms_rtv_heap.p, 9))(ms_rtv_heap.p))};
512 device->CreateRenderTargetView(ms_target.p, nullptr, ms_rtv);
513
514 auto ms_pso_desc = pso_desc;
515 ms_pso_desc.SampleDesc.Count = 4;
516 Ref<ID3D12PipelineState> ms_full_pso, ms_half_pso;
517 ms_pso_desc.SampleMask = 0xFFFFFFFFu;
518 EXPECT(SUCCEEDED(device->CreateGraphicsPipelineState(&ms_pso_desc, IID_PPV_ARGS(&ms_full_pso.p))));
519 ms_pso_desc.SampleMask = 0x5u;
520 EXPECT(SUCCEEDED(device->CreateGraphicsPipelineState(&ms_pso_desc, IID_PPV_ARGS(&ms_half_pso.p))));
521
522 struct MsaaPass {
523 ID3D12PipelineState* pso;
524 std::vector<std::uint8_t>* out;
525 };
526 const MsaaPass ms_passes[] = {{ms_full_pso.p, &msaa_full_pixels}, {ms_half_pso.p, &msaa_half_pixels}};
527 UINT64 ms_fence = 20;
528 for (UINT pass = 0; pass < std::size(ms_passes); ++pass) {
529 EXPECT(SUCCEEDED(allocator->Reset()) && SUCCEEDED(list->Reset(allocator.p, ms_passes[pass].pso)));
530 if (pass > 0) {
531 const auto ms_to_rt = transition(ms_target.p, D3D12_RESOURCE_STATE_RESOLVE_SOURCE,
532 D3D12_RESOURCE_STATE_RENDER_TARGET);
533 list->ResourceBarrier(1, &ms_to_rt);
534 }
535 list->ClearRenderTargetView(ms_rtv, blue, 0, nullptr);
536 list->SetGraphicsRootSignature(root.p);
537 list->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
538 list->IASetVertexBuffers(0, 1, &vbv);
539 list->IASetIndexBuffer(&ibv);
540 list->RSSetViewports(1, &viewport);
541 list->RSSetScissorRects(1, &scissor);
542 list->OMSetRenderTargets(1, &ms_rtv, FALSE, nullptr);
543 list->SetGraphicsRoot32BitConstants(0, 2, origin, 0);
544 list->SetGraphicsRootConstantBufferView(1, upload_va + 512);
545 list->DrawIndexedInstanced(6, 1, 0, 0, 0);
546 const D3D12_RESOURCE_BARRIER pre_resolve[] = {
547 transition(ms_target.p, D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_RESOLVE_SOURCE),
548 transition(target.p, D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_RESOLVE_DEST),
549 };
550 list->ResourceBarrier(2, pre_resolve);
551 list->ResolveSubresource(target.p, 0, ms_target.p, 0, DXGI_FORMAT_R8G8B8A8_UNORM);
552 const auto post_resolve =
553 transition(target.p, D3D12_RESOURCE_STATE_RESOLVE_DEST, D3D12_RESOURCE_STATE_COPY_SOURCE);
554 list->ResourceBarrier(1, &post_resolve);
555 list->CopyTextureRegion(&dst, 0, 0, 0, &src, nullptr);
556 EXPECT(list->Close() == S_OK);
557 queue->ExecuteCommandLists(1, lists);
558 EXPECT(rt::d3d12::last_execute_result(queue.p) == leonida::ReplayResult::success);
559 ++ms_fence;
560 EXPECT(SUCCEEDED(queue->Signal(fence.p, ms_fence)) &&
561 SUCCEEDED(fence->SetEventOnCompletion(ms_fence, nullptr)));
562 std::memcpy(ms_passes[pass].out->data(), mapped, ms_passes[pass].out->size());
563 }
564 ran_msaa = true;
565 }
566 }
567
469 // A draw with no viewport (never set, or unbound with a count of 0) rasterizes nothing in D3D12. It is not 568 // A draw with no viewport (never set, or unbound with a count of 0) rasterizes nothing in D3D12. It is not
470 // recorded, so the list closes and executes cleanly (Vulkan forbids a 0x0 viewport). 569 // recorded, so the list closes and executes cleanly (Vulkan forbids a 0x0 viewport).
471 EXPECT(SUCCEEDED(allocator->Reset()) && SUCCEEDED(list->Reset(allocator.p, pso.p))); 570 EXPECT(SUCCEEDED(allocator->Reset()) && SUCCEEDED(list->Reset(allocator.p, pso.p)));
@@ -478,7 +577,7 @@ int main() {
478 EXPECT(list->Close() == S_OK); 577 EXPECT(list->Close() == S_OK);
479 queue->ExecuteCommandLists(1, lists); 578 queue->ExecuteCommandLists(1, lists);
480 EXPECT(rt::d3d12::last_execute_result(queue.p) == leonida::ReplayResult::success); 579 EXPECT(rt::d3d12::last_execute_result(queue.p) == leonida::ReplayResult::success);
481 EXPECT(SUCCEEDED(queue->Signal(fence.p, 20)) && SUCCEEDED(fence->SetEventOnCompletion(20, nullptr))); 580 EXPECT(SUCCEEDED(queue->Signal(fence.p, 30)) && SUCCEEDED(fence->SetEventOnCompletion(30, nullptr)));
482 581
483 // Each parent draw starts with a 0.25 blend factor, then executes one of four bundles. 582 // Each parent draw starts with a 0.25 blend factor, then executes one of four bundles.
484 // Empty and reset bundles preserve it. Explicit zero and nullptr replace it with zero and one. 583 // Empty and reset bundles preserve it. Explicit zero and nullptr replace it with zero and one.
@@ -531,7 +630,8 @@ int main() {
531 EXPECT(list->Close() == S_OK); 630 EXPECT(list->Close() == S_OK);
532 queue->ExecuteCommandLists(1, lists); 631 queue->ExecuteCommandLists(1, lists);
533 EXPECT(rt::d3d12::last_execute_result(queue.p) == leonida::ReplayResult::success); 632 EXPECT(rt::d3d12::last_execute_result(queue.p) == leonida::ReplayResult::success);
534 EXPECT(SUCCEEDED(queue->Signal(fence.p, 4)) && SUCCEEDED(fence->SetEventOnCompletion(4, nullptr))); 633 // Above the strip passes' 20: a lower value is already reached, so the wait would return at once.
634 EXPECT(SUCCEEDED(queue->Signal(fence.p, 21)) && SUCCEEDED(fence->SetEventOnCompletion(21, nullptr)));
535 const auto* result = static_cast<const std::uint8_t*>(mapped); 635 const auto* result = static_cast<const std::uint8_t*>(mapped);
536 for (UINT row = 0; row < size; ++row) { 636 for (UINT row = 0; row < size; ++row) {
537 for (UINT col = 0; col < size; ++col) { 637 for (UINT col = 0; col < size; ++col) {
@@ -629,6 +729,38 @@ int main() {
629 std::printf("strip cut (0xFFFF & 0xFFFFFFFF): 4096/4096 pixels matched each (no-cut negative control painted %u " 729 std::printf("strip cut (0xFFFF & 0xFFFFFFFF): 4096/4096 pixels matched each (no-cut negative control painted %u "
630 "bridge pixels in bottom-left)\n", 730 "bridge pixels in bottom-left)\n",
631 nocut_bl_red); 731 nocut_bl_red);
732 if (ran_msaa) {
733 UINT half_changed = 0;
734 for (UINT row = 0; row < size; ++row) {
735 for (UINT col = 0; col < size; ++col) {
736 const bool top_left = row < size / 2 && col < size / 2;
737 const std::uint8_t* got_full = msaa_full_pixels.data() + row * 256 + col * 4;
738 const std::uint8_t* got_half = msaa_half_pixels.data() + row * 256 + col * 4;
739 const std::uint8_t want_full[4] = {std::uint8_t(top_left ? 255 : 0), 0,
740 std::uint8_t(top_left ? 0 : 255), 255};
741 if (std::memcmp(got_full, want_full, 4) != 0 && mismatches++ < 6)
742 std::fprintf(stderr, "4x MSAA full mask (%u,%u): got %u,%u,%u,%u want %u,%u,%u,%u\n", col, row,
743 got_full[0], got_full[1], got_full[2], got_full[3], want_full[0], want_full[1],
744 want_full[2], want_full[3]);
745 if (top_left) {
746 const bool ok = std::abs(int(got_half[0]) - 128) <= 1 && got_half[1] == 0 &&
747 std::abs(int(got_half[2]) - 128) <= 1 && got_half[3] == 255;
748 if (!ok && mismatches++ < 6)
749 std::fprintf(stderr, "4x MSAA half mask (%u,%u): got %u,%u,%u,%u want ~128,0,128,255\n", col,
750 row, got_half[0], got_half[1], got_half[2], got_half[3]);
751 if (std::memcmp(got_half, got_full, 4) != 0) ++half_changed;
752 } else if (std::memcmp(got_half, want_full, 4) != 0 && mismatches++ < 6) {
753 std::fprintf(stderr, "4x MSAA half mask bg (%u,%u): got %u,%u,%u,%u want 0,0,255,255\n", col, row,
754 got_half[0], got_half[1], got_half[2], got_half[3]);
755 }
756 }
757 }
758 EXPECT(!mismatches);
759 EXPECT(half_changed == (size / 2) * (size / 2));
760 std::printf("4x MSAA graphics pipeline: 4096/4096 resolved pixels matched (SampleMask 0x5 changed %u/%u "
761 "top-left pixels to purple)\n",
762 half_changed, (size / 2) * (size / 2));
763 }
632 if (d.validation_errors()) { 764 if (d.validation_errors()) {
633 std::fprintf(stderr, "%u validation errors\n", d.validation_errors()); 765 std::fprintf(stderr, "%u validation errors\n", d.validation_errors());
634 return 1; 766 return 1;
diff --git a/runtime/test/d3d12_gcl8_test.cpp b/runtime/test/d3d12_gcl8_test.cpp
index 7e3020583..8b0426e6c 100644
--- a/runtime/test/d3d12_gcl8_test.cpp
+++ b/runtime/test/d3d12_gcl8_test.cpp
@@ -36,6 +36,10 @@ int main(int argc, char** argv) {
36 EXPECT(SUCCEEDED(create_command_allocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator.p)))); 36 EXPECT(SUCCEEDED(create_command_allocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator.p))));
37 EXPECT(SUCCEEDED(create_command_list(D3D12_COMMAND_LIST_TYPE_DIRECT, allocator.p, IID_PPV_ARGS(&list7.p)))); 37 EXPECT(SUCCEEDED(create_command_list(D3D12_COMMAND_LIST_TYPE_DIRECT, allocator.p, IID_PPV_ARGS(&list7.p))));
38 38
39 // Null bindings exercise the public entry points without creating a pipeline or loading Vulkan.
40 list7.p->SetPipelineState(nullptr);
41 list7.p->SetGraphicsRootSignature(nullptr);
42
39 // AddRef through the GCL7 pointer gives the count this test expects while the QueryInterface reference is held. 43 // AddRef through the GCL7 pointer gives the count this test expects while the QueryInterface reference is held.
40 const ULONG held = list7.p->AddRef(); 44 const ULONG held = list7.p->AddRef();
41 list7.p->Release(); 45 list7.p->Release();
@@ -82,6 +86,11 @@ int main(int argc, char** argv) {
82 EXPECT(list7.p->AddRef() == held); // QueryInterface released its reference 86 EXPECT(list7.p->AddRef() == held); // QueryInterface released its reference
83 list7.p->Release(); 87 list7.p->Release();
84 88
89 // Calls made before pipeline setup still belong in the trace. They invalidate this list without needing a GPU.
90 list7.p->DrawInstanced(3, 1, 0, 0);
91 list7.p->DrawIndexedInstanced(3, 1, 0, 0, 0);
92 EXPECT(list7.p->Close() == E_INVALIDARG);
93
85 UINT ignored_front = 0, ignored_back = 0; 94 UINT ignored_front = 0, ignored_back = 0;
86 EXPECT(!front_back_stencil_ref(nullptr, ignored_front, ignored_back)); 95 EXPECT(!front_back_stencil_ref(nullptr, ignored_front, ignored_back));
87 96
diff --git a/runtime/test/d3d12_m2_textured_test.cpp b/runtime/test/d3d12_m2_textured_test.cpp
index db8e9fd3f..8d13bf214 100644
--- a/runtime/test/d3d12_m2_textured_test.cpp
+++ b/runtime/test/d3d12_m2_textured_test.cpp
@@ -20,6 +20,7 @@
20// [1] POINT/WRAP. The left half takes the WRAP sampler (U + 1 wraps back: the gradient again), the right half the 20// [1] POINT/WRAP. The left half takes the WRAP sampler (U + 1 wraps back: the gradient again), the right half the
21// CLAMP one (U + 1 clamps to the last column: each row is that row's right-edge texel of the reflected texture). The 21// CLAMP one (U + 1 clamps to the last column: each row is that row's right-edge texel of the reflected texture). The
22// pixels are predicted on the CPU, error 0, and 1536 of them differ from the plain reflection. 22// pixels are predicted on the CPU, error 0, and 1536 of them differ from the plain reflection.
23// The control also keeps one unbounded SRV table bound and selects its two entries by a root constant.
23// Set LEONIDA_VK_VALIDATION=1 to run under VK_LAYER_KHRONOS_validation (0 errors required). 24// Set LEONIDA_VK_VALIDATION=1 to run under VK_LAYER_KHRONOS_validation (0 errors required).
24#include "vk_test_device.h" 25#include "vk_test_device.h"
25#include "d3d12_test_shaders.h" 26#include "d3d12_test_shaders.h"
@@ -148,6 +149,22 @@ int main() {
148 pso_desc.SampleDesc.Count = 1; 149 pso_desc.SampleDesc.Count = 1;
149 Ref<ID3D12PipelineState> pso, uoff_pso; 150 Ref<ID3D12PipelineState> pso, uoff_pso;
150 EXPECT(SUCCEEDED(device->CreateGraphicsPipelineState(&pso_desc, IID_PPV_ARGS(&pso.p)))); 151 EXPECT(SUCCEEDED(device->CreateGraphicsPipelineState(&pso_desc, IID_PPV_ARGS(&pso.p))));
152 D3D12_DESCRIPTOR_RANGE indexed_range = srv_range;
153 indexed_range.NumDescriptors = UINT32_MAX;
154 D3D12_ROOT_PARAMETER indexed_params[3] = {params[0], params[1], {}};
155 indexed_params[0].DescriptorTable = {1, &indexed_range};
156 indexed_params[2].ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS;
157 indexed_params[2].ShaderVisibility = D3D12_SHADER_VISIBILITY_PIXEL;
158 indexed_params[2].Constants = {0, 0, 2}; // s4 = SRV index, s5 = SRV stride in bytes
159 D3D12_VERSIONED_ROOT_SIGNATURE_DESC indexed_desc = root_desc;
160 indexed_desc.Desc_1_0.NumParameters = 3;
161 indexed_desc.Desc_1_0.pParameters = indexed_params;
162 const auto indexed_blob = serialize_root_signature(indexed_desc);
163 EXPECT(!indexed_blob.empty());
164 Ref<ID3D12RootSignature> indexed_root;
165 EXPECT(SUCCEEDED(device->CreateRootSignature(0, indexed_blob.data(), indexed_blob.size(),
166 IID_PPV_ARGS(&indexed_root.p))));
167 pso_desc.pRootSignature = indexed_root.p;
151 pso_desc.PS = {uoff_container.data(), uoff_container.size()}; 168 pso_desc.PS = {uoff_container.data(), uoff_container.size()};
152 EXPECT(SUCCEEDED(device->CreateGraphicsPipelineState(&pso_desc, IID_PPV_ARGS(&uoff_pso.p)))); 169 EXPECT(SUCCEEDED(device->CreateGraphicsPipelineState(&pso_desc, IID_PPV_ARGS(&uoff_pso.p))));
153 170
@@ -350,8 +367,9 @@ int main() {
350 D3D12_RESOURCE_STATE_RENDER_TARGET); 367 D3D12_RESOURCE_STATE_RENDER_TARGET);
351 list2->ResourceBarrier(1, &back); 368 list2->ResourceBarrier(1, &back);
352 list2->ClearRenderTargetView(rtv, clear, 0, nullptr); 369 list2->ClearRenderTargetView(rtv, clear, 0, nullptr);
353 list2->SetGraphicsRootSignature(root.p); 370 list2->SetGraphicsRootSignature(indexed_root.p);
354 list2->SetDescriptorHeaps(2, heaps); 371 list2->SetDescriptorHeaps(2, heaps);
372 list2->SetGraphicsRootDescriptorTable(0, D3D12_GPU_DESCRIPTOR_HANDLE{srv_gpu});
355 list2->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); 373 list2->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
356 list2->IASetIndexBuffer(&ibv); 374 list2->IASetIndexBuffer(&ibv);
357 list2->RSSetViewports(1, &viewport); 375 list2->RSSetViewports(1, &viewport);
@@ -359,7 +377,8 @@ int main() {
359 for (UINT half = 0; half < 2; ++half) { 377 for (UINT half = 0; half < 2; ++half) {
360 const D3D12_RECT scissor{LONG(half * target_size / 2), 0, LONG((half + 1) * target_size / 2), LONG(target_size)}; 378 const D3D12_RECT scissor{LONG(half * target_size / 2), 0, LONG((half + 1) * target_size / 2), LONG(target_size)};
361 list2->RSSetScissorRects(1, &scissor); 379 list2->RSSetScissorRects(1, &scissor);
362 list2->SetGraphicsRootDescriptorTable(0, D3D12_GPU_DESCRIPTOR_HANDLE{srv_gpu + std::uint64_t(half) * step}); 380 const UINT srv_args[] = {half, step};
381 list2->SetGraphicsRoot32BitConstants(2, 2, srv_args, 0);
363 list2->SetGraphicsRootDescriptorTable( 382 list2->SetGraphicsRootDescriptorTable(
364 1, D3D12_GPU_DESCRIPTOR_HANDLE{sampler_gpu + std::uint64_t(half == 0 ? sampler_step : 0)}); 383 1, D3D12_GPU_DESCRIPTOR_HANDLE{sampler_gpu + std::uint64_t(half == 0 ? sampler_step : 0)});
365 list2->DrawIndexedInstanced(6, 1, 0, 0, 0); 384 list2->DrawIndexedInstanced(6, 1, 0, 0, 0);
@@ -387,6 +406,7 @@ int main() {
387 uoff_pso.reset(); 406 uoff_pso.reset();
388 list2.reset(); 407 list2.reset();
389 allocator2.reset(); 408 allocator2.reset();
409 indexed_root.reset();
390 root.reset(); 410 root.reset();
391 srv_heap.reset(); 411 srv_heap.reset();
392 sampler_heap.reset(); 412 sampler_heap.reset();
diff --git a/runtime/test/d3d12_present_test.cpp b/runtime/test/d3d12_present_test.cpp
index 764b3e0f5..8b28eb67a 100644
--- a/runtime/test/d3d12_present_test.cpp
+++ b/runtime/test/d3d12_present_test.cpp
@@ -108,11 +108,13 @@ PFN_vkCreateSemaphore real_create_semaphore = nullptr;
108PFN_vkDestroySemaphore real_destroy_semaphore = nullptr; 108PFN_vkDestroySemaphore real_destroy_semaphore = nullptr;
109PFN_vkGetPhysicalDeviceSurfaceFormatsKHR real_surface_formats = nullptr; 109PFN_vkGetPhysicalDeviceSurfaceFormatsKHR real_surface_formats = nullptr;
110PFN_vkCreateSwapchainKHR real_create_swapchain = nullptr; 110PFN_vkCreateSwapchainKHR real_create_swapchain = nullptr;
111PFN_vkGetPhysicalDeviceSurfaceCapabilitiesKHR real_get_caps = nullptr;
111VkResult fail_next_submit = VK_SUCCESS; // armed: the next vkQueueSubmit returns this and submits nothing 112VkResult fail_next_submit = VK_SUCCESS; // armed: the next vkQueueSubmit returns this and submits nothing
112VkResult next_present = VK_SUCCESS; // armed: the next present that succeeds reports this instead 113VkResult next_present = VK_SUCCESS; // armed: the next present that succeeds reports this instead
113int fail_semaphore_in = 0; // armed: the n-th vkCreateSemaphore from now fails 114int fail_semaphore_in = 0; // armed: the n-th vkCreateSemaphore from now fails
114bool fail_surface_formats = false; // armed: the next surface-format query fails before creation 115bool fail_surface_formats = false; // armed: the next surface-format query fails before creation
115bool observe_next_swapchain = false; 116bool observe_next_swapchain = false;
117bool report_undefined_extent = false; // armed: surface capabilities reports undefined extent (0xFFFFFFFF)
116VkSwapchainKHR last_created_swapchain = VK_NULL_HANDLE; 118VkSwapchainKHR last_created_swapchain = VK_NULL_HANDLE;
117VkSwapchainKHR observed_old_swapchain = VK_NULL_HANDLE; 119VkSwapchainKHR observed_old_swapchain = VK_NULL_HANDLE;
118unsigned out_of_date = 0; // presents the real driver reported out of date 120unsigned out_of_date = 0; // presents the real driver reported out of date
@@ -177,6 +179,16 @@ VKAPI_ATTR VkResult VKAPI_CALL create_swapchain(VkDevice device, const VkSwapcha
177 return result; 179 return result;
178} 180}
179 181
182VKAPI_ATTR VkResult VKAPI_CALL get_surface_capabilities(VkPhysicalDevice physical, VkSurfaceKHR surface,
183 VkSurfaceCapabilitiesKHR* caps) {
184 const VkResult result = real_get_caps(physical, surface, caps);
185 if (result == VK_SUCCESS && report_undefined_extent && caps) {
186 caps->currentExtent.width = 0xFFFFFFFF;
187 caps->currentExtent.height = 0xFFFFFFFF;
188 }
189 return result;
190}
191
180VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL get_device(VkDevice device, const char* name) { 192VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL get_device(VkDevice device, const char* name) {
181 const std::string_view n = name; 193 const std::string_view n = name;
182 if (n == "vkQueueSubmit") return reinterpret_cast<PFN_vkVoidFunction>(queue_submit); 194 if (n == "vkQueueSubmit") return reinterpret_cast<PFN_vkVoidFunction>(queue_submit);
@@ -188,9 +200,12 @@ VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL get_device(VkDevice device, const char*
188} 200}
189 201
190VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL get_instance(VkInstance instance, const char* name) { 202VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL get_instance(VkInstance instance, const char* name) {
191 if (std::string_view(name) == "vkGetDeviceProcAddr") return reinterpret_cast<PFN_vkVoidFunction>(get_device); 203 const std::string_view n = name;
192 if (std::string_view(name) == "vkGetPhysicalDeviceSurfaceFormatsKHR") 204 if (n == "vkGetDeviceProcAddr") return reinterpret_cast<PFN_vkVoidFunction>(get_device);
205 if (n == "vkGetPhysicalDeviceSurfaceFormatsKHR")
193 return reinterpret_cast<PFN_vkVoidFunction>(surface_formats); 206 return reinterpret_cast<PFN_vkVoidFunction>(surface_formats);
207 if (n == "vkGetPhysicalDeviceSurfaceCapabilitiesKHR")
208 return reinterpret_cast<PFN_vkVoidFunction>(get_surface_capabilities);
194 return real_get_instance(instance, name); 209 return real_get_instance(instance, name);
195} 210}
196 211
@@ -204,6 +219,8 @@ void install(PFN_vkGetInstanceProcAddr instance_proc, VkInstance instance, VkDev
204 real_surface_formats = reinterpret_cast<PFN_vkGetPhysicalDeviceSurfaceFormatsKHR>( 219 real_surface_formats = reinterpret_cast<PFN_vkGetPhysicalDeviceSurfaceFormatsKHR>(
205 instance_proc(instance, "vkGetPhysicalDeviceSurfaceFormatsKHR")); 220 instance_proc(instance, "vkGetPhysicalDeviceSurfaceFormatsKHR"));
206 real_create_swapchain = reinterpret_cast<PFN_vkCreateSwapchainKHR>(real_get_device(device, "vkCreateSwapchainKHR")); 221 real_create_swapchain = reinterpret_cast<PFN_vkCreateSwapchainKHR>(real_get_device(device, "vkCreateSwapchainKHR"));
222 real_get_caps = reinterpret_cast<PFN_vkGetPhysicalDeviceSurfaceCapabilitiesKHR>(
223 instance_proc(instance, "vkGetPhysicalDeviceSurfaceCapabilitiesKHR"));
207} 224}
208} // namespace driver 225} // namespace driver
209 226
@@ -390,8 +407,17 @@ int main() {
390 for (int i = 0; i < 4; ++i) EXPECT(frame(1)); // both frames in flight come round again 407 for (int i = 0; i < 4; ++i) EXPECT(frame(1)); // both frames in flight come round again
391 EXPECT(presenter->presented() == before + 4 - (driver::out_of_date - out_of_date_before)); 408 EXPECT(presenter->presented() == before + 4 - (driver::out_of_date - out_of_date_before));
392 EXPECT(SUCCEEDED(fence->SetEventOnCompletion(signalled, nullptr))); 409 EXPECT(SUCCEEDED(fence->SetEventOnCompletion(signalled, nullptr)));
410
411 // 4. Undefined surface extent (0xFFFFFFFF, reported by Intel UHD graphics / Win32 WSI; D3D-165):
412 // the presenter queries the window client extent and clamps to surface bounds.
413 driver::report_undefined_extent = true;
414 EXPECT(frame(1));
415 EXPECT(presenter->extent().width == 400 && presenter->extent().height == 300);
416 driver::report_undefined_extent = false;
417
393 std::printf("injected: out-of-date and suboptimal presents counted apart, a failed swapchain recreation " 418 std::printf("injected: out-of-date and suboptimal presents counted apart, a failed swapchain recreation "
394 "released and retried, a failed blit submission recovered (%u real out-of-date presents)\n", 419 "released and retried, a failed blit submission recovered, undefined surface extent resolved "
420 "(%u real out-of-date presents)\n",
395 real_out_of_date); 421 real_out_of_date);
396 422
397 // What reached the screen: the centre of the client area, if the window is in front. 423 // What reached the screen: the centre of the client area, if the window is in front.
diff --git a/runtime/test/d3d12_queue_wait_test.cpp b/runtime/test/d3d12_queue_wait_test.cpp
index d1a868a25..3dfb1bad3 100644
--- a/runtime/test/d3d12_queue_wait_test.cpp
+++ b/runtime/test/d3d12_queue_wait_test.cpp
@@ -1,7 +1,9 @@
1// D3D-97: cross-queue Wait-before-Signal must make progress. No game files. 1// D3D-97: cross-queue Wait-before-Signal must make progress. No game files.
2#include "../shims/d3d12_com.h" 2#include "../shims/d3d12_com.h"
3 3
4#include <cstdlib>
4#include <cstdio> 5#include <cstdio>
6#include <cstring>
5 7
6namespace { 8namespace {
7template<class T> struct Ref { 9template<class T> struct Ref {
@@ -10,19 +12,35 @@ template<class T> struct Ref {
10 T* operator->() const { return p; } 12 T* operator->() const { return p; }
11}; 13};
12 14
13bool wait_for(ID3D12Fence* fence, UINT64 value) { 15bool wait_for(ID3D12Fence* fence, UINT64 value, DWORD timeout_ms = 3000) {
14 HANDLE event = CreateEventW(nullptr, FALSE, FALSE, nullptr); 16 HANDLE event = CreateEventW(nullptr, FALSE, FALSE, nullptr);
15 if (!event) return false; 17 if (!event) return false;
16 const bool complete = SUCCEEDED(fence->SetEventOnCompletion(value, event)) && 18 if (FAILED(fence->SetEventOnCompletion(value, event))) {
17 WaitForSingleObject(event, 3000) == WAIT_OBJECT_0; 19 CloseHandle(event); // no wait was registered
20 return false;
21 }
22 if (WaitForSingleObject(event, timeout_ms) != WAIT_OBJECT_0) {
23 // The fence dispatcher can still hold this event, and a queued GPU Wait can keep the queue destructor
24 // blocked forever. End the failed test without closing live handles or waiting for blocked queues.
25 std::fputs("cross-queue Wait-before-Signal timed out\n", stderr);
26 std::fflush(stderr);
27 std::_Exit(1);
28 }
18 CloseHandle(event); 29 CloseHandle(event);
19 return complete; 30 return true;
20} 31}
21} // namespace 32} // namespace
22 33
23int main() { 34int main(int argc, char** argv) {
24 Ref<ID3D12Device> device; 35 Ref<ID3D12Device> device;
25 if (FAILED(rt::d3d12::create_vulkan_device_standalone(IID_PPV_ARGS(&device.p)))) return 77; 36 if (FAILED(rt::d3d12::create_vulkan_device_standalone(IID_PPV_ARGS(&device.p)))) return 77;
37 if (argc == 2 && std::strcmp(argv[1], "--timeout-control") == 0) {
38 Ref<ID3D12Fence> never_signaled;
39 if (FAILED(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&never_signaled.p)))) return 1;
40 // Expected to leave the process with code 1 promptly, without destroying the pending event.
41 wait_for(never_signaled.p, 1, 20);
42 return 0; // a completed wait here means the control did not exercise the timeout path
43 }
26 D3D12_COMMAND_QUEUE_DESC desc{}; 44 D3D12_COMMAND_QUEUE_DESC desc{};
27 Ref<ID3D12CommandQueue> copy, compute, direct_a, direct_b; 45 Ref<ID3D12CommandQueue> copy, compute, direct_a, direct_b;
28 desc.Type = D3D12_COMMAND_LIST_TYPE_COPY; 46 desc.Type = D3D12_COMMAND_LIST_TYPE_COPY;
@@ -49,11 +67,11 @@ int main() {
49 const bool copy_complete = submitted && wait_for(done_copy.p, 1); 67 const bool copy_complete = submitted && wait_for(done_copy.p, 1);
50 const bool direct_complete = submitted && wait_for(done_direct.p, 1); 68 const bool direct_complete = submitted && wait_for(done_direct.p, 1);
51 if (!copy_complete || !direct_complete) { 69 if (!copy_complete || !direct_complete) {
52 // Unblock submitted waits before queue destructors call vkQueueWaitIdle. 70 // A failed submit can leave a GPU Wait pending. Gate 1 is not a valid fallback once queue signals
53 gate_copy->Signal(1); 71 // have claimed 2, so do not destroy queues or fences while their work may still be outstanding.
54 gate_direct->Signal(1); 72 std::fputs("cross-queue Wait-before-Signal did not complete\n", stderr);
55 std::fprintf(stderr, "cross-queue Wait-before-Signal did not complete\n"); 73 std::fflush(stderr);
56 return 1; 74 std::_Exit(1);
57 } 75 }
58 std::puts("copy/compute and direct/direct Wait-before-Signal completed"); 76 std::puts("copy/compute and direct/direct Wait-before-Signal completed");
59 return 0; 77 return 0;
diff --git a/runtime/test/d3d12_set0_compute_test.cpp b/runtime/test/d3d12_set0_compute_test.cpp
new file mode 100644
index 000000000..69663d764
--- /dev/null
+++ b/runtime/test/d3d12_set0_compute_test.cpp
@@ -0,0 +1,337 @@
1// Set 0 from the compute bind point, through the Xbox-ABI proxy over the Vulkan device. A compute PSO whose shader
2// declares set-0 bindings is created and dispatched through D3D12 alone; nothing in the test touches Vulkan's
3// descriptor sets. The dispatches only give the right words if the layer has the device's bindless set 0 in the
4// pipeline layout and binds it at the dispatch:
5// - two 8x8 textures, a gradient and its point reflection, uploaded with Map and CopyTextureRegion;
6// - a shader-visible CBV/SRV/UAV heap with an SRV for each in slots 0 and 1 and 32 bytes no view was made for in
7// slot 2, and a sampler heap with a POINT sampler that wraps in slot 0 and one that clamps in slot 1;
8// - a root signature of two constants, a root UAV and the two descriptor tables.
9// test/glsl/cs_set0_sample.comp loads the T# and the S# from the tables in the GPU address arena, looks them up in
10// the descriptor hash table (set 0, binding 2) and samples one tile to the right in U. Four dispatches:
11// 1. slot 0 with the wrapping sampler: the gradient, texel for texel;
12// 2. slot 1 with the wrapping sampler: the reflected texture, so the T# decides the image;
13// 3. slot 2 with the wrapping sampler: the fallback image, one colour everywhere;
14// 4. slot 0 with the clamping sampler: the gradient's right edge in every column, so the S# decides the sampler.
15// A device without the bindless set refuses the PSO. No game data: the program is two marker words and the module is
16// GLSL written to the translator's contract.
17// Set LEONIDA_VK_VALIDATION=1 to run under VK_LAYER_KHRONOS_validation (0 errors required).
18#include "vk_test_device.h"
19#include "d3d12_test_shaders.h"
20#include "../shims/d3d12_com.h"
21#include "../shims/d3d12_xs_device.h"
22#include "../src/shader_library.h"
23
24#include <array>
25#include <cstdint>
26#include <cstring>
27#include <filesystem>
28#include <fstream>
29#include <vector>
30
31#ifndef LEONIDA_TEST_CS_SET0_SAMPLE_SPV
32#error "LEONIDA_TEST_CS_SET0_SAMPLE_SPV must name the compiled test shader"
33#endif
34
35#define EXPECT(condition) do { \
36 if (!(condition)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); return 1; } \
37} while (0)
38
39using namespace d3d12test;
40using XboxHeapHandleFn = std::uint64_t(WINAPI*)(void* heap); // heap slots 9/10: handle in RAX
41
42namespace {
43
44using Texel = std::array<std::uint8_t, 4>;
45constexpr UINT texture_size = 8, texels = texture_size * texture_size, run_bytes = texels * 4, runs = 4;
46
47// The synthetic gradient: red rises with x, green with y, blue falls along the diagonal.
48Texel gradient(UINT x, UINT y) {
49 return {std::uint8_t(x * 36), std::uint8_t(y * 36), std::uint8_t(255 - (x + y) * 16), 255};
50}
51// The second texture: the first one point-reflected, so no texel of it is in the same place.
52Texel reflected(UINT x, UINT y) { return gradient(texture_size - 1 - x, texture_size - 1 - y); }
53
54} // namespace
55
56int main() {
57 vktest::Device d;
58 const auto device_status = d.initialize();
59 if (device_status == vktest::DeviceStatus::unavailable) return 77; // no Vulkan GPU: ctest skips
60 if (device_status != vktest::DeviceStatus::ready) return 1;
61 if (!d.bindless) {
62 std::printf("SKIP: the device lacks the descriptor indexing features of the bindless set 0\n");
63 return 77;
64 }
65
66 // The program the PSO carries, and a translator index that maps its hash to the test module. The index lists
67 // set-0 bindings for the shader, as the translator does for one that samples.
68 const auto program = fssm_program({0x43530003, 0xbf810000});
69 const auto container = shader_container(program);
70 const auto library = std::filesystem::temp_directory_path() / "leonida_set0_compute_test";
71 std::filesystem::create_directories(library);
72 std::filesystem::copy_file(LEONIDA_TEST_CS_SET0_SAMPLE_SPV, library / "cs_set0_sample.spv",
73 std::filesystem::copy_options::overwrite_existing);
74 {
75 std::ofstream index(library / "index.json", std::ios::binary);
76 index << "{\"cs_set0_sample\": {\"stage\": \"cs\", \"fssm_sha256\": \"" << leonida::sha256_hex(program)
77 << "\", \"bindings\": [0, 1, 2], \"push_constant_bytes\": 144, \"local_size\": [64, 1, 1], "
78 "\"uses_code_base\": false, \"wave64\": false}}";
79 }
80
81 std::vector<std::uint8_t> results(runs * run_bytes);
82 {
83 rt::d3d12::VulkanDeviceInfo info{};
84 info.get_instance_proc = d.instance_proc;
85 info.instance = d.instance;
86 info.physical = d.physical;
87 info.device = d.device;
88 info.queue = d.queue;
89 info.queue_family = d.family;
90 info.buffer_device_address = true;
91 info.bindless = d.bindless;
92 info.bindless_partially_bound = d.partially_bound;
93 info.image_view_min_lod = d.image_view_min_lod;
94 info.shader_dir = library.string();
95 ID3D12Device* inner = nullptr;
96 EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&inner))));
97 Ref<ID3D12Device> device;
98 EXPECT(SUCCEEDED(rt::d3d12_xs::create_device_proxy(inner, __uuidof(ID3D12Device),
99 reinterpret_cast<void**>(&device.p))));
100 rt::d3d12::set_device_outer(inner, device.p);
101 EXPECT(rt::d3d12::bindless_set(device.p) != VK_NULL_HANDLE);
102
103 // Root signature: [0] two constants (s0: the view slot's offset in dwords, s1: the first output element),
104 // [1] a root UAV (s2:s3, the output buffer), [2] the table of views (s4:s5), [3] the table of samplers
105 // (s6:s7).
106 D3D12_DESCRIPTOR_RANGE view_range{D3D12_DESCRIPTOR_RANGE_TYPE_SRV, 3, 0, 0, 0};
107 D3D12_DESCRIPTOR_RANGE sampler_range{D3D12_DESCRIPTOR_RANGE_TYPE_SAMPLER, 1, 0, 0, 0};
108 D3D12_ROOT_PARAMETER params[4] = {};
109 params[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS;
110 params[0].Constants = {0, 0, 2};
111 params[1].ParameterType = D3D12_ROOT_PARAMETER_TYPE_UAV;
112 params[1].Descriptor = {0, 0};
113 params[2].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE;
114 params[2].DescriptorTable = {1, &view_range};
115 params[3].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE;
116 params[3].DescriptorTable = {1, &sampler_range};
117 D3D12_VERSIONED_ROOT_SIGNATURE_DESC root_desc{};
118 root_desc.Version = D3D_ROOT_SIGNATURE_VERSION_1_0;
119 root_desc.Desc_1_0 = {4, params, 0, nullptr, D3D12_ROOT_SIGNATURE_FLAG_NONE};
120 const auto root_blob = serialize_root_signature(root_desc);
121 EXPECT(!root_blob.empty());
122 Ref<ID3D12RootSignature> root;
123 EXPECT(SUCCEEDED(device->CreateRootSignature(0, root_blob.data(), root_blob.size(), IID_PPV_ARGS(&root.p))));
124
125 // The PSO: its shader has set-0 bindings, so its layout holds the device's set.
126 D3D12_COMPUTE_PIPELINE_STATE_DESC pso_desc{};
127 pso_desc.pRootSignature = root.p;
128 pso_desc.CS = {container.data(), container.size()};
129 Ref<ID3D12PipelineState> pso;
130 EXPECT(SUCCEEDED(device->CreateComputePipelineState(&pso_desc, IID_PPV_ARGS(&pso.p))));
131
132 // A device without the bindless set has nothing such a shader could find its images in: the PSO is refused.
133 {
134 rt::d3d12::VulkanDeviceInfo plain_info = info;
135 plain_info.bindless = plain_info.bindless_partially_bound = false;
136 Ref<ID3D12Device> plain;
137 EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(plain_info, IID_PPV_ARGS(&plain.p))));
138 EXPECT(rt::d3d12::bindless_set(plain.p) == VK_NULL_HANDLE);
139 Ref<ID3D12RootSignature> plain_root;
140 EXPECT(SUCCEEDED(plain->CreateRootSignature(0, root_blob.data(), root_blob.size(),
141 IID_PPV_ARGS(&plain_root.p))));
142 D3D12_COMPUTE_PIPELINE_STATE_DESC plain_desc = pso_desc;
143 plain_desc.pRootSignature = plain_root.p;
144 Ref<ID3D12PipelineState> refused;
145 EXPECT(plain->CreateComputePipelineState(&plain_desc, IID_PPV_ARGS(&refused.p)) == E_NOTIMPL && !refused.p);
146 }
147
148 const D3D12_HEAP_PROPERTIES default_heap{D3D12_HEAP_TYPE_DEFAULT};
149 const D3D12_HEAP_PROPERTIES upload_heap{D3D12_HEAP_TYPE_UPLOAD};
150 const D3D12_HEAP_PROPERTIES readback_heap{D3D12_HEAP_TYPE_READBACK};
151 D3D12_RESOURCE_DESC texture_desc{};
152 texture_desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D;
153 texture_desc.Width = texture_desc.Height = texture_size;
154 texture_desc.DepthOrArraySize = 1;
155 texture_desc.MipLevels = 1;
156 texture_desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
157 texture_desc.SampleDesc.Count = 1;
158 Ref<ID3D12Resource> textures[2], upload, output, readback;
159 for (auto& texture : textures)
160 EXPECT(SUCCEEDED(device->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &texture_desc,
161 D3D12_RESOURCE_STATE_COPY_DEST, nullptr,
162 IID_PPV_ARGS(&texture.p))));
163 // The upload buffer: texture A at 0, texture B at 2048 (8 rows of the 256-byte pitch).
164 constexpr UINT64 b_offset = 2048;
165 const auto upload_desc = buffer_desc(4096);
166 EXPECT(SUCCEEDED(device->CreateCommittedResource(&upload_heap, D3D12_HEAP_FLAG_NONE, &upload_desc,
167 D3D12_RESOURCE_STATE_GENERIC_READ, nullptr,
168 IID_PPV_ARGS(&upload.p))));
169 const auto output_desc = buffer_desc(results.size(), D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS);
170 EXPECT(SUCCEEDED(device->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &output_desc,
171 D3D12_RESOURCE_STATE_UNORDERED_ACCESS, nullptr,
172 IID_PPV_ARGS(&output.p))));
173 const auto readback_desc = buffer_desc(results.size());
174 EXPECT(SUCCEEDED(device->CreateCommittedResource(&readback_heap, D3D12_HEAP_FLAG_NONE, &readback_desc,
175 D3D12_RESOURCE_STATE_COPY_DEST, nullptr,
176 IID_PPV_ARGS(&readback.p))));
177 D3D12_PLACED_SUBRESOURCE_FOOTPRINT footprint{};
178 device->GetCopyableFootprints(&texture_desc, 0, 1, 0, &footprint, nullptr, nullptr, nullptr);
179 EXPECT(footprint.Footprint.RowPitch == 256 && footprint.Footprint.RowPitch * texture_size <= b_offset);
180 std::uint8_t* up = nullptr;
181 EXPECT(SUCCEEDED(upload->Map(0, nullptr, reinterpret_cast<void**>(&up))));
182 for (UINT y = 0; y < texture_size; ++y)
183 for (UINT x = 0; x < texture_size; ++x) {
184 const Texel a = gradient(x, y), b = reflected(x, y);
185 std::memcpy(up + y * footprint.Footprint.RowPitch + x * 4, a.data(), 4);
186 std::memcpy(up + b_offset + y * footprint.Footprint.RowPitch + x * 4, b.data(), 4);
187 }
188
189 // The two heaps; their start handles come back in RAX (heap slots 9 and 10). Shader-visible heaps live in
190 // the GPU address arena, so the GPU handles are console VAs and the bytes the views and the samplers wrote
191 // are what the shader loads.
192 const D3D12_DESCRIPTOR_HEAP_DESC view_heap_desc{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 4,
193 D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, 0};
194 const D3D12_DESCRIPTOR_HEAP_DESC sampler_heap_desc{D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER, 2,
195 D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, 0};
196 Ref<ID3D12DescriptorHeap> view_heap, sampler_heap;
197 EXPECT(SUCCEEDED(device->CreateDescriptorHeap(&view_heap_desc, IID_PPV_ARGS(&view_heap.p))));
198 EXPECT(SUCCEEDED(device->CreateDescriptorHeap(&sampler_heap_desc, IID_PPV_ARGS(&sampler_heap.p))));
199 const std::uint64_t view_cpu = reinterpret_cast<XboxHeapHandleFn>(slot(view_heap.p, 9))(view_heap.p);
200 const std::uint64_t view_gpu = reinterpret_cast<XboxHeapHandleFn>(slot(view_heap.p, 10))(view_heap.p);
201 const std::uint64_t sampler_cpu = reinterpret_cast<XboxHeapHandleFn>(slot(sampler_heap.p, 9))(sampler_heap.p);
202 const std::uint64_t sampler_gpu = reinterpret_cast<XboxHeapHandleFn>(slot(sampler_heap.p, 10))(sampler_heap.p);
203 const UINT view_step = device->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV);
204 const UINT sampler_step = device->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER);
205 EXPECT(view_cpu && sampler_cpu && view_gpu >= 0x10000 && sampler_gpu >= 0x10000);
206 EXPECT(view_gpu < (1ull << 32) && sampler_gpu < (1ull << 32));
207 EXPECT(view_step >= 32 && view_step % 4 == 0 && sampler_step >= 16);
208
209 for (UINT i = 0; i < 2; ++i) {
210 D3D12_SHADER_RESOURCE_VIEW_DESC srv{};
211 srv.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
212 srv.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D;
213 srv.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING;
214 srv.Texture2D = {0, 1, 0, 0.0f};
215 device->CreateShaderResourceView(textures[i].p, &srv,
216 D3D12_CPU_DESCRIPTOR_HANDLE{SIZE_T(view_cpu + i * view_step)});
217 }
218 // Slot 2: bytes no view was made for. The hash table has no entry for them.
219 std::uint32_t unknown[8];
220 for (std::uint32_t i = 0; i < 8; ++i) unknown[i] = 0x5a5a0000u + i;
221 std::memcpy(reinterpret_cast<void*>(view_cpu + 2 * view_step), unknown, sizeof(unknown));
222 EXPECT(rt::d3d12::bindless_hash_lookup(device.p, unknown) == 0);
223 for (UINT i = 0; i < 2; ++i) {
224 D3D12_SAMPLER_DESC sampler_desc{};
225 sampler_desc.Filter = D3D12_FILTER_MIN_MAG_MIP_POINT;
226 sampler_desc.AddressU = sampler_desc.AddressV = sampler_desc.AddressW =
227 i ? D3D12_TEXTURE_ADDRESS_MODE_CLAMP : D3D12_TEXTURE_ADDRESS_MODE_WRAP;
228 sampler_desc.MaxAnisotropy = 1;
229 sampler_desc.ComparisonFunc = D3D12_COMPARISON_FUNC_NEVER;
230 sampler_desc.MaxLOD = D3D12_FLOAT32_MAX;
231 device->CreateSampler(&sampler_desc, D3D12_CPU_DESCRIPTOR_HANDLE{SIZE_T(sampler_cpu + i * sampler_step)});
232 }
233
234 D3D12_COMMAND_QUEUE_DESC queue_desc{};
235 Ref<ID3D12CommandQueue> queue;
236 Ref<ID3D12CommandAllocator> allocator;
237 Ref<ID3D12GraphicsCommandList> list;
238 Ref<ID3D12Fence> fence;
239 EXPECT(SUCCEEDED(device->CreateCommandQueue(&queue_desc, IID_PPV_ARGS(&queue.p))));
240 EXPECT(SUCCEEDED(device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator.p))));
241 EXPECT(SUCCEEDED(device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocator.p, nullptr,
242 IID_PPV_ARGS(&list.p))));
243 EXPECT(SUCCEEDED(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence.p))));
244
245 // Upload both textures and make them shader resources for a compute shader.
246 for (UINT i = 0; i < 2; ++i) {
247 D3D12_TEXTURE_COPY_LOCATION dst{};
248 dst.pResource = textures[i].p;
249 dst.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX;
250 D3D12_TEXTURE_COPY_LOCATION src{};
251 src.pResource = upload.p;
252 src.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT;
253 src.PlacedFootprint = footprint;
254 src.PlacedFootprint.Offset = i ? b_offset : 0;
255 list->CopyTextureRegion(&dst, 0, 0, 0, &src, nullptr);
256 }
257 D3D12_RESOURCE_BARRIER sampled[2] = {
258 transition(textures[0].p, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE),
259 transition(textures[1].p, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE)};
260 list->ResourceBarrier(2, sampled);
261
262 // The four dispatches. Each keeps the slot, the output position and the sampler table it was recorded with.
263 const D3D12_GPU_VIRTUAL_ADDRESS output_va = output->GetGPUVirtualAddress();
264 EXPECT(output_va >= 0x10000 && output_va < (1ull << 32));
265 ID3D12DescriptorHeap* heaps[] = {view_heap.p, sampler_heap.p};
266 list->SetDescriptorHeaps(2, heaps);
267 list->SetComputeRootSignature(root.p);
268 list->SetPipelineState(pso.p);
269 list->SetComputeRootUnorderedAccessView(1, output_va);
270 list->SetComputeRootDescriptorTable(2, D3D12_GPU_DESCRIPTOR_HANDLE{view_gpu});
271 const UINT view_slot[runs] = {0, 1, 2, 0};
272 const UINT sampler_slot[runs] = {0, 0, 0, 1};
273 for (UINT run = 0; run < runs; ++run) {
274 const std::uint32_t offset_and_first[2] = {view_slot[run] * view_step / 4, run * texels};
275 list->SetComputeRoot32BitConstants(0, 2, offset_and_first, 0);
276 list->SetComputeRootDescriptorTable(
277 3, D3D12_GPU_DESCRIPTOR_HANDLE{sampler_gpu + std::uint64_t(sampler_slot[run]) * sampler_step});
278 list->Dispatch(1, 1, 1);
279 }
280 D3D12_RESOURCE_BARRIER to_copy = transition(output.p, D3D12_RESOURCE_STATE_UNORDERED_ACCESS,
281 D3D12_RESOURCE_STATE_COPY_SOURCE);
282 list->ResourceBarrier(1, &to_copy);
283 list->CopyBufferRegion(readback.p, 0, output.p, 0, results.size());
284 EXPECT(list->Close() == S_OK);
285 ID3D12CommandList* lists[] = {list.p};
286 queue->ExecuteCommandLists(1, lists);
287 EXPECT(rt::d3d12::last_execute_result(queue.p) == leonida::ReplayResult::success);
288 EXPECT(SUCCEEDED(queue->Signal(fence.p, 1)));
289 EXPECT(SUCCEEDED(fence->SetEventOnCompletion(1, nullptr)));
290 void* mapped = nullptr;
291 EXPECT(SUCCEEDED(readback->Map(0, nullptr, &mapped)));
292 std::memcpy(results.data(), mapped, results.size());
293
294 for (auto& texture : textures) texture.reset();
295 for (auto* r : {&upload, &output, &readback}) r->reset();
296 pso.reset();
297 root.reset();
298 view_heap.reset();
299 sampler_heap.reset();
300 list.reset();
301 allocator.reset();
302 queue.reset();
303 fence.reset();
304 EXPECT(rt::d3d12_xs::device_proxy_ref_count(device.p) == 1);
305 }
306 std::filesystem::remove_all(library);
307
308 // Runs 0, 1 and 3 against the textures; run 2 is the fallback image, whose colour the test does not fix: it
309 // must be one colour everywhere, which neither texture gives.
310 const char* const names[runs] = {"slot 0, wrapping", "slot 1, wrapping", "the unknown slot", "slot 0, clamping"};
311 unsigned mismatches = 0;
312 for (UINT run = 0; run < runs; ++run) {
313 const std::uint8_t* got_run = results.data() + run * run_bytes;
314 for (UINT i = 0; i < texels; ++i) {
315 const UINT x = i % texture_size, y = i / texture_size;
316 const std::uint8_t* got = got_run + i * 4;
317 Texel want{};
318 if (run == 0) want = gradient(x, y);
319 else if (run == 1) want = reflected(x, y);
320 else if (run == 3) want = gradient(texture_size - 1, y);
321 else std::memcpy(want.data(), got_run, 4); // the fallback: texel 0 of the run, everywhere
322 if (std::memcmp(got, want.data(), 4) == 0) continue;
323 if (mismatches++ < 8)
324 std::fprintf(stderr, "%s, texel %u: got %u,%u,%u,%u want %u,%u,%u,%u\n", names[run], i, got[0], got[1],
325 got[2], got[3], want[0], want[1], want[2], want[3]);
326 }
327 }
328 EXPECT(!mismatches);
329 if (d.validation_errors()) {
330 std::fprintf(stderr, "%u validation errors\n", d.validation_errors());
331 return 1;
332 }
333 std::printf("set 0 from compute: four dispatches sampled through the bindless set the layer bound; %u texels "
334 "matched for each of two SRVs and for a clamping sampler, and bytes no view was made for gave the "
335 "fallback image\n", texels);
336 return 0;
337}
diff --git a/runtime/test/d3d12_subgroup_test.cpp b/runtime/test/d3d12_subgroup_test.cpp
new file mode 100644
index 000000000..4eae49a5b
--- /dev/null
+++ b/runtime/test/d3d12_subgroup_test.cpp
@@ -0,0 +1,672 @@
1// Subgroup size control in PSOs, end to end through the Xbox-ABI proxy over the Vulkan device (src/subgroup_size.h):
2// three translated compute shaders from runtime/test/shaders, each dispatched through a D3D12 PSO found by the
3// SHA-256 of its FSSM program, writing eight words through the V# in s[0:3] (four root constants), read back:
4// w64 native cs_w64x_readlane translated natively: v_readlane across both halves of a wave64. Exact only in a
5// 64-wide subgroup, so the PSO must ask for 64 (and full subgroups) on a device that can give it.
6// On a device that cannot (NVIDIA: 32 only) the PSO reports it, and the result is not judged.
7// w64 emulated the same shader translated with --wave64-emulate: exact on any size, the PSO asks for nothing.
8// w32 native cs_wqm_w32, a wave32 shader with whole-quad mode on lane masks; the PSO asks for 32 where the
9// device's default or range would otherwise change it.
10// Each case also prints a control run with the layer's size request switched off, to show what the request changes
11// on this GPU; the control is not judged. No game data. Set LEONIDA_VK_VALIDATION=1 to run under
12// VK_LAYER_KHRONOS_validation; validation errors fail the test.
13#include "vk_test_device.h"
14#include "../shims/d3d12_com.h"
15#include "../src/shader_library.h"
16#include "../shims/d3d12_xs_device.h"
17
18#include <array>
19#include <cstdint>
20#include <cstring>
21#include <filesystem>
22#include <string>
23#include <vector>
24
25#ifndef LEONIDA_TEST_SUBGROUP_SHADERS
26#error "LEONIDA_TEST_SUBGROUP_SHADERS must name the folder with the translated test shaders"
27#endif
28
29#define EXPECT(condition) do { \
30 if (!(condition)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); return 1; } \
31} while (0)
32
33namespace {
34
35using XboxComputePipelineFn = HRESULT(WINAPI*)(void* device, const D3D12_COMPUTE_PIPELINE_STATE_DESC*, std::uint64_t,
36 std::uint64_t, const IID*, void**);
37using XboxHeapHandleFn = std::uint64_t(WINAPI*)(void* heap); // heap slots 9/10: handle in RAX
38using SerializeFn = HRESULT(WINAPI*)(const D3D12_VERSIONED_ROOT_SIGNATURE_DESC*, ID3DBlob**, ID3DBlob**);
39
40template<class T>
41struct Ref {
42 T* p = nullptr;
43 ~Ref() { reset(); }
44 void reset() {
45 if (p) p->Release();
46 p = nullptr;
47 }
48 T* operator->() const { return p; }
49};
50
51void* slot(void* object, unsigned index) { return (*reinterpret_cast<void***>(object))[index]; }
52
53void put32(std::vector<std::uint8_t>& out, std::uint32_t v) {
54 for (int i = 0; i < 4; ++i) out.push_back(std::uint8_t(v >> (8 * i)));
55}
56
57std::vector<std::uint8_t> zlib_stored(const std::vector<std::uint8_t>& data) {
58 std::vector<std::uint8_t> out = {0x78, 0x01, 0x01};
59 const auto length = std::uint16_t(data.size());
60 out.insert(out.end(), {std::uint8_t(length), std::uint8_t(length >> 8), std::uint8_t(~length),
61 std::uint8_t(~length >> 8)});
62 out.insert(out.end(), data.begin(), data.end());
63 std::uint32_t a = 1, b = 0;
64 for (const std::uint8_t x : data) {
65 a = (a + x) % 65521;
66 b = (b + a) % 65521;
67 }
68 const std::uint32_t adler = (b << 16) | a;
69 out.insert(out.end(), {std::uint8_t(adler >> 24), std::uint8_t(adler >> 16), std::uint8_t(adler >> 8),
70 std::uint8_t(adler)});
71 return out;
72}
73
74// DXBC { DXIL { stub, XDAT { 0x0D: XBCH + zlib(fssm) } } }, the layout tools/fssm_unpack.py reads.
75std::vector<std::uint8_t> shader_container(const std::vector<std::uint8_t>& fssm) {
76 const auto stream = zlib_stored(fssm);
77 std::vector<std::uint8_t> xbch = {'X', 'B', 'C', 'H'};
78 for (const std::uint32_t v : {1u, std::uint32_t(stream.size()), 0u, std::uint32_t(fssm.size()), 0u}) put32(xbch, v);
79 xbch.insert(xbch.end(), stream.begin(), stream.end());
80 std::vector<std::uint8_t> dxil(16, 0);
81 dxil.insert(dxil.end(), {'X', 'D', 'A', 'T'});
82 put32(dxil, 1);
83 put32(dxil, 12);
84 put32(dxil, 0x0d);
85 put32(dxil, 16 + 12 + 12);
86 put32(dxil, std::uint32_t(xbch.size()));
87 dxil.insert(dxil.end(), xbch.begin(), xbch.end());
88 std::vector<std::uint8_t> out = {'D', 'X', 'B', 'C'};
89 out.resize(28, 0);
90 put32(out, 1);
91 put32(out, 36);
92 out.insert(out.end(), {'D', 'X', 'I', 'L'});
93 put32(out, std::uint32_t(dxil.size()));
94 out.insert(out.end(), dxil.begin(), dxil.end());
95 return out;
96}
97
98// runtime/test/shaders/compute_fixture.py's header for a compute shader without "; group:" or "; rsrc2:" lines:
99// 0x148 bytes, COMPUTE_PGM_RSRC2 0x8088 (four user SGPRs, TGID_X, 512 bytes of LDS) at 0x138 and a 64x1x1 group.
100std::vector<std::uint8_t> fixture_fssm() {
101 std::vector<std::uint8_t> fssm(0x138, 0);
102 for (const std::uint32_t v : {0x8088u, 64u, 1u, 1u}) put32(fssm, v);
103 return fssm;
104}
105
106std::vector<std::uint8_t> serialize(const D3D12_VERSIONED_ROOT_SIGNATURE_DESC& desc) {
107 const HMODULE d3d12 = LoadLibraryExA("d3d12.dll", nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32);
108 const auto fn = d3d12 ? reinterpret_cast<SerializeFn>(
109 reinterpret_cast<void*>(GetProcAddress(d3d12, "D3D12SerializeVersionedRootSignature")))
110 : nullptr;
111 std::vector<std::uint8_t> out;
112 ID3DBlob* blob = nullptr;
113 if (fn && SUCCEEDED(fn(&desc, &blob, nullptr)) && blob) {
114 const auto* p = static_cast<const std::uint8_t*>(blob->GetBufferPointer());
115 out.assign(p, p + blob->GetBufferSize());
116 blob->Release();
117 }
118 return out;
119}
120
121D3D12_RESOURCE_DESC buffer_desc(UINT64 bytes, D3D12_RESOURCE_FLAGS flags) {
122 D3D12_RESOURCE_DESC desc{};
123 desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;
124 desc.Width = bytes;
125 desc.Height = 1;
126 desc.DepthOrArraySize = 1;
127 desc.MipLevels = 1;
128 desc.SampleDesc.Count = 1;
129 desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
130 desc.Flags = flags;
131 return desc;
132}
133
134using Words = std::array<std::uint32_t, 8>;
135
136struct Shader {
137 const char* label;
138 const char* folder; // under LEONIDA_TEST_SUBGROUP_SHADERS; its spirv/ holds index.json and the module
139 Words expected;
140};
141
142constexpr Shader w64_native{"w64 native (cs_w64x_readlane)", "w64_native", {121, 121, 16, 97, 16, 100, 100, 121}};
143constexpr Shader w64_emulated{"w64 emulated (cs_w64x_readlane, --wave64-emulate)", "w64_emulated",
144 {121, 121, 16, 97, 16, 100, 100, 121}};
145constexpr Shader w32_native{"w32 native (cs_wqm_w32)", "w32_native", {12, 1, 4, 0, 8, 15728880, 4, 32}};
146
147struct Result {
148 int failure = 0; // a line number, 0 when the case ran
149 Words words{};
150 std::vector<leonida::SubgroupRequest> requests;
151};
152
153// One dispatch of the shader's PSO on a device created with `caps` as what the layer knows of the GPU.
154Result run(vktest::Device& d, const std::filesystem::path& library, const leonida::SubgroupSizeCaps& caps) {
155 Result result;
156 const auto fail = [&](int line) {
157 result.failure = line;
158 return result;
159 };
160#define CASE_EXPECT(condition) do { if (!(condition)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); return fail(__LINE__); } } while (0)
161
162 const auto fssm = fixture_fssm();
163 const auto container = shader_container(fssm);
164 CASE_EXPECT(leonida::fssm_program(container) == fssm);
165 {
166 leonida::ShaderLibrary index;
167 CASE_EXPECT(index.load(library.string()));
168 CASE_EXPECT(index.find("cs", leonida::sha256_hex(fssm))); // the translator's header is the fixture's
169 }
170
171 rt::d3d12::VulkanDeviceInfo info{};
172 info.get_instance_proc = d.instance_proc;
173 info.instance = d.instance;
174 info.physical = d.physical;
175 info.device = d.device;
176 info.queue = d.queue;
177 info.queue_family = d.family;
178 info.buffer_device_address = true;
179 info.shader_dir = library.string();
180 info.subgroup = caps;
181 ID3D12Device* inner = nullptr;
182 CASE_EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&inner))));
183 Ref<ID3D12Device> device;
184 CASE_EXPECT(SUCCEEDED(rt::d3d12_xs::create_device_proxy(inner, __uuidof(ID3D12Device),
185 reinterpret_cast<void**>(&device.p))));
186 rt::d3d12::set_device_outer(inner, device.p);
187
188 // Root signature: [0] four constants (s0..s3), the V# the shaders store through.
189 D3D12_ROOT_PARAMETER param{};
190 param.ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS;
191 param.Constants = {0, 0, 4};
192 D3D12_VERSIONED_ROOT_SIGNATURE_DESC root_desc{};
193 root_desc.Version = D3D_ROOT_SIGNATURE_VERSION_1_0;
194 root_desc.Desc_1_0 = {1, &param, 0, nullptr, D3D12_ROOT_SIGNATURE_FLAG_NONE};
195 const auto root_blob = serialize(root_desc);
196 CASE_EXPECT(!root_blob.empty());
197 Ref<ID3D12RootSignature> root;
198 CASE_EXPECT(SUCCEEDED(device->CreateRootSignature(0, root_blob.data(), root_blob.size(), IID_PPV_ARGS(&root.p))));
199
200 D3D12_COMPUTE_PIPELINE_STATE_DESC pso_desc{};
201 pso_desc.pRootSignature = root.p;
202 pso_desc.CS = {container.data(), container.size()};
203 const IID pso_iid = __uuidof(ID3D12PipelineState);
204 Ref<ID3D12PipelineState> pso;
205 CASE_EXPECT(SUCCEEDED(reinterpret_cast<XboxComputePipelineFn>(slot(device.p, 62))(
206 device.p, &pso_desc, 0, 0, &pso_iid, reinterpret_cast<void**>(&pso.p))));
207 const auto* requests = rt::d3d12::pipeline_subgroup_requests(pso.p);
208 CASE_EXPECT(requests && requests->size() == 1);
209 result.requests = *requests;
210
211 constexpr UINT bytes = 256;
212 const D3D12_HEAP_PROPERTIES default_heap{D3D12_HEAP_TYPE_DEFAULT};
213 const D3D12_HEAP_PROPERTIES readback_heap{D3D12_HEAP_TYPE_READBACK};
214 Ref<ID3D12Resource> out, readback;
215 const auto uav = buffer_desc(bytes, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS);
216 CASE_EXPECT(SUCCEEDED(device->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &uav,
217 D3D12_RESOURCE_STATE_UNORDERED_ACCESS, nullptr,
218 IID_PPV_ARGS(&out.p))));
219 const auto readback_desc = buffer_desc(bytes, D3D12_RESOURCE_FLAG_NONE);
220 CASE_EXPECT(SUCCEEDED(device->CreateCommittedResource(&readback_heap, D3D12_HEAP_FLAG_NONE, &readback_desc,
221 D3D12_RESOURCE_STATE_COPY_DEST, nullptr,
222 IID_PPV_ARGS(&readback.p))));
223 const D3D12_GPU_VIRTUAL_ADDRESS va = out->GetGPUVirtualAddress();
224 CASE_EXPECT(va >= 0x10000 && va < (1ull << 32));
225
226 D3D12_COMMAND_QUEUE_DESC queue_desc{};
227 Ref<ID3D12CommandQueue> queue;
228 Ref<ID3D12CommandAllocator> allocator;
229 Ref<ID3D12GraphicsCommandList> list;
230 Ref<ID3D12Fence> fence;
231 CASE_EXPECT(SUCCEEDED(device->CreateCommandQueue(&queue_desc, IID_PPV_ARGS(&queue.p))));
232 CASE_EXPECT(SUCCEEDED(device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator.p))));
233 CASE_EXPECT(SUCCEEDED(device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocator.p, pso.p,
234 IID_PPV_ARGS(&list.p))));
235 CASE_EXPECT(SUCCEEDED(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence.p))));
236
237 // The V# the shaders read from s[0:3]: base = the buffer's console VA (the shader adds the heap base), stride 0,
238 // num_records unlimited, OOB_SELECT 3 (raw: a stride of 0 is a bounds check in the other modes).
239 list->SetComputeRootSignature(root.p);
240 const std::uint32_t vsharp[4] = {std::uint32_t(va), std::uint32_t(va >> 32) & 0xffff, 0xffffffffu, 0x31016FACu};
241 list->SetComputeRoot32BitConstants(0, 4, vsharp, 0);
242 list->Dispatch(1, 1, 1);
243 D3D12_RESOURCE_BARRIER barrier{};
244 barrier.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;
245 barrier.Transition = {out.p, D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, D3D12_RESOURCE_STATE_UNORDERED_ACCESS,
246 D3D12_RESOURCE_STATE_COPY_SOURCE};
247 list->ResourceBarrier(1, &barrier);
248 list->CopyBufferRegion(readback.p, 0, out.p, 0, bytes);
249 CASE_EXPECT(list->Close() == S_OK);
250 ID3D12CommandList* lists[] = {list.p};
251 queue->ExecuteCommandLists(1, lists);
252 CASE_EXPECT(rt::d3d12::last_execute_result(queue.p) == leonida::ReplayResult::success);
253 CASE_EXPECT(SUCCEEDED(queue->Signal(fence.p, 1)));
254 CASE_EXPECT(SUCCEEDED(fence->SetEventOnCompletion(1, nullptr)));
255 void* mapped = nullptr;
256 CASE_EXPECT(SUCCEEDED(readback->Map(0, nullptr, &mapped)));
257 std::memcpy(result.words.data(), mapped, sizeof(result.words));
258
259 for (auto* r : {&out, &readback}) r->reset();
260 pso.reset();
261 root.reset();
262 list.reset();
263 allocator.reset();
264 queue.reset();
265 fence.reset();
266 CASE_EXPECT(rt::d3d12_xs::device_proxy_ref_count(device.p) == 1);
267#undef CASE_EXPECT
268 return result;
269}
270
271std::string words_text(const Words& w) {
272 std::string s;
273 for (const std::uint32_t v : w) s += (s.empty() ? "" : " ") + std::to_string(v);
274 return s;
275}
276
277// What the decision function says about the shader's own index entry on this device.
278leonida::SubgroupRequest expected_request(const Shader& shader, const leonida::SubgroupSizeCaps& caps) {
279 leonida::ShaderLibrary index;
280 const auto dir = std::filesystem::path(LEONIDA_TEST_SUBGROUP_SHADERS) / shader.folder / "spirv";
281 if (!index.load(dir.string())) return {};
282 const auto* entry = index.find("cs", leonida::sha256_hex(fixture_fssm()));
283 return entry ? leonida::decide_subgroup_size(*entry, caps) : leonida::SubgroupRequest{};
284}
285
286std::filesystem::path shader_dir(const Shader& shader) {
287 return std::filesystem::path(LEONIDA_TEST_SUBGROUP_SHADERS) / shader.folder / "spirv";
288}
289
290// ---- Probe shaders (GLSL, test/glsl) and the graphics path -----------------------------------------------------------
291// What the translator would write into an index entry for a shader of each kind.
292struct Mode {
293 const char* label;
294 bool wave64;
295 std::uint32_t size; // subgroup_size
296 bool emulated; // --wave64-emulate: subgroup_size null, wave64_exchange "workgroup"
297};
298constexpr Mode mode_w64{"wave64, subgroup_size 64", true, 64, false};
299constexpr Mode mode_w32{"wave32, subgroup_size 32", false, 32, false};
300constexpr Mode mode_emulated{"emulated (wave64_exchange)", true, 0, true};
301
302std::string mode_json(const Mode& m) {
303 std::string s = std::string("\"wave64\": ") + (m.wave64 ? "true" : "false") + ", \"subgroup_size\": " +
304 (m.emulated ? std::string("null") : std::to_string(m.size));
305 if (m.emulated) s += ", \"wave64_exchange\": \"workgroup\"";
306 return s;
307}
308
309struct LibraryEntry {
310 std::string name, stage, tail; // tail: the rest of the index entry's members
311 std::filesystem::path spv;
312};
313
314// A translator-style folder with the entries' modules, every entry keyed by the fixture program's hash.
315std::filesystem::path make_library(const std::string& tag, const std::vector<LibraryEntry>& entries) {
316 const auto dir = std::filesystem::temp_directory_path() / ("leonida_subgroup_" + tag);
317 std::filesystem::remove_all(dir);
318 std::filesystem::create_directories(dir);
319 std::ofstream index(dir / "index.json", std::ios::binary);
320 index << "{";
321 bool first = true;
322 for (const LibraryEntry& e : entries) {
323 std::filesystem::copy_file(e.spv, dir / (e.name + ".spv"), std::filesystem::copy_options::overwrite_existing);
324 index << (first ? "" : ",\n") << "\"" << e.name << "\": {\"stage\": \"" << e.stage << "\", \"fssm_sha256\": \""
325 << leonida::sha256_hex(fixture_fssm()) << "\", \"bindings\": [], \"push_constant_bytes\": 144, "
326 << e.tail << "}";
327 first = false;
328 }
329 index << "}";
330 return dir;
331}
332
333std::filesystem::path glsl_spv(const char* name) {
334 return std::filesystem::path(LEONIDA_TEST_SUBGROUP_SHADERS) / "glsl" / (std::string(name) + ".spv");
335}
336
337// The compute probe: a library with cs_sg_probe in the given mode.
338std::filesystem::path compute_probe_library(const Mode& mode) {
339 return make_library("cs_probe", {{"cs_sg_probe", "cs",
340 "\"local_size\": [64, 1, 1], \"uses_code_base\": false, " + mode_json(mode),
341 glsl_spv("cs_sg_probe.comp")}});
342}
343
344constexpr UINT draw_size = 64;
345using Pixel = std::array<std::uint32_t, 4>;
346
347struct DrawResult {
348 int failure = 0;
349 std::vector<Pixel> pixels; // draw_size * draw_size
350 std::vector<leonida::SubgroupRequest> requests; // vertex, pixel
351};
352
353// One draw of a full-viewport triangle through a graphics PSO whose VS is vs_fullscreen and whose PS is `ps` of the
354// library, into a 64x64 R32G32B32A32_FLOAT target that is read back as bit patterns.
355DrawResult draw(vktest::Device& d, const std::filesystem::path& library, const leonida::SubgroupSizeCaps& caps) {
356 DrawResult result;
357 const auto fail = [&](int line) {
358 result.failure = line;
359 return result;
360 };
361#define CASE_EXPECT(condition) do { if (!(condition)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); return fail(__LINE__); } } while (0)
362 const auto container = shader_container(fixture_fssm());
363
364 rt::d3d12::VulkanDeviceInfo info{};
365 info.get_instance_proc = d.instance_proc;
366 info.instance = d.instance;
367 info.physical = d.physical;
368 info.device = d.device;
369 info.queue = d.queue;
370 info.queue_family = d.family;
371 info.buffer_device_address = true;
372 info.shader_dir = library.string();
373 info.subgroup = caps;
374 ID3D12Device* inner = nullptr;
375 CASE_EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&inner))));
376 Ref<ID3D12Device> device;
377 CASE_EXPECT(SUCCEEDED(rt::d3d12_xs::create_device_proxy(inner, __uuidof(ID3D12Device),
378 reinterpret_cast<void**>(&device.p))));
379 rt::d3d12::set_device_outer(inner, device.p);
380
381 D3D12_VERSIONED_ROOT_SIGNATURE_DESC root_desc{};
382 root_desc.Version = D3D_ROOT_SIGNATURE_VERSION_1_0;
383 root_desc.Desc_1_0 = {0, nullptr, 0, nullptr, D3D12_ROOT_SIGNATURE_FLAG_NONE};
384 const auto root_blob = serialize(root_desc);
385 CASE_EXPECT(!root_blob.empty());
386 Ref<ID3D12RootSignature> root;
387 CASE_EXPECT(SUCCEEDED(device->CreateRootSignature(0, root_blob.data(), root_blob.size(), IID_PPV_ARGS(&root.p))));
388
389 D3D12_GRAPHICS_PIPELINE_STATE_DESC pso_desc{};
390 pso_desc.pRootSignature = root.p;
391 pso_desc.VS = {container.data(), container.size()};
392 pso_desc.PS = {container.data(), container.size()};
393 pso_desc.BlendState.RenderTarget[0].RenderTargetWriteMask = D3D12_COLOR_WRITE_ENABLE_ALL;
394 pso_desc.SampleMask = 0xffffffff;
395 pso_desc.RasterizerState.FillMode = D3D12_FILL_MODE_SOLID;
396 pso_desc.RasterizerState.CullMode = D3D12_CULL_MODE_NONE;
397 pso_desc.RasterizerState.DepthClipEnable = TRUE;
398 pso_desc.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE;
399 pso_desc.NumRenderTargets = 1;
400 pso_desc.RTVFormats[0] = DXGI_FORMAT_R32G32B32A32_FLOAT;
401 pso_desc.SampleDesc.Count = 1;
402 Ref<ID3D12PipelineState> pso;
403 CASE_EXPECT(SUCCEEDED(device->CreateGraphicsPipelineState(&pso_desc, IID_PPV_ARGS(&pso.p))));
404 const auto* requests = rt::d3d12::pipeline_subgroup_requests(pso.p);
405 CASE_EXPECT(requests && requests->size() == 2);
406 result.requests = *requests;
407
408 const D3D12_HEAP_PROPERTIES default_heap{D3D12_HEAP_TYPE_DEFAULT};
409 const D3D12_HEAP_PROPERTIES readback_heap{D3D12_HEAP_TYPE_READBACK};
410 constexpr UINT pitch = draw_size * 16;
411 Ref<ID3D12Resource> readback, target;
412 const auto readback_desc = buffer_desc(pitch * draw_size, D3D12_RESOURCE_FLAG_NONE);
413 CASE_EXPECT(SUCCEEDED(device->CreateCommittedResource(&readback_heap, D3D12_HEAP_FLAG_NONE, &readback_desc,
414 D3D12_RESOURCE_STATE_COPY_DEST, nullptr,
415 IID_PPV_ARGS(&readback.p))));
416 D3D12_RESOURCE_DESC rt_desc{};
417 rt_desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D;
418 rt_desc.Width = rt_desc.Height = draw_size;
419 rt_desc.DepthOrArraySize = 1;
420 rt_desc.MipLevels = 1;
421 rt_desc.Format = DXGI_FORMAT_R32G32B32A32_FLOAT;
422 rt_desc.SampleDesc.Count = 1;
423 rt_desc.Flags = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET;
424 CASE_EXPECT(SUCCEEDED(device->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &rt_desc,
425 D3D12_RESOURCE_STATE_COMMON, nullptr,
426 IID_PPV_ARGS(&target.p))));
427 const D3D12_DESCRIPTOR_HEAP_DESC heap_desc{D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 1, D3D12_DESCRIPTOR_HEAP_FLAG_NONE, 0};
428 Ref<ID3D12DescriptorHeap> rtv_heap;
429 CASE_EXPECT(SUCCEEDED(device->CreateDescriptorHeap(&heap_desc, IID_PPV_ARGS(&rtv_heap.p))));
430 const D3D12_CPU_DESCRIPTOR_HANDLE rtv{SIZE_T(reinterpret_cast<XboxHeapHandleFn>(slot(rtv_heap.p, 9))(rtv_heap.p))};
431 device->CreateRenderTargetView(target.p, nullptr, rtv);
432
433 D3D12_COMMAND_QUEUE_DESC queue_desc{};
434 Ref<ID3D12CommandQueue> queue;
435 Ref<ID3D12CommandAllocator> allocator;
436 Ref<ID3D12GraphicsCommandList> list;
437 Ref<ID3D12Fence> fence;
438 CASE_EXPECT(SUCCEEDED(device->CreateCommandQueue(&queue_desc, IID_PPV_ARGS(&queue.p))));
439 CASE_EXPECT(SUCCEEDED(device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator.p))));
440 CASE_EXPECT(SUCCEEDED(device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocator.p, pso.p,
441 IID_PPV_ARGS(&list.p))));
442 CASE_EXPECT(SUCCEEDED(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence.p))));
443
444 D3D12_RESOURCE_BARRIER to_target{};
445 to_target.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;
446 to_target.Transition = {target.p, D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, D3D12_RESOURCE_STATE_COMMON,
447 D3D12_RESOURCE_STATE_RENDER_TARGET};
448 list->ResourceBarrier(1, &to_target);
449 const FLOAT zero[4] = {0, 0, 0, 0};
450 list->ClearRenderTargetView(rtv, zero, 0, nullptr);
451 list->SetGraphicsRootSignature(root.p);
452 list->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
453 const D3D12_VIEWPORT viewport{0, 0, float(draw_size), float(draw_size), 0, 1};
454 const D3D12_RECT scissor{0, 0, LONG(draw_size), LONG(draw_size)};
455 list->RSSetViewports(1, &viewport);
456 list->RSSetScissorRects(1, &scissor);
457 list->OMSetRenderTargets(1, &rtv, FALSE, nullptr);
458 list->DrawInstanced(3, 1, 0, 0);
459 D3D12_RESOURCE_BARRIER to_copy{};
460 to_copy.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;
461 to_copy.Transition = {target.p, D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, D3D12_RESOURCE_STATE_RENDER_TARGET,
462 D3D12_RESOURCE_STATE_COPY_SOURCE};
463 list->ResourceBarrier(1, &to_copy);
464 D3D12_TEXTURE_COPY_LOCATION dst{};
465 dst.pResource = readback.p;
466 dst.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT;
467 dst.PlacedFootprint = {0, {DXGI_FORMAT_R32G32B32A32_FLOAT, draw_size, draw_size, 1, pitch}};
468 D3D12_TEXTURE_COPY_LOCATION src{};
469 src.pResource = target.p;
470 src.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX;
471 list->CopyTextureRegion(&dst, 0, 0, 0, &src, nullptr);
472 CASE_EXPECT(list->Close() == S_OK);
473 ID3D12CommandList* lists[] = {list.p};
474 queue->ExecuteCommandLists(1, lists);
475 CASE_EXPECT(rt::d3d12::last_execute_result(queue.p) == leonida::ReplayResult::success);
476 CASE_EXPECT(SUCCEEDED(queue->Signal(fence.p, 1)));
477 CASE_EXPECT(SUCCEEDED(fence->SetEventOnCompletion(1, nullptr)));
478 void* mapped = nullptr;
479 CASE_EXPECT(SUCCEEDED(readback->Map(0, nullptr, &mapped)));
480 result.pixels.resize(draw_size * draw_size);
481 std::memcpy(result.pixels.data(), mapped, result.pixels.size() * sizeof(Pixel));
482
483 for (auto* r : {&readback, &target}) r->reset();
484 pso.reset();
485 root.reset();
486 rtv_heap.reset();
487 list.reset();
488 allocator.reset();
489 queue.reset();
490 fence.reset();
491 CASE_EXPECT(rt::d3d12_xs::device_proxy_ref_count(device.p) == 1);
492#undef CASE_EXPECT
493 return result;
494}
495
496// The vertex shader of every draw. It is marked emulated so that it asks for nothing: only the pixel stage is under test.
497LibraryEntry fullscreen_vs() {
498 return {"vs_fullscreen", "vs", "\"input_signature\": [], " + mode_json(mode_emulated), glsl_spv("vs_sg_fullscreen.vert")};
499}
500
501LibraryEntry ps_probe(const Mode& mode) {
502 return {"ps_sg_probe", "ps", "\"outputs\": [0], " + mode_json(mode), glsl_spv("ps_sg_probe.frag")};
503}
504
505// The wave64 pixel shader with readlane across both halves, translated by the build (test/shaders/ps_w64x_readlane.asm).
506LibraryEntry ps_readlane(const Mode& mode) {
507 return {"ps_w64x_readlane", "ps", "\"outputs\": [0], " + mode_json(mode),
508 std::filesystem::path(LEONIDA_TEST_SUBGROUP_SHADERS) / "ps_w64_native" / "spirv" / "ps_w64x_readlane.spv"};
509}
510
511// The subgroup size a probe pixel reports, or 0 when the pixels disagree or do not look like a probe's.
512std::uint32_t probed_size(const std::vector<Pixel>& pixels) {
513 std::uint32_t size = 0;
514 for (const Pixel& p : pixels) {
515 if ((p[0] & 0xffff0000u) != 0x40000000u) return 0;
516 const std::uint32_t s = p[0] & 0xffff;
517 if (size && s != size) return 0;
518 size = s;
519 }
520 return size;
521}
522
523const Pixel readlane_expected = {0x40000079u, 0x40000010u, 0x40000064u, 0x400000beu};
524
525} // namespace
526
527int main() {
528 vktest::Device d;
529 const auto device_status = d.initialize();
530 if (device_status == vktest::DeviceStatus::unavailable) return 77; // no Vulkan GPU: ctest skips
531 if (device_status != vktest::DeviceStatus::ready) return 1;
532 const leonida::SubgroupSizeCaps& caps = d.subgroup;
533 leonida::SubgroupSizeCaps off = caps; // the control: the layer knows nothing of the device's sizes
534 off.min_size = off.max_size = off.default_size = 0;
535 off.subgroup_size_control = off.compute_full_subgroups = false;
536 off.required_stages = 0;
537
538 unsigned judged = 0;
539 for (const Shader* shader : {&w64_native, &w64_emulated, &w32_native}) {
540 const leonida::SubgroupRequest want = expected_request(*shader, caps);
541 const Result result = run(d, shader_dir(*shader), caps);
542 EXPECT(!result.failure);
543 EXPECT(result.requests.size() == 1);
544 const leonida::SubgroupRequest& got = result.requests[0];
545 // The PSO asked for what the decision function says.
546 EXPECT(got.outcome == want.outcome && got.size == want.size && got.flags == want.flags);
547 EXPECT(got.stage == VK_SHADER_STAGE_COMPUTE_BIT);
548
549 const bool exact = result.words == shader->expected;
550 std::printf("%s: outcome %d, required size %u, full subgroups %s; result %s (%s)\n", shader->label,
551 int(got.outcome), got.size, got.flags ? "yes" : "no", exact ? "exact" : "DIFFERS",
552 words_text(result.words).c_str());
553 if (shader == &w64_native && got.outcome == leonida::SubgroupOutcome::unavailable) {
554 // This GPU cannot give a wave64 compute shader 64 lanes. The layer said so (a log line, above); the
555 // build for this GPU should have used --wave64-emulate, which the next case checks.
556 std::printf(" this device has no 64-wide compute subgroup (sizes %u..%u): native wave64 not judged\n",
557 caps.min_size, caps.max_size);
558 } else {
559 if (!exact) std::fprintf(stderr, "%s: wanted %s\n", shader->label, words_text(shader->expected).c_str());
560 EXPECT(exact);
561 ++judged;
562 }
563 if (shader == &w64_native && got.outcome != leonida::SubgroupOutcome::unavailable) {
564 EXPECT(got.outcome != leonida::SubgroupOutcome::unknown_device);
565 EXPECT(got.outcome == leonida::SubgroupOutcome::required || got.outcome == leonida::SubgroupOutcome::device_fixed ||
566 got.outcome == leonida::SubgroupOutcome::device_default);
567 if (got.outcome == leonida::SubgroupOutcome::required) {
568 EXPECT(got.size == 64);
569 EXPECT(!caps.compute_full_subgroups ||
570 got.flags == VK_PIPELINE_SHADER_STAGE_CREATE_REQUIRE_FULL_SUBGROUPS_BIT);
571 }
572 }
573 if (shader == &w64_emulated) EXPECT(got.outcome == leonida::SubgroupOutcome::emulated && !got.size && !got.flags);
574
575 // Control, not judged: the same PSO with no size asked for.
576 if (shader != &w64_emulated) {
577 const Result control = run(d, shader_dir(*shader), off);
578 EXPECT(!control.failure);
579 std::printf(" control, nothing requested: %s (%s)\n", control.words == shader->expected ? "exact" : "differs",
580 words_text(control.words).c_str());
581 }
582 }
583 // --- The driver's choice, observed: probe shaders that store gl_SubgroupSize ------------------------------------
584 const auto exact_outcome = [](leonida::SubgroupOutcome o) {
585 return o == leonida::SubgroupOutcome::required || o == leonida::SubgroupOutcome::device_fixed;
586 };
587 for (const Mode* mode : {&mode_w64, &mode_w32, &mode_emulated}) {
588 const auto library = compute_probe_library(*mode);
589 const Result r = run(d, library, caps);
590 EXPECT(!r.failure && r.requests.size() == 1);
591 const leonida::SubgroupRequest& req = r.requests[0];
592 const std::uint32_t seen = r.words[0];
593 std::printf("compute probe, %s: outcome %d (asked %u), the driver ran it %u-wide\n", mode->label,
594 int(req.outcome), req.size, seen);
595 if (exact_outcome(req.outcome)) EXPECT(seen == req.wanted); // the size the PSO asked for is the size it got
596 const Result control = run(d, library, off);
597 EXPECT(!control.failure);
598 std::printf(" control, nothing requested: %u-wide (device default %u)\n", control.words[0], caps.default_size);
599 // The request matters: a wave32 shader on a device whose default is not 32 runs at the default without it.
600 if (mode == &mode_w32 && req.outcome == leonida::SubgroupOutcome::required && caps.default_size != 32)
601 EXPECT(control.words[0] != 32);
602 std::filesystem::remove_all(library);
603 }
604
605 std::uint32_t fragment_default = 0;
606 {
607 const auto library = make_library("ps_probe", {fullscreen_vs(), ps_probe(mode_w32)});
608 const DrawResult control = draw(d, library, off);
609 EXPECT(!control.failure);
610 fragment_default = probed_size(control.pixels);
611 EXPECT(fragment_default);
612 std::printf("pixel probe, nothing requested: the driver runs pixel shaders %u-wide\n", fragment_default);
613 std::filesystem::remove_all(library);
614 }
615 for (const Mode* mode : {&mode_w64, &mode_w32, &mode_emulated}) {
616 const auto library = make_library("ps_probe", {fullscreen_vs(), ps_probe(*mode)});
617 const DrawResult r = draw(d, library, caps);
618 EXPECT(!r.failure && r.requests.size() == 2);
619 const leonida::SubgroupRequest& vs_req = r.requests[0];
620 const leonida::SubgroupRequest& req = r.requests[1];
621 EXPECT(vs_req.outcome == leonida::SubgroupOutcome::emulated && vs_req.stage == VK_SHADER_STAGE_VERTEX_BIT);
622 EXPECT(req.stage == VK_SHADER_STAGE_FRAGMENT_BIT);
623 const std::uint32_t seen = probed_size(r.pixels);
624 EXPECT(seen);
625 std::printf("pixel probe, %s: outcome %d (asked %u), the driver ran it %u-wide\n", mode->label,
626 int(req.outcome), req.size, seen);
627 if (exact_outcome(req.outcome)) EXPECT(seen == req.wanted);
628 if (req.outcome == leonida::SubgroupOutcome::required && fragment_default != req.wanted)
629 std::printf(" the request changes it: %u-wide without, %u-wide with\n", fragment_default, seen);
630 std::filesystem::remove_all(library);
631 }
632
633 // --- A wave64 pixel shader with a cross-half v_readlane, through a graphics PSO ---------------------------------
634 {
635 const auto library = make_library("ps_readlane", {fullscreen_vs(), ps_readlane(mode_w64)});
636 const auto count_exact = [](const std::vector<Pixel>& pixels) {
637 std::size_t n = 0;
638 for (const Pixel& p : pixels) n += p == readlane_expected;
639 return n;
640 };
641 const DrawResult r = draw(d, library, caps);
642 EXPECT(!r.failure && r.requests.size() == 2);
643 const leonida::SubgroupRequest& req = r.requests[1];
644 const std::size_t exact = count_exact(r.pixels), total = r.pixels.size();
645 std::printf("wave64 pixel shader (ps_w64x_readlane): outcome %d, required size %u; %zu of %zu pixels exact\n",
646 int(req.outcome), req.size, exact, total);
647 if (exact_outcome(req.outcome)) {
648 if (exact != total)
649 std::fprintf(stderr, "first pixel %08x %08x %08x %08x\n", r.pixels[0][0], r.pixels[0][1],
650 r.pixels[0][2], r.pixels[0][3]);
651 EXPECT(exact == total);
652 ++judged;
653 } else {
654 std::printf(" this device cannot require 64 for a wave64 pixel shader: not judged\n");
655 }
656 const DrawResult control = draw(d, library, off);
657 EXPECT(!control.failure);
658 const std::size_t control_exact = count_exact(control.pixels);
659 std::printf(" control, nothing requested (pixel shaders run %u-wide): %zu of %zu pixels exact\n",
660 fragment_default, control_exact, total);
661 // Where the default is not 64, the shader crosses halves that are not there: the request must matter.
662 if (req.outcome == leonida::SubgroupOutcome::required && fragment_default != 64) EXPECT(control_exact < total);
663 std::filesystem::remove_all(library);
664 }
665 if (d.validation_errors()) {
666 std::fprintf(stderr, "%u validation errors\n", d.validation_errors());
667 return 1;
668 }
669 std::printf("subgroup size: %u shaders judged exact through the layer's PSOs (sizes %u..%u, default %u)\n",
670 judged, caps.min_size, caps.max_size, caps.default_size);
671 return 0;
672}
diff --git a/runtime/test/d3d12_vulkan_device_test.cpp b/runtime/test/d3d12_vulkan_device_test.cpp
index 1eb25adf1..a528202bc 100644
--- a/runtime/test/d3d12_vulkan_device_test.cpp
+++ b/runtime/test/d3d12_vulkan_device_test.cpp
@@ -324,8 +324,8 @@ int cpu_copies(ID3D12Device* device, bool bc, const char* path) {
324 return 0; 324 return 0;
325} 325}
326 326
327// The host PC runtime's D3D12 device to compare answers with: the default adapter, or the one LEONIDA_HOST_ADAPTER 327// The host PC runtime's D3D12 device to compare answers with: the layer's own adapter (set in main), else the default
328// names ("warp", or part of an adapter's name); false if there is none. 328// one, or the one LEONIDA_HOST_ADAPTER names ("warp", or part of an adapter's name); false if there is none.
329// Under Wine there is none (copycmp::create_host). 329// Under Wine there is none (copycmp::create_host).
330bool create_host_device(Ref<ID3D12Device>& host, std::string* adapter_name = nullptr) { 330bool create_host_device(Ref<ID3D12Device>& host, std::string* adapter_name = nullptr) {
331 copycmp::Ptr<ID3D12Device> device; 331 copycmp::Ptr<ID3D12Device> device;
@@ -506,6 +506,9 @@ int compare_footprints(ID3D12Device* ours) {
506 {texture_desc(13, 7, DXGI_FORMAT_B5G5R5A1_UNORM, D3D12_RESOURCE_FLAG_NONE, 4, 2), 8}, 506 {texture_desc(13, 7, DXGI_FORMAT_B5G5R5A1_UNORM, D3D12_RESOURCE_FLAG_NONE, 4, 2), 8},
507 {texture_desc(13, 7, DXGI_FORMAT_A8_UNORM, D3D12_RESOURCE_FLAG_NONE, 4, 2), 8}, 507 {texture_desc(13, 7, DXGI_FORMAT_A8_UNORM, D3D12_RESOURCE_FLAG_NONE, 4, 2), 8},
508 {texture_desc(13, 7, DXGI_FORMAT_R16G16B16A16_FLOAT, D3D12_RESOURCE_FLAG_NONE, 4), 4}, 508 {texture_desc(13, 7, DXGI_FORMAT_R16G16B16A16_FLOAT, D3D12_RESOURCE_FLAG_NONE, 4), 4},
509 {texture_desc(13, 7, DXGI_FORMAT_B8G8R8X8_UNORM, D3D12_RESOURCE_FLAG_NONE, 4, 2), 8},
510 {texture_desc(13, 7, DXGI_FORMAT_B8G8R8X8_UNORM_SRGB, D3D12_RESOURCE_FLAG_NONE, 4), 4},
511 {texture_desc(16, 16, DXGI_FORMAT_B8G8R8X8_TYPELESS, D3D12_RESOURCE_FLAG_NONE, 3), 3},
509 {texture_desc(10, 6, DXGI_FORMAT_BC1_UNORM, D3D12_RESOURCE_FLAG_NONE, 4), 4}, 512 {texture_desc(10, 6, DXGI_FORMAT_BC1_UNORM, D3D12_RESOURCE_FLAG_NONE, 4), 4},
510 {texture_desc(4, 4, DXGI_FORMAT_BC7_UNORM_SRGB, D3D12_RESOURCE_FLAG_NONE, 1, 3), 3}, 513 {texture_desc(4, 4, DXGI_FORMAT_BC7_UNORM_SRGB, D3D12_RESOURCE_FLAG_NONE, 1, 3), 3},
511 {texture_desc(16, 16, DXGI_FORMAT_BC5_UNORM, D3D12_RESOURCE_FLAG_NONE, 5), 5}, 514 {texture_desc(16, 16, DXGI_FORMAT_BC5_UNORM, D3D12_RESOURCE_FLAG_NONE, 5), 5},
@@ -694,6 +697,97 @@ int compare_allocation_info(ID3D12Device* ours) {
694 {"16x16 R8G8_TYPELESS", texture_desc(16, 16, DXGI_FORMAT_R8G8_TYPELESS, none, 1), 16 * 16 * 2}, 697 {"16x16 R8G8_TYPELESS", texture_desc(16, 16, DXGI_FORMAT_R8G8_TYPELESS, none, 1), 16 * 16 * 2},
695 {"16x16 R8G8_UINT", texture_desc(16, 16, DXGI_FORMAT_R8G8_UINT, none, 1), 16 * 16 * 2}, 698 {"16x16 R8G8_UINT", texture_desc(16, 16, DXGI_FORMAT_R8G8_UINT, none, 1), 16 * 16 * 2},
696 {"16x16 R8G8_SINT", texture_desc(16, 16, DXGI_FORMAT_R8G8_SINT, none, 1), 16 * 16 * 2}, 699 {"16x16 R8G8_SINT", texture_desc(16, 16, DXGI_FORMAT_R8G8_SINT, none, 1), 16 * 16 * 2},
700 // Tiled (64KB_UNDEFINED_SWIZZLE) textures: 64 KiB alignment and tile-multiple size; 1D, buffers, 4 KiB
701 // alignment, untileable 96-bit and two-plane depth-stencil formats are invalid.
702 {"tiled 2D 256x256", [&] {
703 D3D12_RESOURCE_DESC d = texture_desc(256, 256, rgba8, none, 1);
704 d.Layout = D3D12_TEXTURE_LAYOUT_64KB_UNDEFINED_SWIZZLE;
705 return d;
706 }(), 256 * 256 * 4},
707 {"tiled 2D D32F 256x256", [&] {
708 D3D12_RESOURCE_DESC d = texture_desc(256, 256, DXGI_FORMAT_D32_FLOAT,
709 D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL, 1);
710 d.Layout = D3D12_TEXTURE_LAYOUT_64KB_UNDEFINED_SWIZZLE;
711 return d;
712 }(), 256 * 256 * 4},
713 {"tiled 3D 64x64x64", [&] {
714 D3D12_RESOURCE_DESC d = small_volume(64, 64, 64, rgba8);
715 d.Alignment = 0;
716 d.Layout = D3D12_TEXTURE_LAYOUT_64KB_UNDEFINED_SWIZZLE;
717 return d;
718 }(), 64 * 64 * 64 * 4},
719 {"tiled buffer (invalid)", [&] {
720 D3D12_RESOURCE_DESC d = buffer_desc(4096);
721 d.Layout = D3D12_TEXTURE_LAYOUT_64KB_UNDEFINED_SWIZZLE;
722 return d;
723 }(), 0},
724 {"tiled 1D (invalid)", [&] {
725 D3D12_RESOURCE_DESC d = line_desc(256, 1, 1, rgba8);
726 d.Layout = D3D12_TEXTURE_LAYOUT_64KB_UNDEFINED_SWIZZLE;
727 return d;
728 }(), 0},
729 {"tiled 2D 4K alignment (invalid)", [&] {
730 D3D12_RESOURCE_DESC d = with(texture_desc(16, 16, rgba8, none, 1), k4);
731 d.Layout = D3D12_TEXTURE_LAYOUT_64KB_UNDEFINED_SWIZZLE;
732 return d;
733 }(), 0},
734 {"tiled 2D RGB32F (invalid)", [&] {
735 D3D12_RESOURCE_DESC d = texture_desc(64, 64, DXGI_FORMAT_R32G32B32_FLOAT, none, 1);
736 d.Layout = D3D12_TEXTURE_LAYOUT_64KB_UNDEFINED_SWIZZLE;
737 return d;
738 }(), 0},
739 {"tiled 2D D24S8 (invalid)", [&] {
740 D3D12_RESOURCE_DESC d = texture_desc(64, 64, DXGI_FORMAT_D24_UNORM_S8_UINT,
741 D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL, 1);
742 d.Layout = D3D12_TEXTURE_LAYOUT_64KB_UNDEFINED_SWIZZLE;
743 return d;
744 }(), 0},
745 {"tiled 2D 4x MSAA RGBA8", [&] {
746 D3D12_RESOURCE_DESC d = with(texture_desc(256, 256, rgba8, rt, 1), 0, 4);
747 d.Layout = D3D12_TEXTURE_LAYOUT_64KB_UNDEFINED_SWIZZLE;
748 return d;
749 }(), 256 * 256 * 4 * 4},
750 {"tiled 2D 4x MSAA RGBA32F", [&] {
751 D3D12_RESOURCE_DESC d = with(texture_desc(256, 256, DXGI_FORMAT_R32G32B32A32_FLOAT, rt, 1), 0, 4);
752 d.Layout = D3D12_TEXTURE_LAYOUT_64KB_UNDEFINED_SWIZZLE;
753 return d;
754 }(), 256 * 256 * 16 * 4},
755 {"tiled 2D 4x MSAA D32F", [&] {
756 D3D12_RESOURCE_DESC d = with(texture_desc(256, 256, DXGI_FORMAT_D32_FLOAT,
757 D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL, 1), 0, 4);
758 d.Layout = D3D12_TEXTURE_LAYOUT_64KB_UNDEFINED_SWIZZLE;
759 return d;
760 }(), 256 * 256 * 4 * 4},
761 {"tiled 2D 2x MSAA (invalid)", [&] {
762 D3D12_RESOURCE_DESC d = with(texture_desc(256, 256, rgba8, rt, 1), 0, 2);
763 d.Layout = D3D12_TEXTURE_LAYOUT_64KB_UNDEFINED_SWIZZLE;
764 return d;
765 }(), 0},
766 {"tiled 2D 8x MSAA (invalid)", [&] {
767 D3D12_RESOURCE_DESC d = with(texture_desc(256, 256, rgba8, rt, 1), 0, 8);
768 d.Layout = D3D12_TEXTURE_LAYOUT_64KB_UNDEFINED_SWIZZLE;
769 return d;
770 }(), 0},
771 {"tiled 2D 4x MSAA NONE (invalid)", [&] {
772 D3D12_RESOURCE_DESC d = with(texture_desc(256, 256, rgba8, none, 1), 0, 4);
773 d.Layout = D3D12_TEXTURE_LAYOUT_64KB_UNDEFINED_SWIZZLE;
774 return d;
775 }(), 0},
776 {"tiled 2D 4x MSAA RT+DS (invalid)", [&] {
777 D3D12_RESOURCE_DESC d = with(texture_desc(256, 256, rgba8,
778 rt | D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL, 1), 0, 4);
779 d.Layout = D3D12_TEXTURE_LAYOUT_64KB_UNDEFINED_SWIZZLE;
780 return d;
781 }(), 0},
782 {"tiled 2D 4x MSAA 4M alignment (invalid)", [&] {
783 D3D12_RESOURCE_DESC d = with(texture_desc(256, 256, rgba8, rt, 1),
784 D3D12_DEFAULT_MSAA_RESOURCE_PLACEMENT_ALIGNMENT, 4);
785 d.Layout = D3D12_TEXTURE_LAYOUT_64KB_UNDEFINED_SWIZZLE;
786 return d;
787 }(), 0},
788 {"UNKNOWN 4x MSAA NONE (invalid)", with(texture_desc(256, 256, rgba8, none, 1), 0, 4), 0},
789 {"UNKNOWN 4x MSAA RT+DS (invalid)",
790 with(texture_desc(256, 256, rgba8, rt | D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL, 1), 0, 4), 0},
697 }; 791 };
698 int mismatches = 0; 792 int mismatches = 0;
699 const auto mismatch = [&](const char* name, const D3D12_RESOURCE_ALLOCATION_INFO& a, 793 const auto mismatch = [&](const char* name, const D3D12_RESOURCE_ALLOCATION_INFO& a,
@@ -706,6 +800,18 @@ int compare_allocation_info(ID3D12Device* ours) {
706 for (const Case& c : cases) { 800 for (const Case& c : cases) {
707 const D3D12_RESOURCE_ALLOCATION_INFO a = ours->GetResourceAllocationInfo(0, 1, &c.desc); 801 const D3D12_RESOURCE_ALLOCATION_INFO a = ours->GetResourceAllocationInfo(0, 1, &c.desc);
708 const D3D12_RESOURCE_ALLOCATION_INFO b = host->GetResourceAllocationInfo(0, 1, &c.desc); 802 const D3D12_RESOURCE_ALLOCATION_INFO b = host->GetResourceAllocationInfo(0, 1, &c.desc);
803 if (c.top_mip_bytes && b.SizeInBytes == UINT64_MAX && c.desc.SampleDesc.Count > 1 &&
804 c.desc.Layout == D3D12_TEXTURE_LAYOUT_64KB_UNDEFINED_SWIZZLE) {
805 D3D12_FEATURE_DATA_MULTISAMPLE_QUALITY_LEVELS ms{
806 c.desc.Format, c.desc.SampleDesc.Count, D3D12_MULTISAMPLE_QUALITY_LEVELS_FLAG_TILED_RESOURCE, 0};
807 if (SUCCEEDED(host->CheckFeatureSupport(D3D12_FEATURE_MULTISAMPLE_QUALITY_LEVELS, &ms, sizeof(ms))) &&
808 ms.NumQualityLevels == 0) {
809 if (a.SizeInBytes == UINT64_MAX || a.Alignment != D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT)
810 mismatch(c.name, a, b);
811 std::printf("allocation info %s: host unsupported (NumQualityLevels=0), skipped\n", c.name);
812 continue;
813 }
814 }
709 if (b.SizeInBytes == UINT64_MAX || !c.top_mip_bytes) { 815 if (b.SizeInBytes == UINT64_MAX || !c.top_mip_bytes) {
710 if (a.SizeInBytes != b.SizeInBytes || (b.SizeInBytes != UINT64_MAX && a.Alignment != b.Alignment)) 816 if (a.SizeInBytes != b.SizeInBytes || (b.SizeInBytes != UINT64_MAX && a.Alignment != b.Alignment))
711 mismatch(c.name, a, b); 817 mismatch(c.name, a, b);
@@ -1506,6 +1612,15 @@ int compare_feature_support(ID3D12Device* ours) {
1506 1612
1507// Same-adapter host D3D12 device matched by VkPhysicalDeviceIDProperties (LUID first, then PCI IDs), falling back 1613// Same-adapter host D3D12 device matched by VkPhysicalDeviceIDProperties (LUID first, then PCI IDs), falling back
1508// to the default adapter. False if the host has no D3D12 device. 1614// to the default adapter. False if the host has no D3D12 device.
1615// D3D11.3 spec 3.2.3.8's ideal FLOAT -> SRGB encoding of c in [0, 1], before scaling to the format's maximum.
1616double ideal_srgb(double c) { return c <= 0.0031308 ? c * 12.92 : 1.055 * std::pow(c, 1.0 / 2.4) - 0.055; }
1617
1618// Both bytes within 0.6 ULP (on the integer side) of the ideal value: the tolerance spec 3.2.3.6 (FLOAT -> UNORM)
1619// and 3.2.3.8 (FLOAT -> SRGB) permit, so two drivers may give the codes either side of a near-tie.
1620bool within_06_ulp(std::uint8_t a, std::uint8_t b, double ideal) {
1621 return std::abs(double(a) - ideal) <= 0.6 && std::abs(double(b) - ideal) <= 0.6;
1622}
1623
1509bool create_host_device_for_physical(VkInstance instance, VkPhysicalDevice physical, 1624bool create_host_device_for_physical(VkInstance instance, VkPhysicalDevice physical,
1510 PFN_vkGetInstanceProcAddr instance_proc, Ref<ID3D12Device>& host, 1625 PFN_vkGetInstanceProcAddr instance_proc, Ref<ID3D12Device>& host,
1511 std::string& adapter_name) { 1626 std::string& adapter_name) {
@@ -2147,6 +2262,21 @@ int compare_invalid_arguments(ID3D12Device* ours) {
2147 struct Case { 2262 struct Case {
2148 const char* name; 2263 const char* name;
2149 InvalidCase call; 2264 InvalidCase call;
2265 bool (*comparable)(ID3D12Device*) = nullptr;
2266 };
2267 const auto device10 = [](ID3D12Device* d) {
2268 Ref<ID3D12Device10> newer;
2269 return SUCCEEDED(d->QueryInterface(IID_PPV_ARGS(&newer.p)));
2270 };
2271 const auto not_elevated = [](ID3D12Device*) {
2272 HANDLE token = nullptr;
2273 TOKEN_ELEVATION elevation{};
2274 DWORD size = 0;
2275 const bool elevated = OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &token) &&
2276 GetTokenInformation(token, TokenElevation, &elevation, sizeof(elevation), &size) &&
2277 elevation.TokenIsElevated;
2278 if (token) CloseHandle(token);
2279 return !elevated;
2150 }; 2280 };
2151 static const Case cases[] = { 2281 static const Case cases[] = {
2152 // CreateCommittedResource: arguments. 2282 // CreateCommittedResource: arguments.
@@ -2224,7 +2354,7 @@ int compare_invalid_arguments(ID3D12Device* ours) {
2224 }}, 2354 }},
2225 {"committed: upload buffer in COMMON", [](ID3D12Device* d) { 2355 {"committed: upload buffer in COMMON", [](ID3D12Device* d) {
2226 return committed(d, {D3D12_HEAP_TYPE_UPLOAD}, buffer_desc(256), D3D12_RESOURCE_STATE_COMMON); 2356 return committed(d, {D3D12_HEAP_TYPE_UPLOAD}, buffer_desc(256), D3D12_RESOURCE_STATE_COMMON);
2227 }}, 2357 }, +device10},
2228 {"committed: upload buffer in COPY_DEST", [](ID3D12Device* d) { 2358 {"committed: upload buffer in COPY_DEST", [](ID3D12Device* d) {
2229 return committed(d, {D3D12_HEAP_TYPE_UPLOAD}, buffer_desc(256), D3D12_RESOURCE_STATE_COPY_DEST); 2359 return committed(d, {D3D12_HEAP_TYPE_UPLOAD}, buffer_desc(256), D3D12_RESOURCE_STATE_COPY_DEST);
2230 }}, 2360 }},
@@ -2350,7 +2480,7 @@ int compare_invalid_arguments(ID3D12Device* ours) {
2350 {"committed: BC1 6x6 top mip", [](ID3D12Device* d) { 2480 {"committed: BC1 6x6 top mip", [](ID3D12Device* d) {
2351 return committed(d, {D3D12_HEAP_TYPE_DEFAULT}, 2481 return committed(d, {D3D12_HEAP_TYPE_DEFAULT},
2352 texture_desc(6, 6, DXGI_FORMAT_BC1_UNORM, D3D12_RESOURCE_FLAG_NONE)); 2482 texture_desc(6, 6, DXGI_FORMAT_BC1_UNORM, D3D12_RESOURCE_FLAG_NONE));
2353 }}, 2483 }, host_supports_unaligned_block_textures},
2354 {"committed: render target and depth stencil", [](ID3D12Device* d) { 2484 {"committed: render target and depth stencil", [](ID3D12Device* d) {
2355 return committed(d, {D3D12_HEAP_TYPE_DEFAULT}, 2485 return committed(d, {D3D12_HEAP_TYPE_DEFAULT},
2356 texture_desc(16, 16, DXGI_FORMAT_D32_FLOAT, 2486 texture_desc(16, 16, DXGI_FORMAT_D32_FLOAT,
@@ -2422,7 +2552,7 @@ int compare_invalid_arguments(ID3D12Device* ours) {
2422 }}, 2552 }},
2423 {"committed: readback buffer in COMMON", [](ID3D12Device* d) { 2553 {"committed: readback buffer in COMMON", [](ID3D12Device* d) {
2424 return committed(d, {D3D12_HEAP_TYPE_READBACK}, buffer_desc(256), D3D12_RESOURCE_STATE_COMMON); 2554 return committed(d, {D3D12_HEAP_TYPE_READBACK}, buffer_desc(256), D3D12_RESOURCE_STATE_COMMON);
2425 }}, 2555 }, +device10},
2426 {"committed: readback buffer with UAV", [](ID3D12Device* d) { 2556 {"committed: readback buffer with UAV", [](ID3D12Device* d) {
2427 auto desc = buffer_desc(256); 2557 auto desc = buffer_desc(256);
2428 desc.Flags = D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; 2558 desc.Flags = D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS;
@@ -2582,7 +2712,7 @@ int compare_invalid_arguments(ID3D12Device* ours) {
2582 }}, 2712 }},
2583 {"committed: heap flag HARDWARE_PROTECTED on a texture", [](ID3D12Device* d) { 2713 {"committed: heap flag HARDWARE_PROTECTED on a texture", [](ID3D12Device* d) {
2584 return with_heap_flags(d, rgba8(), D3D12_HEAP_FLAG_HARDWARE_PROTECTED); 2714 return with_heap_flags(d, rgba8(), D3D12_HEAP_FLAG_HARDWARE_PROTECTED);
2585 }}, 2715 }, +device10},
2586 {"committed: heap flag ALLOW_WRITE_WATCH on a buffer", [](ID3D12Device* d) { 2716 {"committed: heap flag ALLOW_WRITE_WATCH on a buffer", [](ID3D12Device* d) {
2587 return with_heap_flags(d, buffer_desc(256), D3D12_HEAP_FLAG_ALLOW_WRITE_WATCH); 2717 return with_heap_flags(d, buffer_desc(256), D3D12_HEAP_FLAG_ALLOW_WRITE_WATCH);
2588 }}, 2718 }},
@@ -2637,7 +2767,7 @@ int compare_invalid_arguments(ID3D12Device* ours) {
2637 auto desc = buffer_desc(256); 2767 auto desc = buffer_desc(256);
2638 desc.Flags = D3D12_RESOURCE_FLAGS(D3D12_RESOURCE_FLAG_RAYTRACING_ACCELERATION_STRUCTURE); 2768 desc.Flags = D3D12_RESOURCE_FLAGS(D3D12_RESOURCE_FLAG_RAYTRACING_ACCELERATION_STRUCTURE);
2639 return committed(d, {D3D12_HEAP_TYPE_DEFAULT}, desc); 2769 return committed(d, {D3D12_HEAP_TYPE_DEFAULT}, desc);
2640 }}, 2770 }, +device10},
2641 {"committed: resource flag 0x200 on a buffer", [](ID3D12Device* d) { 2771 {"committed: resource flag 0x200 on a buffer", [](ID3D12Device* d) {
2642 auto desc = buffer_desc(256); 2772 auto desc = buffer_desc(256);
2643 desc.Flags = D3D12_RESOURCE_FLAGS(0x200); 2773 desc.Flags = D3D12_RESOURCE_FLAGS(0x200);
@@ -2665,15 +2795,15 @@ int compare_invalid_arguments(ID3D12Device* ours) {
2665 {"committed: resource flag RAYTRACING_ACCELERATION_STRUCTURE on a texture", [](ID3D12Device* d) { 2795 {"committed: resource flag RAYTRACING_ACCELERATION_STRUCTURE on a texture", [](ID3D12Device* d) {
2666 auto desc = rgba8(D3D12_RESOURCE_FLAG_RAYTRACING_ACCELERATION_STRUCTURE); 2796 auto desc = rgba8(D3D12_RESOURCE_FLAG_RAYTRACING_ACCELERATION_STRUCTURE);
2667 return committed(d, {D3D12_HEAP_TYPE_DEFAULT}, desc); 2797 return committed(d, {D3D12_HEAP_TYPE_DEFAULT}, desc);
2668 }}, 2798 }, +device10},
2669 {"committed: resource flag 0x400 on a buffer", [](ID3D12Device* d) { 2799 {"committed: resource flag 0x400 on a buffer", [](ID3D12Device* d) {
2670 auto desc = buffer_desc(256); 2800 auto desc = buffer_desc(256);
2671 desc.Flags = D3D12_RESOURCE_FLAGS(0x400); 2801 desc.Flags = D3D12_RESOURCE_FLAGS(0x400);
2672 return committed(d, {D3D12_HEAP_TYPE_DEFAULT}, desc); 2802 return committed(d, {D3D12_HEAP_TYPE_DEFAULT}, desc);
2673 }}, 2803 }, +device10},
2674 {"committed: resource flag 0x400 on a texture", [](ID3D12Device* d) { 2804 {"committed: resource flag 0x400 on a texture", [](ID3D12Device* d) {
2675 return committed(d, {D3D12_HEAP_TYPE_DEFAULT}, rgba8(D3D12_RESOURCE_FLAGS(0x400))); 2805 return committed(d, {D3D12_HEAP_TYPE_DEFAULT}, rgba8(D3D12_RESOURCE_FLAGS(0x400)));
2676 }}, 2806 }, +device10},
2677 // A null output is a capability check; with invalid arguments too, the host's answer says which comes first. 2807 // A null output is a capability check; with invalid arguments too, the host's answer says which comes first.
2678 {"committed: heap type 99, null output", [](ID3D12Device* d) { 2808 {"committed: heap type 99, null output", [](ID3D12Device* d) {
2679 const H heap{D3D12_HEAP_TYPE(99)}; 2809 const H heap{D3D12_HEAP_TYPE(99)};
@@ -2726,7 +2856,7 @@ int compare_invalid_arguments(ID3D12Device* ours) {
2726 {"descriptor heap: shader-visible 2049 samplers", [](ID3D12Device* d) { 2856 {"descriptor heap: shader-visible 2049 samplers", [](ID3D12Device* d) {
2727 return descriptor_heap(d, {D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER, 2049, 2857 return descriptor_heap(d, {D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER, 2049,
2728 D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE}); 2858 D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE});
2729 }}, 2859 }, +device10},
2730 {"descriptor heap: shader-visible 2048 samplers", [](ID3D12Device* d) { 2860 {"descriptor heap: shader-visible 2048 samplers", [](ID3D12Device* d) {
2731 return descriptor_heap(d, {D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER, 2048, 2861 return descriptor_heap(d, {D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER, 2048,
2732 D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE}); 2862 D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE});
@@ -2771,7 +2901,7 @@ int compare_invalid_arguments(ID3D12Device* ours) {
2771 }}, 2901 }},
2772 {"command queue: global realtime priority", [](ID3D12Device* d) { 2902 {"command queue: global realtime priority", [](ID3D12Device* d) {
2773 return command_queue(d, {D3D12_COMMAND_LIST_TYPE_DIRECT, D3D12_COMMAND_QUEUE_PRIORITY_GLOBAL_REALTIME}); 2903 return command_queue(d, {D3D12_COMMAND_LIST_TYPE_DIRECT, D3D12_COMMAND_QUEUE_PRIORITY_GLOBAL_REALTIME});
2774 }}, 2904 }, +not_elevated},
2775 {"command queue: compute", [](ID3D12Device* d) { return command_queue(d, {D3D12_COMMAND_LIST_TYPE_COMPUTE}); }}, 2905 {"command queue: compute", [](ID3D12Device* d) { return command_queue(d, {D3D12_COMMAND_LIST_TYPE_COMPUTE}); }},
2776 {"command queue: copy", [](ID3D12Device* d) { return command_queue(d, {D3D12_COMMAND_LIST_TYPE_COPY}); }}, 2906 {"command queue: copy", [](ID3D12Device* d) { return command_queue(d, {D3D12_COMMAND_LIST_TYPE_COPY}); }},
2777 {"command queue: high priority", [](ID3D12Device* d) { 2907 {"command queue: high priority", [](ID3D12Device* d) {
@@ -2861,6 +2991,11 @@ int compare_invalid_arguments(ID3D12Device* ours) {
2861 const HRESULT a = call_guarded(c.call, ours), b = call_guarded(c.call, host.p); 2991 const HRESULT a = call_guarded(c.call, ours), b = call_guarded(c.call, host.p);
2862 if (verbose) std::printf(" ours 0x%08lx host 0x%08lx\n", a, b); 2992 if (verbose) std::printf(" ours 0x%08lx host 0x%08lx\n", a, b);
2863 if (a == b) continue; 2993 if (a == b) continue;
2994 if (c.comparable && !c.comparable(host.p)) {
2995 std::printf("invalid arguments %s: not comparable on this host (ours 0x%08lx, host 0x%08lx)\n", c.name,
2996 a, b);
2997 continue;
2998 }
2864 ++mismatches; 2999 ++mismatches;
2865 std::fprintf(stderr, "invalid arguments %s: ours 0x%08lx, host 0x%08lx\n", c.name, a, b); 3000 std::fprintf(stderr, "invalid arguments %s: ours 0x%08lx, host 0x%08lx\n", c.name, a, b);
2866 } 3001 }
@@ -2925,6 +3060,18 @@ int main() {
2925 const auto status = d.initialize(); 3060 const auto status = d.initialize();
2926 if (status == vktest::DeviceStatus::unavailable) return 77; 3061 if (status == vktest::DeviceStatus::unavailable) return 77;
2927 if (status == vktest::DeviceStatus::failed) return 1; 3062 if (status == vktest::DeviceStatus::failed) return 1;
3063 {
3064 // The host comparisons (create_host_device, the copies) run on the layer's own adapter, not D3D12's default
3065 // one, which on a PC with two GPUs can be the other GPU (copycmp::layer_adapter).
3066 VkPhysicalDeviceIDProperties id{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_ID_PROPERTIES};
3067 VkPhysicalDeviceProperties2 properties{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2, &id};
3068 d.instance_fn<PFN_vkGetPhysicalDeviceProperties2>("vkGetPhysicalDeviceProperties2")(d.physical, &properties);
3069 if (id.deviceLUIDValid) {
3070 LUID luid{};
3071 std::memcpy(&luid, id.deviceLUID, sizeof(luid));
3072 copycmp::layer_adapter() = luid;
3073 }
3074 }
2928 EXPECT(d.depth_format_usable(VK_FORMAT_D32_SFLOAT_S8_UINT)); 3075 EXPECT(d.depth_format_usable(VK_FORMAT_D32_SFLOAT_S8_UINT));
2929 VkSampleCountFlags depth_sample_counts = 0, color_sample_counts = 0; 3076 VkSampleCountFlags depth_sample_counts = 0, color_sample_counts = 0;
2930 { 3077 {
@@ -3142,7 +3289,8 @@ int main() {
3142 DXGI_FORMAT_R16G16B16A16_UINT, DXGI_FORMAT_R16G16B16A16_SINT, 3289 DXGI_FORMAT_R16G16B16A16_UINT, DXGI_FORMAT_R16G16B16A16_SINT,
3143 DXGI_FORMAT_R10G10B10A2_UINT, DXGI_FORMAT_R16G16_TYPELESS, DXGI_FORMAT_R16G16_UINT, 3290 DXGI_FORMAT_R10G10B10A2_UINT, DXGI_FORMAT_R16G16_TYPELESS, DXGI_FORMAT_R16G16_UINT,
3144 DXGI_FORMAT_R16G16_SINT, DXGI_FORMAT_R8G8_TYPELESS, DXGI_FORMAT_R8G8_UINT, 3291 DXGI_FORMAT_R16G16_SINT, DXGI_FORMAT_R8G8_TYPELESS, DXGI_FORMAT_R8G8_UINT,
3145 DXGI_FORMAT_R8G8_SINT}) { 3292 DXGI_FORMAT_R8G8_SINT, DXGI_FORMAT_B8G8R8X8_TYPELESS, DXGI_FORMAT_B8G8R8X8_UNORM,
3293 DXGI_FORMAT_B8G8R8X8_UNORM_SRGB}) {
3146 D3D12_FEATURE_DATA_FORMAT_SUPPORT fs{f}; 3294 D3D12_FEATURE_DATA_FORMAT_SUPPORT fs{f};
3147 EXPECT(SUCCEEDED(device->CheckFeatureSupport(D3D12_FEATURE_FORMAT_SUPPORT, &fs, sizeof(fs)))); 3295 EXPECT(SUCCEEDED(device->CheckFeatureSupport(D3D12_FEATURE_FORMAT_SUPPORT, &fs, sizeof(fs))));
3148 EXPECT(fs.Support1 & D3D12_FORMAT_SUPPORT1_TEXTURE2D); 3296 EXPECT(fs.Support1 & D3D12_FORMAT_SUPPORT1_TEXTURE2D);
@@ -3154,6 +3302,42 @@ int main() {
3154 EXPECT(tex.p != nullptr); 3302 EXPECT(tex.p != nullptr);
3155 } 3303 }
3156 } 3304 }
3305 // D3D-87, B8G8R8X8: no typed UAV and no typed texture that allows unordered access (the typeless family may),
3306 // as the host runtime answers; render targets as for B8G8R8A8.
3307 {
3308 Ref<ID3D12Device> host;
3309 if (create_host_device(host)) {
3310 const D3D12_HEAP_PROPERTIES default_heap{D3D12_HEAP_TYPE_DEFAULT};
3311 for (DXGI_FORMAT f : {DXGI_FORMAT_B8G8R8X8_UNORM, DXGI_FORMAT_B8G8R8X8_UNORM_SRGB,
3312 DXGI_FORMAT_B8G8R8X8_TYPELESS}) {
3313 D3D12_FEATURE_DATA_FORMAT_SUPPORT a{f}, b{f};
3314 EXPECT(SUCCEEDED(device->CheckFeatureSupport(D3D12_FEATURE_FORMAT_SUPPORT, &a, sizeof(a))));
3315 EXPECT(SUCCEEDED(host->CheckFeatureSupport(D3D12_FEATURE_FORMAT_SUPPORT, &b, sizeof(b))));
3316 constexpr UINT typed_uav = D3D12_FORMAT_SUPPORT1_TYPED_UNORDERED_ACCESS_VIEW;
3317 constexpr UINT typed_uav2 = D3D12_FORMAT_SUPPORT2_UAV_TYPED_LOAD | D3D12_FORMAT_SUPPORT2_UAV_TYPED_STORE;
3318 EXPECT((UINT(a.Support1) & typed_uav) == (UINT(b.Support1) & typed_uav));
3319 EXPECT((UINT(a.Support2) & typed_uav2) == (UINT(b.Support2) & typed_uav2));
3320 for (auto flag : {D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET}) {
3321 const D3D12_RESOURCE_DESC desc = texture_desc(16, 16, f, flag, 1);
3322 Ref<ID3D12Resource> ours_resource, host_resource;
3323 const HRESULT ours_hr = device->CreateCommittedResource(
3324 &default_heap, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_COMMON, nullptr,
3325 IID_PPV_ARGS(&ours_resource.p));
3326 const HRESULT host_hr = host->CreateCommittedResource(
3327 &default_heap, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_COMMON, nullptr,
3328 IID_PPV_ARGS(&host_resource.p));
3329 if (SUCCEEDED(ours_hr) != SUCCEEDED(host_hr))
3330 std::fprintf(stderr, "B8G8R8X8 format %d flags %d: ours %08lx, host %08lx\n", int(f),
3331 int(flag), static_cast<unsigned long>(ours_hr),
3332 static_cast<unsigned long>(host_hr));
3333 EXPECT(SUCCEEDED(ours_hr) == SUCCEEDED(host_hr));
3334 }
3335 }
3336 std::printf("B8G8R8X8: typed UAV support and UAV/RTV resource creation match the host runtime\n");
3337 } else {
3338 std::printf("B8G8R8X8: no host D3D12 device to compare with, skipped\n");
3339 }
3340 }
3157 3341
3158 const int options_mismatches = compare_feature_options(device.p, info); 3342 const int options_mismatches = compare_feature_options(device.p, info);
3159 EXPECT(options_mismatches == 0); 3343 EXPECT(options_mismatches == 0);
@@ -4578,16 +4762,16 @@ int main() {
4578 EXPECT(placed_va && placed_va % D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT == 0); 4762 EXPECT(placed_va && placed_va % D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT == 0);
4579 EXPECT(placed_b->GetGPUVirtualAddress() == placed_va + 65536); 4763 EXPECT(placed_b->GetGPUVirtualAddress() == placed_va + 65536);
4580 EXPECT(placed_image->GetGPUVirtualAddress() == 0); // only buffers are addressable, as in D3D12 4764 EXPECT(placed_image->GetGPUVirtualAddress() == 0); // only buffers are addressable, as in D3D12
4581 // Off the 64 KiB grid, past the heap end, and tiled: refused, not placed somewhere wrong. 4765 // Off the 64 KiB grid, past the heap end, and non-ROW_MAJOR buffers: E_INVALIDARG, not placed somewhere wrong.
4582 EXPECT(standalone->CreatePlacedResource(placed_heap.p, 512, &placed_buffer, D3D12_RESOURCE_STATE_COMMON, 4766 EXPECT(standalone->CreatePlacedResource(placed_heap.p, 512, &placed_buffer, D3D12_RESOURCE_STATE_COMMON,
4583 nullptr, IID_PPV_ARGS(&refused.p)) == E_INVALIDARG); 4767 nullptr, IID_PPV_ARGS(&refused.p)) == E_INVALIDARG);
4584 EXPECT(standalone->CreatePlacedResource(placed_heap.p, 256 * 1024, &placed_buffer, 4768 EXPECT(standalone->CreatePlacedResource(placed_heap.p, 256 * 1024, &placed_buffer,
4585 D3D12_RESOURCE_STATE_COMMON, nullptr, 4769 D3D12_RESOURCE_STATE_COMMON, nullptr,
4586 IID_PPV_ARGS(&refused.p)) == E_INVALIDARG); 4770 IID_PPV_ARGS(&refused.p)) == E_INVALIDARG);
4587 D3D12_RESOURCE_DESC tiled = buffer_desc(4096); 4771 D3D12_RESOURCE_DESC tiled_buf = buffer_desc(4096);
4588 tiled.Layout = D3D12_TEXTURE_LAYOUT_64KB_UNDEFINED_SWIZZLE; 4772 tiled_buf.Layout = D3D12_TEXTURE_LAYOUT_64KB_UNDEFINED_SWIZZLE;
4589 EXPECT(standalone->CreatePlacedResource(placed_heap.p, 0, &tiled, D3D12_RESOURCE_STATE_COMMON, nullptr, 4773 EXPECT(standalone->CreatePlacedResource(placed_heap.p, 0, &tiled_buf, D3D12_RESOURCE_STATE_COMMON, nullptr,
4590 IID_PPV_ARGS(&refused.p)) == E_NOTIMPL); 4774 IID_PPV_ARGS(&refused.p)) == E_INVALIDARG);
4591 EXPECT(!refused.p); 4775 EXPECT(!refused.p);
4592 // A placed buffer reads as zeroed through the copy path, at its console VA. 4776 // A placed buffer reads as zeroed through the copy path, at its console VA.
4593 D3D12_HEAP_PROPERTIES readback_props{}; 4777 D3D12_HEAP_PROPERTIES readback_props{};
@@ -4613,6 +4797,44 @@ int main() {
4613 EXPECT(SUCCEEDED(zeroes->Map(0, nullptr, &zero_bytes))); 4797 EXPECT(SUCCEEDED(zeroes->Map(0, nullptr, &zero_bytes)));
4614 report("placed buffer", 0, static_cast<std::uint8_t*>(zero_bytes), std::array<std::uint8_t, 64>{}.data(), 64); 4798 report("placed buffer", 0, static_cast<std::uint8_t*>(zero_bytes), std::array<std::uint8_t, 64>{}.data(), 64);
4615 zeroes->Unmap(0, nullptr); 4799 zeroes->Unmap(0, nullptr);
4800
4801 // Placed buffers carry their console VA in VulkanContext (so VA-resolved commands like WriteBufferImmediate
4802 // find them) and placed readback buffers mark host_readable (so the submission flushes GPU writes to host).
4803 {
4804 D3D12_HEAP_DESC rb_heap_desc{};
4805 rb_heap_desc.Properties.Type = D3D12_HEAP_TYPE_READBACK;
4806 rb_heap_desc.SizeInBytes = 65536;
4807 rb_heap_desc.Alignment = D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT;
4808 Ref<ID3D12Heap> rb_heap;
4809 Ref<ID3D12Resource> placed_rb;
4810 EXPECT(SUCCEEDED(standalone->CreateHeap(&rb_heap_desc, IID_PPV_ARGS(&rb_heap.p))));
4811 EXPECT(SUCCEEDED(standalone->CreatePlacedResource(rb_heap.p, 0, &placed_buffer,
4812 D3D12_RESOURCE_STATE_COPY_DEST, nullptr,
4813 IID_PPV_ARGS(&placed_rb.p))));
4814 Ref<ID3D12GraphicsCommandList2> placed_list2;
4815 EXPECT(SUCCEEDED(placed_list->QueryInterface(IID_PPV_ARGS(&placed_list2.p))));
4816 EXPECT(SUCCEEDED(placed_allocator->Reset()) && SUCCEEDED(placed_list->Reset(placed_allocator.p, nullptr)));
4817 const D3D12_WRITEBUFFERIMMEDIATE_PARAMETER wp{placed_va + 16, 0xCAFEBABEu};
4818 const D3D12_WRITEBUFFERIMMEDIATE_MODE wm = D3D12_WRITEBUFFERIMMEDIATE_MODE_DEFAULT;
4819 placed_list2->WriteBufferImmediate(1, &wp, &wm);
4820 D3D12_RESOURCE_BARRIER b{};
4821 b.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;
4822 b.Transition = {placed_a.p, D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES,
4823 D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_COPY_SOURCE};
4824 placed_list->ResourceBarrier(1, &b);
4825 placed_list->CopyBufferRegion(placed_rb.p, 0, placed_a.p, 0, 64);
4826 EXPECT(SUCCEEDED(placed_list->Close()));
4827 queue->ExecuteCommandLists(1, placed_lists);
4828 EXPECT(rt::d3d12::last_execute_result(queue.p) == leonida::ReplayResult::success);
4829 EXPECT(SUCCEEDED(queue->Signal(fence.p, 7)) && SUCCEEDED(fence->SetEventOnCompletion(7, nullptr)));
4830 void* rb_bytes = nullptr;
4831 EXPECT(SUCCEEDED(placed_rb->Map(0, nullptr, &rb_bytes)));
4832 std::uint32_t word = 0;
4833 std::memcpy(&word, static_cast<const std::uint8_t*>(rb_bytes) + 16, sizeof(word));
4834 EXPECT(word == 0xCAFEBABEu);
4835 placed_rb->Unmap(0, nullptr);
4836 }
4837
4616 // The heap owns the range: releasing it puts the next heap of that size back at the same place. 4838 // The heap owns the range: releasing it puts the next heap of that size back at the same place.
4617 placed_image.reset(); 4839 placed_image.reset();
4618 placed_b.reset(); 4840 placed_b.reset();
@@ -4622,6 +4844,437 @@ int main() {
4622 EXPECT(SUCCEEDED(standalone->CreatePlacedResource(again.p, 0, &placed_buffer, D3D12_RESOURCE_STATE_GENERIC_READ, 4844 EXPECT(SUCCEEDED(standalone->CreatePlacedResource(again.p, 0, &placed_buffer, D3D12_RESOURCE_STATE_GENERIC_READ,
4623 nullptr, IID_PPV_ARGS(&placed_a.p)))); 4845 nullptr, IID_PPV_ARGS(&placed_a.p))));
4624 EXPECT(placed_a->GetGPUVirtualAddress() == placed_va); 4846 EXPECT(placed_a->GetGPUVirtualAddress() == placed_va);
4847
4848 // D3D-191: tiled placed resources (D3D12_TEXTURE_LAYOUT_64KB_UNDEFINED_SWIZZLE and Xbox 0x101).
4849 D3D12_HEAP_DESC tiled_heap_desc{};
4850 tiled_heap_desc.Properties.Type = D3D12_HEAP_TYPE_DEFAULT;
4851 tiled_heap_desc.SizeInBytes = 2 * 1024 * 1024;
4852 tiled_heap_desc.Alignment = D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT;
4853 Ref<ID3D12Heap> tiled_heap, upload_placed_heap;
4854 EXPECT(SUCCEEDED(standalone->CreateHeap(&tiled_heap_desc, IID_PPV_ARGS(&tiled_heap.p))));
4855 D3D12_HEAP_DESC upload_heap_desc = tiled_heap_desc;
4856 upload_heap_desc.Properties.Type = D3D12_HEAP_TYPE_UPLOAD;
4857 EXPECT(SUCCEEDED(standalone->CreateHeap(&upload_heap_desc, IID_PPV_ARGS(&upload_placed_heap.p))));
4858
4859 auto tiled_2d = [&](UINT w, UINT h, DXGI_FORMAT fmt, UINT16 mips, D3D12_RESOURCE_FLAGS flags,
4860 UINT64 align = 0) {
4861 D3D12_RESOURCE_DESC d = texture_desc(w, h, fmt, flags, mips);
4862 d.Alignment = align;
4863 d.Layout = D3D12_TEXTURE_LAYOUT_64KB_UNDEFINED_SWIZZLE;
4864 return d;
4865 };
4866 const D3D12_RESOURCE_DESC tiled_rt_desc =
4867 tiled_2d(256, 256, DXGI_FORMAT_R8G8B8A8_UNORM, 0, D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET);
4868 const D3D12_RESOURCE_DESC tiled_bc_desc =
4869 tiled_2d(256, 256, DXGI_FORMAT_BC1_UNORM, 0, D3D12_RESOURCE_FLAG_NONE);
4870 const D3D12_RESOURCE_DESC tiled_ds_desc =
4871 tiled_2d(256, 256, DXGI_FORMAT_D32_FLOAT, 1, D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL);
4872 D3D12_RESOURCE_DESC tiled_3d_desc =
4873 tiled_2d(64, 64, DXGI_FORMAT_R8G8B8A8_UNORM, 0, D3D12_RESOURCE_FLAG_NONE);
4874 tiled_3d_desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE3D;
4875 tiled_3d_desc.DepthOrArraySize = 32;
4876 D3D12_RESOURCE_DESC xbox_tiled_desc =
4877 tiled_2d(256, 256, DXGI_FORMAT_R8G8B8A8_UNORM, 1, D3D12_RESOURCE_FLAG_NONE);
4878 xbox_tiled_desc.Layout = static_cast<D3D12_TEXTURE_LAYOUT>(0x101);
4879
4880 Ref<ID3D12Resource> tiled_rt, tiled_bc, tiled_ds, tiled_3d, xbox_tiled;
4881 EXPECT(SUCCEEDED(standalone->CreatePlacedResource(tiled_heap.p, 0, &tiled_rt_desc, D3D12_RESOURCE_STATE_COMMON,
4882 nullptr, IID_PPV_ARGS(&tiled_rt.p))));
4883 EXPECT(SUCCEEDED(standalone->CreatePlacedResource(tiled_heap.p, 512 * 1024, &tiled_bc_desc,
4884 D3D12_RESOURCE_STATE_COMMON, nullptr,
4885 IID_PPV_ARGS(&tiled_bc.p))));
4886 EXPECT(SUCCEEDED(standalone->CreatePlacedResource(tiled_heap.p, 640 * 1024, &tiled_ds_desc,
4887 D3D12_RESOURCE_STATE_COMMON, nullptr,
4888 IID_PPV_ARGS(&tiled_ds.p))));
4889 EXPECT(SUCCEEDED(standalone->CreatePlacedResource(tiled_heap.p, 1024 * 1024, &tiled_3d_desc,
4890 D3D12_RESOURCE_STATE_COMMON, nullptr,
4891 IID_PPV_ARGS(&tiled_3d.p))));
4892 EXPECT(SUCCEEDED(standalone->CreatePlacedResource(tiled_heap.p, 0, &xbox_tiled_desc, D3D12_RESOURCE_STATE_COMMON,
4893 nullptr, IID_PPV_ARGS(&xbox_tiled.p))));
4894
4895 for (ID3D12Resource* r : {tiled_rt.p, tiled_bc.p, tiled_ds.p, tiled_3d.p}) {
4896 const D3D12_RESOURCE_DESC got = r->GetDesc();
4897 EXPECT(r->GetGPUVirtualAddress() == 0);
4898 EXPECT(got.Layout == D3D12_TEXTURE_LAYOUT_64KB_UNDEFINED_SWIZZLE);
4899 EXPECT(got.Alignment == D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT);
4900 EXPECT(got.MipLevels > 0);
4901 D3D12_HEAP_PROPERTIES got_hp{};
4902 D3D12_HEAP_FLAGS got_hf = D3D12_HEAP_FLAG_NONE;
4903 EXPECT(SUCCEEDED(r->GetHeapProperties(&got_hp, &got_hf)));
4904 EXPECT(got_hp.Type == D3D12_HEAP_TYPE_DEFAULT);
4905 const D3D12_RESOURCE_ALLOCATION_INFO ai = standalone->GetResourceAllocationInfo(0, 1, &got);
4906 UINT tiles = 0;
4907 D3D12_TILE_SHAPE shape{};
4908 standalone->GetResourceTiling(r, &tiles, nullptr, &shape, nullptr, 0, nullptr);
4909 EXPECT(tiles > 0 && shape.WidthInTexels > 0 && ai.Alignment == D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT);
4910 EXPECT(ai.SizeInBytes == UINT64(tiles) * D3D12_TILED_RESOURCE_TILE_SIZE_IN_BYTES);
4911 }
4912 EXPECT(static_cast<UINT>(xbox_tiled->GetDesc().Layout) == 0x101);
4913 UINT xbox_tiles = 0;
4914 standalone->GetResourceTiling(xbox_tiled.p, &xbox_tiles, nullptr, nullptr, nullptr, 0, nullptr);
4915 EXPECT(xbox_tiles == 4);
4916
4917 // Refusals matching host D3D12: 1D, 4 KiB alignment, 96-bit, two-plane DS, invalid MSAA, upload heap, past-end.
4918 D3D12_RESOURCE_DESC bad_1d = line_desc(256, 1, 1, DXGI_FORMAT_R8G8B8A8_UNORM);
4919 bad_1d.Layout = D3D12_TEXTURE_LAYOUT_64KB_UNDEFINED_SWIZZLE;
4920 auto tiled_2d_msaa = [&](UINT samples, D3D12_RESOURCE_FLAGS flags, UINT64 align = 0) {
4921 D3D12_RESOURCE_DESC d = tiled_2d(256, 256, DXGI_FORMAT_R8G8B8A8_UNORM, 1, flags, align);
4922 d.SampleDesc.Count = samples;
4923 return d;
4924 };
4925 const D3D12_RESOURCE_DESC bad_cases[] = {
4926 bad_1d,
4927 tiled_2d(16, 16, DXGI_FORMAT_R8G8B8A8_UNORM, 1, D3D12_RESOURCE_FLAG_NONE,
4928 D3D12_SMALL_RESOURCE_PLACEMENT_ALIGNMENT),
4929 tiled_2d(64, 64, DXGI_FORMAT_R32G32B32_FLOAT, 1, D3D12_RESOURCE_FLAG_NONE),
4930 tiled_2d(64, 64, DXGI_FORMAT_D24_UNORM_S8_UINT, 1, D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL),
4931 tiled_2d(64, 64, DXGI_FORMAT_D32_FLOAT_S8X24_UINT, 1, D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL),
4932 tiled_2d_msaa(2, D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET),
4933 tiled_2d_msaa(4, D3D12_RESOURCE_FLAG_NONE),
4934 tiled_2d_msaa(4, D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET, D3D12_DEFAULT_MSAA_RESOURCE_PLACEMENT_ALIGNMENT),
4935 };
4936 for (const D3D12_RESOURCE_DESC& bad : bad_cases) {
4937 Ref<ID3D12Resource> fail;
4938 EXPECT(standalone->CreatePlacedResource(tiled_heap.p, 0, &bad, D3D12_RESOURCE_STATE_COMMON, nullptr,
4939 IID_PPV_ARGS(&fail.p)) == E_INVALIDARG);
4940 EXPECT(!fail.p);
4941 }
4942 {
4943 Ref<ID3D12Resource> fail;
4944 EXPECT(standalone->CreatePlacedResource(upload_placed_heap.p, 0, &tiled_rt_desc,
4945 D3D12_RESOURCE_STATE_COMMON, nullptr,
4946 IID_PPV_ARGS(&fail.p)) == E_INVALIDARG);
4947 const D3D12_RESOURCE_ALLOCATION_INFO rt_alloc = standalone->GetResourceAllocationInfo(0, 1, &tiled_rt_desc);
4948 EXPECT(standalone->CreatePlacedResource(tiled_heap.p,
4949 tiled_heap_desc.SizeInBytes - rt_alloc.SizeInBytes + 65536,
4950 &tiled_rt_desc, D3D12_RESOURCE_STATE_COMMON, nullptr,
4951 IID_PPV_ARGS(&fail.p)) == E_INVALIDARG);
4952 EXPECT(!fail.p);
4953 }
4954
4955 // Clear and read back a placed tiled RTV to verify GPU execution.
4956 D3D12_DESCRIPTOR_HEAP_DESC tiled_rtv_desc{};
4957 tiled_rtv_desc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_RTV;
4958 tiled_rtv_desc.NumDescriptors = 1;
4959 Ref<ID3D12DescriptorHeap> tiled_rtv_heap;
4960 EXPECT(SUCCEEDED(standalone->CreateDescriptorHeap(&tiled_rtv_desc, IID_PPV_ARGS(&tiled_rtv_heap.p))));
4961 standalone->CreateRenderTargetView(tiled_rt.p, nullptr, tiled_rtv_heap->GetCPUDescriptorHandleForHeapStart());
4962 D3D12_HEAP_PROPERTIES rb_props{D3D12_HEAP_TYPE_READBACK};
4963 const D3D12_RESOURCE_DESC rb_desc = buffer_desc(256);
4964 Ref<ID3D12Resource> tiled_rb;
4965 EXPECT(SUCCEEDED(standalone->CreateCommittedResource(&rb_props, D3D12_HEAP_FLAG_NONE, &rb_desc,
4966 D3D12_RESOURCE_STATE_COPY_DEST, nullptr,
4967 IID_PPV_ARGS(&tiled_rb.p))));
4968 Ref<ID3D12CommandAllocator> tiled_alloc;
4969 Ref<ID3D12GraphicsCommandList> tiled_list;
4970 EXPECT(SUCCEEDED(standalone->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT,
4971 IID_PPV_ARGS(&tiled_alloc.p))));
4972 EXPECT(SUCCEEDED(standalone->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, tiled_alloc.p, nullptr,
4973 IID_PPV_ARGS(&tiled_list.p))));
4974 const FLOAT tiled_color[4] = {64.0f / 255.0f, 128.0f / 255.0f, 191.0f / 255.0f, 1.0f};
4975 D3D12_RESOURCE_BARRIER b = transition(tiled_rt.p, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_RENDER_TARGET);
4976 tiled_list->ResourceBarrier(1, &b);
4977 tiled_list->ClearRenderTargetView(tiled_rtv_heap->GetCPUDescriptorHandleForHeapStart(), tiled_color, 0, nullptr);
4978 b = transition(tiled_rt.p, D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_COPY_SOURCE);
4979 tiled_list->ResourceBarrier(1, &b);
4980 D3D12_PLACED_SUBRESOURCE_FOOTPRINT fp{};
4981 fp.Footprint = {DXGI_FORMAT_R8G8B8A8_UNORM, 1, 1, 1, D3D12_TEXTURE_DATA_PITCH_ALIGNMENT};
4982 const D3D12_TEXTURE_COPY_LOCATION copy_dst = footprint(tiled_rb.p, fp);
4983 const D3D12_TEXTURE_COPY_LOCATION copy_src = subresource(tiled_rt.p, 0);
4984 D3D12_BOX box{0, 0, 0, 1, 1, 1};
4985 tiled_list->CopyTextureRegion(&copy_dst, 0, 0, 0, &copy_src, &box);
4986 EXPECT(SUCCEEDED(tiled_list->Close()));
4987 ID3D12CommandList* tiled_lists[] = {tiled_list.p};
4988 queue->ExecuteCommandLists(1, tiled_lists);
4989 EXPECT(rt::d3d12::last_execute_result(queue.p) == leonida::ReplayResult::success);
4990 EXPECT(SUCCEEDED(queue->Signal(fence.p, 8)) && SUCCEEDED(fence->SetEventOnCompletion(8, nullptr)));
4991 void* tiled_bytes = nullptr;
4992 EXPECT(SUCCEEDED(tiled_rb->Map(0, nullptr, &tiled_bytes)));
4993 const std::uint8_t want_rgba[4] = {64, 128, 191, 255};
4994 report("tiled placed RTV", 0, static_cast<std::uint8_t*>(tiled_bytes), want_rgba, 4);
4995 EXPECT(std::memcmp(tiled_bytes, want_rgba, 4) == 0);
4996 tiled_rb->Unmap(0, nullptr);
4997
4998 // Compare placed 64KB_UNDEFINED_SWIZZLE acceptance, layout, alignment, heap props and tile shape with host.
4999 Ref<ID3D12Device> host_dev;
5000 if (create_host_device(host_dev)) {
5001 D3D12_FEATURE_DATA_D3D12_OPTIONS host_opts{};
5002 if (SUCCEEDED(host_dev->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS, &host_opts, sizeof(host_opts))) &&
5003 host_opts.TiledResourcesTier != D3D12_TILED_RESOURCES_TIER_NOT_SUPPORTED) {
5004 Ref<ID3D12Heap> host_heap;
5005 if (SUCCEEDED(host_dev->CreateHeap(&tiled_heap_desc, IID_PPV_ARGS(&host_heap.p)))) {
5006 const D3D12_RESOURCE_DESC host_cases[] = {
5007 tiled_2d(256, 256, DXGI_FORMAT_R8G8B8A8_UNORM, 1, D3D12_RESOURCE_FLAG_NONE),
5008 tiled_2d(256, 256, DXGI_FORMAT_D32_FLOAT, 1, D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL),
5009 tiled_3d_desc,
5010 };
5011 for (int idx = 0; idx < int(std::size(host_cases)); ++idx) {
5012 const D3D12_RESOURCE_DESC& host_desc = host_cases[idx];
5013 if (host_desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D &&
5014 host_opts.TiledResourcesTier < D3D12_TILED_RESOURCES_TIER_3)
5015 continue;
5016 Ref<ID3D12Resource> our_r, host_r;
5017 const HRESULT our_hr = standalone->CreatePlacedResource(
5018 tiled_heap.p, 0, &host_desc, D3D12_RESOURCE_STATE_COMMON, nullptr, IID_PPV_ARGS(&our_r.p));
5019 const HRESULT host_hr = host_dev->CreatePlacedResource(
5020 host_heap.p, 0, &host_desc, D3D12_RESOURCE_STATE_COMMON, nullptr, IID_PPV_ARGS(&host_r.p));
5021 if (FAILED(host_hr)) continue;
5022 EXPECT(SUCCEEDED(our_hr));
5023 EXPECT(our_r->GetDesc().Layout == host_r->GetDesc().Layout);
5024 EXPECT(our_r->GetDesc().Alignment == host_r->GetDesc().Alignment);
5025 D3D12_HEAP_PROPERTIES ohp{}, hhp{};
5026 EXPECT(SUCCEEDED(our_r->GetHeapProperties(&ohp, nullptr)) &&
5027 SUCCEEDED(host_r->GetHeapProperties(&hhp, nullptr)));
5028 EXPECT(ohp.Type == hhp.Type);
5029 D3D12_TILE_SHAPE os{}, hs{};
5030 standalone->GetResourceTiling(our_r.p, nullptr, nullptr, &os, nullptr, 0, nullptr);
5031 host_dev->GetResourceTiling(host_r.p, nullptr, nullptr, &hs, nullptr, 0, nullptr);
5032 EXPECT(os.WidthInTexels == hs.WidthInTexels && os.HeightInTexels == hs.HeightInTexels &&
5033 os.DepthInTexels == hs.DepthInTexels);
5034 }
5035 }
5036 }
5037 }
5038
5039 // D3D-222: multisampled placed textures (UNKNOWN and 4x tiled).
5040 D3D12_HEAP_DESC msaa_heap_desc{};
5041 msaa_heap_desc.Properties.Type = D3D12_HEAP_TYPE_DEFAULT;
5042 msaa_heap_desc.SizeInBytes = 16 * 1024 * 1024;
5043 msaa_heap_desc.Alignment = D3D12_DEFAULT_MSAA_RESOURCE_PLACEMENT_ALIGNMENT;
5044 Ref<ID3D12Heap> msaa_heap;
5045 EXPECT(SUCCEEDED(standalone->CreateHeap(&msaa_heap_desc, IID_PPV_ARGS(&msaa_heap.p))));
5046 D3D12_HEAP_DESC deny_rt_desc = tiled_heap_desc;
5047 deny_rt_desc.Flags = D3D12_HEAP_FLAG_ALLOW_ONLY_NON_RT_DS_TEXTURES;
5048 Ref<ID3D12Heap> deny_rt_heap;
5049 EXPECT(SUCCEEDED(standalone->CreateHeap(&deny_rt_desc, IID_PPV_ARGS(&deny_rt_heap.p))));
5050
5051 auto msaa_desc = [&](UINT w, UINT h, UINT samples, UINT64 align, D3D12_TEXTURE_LAYOUT layout,
5052 D3D12_RESOURCE_FLAGS flags, DXGI_FORMAT fmt = DXGI_FORMAT_R8G8B8A8_UNORM,
5053 UINT16 mips = 1) {
5054 D3D12_RESOURCE_DESC d = texture_desc(w, h, fmt, flags, mips);
5055 d.Alignment = align;
5056 d.SampleDesc.Count = samples;
5057 d.Layout = layout;
5058 return d;
5059 };
5060 const D3D12_RESOURCE_DESC msaa_unk_rt_desc =
5061 msaa_desc(256, 256, 4, 0, D3D12_TEXTURE_LAYOUT_UNKNOWN, D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET);
5062 const D3D12_RESOURCE_DESC msaa_unk_small_desc = msaa_desc(
5063 256, 256, 4, D3D12_SMALL_MSAA_RESOURCE_PLACEMENT_ALIGNMENT, D3D12_TEXTURE_LAYOUT_UNKNOWN,
5064 D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET);
5065 const D3D12_RESOURCE_DESC msaa_unk_ds_desc =
5066 msaa_desc(256, 256, 4, 0, D3D12_TEXTURE_LAYOUT_UNKNOWN, D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL,
5067 DXGI_FORMAT_D32_FLOAT);
5068 const D3D12_RESOURCE_DESC msaa_tiled_rt_desc = tiled_2d_msaa(4, D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET);
5069 D3D12_RESOURCE_DESC msaa_xbox_rt_desc = msaa_tiled_rt_desc;
5070 msaa_xbox_rt_desc.Layout = static_cast<D3D12_TEXTURE_LAYOUT>(0x101);
5071
5072 Ref<ID3D12Resource> msaa_unk_rt, msaa_unk_small, msaa_unk_ds, msaa_tiled_rt, msaa_xbox_rt, msaa_cast_rt;
5073 EXPECT(SUCCEEDED(standalone->CreatePlacedResource(msaa_heap.p, D3D12_DEFAULT_MSAA_RESOURCE_PLACEMENT_ALIGNMENT,
5074 &msaa_unk_rt_desc, D3D12_RESOURCE_STATE_COMMON, nullptr,
5075 IID_PPV_ARGS(&msaa_unk_rt.p))));
5076 EXPECT(msaa_unk_rt->GetGPUVirtualAddress() == 0);
5077 EXPECT(msaa_unk_rt->GetDesc().Alignment == D3D12_DEFAULT_MSAA_RESOURCE_PLACEMENT_ALIGNMENT);
5078 EXPECT(msaa_unk_rt->GetDesc().SampleDesc.Count == 4);
5079 EXPECT(SUCCEEDED(standalone->CreatePlacedResource(tiled_heap.p, 65536, &msaa_unk_small_desc,
5080 D3D12_RESOURCE_STATE_COMMON, nullptr,
5081 IID_PPV_ARGS(&msaa_unk_small.p))));
5082 EXPECT(msaa_unk_small->GetDesc().Alignment == D3D12_SMALL_MSAA_RESOURCE_PLACEMENT_ALIGNMENT);
5083 EXPECT(SUCCEEDED(standalone->CreatePlacedResource(msaa_heap.p, 8 * 1024 * 1024, &msaa_unk_ds_desc,
5084 D3D12_RESOURCE_STATE_COMMON, nullptr,
5085 IID_PPV_ARGS(&msaa_unk_ds.p))));
5086 EXPECT(SUCCEEDED(standalone->CreatePlacedResource(tiled_heap.p, 65536, &msaa_tiled_rt_desc,
5087 D3D12_RESOURCE_STATE_COMMON, nullptr,
5088 IID_PPV_ARGS(&msaa_tiled_rt.p))));
5089 EXPECT(msaa_tiled_rt->GetDesc().Alignment == D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT);
5090 UINT msaa_tiles = 0;
5091 D3D12_TILE_SHAPE msaa_shape{};
5092 standalone->GetResourceTiling(msaa_tiled_rt.p, &msaa_tiles, nullptr, &msaa_shape, nullptr, 0, nullptr);
5093 EXPECT(msaa_tiles == 16 && msaa_shape.WidthInTexels == 64 && msaa_shape.HeightInTexels == 64);
5094 EXPECT(SUCCEEDED(standalone->CreatePlacedResource(tiled_heap.p, 65536, &msaa_xbox_rt_desc,
5095 D3D12_RESOURCE_STATE_COMMON, nullptr,
5096 IID_PPV_ARGS(&msaa_xbox_rt.p))));
5097 EXPECT(msaa_xbox_rt->GetDesc().Alignment == D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT);
5098 EXPECT(static_cast<UINT>(msaa_xbox_rt->GetDesc().Layout) == 0x101);
5099
5100 {
5101 Ref<ID3D12Device10> standalone10;
5102 EXPECT(SUCCEEDED(standalone->QueryInterface(IID_PPV_ARGS(&standalone10.p))));
5103 D3D12_RESOURCE_DESC1 cast_msaa{};
5104 cast_msaa.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D;
5105 cast_msaa.Width = 64;
5106 cast_msaa.Height = 64;
5107 cast_msaa.DepthOrArraySize = 1;
5108 cast_msaa.MipLevels = 1;
5109 cast_msaa.Format = DXGI_FORMAT_R8G8B8A8_TYPELESS;
5110 cast_msaa.SampleDesc.Count = 4;
5111 cast_msaa.Flags = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET;
5112 const DXGI_FORMAT cast_list[] = {DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_FORMAT_R8G8B8A8_UNORM_SRGB};
5113 EXPECT(SUCCEEDED(standalone10->CreatePlacedResource2(
5114 msaa_heap.p, 0, &cast_msaa, D3D12_BARRIER_LAYOUT_COMMON, nullptr, 2, cast_list,
5115 IID_PPV_ARGS(&msaa_cast_rt.p))));
5116 }
5117
5118 // Refusals matching host D3D12 for MSAA placed resources.
5119 {
5120 struct BadMsaaCase {
5121 ID3D12Heap* heap;
5122 UINT64 offset;
5123 D3D12_RESOURCE_DESC desc;
5124 };
5125 D3D12_RESOURCE_DESC msaa_3d =
5126 msaa_desc(16, 16, 4, 0, D3D12_TEXTURE_LAYOUT_UNKNOWN, D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET);
5127 msaa_3d.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE3D;
5128 msaa_3d.DepthOrArraySize = 8;
5129 const BadMsaaCase bad_msaa[] = {
5130 // 4 MiB-aligned UNKNOWN MSAA fails on a 64 KiB heap (even at offset 0) and at misaligned offsets.
5131 {tiled_heap.p, 0, msaa_unk_rt_desc},
5132 {msaa_heap.p, 65536, msaa_unk_rt_desc},
5133 {msaa_heap.p, msaa_heap_desc.SizeInBytes - 65536, msaa_unk_small_desc},
5134 {upload_placed_heap.p, 0, msaa_unk_small_desc},
5135 {deny_rt_heap.p, 0, msaa_unk_small_desc},
5136 {msaa_heap.p, 0,
5137 msaa_desc(256, 256, 4, 0, D3D12_TEXTURE_LAYOUT_UNKNOWN, D3D12_RESOURCE_FLAG_NONE)},
5138 {msaa_heap.p, 0,
5139 msaa_desc(256, 256, 4, 0, D3D12_TEXTURE_LAYOUT_UNKNOWN,
5140 D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET | D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL)},
5141 {msaa_heap.p, 0,
5142 msaa_desc(64, 64, 4, 0, D3D12_TEXTURE_LAYOUT_UNKNOWN, D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET,
5143 DXGI_FORMAT_R8G8B8A8_UNORM, 0)},
5144 {msaa_heap.p, 0, msaa_3d},
5145 };
5146 for (const BadMsaaCase& bad : bad_msaa) {
5147 Ref<ID3D12Resource> fail;
5148 EXPECT(standalone->CreatePlacedResource(bad.heap, bad.offset, &bad.desc, D3D12_RESOURCE_STATE_COMMON,
5149 nullptr, IID_PPV_ARGS(&fail.p)) == E_INVALIDARG);
5150 EXPECT(!fail.p);
5151 }
5152 }
5153
5154 // Clear placed 4x MSAA RTVs (UNKNOWN + tiled) and DSV, resolve, and read back to verify GPU execution.
5155 {
5156 const D3D12_RESOURCE_DESC resolved_desc =
5157 texture_desc(256, 256, DXGI_FORMAT_R8G8B8A8_UNORM, D3D12_RESOURCE_FLAG_NONE, 1);
5158 Ref<ID3D12Resource> msaa_resolved_unk, msaa_resolved_tiled;
5159 D3D12_HEAP_PROPERTIES def_hp{D3D12_HEAP_TYPE_DEFAULT};
5160 EXPECT(SUCCEEDED(standalone->CreateCommittedResource(&def_hp, D3D12_HEAP_FLAG_NONE, &resolved_desc,
5161 D3D12_RESOURCE_STATE_RESOLVE_DEST, nullptr,
5162 IID_PPV_ARGS(&msaa_resolved_unk.p))));
5163 EXPECT(SUCCEEDED(standalone->CreateCommittedResource(&def_hp, D3D12_HEAP_FLAG_NONE, &resolved_desc,
5164 D3D12_RESOURCE_STATE_RESOLVE_DEST, nullptr,
5165 IID_PPV_ARGS(&msaa_resolved_tiled.p))));
5166
5167 D3D12_DESCRIPTOR_HEAP_DESC msaa_rtv_hd{D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 2, D3D12_DESCRIPTOR_HEAP_FLAG_NONE, 0};
5168 D3D12_DESCRIPTOR_HEAP_DESC msaa_dsv_hd{D3D12_DESCRIPTOR_HEAP_TYPE_DSV, 1, D3D12_DESCRIPTOR_HEAP_FLAG_NONE, 0};
5169 Ref<ID3D12DescriptorHeap> msaa_rtv_heap, msaa_dsv_heap;
5170 EXPECT(SUCCEEDED(standalone->CreateDescriptorHeap(&msaa_rtv_hd, IID_PPV_ARGS(&msaa_rtv_heap.p))));
5171 EXPECT(SUCCEEDED(standalone->CreateDescriptorHeap(&msaa_dsv_hd, IID_PPV_ARGS(&msaa_dsv_heap.p))));
5172 const UINT rtv_step = standalone->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_RTV);
5173 const D3D12_CPU_DESCRIPTOR_HANDLE rtv0 = msaa_rtv_heap->GetCPUDescriptorHandleForHeapStart();
5174 const D3D12_CPU_DESCRIPTOR_HANDLE rtv1{rtv0.ptr + rtv_step};
5175 standalone->CreateRenderTargetView(msaa_unk_rt.p, nullptr, rtv0);
5176 standalone->CreateRenderTargetView(msaa_tiled_rt.p, nullptr, rtv1);
5177 standalone->CreateDepthStencilView(msaa_unk_ds.p, nullptr, msaa_dsv_heap->GetCPUDescriptorHandleForHeapStart());
5178
5179 EXPECT(SUCCEEDED(tiled_alloc->Reset()) && SUCCEEDED(tiled_list->Reset(tiled_alloc.p, nullptr)));
5180 D3D12_RESOURCE_BARRIER barriers[] = {
5181 transition(msaa_unk_rt.p, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_RENDER_TARGET),
5182 transition(msaa_tiled_rt.p, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_RENDER_TARGET),
5183 transition(msaa_unk_ds.p, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_DEPTH_WRITE),
5184 };
5185 tiled_list->ResourceBarrier(3, barriers);
5186 tiled_list->ClearRenderTargetView(rtv0, tiled_color, 0, nullptr);
5187 tiled_list->ClearRenderTargetView(rtv1, tiled_color, 0, nullptr);
5188 tiled_list->ClearDepthStencilView(msaa_dsv_heap->GetCPUDescriptorHandleForHeapStart(),
5189 D3D12_CLEAR_FLAG_DEPTH, 0.5f, 0, 0, nullptr);
5190 D3D12_RESOURCE_BARRIER to_resolve[] = {
5191 transition(msaa_unk_rt.p, D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_RESOLVE_SOURCE),
5192 transition(msaa_tiled_rt.p, D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_RESOLVE_SOURCE),
5193 };
5194 tiled_list->ResourceBarrier(2, to_resolve);
5195 tiled_list->ResolveSubresource(msaa_resolved_unk.p, 0, msaa_unk_rt.p, 0, DXGI_FORMAT_R8G8B8A8_UNORM);
5196 tiled_list->ResolveSubresource(msaa_resolved_tiled.p, 0, msaa_tiled_rt.p, 0, DXGI_FORMAT_R8G8B8A8_UNORM);
5197 D3D12_RESOURCE_BARRIER to_copy[] = {
5198 transition(msaa_resolved_unk.p, D3D12_RESOURCE_STATE_RESOLVE_DEST, D3D12_RESOURCE_STATE_COPY_SOURCE),
5199 transition(msaa_resolved_tiled.p, D3D12_RESOURCE_STATE_RESOLVE_DEST, D3D12_RESOURCE_STATE_COPY_SOURCE),
5200 };
5201 tiled_list->ResourceBarrier(2, to_copy);
5202 Ref<ID3D12Resource> msaa_rb;
5203 const D3D12_RESOURCE_DESC msaa_rb_desc = buffer_desc(1024);
5204 EXPECT(SUCCEEDED(standalone->CreateCommittedResource(&rb_props, D3D12_HEAP_FLAG_NONE, &msaa_rb_desc,
5205 D3D12_RESOURCE_STATE_COPY_DEST, nullptr,
5206 IID_PPV_ARGS(&msaa_rb.p))));
5207 D3D12_PLACED_SUBRESOURCE_FOOTPRINT fp_unk{}, fp_tiled{};
5208 fp_unk.Offset = 0;
5209 fp_unk.Footprint = {DXGI_FORMAT_R8G8B8A8_UNORM, 1, 1, 1, D3D12_TEXTURE_DATA_PITCH_ALIGNMENT};
5210 fp_tiled = fp_unk;
5211 fp_tiled.Offset = D3D12_TEXTURE_DATA_PLACEMENT_ALIGNMENT;
5212 const D3D12_TEXTURE_COPY_LOCATION dst_unk = footprint(msaa_rb.p, fp_unk);
5213 const D3D12_TEXTURE_COPY_LOCATION src_unk = subresource(msaa_resolved_unk.p, 0);
5214 const D3D12_TEXTURE_COPY_LOCATION dst_tiled = footprint(msaa_rb.p, fp_tiled);
5215 const D3D12_TEXTURE_COPY_LOCATION src_tiled = subresource(msaa_resolved_tiled.p, 0);
5216 tiled_list->CopyTextureRegion(&dst_unk, 0, 0, 0, &src_unk, &box);
5217 tiled_list->CopyTextureRegion(&dst_tiled, 0, 0, 0, &src_tiled, &box);
5218 EXPECT(SUCCEEDED(tiled_list->Close()));
5219 queue->ExecuteCommandLists(1, tiled_lists);
5220 EXPECT(rt::d3d12::last_execute_result(queue.p) == leonida::ReplayResult::success);
5221 EXPECT(SUCCEEDED(queue->Signal(fence.p, 9)) && SUCCEEDED(fence->SetEventOnCompletion(9, nullptr)));
5222 void* msaa_bytes = nullptr;
5223 EXPECT(SUCCEEDED(msaa_rb->Map(0, nullptr, &msaa_bytes)));
5224 const auto* out_bytes = static_cast<const std::uint8_t*>(msaa_bytes);
5225 report("placed MSAA UNKNOWN RTV resolve", 0, out_bytes, want_rgba, 4);
5226 report("placed MSAA tiled RTV resolve", 0, out_bytes + D3D12_TEXTURE_DATA_PLACEMENT_ALIGNMENT, want_rgba, 4);
5227 EXPECT(std::memcmp(out_bytes, want_rgba, 4) == 0);
5228 EXPECT(std::memcmp(out_bytes + D3D12_TEXTURE_DATA_PLACEMENT_ALIGNMENT, want_rgba, 4) == 0);
5229 msaa_rb->Unmap(0, nullptr);
5230 }
5231
5232 // Host parity for MSAA placed acceptance/refusals, layout, alignment, heap flags and tiled 4x shape.
5233 if (host_dev.p) {
5234 Ref<ID3D12Heap> host_heap64, host_heap4m;
5235 if (SUCCEEDED(host_dev->CreateHeap(&tiled_heap_desc, IID_PPV_ARGS(&host_heap64.p))) &&
5236 SUCCEEDED(host_dev->CreateHeap(&msaa_heap_desc, IID_PPV_ARGS(&host_heap4m.p)))) {
5237 struct MsaaParityCase {
5238 ID3D12Heap* our_heap;
5239 ID3D12Heap* host_heap;
5240 UINT64 offset;
5241 D3D12_RESOURCE_DESC desc;
5242 };
5243 const MsaaParityCase parity[] = {
5244 {tiled_heap.p, host_heap64.p, 0, msaa_unk_rt_desc},
5245 {msaa_heap.p, host_heap4m.p, 65536, msaa_unk_rt_desc},
5246 {msaa_heap.p, host_heap4m.p, 0, msaa_unk_rt_desc},
5247 {tiled_heap.p, host_heap64.p, 65536, msaa_unk_small_desc},
5248 {tiled_heap.p, host_heap64.p, 65536, msaa_tiled_rt_desc},
5249 };
5250 for (const MsaaParityCase& mc : parity) {
5251 Ref<ID3D12Resource> our_r, host_r;
5252 const HRESULT our_hr = standalone->CreatePlacedResource(
5253 mc.our_heap, mc.offset, &mc.desc, D3D12_RESOURCE_STATE_COMMON, nullptr, IID_PPV_ARGS(&our_r.p));
5254 const HRESULT host_hr = host_dev->CreatePlacedResource(
5255 mc.host_heap, mc.offset, &mc.desc, D3D12_RESOURCE_STATE_COMMON, nullptr, IID_PPV_ARGS(&host_r.p));
5256 EXPECT(SUCCEEDED(our_hr) == SUCCEEDED(host_hr));
5257 if (FAILED(host_hr)) {
5258 EXPECT(our_hr == host_hr);
5259 continue;
5260 }
5261 EXPECT(our_r->GetDesc().Layout == host_r->GetDesc().Layout);
5262 EXPECT(our_r->GetDesc().Alignment == host_r->GetDesc().Alignment);
5263 EXPECT(our_r->GetDesc().SampleDesc.Count == host_r->GetDesc().SampleDesc.Count);
5264 D3D12_HEAP_PROPERTIES ohp{}, hhp{};
5265 EXPECT(SUCCEEDED(our_r->GetHeapProperties(&ohp, nullptr)) &&
5266 SUCCEEDED(host_r->GetHeapProperties(&hhp, nullptr)));
5267 EXPECT(ohp.Type == hhp.Type);
5268 if (mc.desc.Layout == D3D12_TEXTURE_LAYOUT_64KB_UNDEFINED_SWIZZLE) {
5269 D3D12_TILE_SHAPE os{}, hs{};
5270 standalone->GetResourceTiling(our_r.p, nullptr, nullptr, &os, nullptr, 0, nullptr);
5271 host_dev->GetResourceTiling(host_r.p, nullptr, nullptr, &hs, nullptr, 0, nullptr);
5272 EXPECT(os.WidthInTexels == hs.WidthInTexels && os.HeightInTexels == hs.HeightInTexels &&
5273 os.DepthInTexels == hs.DepthInTexels);
5274 }
5275 }
5276 }
5277 }
4625 } 5278 }
4626 5279
4627 // D3D-90, the placed half of castable formats: CreatePlacedResource2 takes NumCastableFormats exactly as 5280 // D3D-90, the placed half of castable formats: CreatePlacedResource2 takes NumCastableFormats exactly as
@@ -4853,6 +5506,15 @@ int main() {
4853 EXPECT(words[0] == 0 && words[1] == 0 && words[2] == 0 && words[3] == 0); 5506 EXPECT(words[0] == 0 && words[1] == 0 && words[2] == 0 && words[3] == 0);
4854 } 5507 }
4855 5508
5509 // The tolerance host_side applies, pinned here so every GPU checks it: its accept side only runs where the
5510 // host rounds differently (Intel's SRGB clear), so a change to it would otherwise stay green elsewhere.
5511 // One code either side of a near-tie is accepted; two codes, or a code past 0.6 ULP, are not.
5512 EXPECT(within_06_ulp(187, 188, ideal_srgb(0.5) * 255.0) && within_06_ulp(127, 128, 127.5));
5513 EXPECT(!within_06_ulp(186, 188, ideal_srgb(0.5) * 255.0) && !within_06_ulp(126, 128, 127.5));
5514 EXPECT(!within_06_ulp(224, 225, ideal_srgb(0.75) * 255.0) &&
5515 !within_06_ulp(136, 137, ideal_srgb(0.25) * 255.0));
5516 EXPECT(!within_06_ulp(254, 255, 255.0));
5517
4856 // The host PC runtime's bytes and refusals: the default adapter when it can cast, WARP otherwise. 5518 // The host PC runtime's bytes and refusals: the default adapter when it can cast, WARP otherwise.
4857 bool compared = false; 5519 bool compared = false;
4858 const char* source = "no host"; 5520 const char* source = "no host";
@@ -4862,33 +5524,44 @@ int main() {
4862 if (!placed_cast_scenario(device10, false, host.data())) return false; 5524 if (!placed_cast_scenario(device10, false, host.data())) return false;
4863 if (!placed_cast_refusals(device10, host_refusals)) return false; 5525 if (!placed_cast_refusals(device10, host_refusals)) return false;
4864 unsigned differences = 0; 5526 unsigned differences = 0;
4865 // D3D12 does not pin float -> UNORM at a tie: the D3D11.3 functional spec (3.2.3.6 FLOAT -> UNORM) 5527 // D3D12 does not pin float -> UNORM or float -> SRGB to one code: the D3D11.3 functional spec
4866 // computes c * (2^n - 1) + 0.5 and drops the fraction, but permits a tolerance of 0.6 ULP on the integer 5528 // (3.2.3.6 FLOAT -> UNORM, 3.2.3.8 FLOAT -> SRGB) permits a tolerance of 0.6 ULP on the integer side, so
4867 // side, so a value exactly halfway between two codes (0.5 * 255 = 127.5) may map to either. WARP and AMD 5529 // a value near halfway between two codes may map to either. The plain clear's 0.5 * 255 = 127.5 is a
4868 // give the upper code; NVIDIA's D3D12 driver and its Vulkan driver the lower (RTX 3080 616.64, RTX 3090 5530 // tie: WARP and AMD give the upper code, NVIDIA's D3D12 driver and its Vulkan driver the lower (RTX 3080
4869 // 610.88 and RTX 5070 Laptop 617.42). On the layer's own adapter (same LUID) the comparison stays exact; 5531 // 616.64, RTX 3090 610.88 and RTX 5070 Laptop 617.42). The SRGB-cast clear's 0.5 encodes to 187.516:
4870 // against another adapter or WARP the plain clear accepts either code on a tie channel. 5532 // WARP and NVIDIA's Vulkan driver give 188, Intel's Vulkan driver 187 (UHD 770 101.7092), both within
5533 // 0.6 ULP. On the layer's own adapter (same LUID) the comparison stays exact; against another adapter
5534 // or WARP a byte may differ when both sides are within 0.6 ULP of the ideal value.
4871 const FLOAT clear_value[4] = {0.25f, 0.5f, 0.75f, 1.0f}; // placed_cast_scenario's clear colour 5535 const FLOAT clear_value[4] = {0.25f, 0.5f, 0.75f, 1.0f}; // placed_cast_scenario's clear colour
4872 unsigned tie_bytes_other_way = 0; 5536 const auto within_tolerance = [&](std::uint8_t ours_byte, std::uint8_t host_byte, double ideal) {
5537 return !same_adapter && within_06_ulp(ours_byte, host_byte, ideal);
5538 };
5539 unsigned plain_within = 0, srgb_within = 0;
4873 for (UINT row = 0; row < 4; ++row) 5540 for (UINT row = 0; row < 4; ++row)
4874 for (UINT i = 0; i < 16; ++i) { 5541 for (UINT i = 0; i < 16; ++i) {
4875 const UINT a = row * 256 + i, b = 1024 + row * 256 + i; 5542 const UINT a = row * 256 + i, b = 1024 + row * 256 + i;
4876 const double scaled = double(clear_value[i % 4]) * 255.0; 5543 const double c = clear_value[i % 4];
4877 const bool tie = !same_adapter && scaled - std::floor(scaled) == 0.5; 5544 const double plain_ideal = c * 255.0;
4878 if (tie && std::abs(int(ours[b]) - int(host[b])) == 1) { 5545 const double srgb_ideal = (i % 4 == 3 ? c : ideal_srgb(c)) * 255.0; // alpha stays linear
4879 ++tie_bytes_other_way; 5546 if (ours[b] != host[b]) {
4880 } else if (ours[b] != host[b] && differences++ < 8) { 5547 if (within_tolerance(ours[b], host[b], plain_ideal))
4881 std::fprintf(stderr, "placed plain clear row %u byte %u: ours %02x, host %02x\n", row, i, 5548 ++plain_within;
4882 ours[b], host[b]); 5549 else if (differences++ < 8)
5550 std::fprintf(stderr, "placed plain clear row %u byte %u: ours %02x, host %02x\n", row, i,
5551 ours[b], host[b]);
5552 }
5553 if (ours[a] != host[a]) {
5554 if (within_tolerance(ours[a], host[a], srgb_ideal))
5555 ++srgb_within;
5556 else if (differences++ < 8)
5557 std::fprintf(stderr, "placed SRGB-cast clear row %u byte %u: ours %02x, host %02x\n",
5558 row, i, ours[a], host[a]);
4883 } 5559 }
4884 if (ours[a] != host[a] && differences++ < 8)
4885 std::fprintf(stderr, "placed SRGB-cast clear row %u byte %u: ours %02x, host %02x\n", row,
4886 i, ours[a], host[a]);
4887 } 5560 }
4888 if (tie_bytes_other_way) 5561 if (plain_within || srgb_within)
4889 std::printf("placed plain clear: the host rounds the exact .5 tie the other way in %u bytes (within " 5562 std::printf("placed clears: %u plain and %u SRGB-cast bytes differ from the host by one code, both "
4890 "the 0.6 ULP tolerance of D3D11.3 spec 3.2.3.6)\n", 5563 "within the 0.6 ULP tolerance of D3D11.3 spec 3.2.3.6 and 3.2.3.8\n",
4891 tie_bytes_other_way); 5564 plain_within, srgb_within);
4892 for (UINT i = 0; i < 3; ++i) 5565 for (UINT i = 0; i < 3; ++i)
4893 if (our_refusals[i] != host_refusals[i]) { 5566 if (our_refusals[i] != host_refusals[i]) {
4894 ++differences; 5567 ++differences;
diff --git a/runtime/test/d3d12_xdxr_rt_test.cpp b/runtime/test/d3d12_xdxr_rt_test.cpp
index 9499dbe0d..0b4d3da52 100644
--- a/runtime/test/d3d12_xdxr_rt_test.cpp
+++ b/runtime/test/d3d12_xdxr_rt_test.cpp
@@ -2,7 +2,8 @@
2// 4.8, src/xdxr_build.h), the layout the game's translated traversal shaders read. A BLAS of two geometries (an 2// 4.8, src/xdxr_build.h), the layout the game's translated traversal shaders read. A BLAS of two geometries (an
3// unindexed triangle soup, and an R16-indexed grid with a 16-byte stride and a 3x4 transform) and a TLAS of three 3// unindexed triangle soup, and an R16-indexed grid with a 16-byte stride and a 3x4 transform) and a TLAS of three
4// instances are built through the D3D12 API, sized by GetRaytracingAccelerationStructurePrebuildInfo, copied to 4// instances are built through the D3D12 API, sized by GetRaytracingAccelerationStructurePrebuildInfo, copied to
5// readback buffers and written to <out dir> as <case>.bin + <case>.json at their console GPU virtual addresses. 5// readback buffers and written to <out dir>; the BLAS is then updated in place (PERFORM_UPDATE) after its soup moves,
6// and written again as d3d12_blas_update as <case>.bin + <case>.json at their console GPU virtual addresses.
6// `python -I tools/xdxr_bvh.py check-build <out dir>` validates them and traces rays against brute force (ctest: 7// `python -I tools/xdxr_bvh.py check-build <out dir>` validates them and traces rays against brute force (ctest:
7// d3d12_xdxr_rt + d3d12_xdxr_rt_check). Exit 77 without a Vulkan device, or with LEONIDA_RT_AS=khr. No game files. 8// d3d12_xdxr_rt + d3d12_xdxr_rt_check). Exit 77 without a Vulkan device, or with LEONIDA_RT_AS=khr. No game files.
8#include "../shims/d3d12_com.h" 9#include "../shims/d3d12_com.h"
@@ -153,6 +154,7 @@ int main(int argc, char** argv) {
153 154
154 D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_INPUTS blas_inputs{}; 155 D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_INPUTS blas_inputs{};
155 blas_inputs.Type = D3D12_RAYTRACING_ACCELERATION_STRUCTURE_TYPE_BOTTOM_LEVEL; 156 blas_inputs.Type = D3D12_RAYTRACING_ACCELERATION_STRUCTURE_TYPE_BOTTOM_LEVEL;
157 blas_inputs.Flags = D3D12_RAYTRACING_ACCELERATION_STRUCTURE_BUILD_FLAG_ALLOW_UPDATE; // updated below
156 blas_inputs.DescsLayout = D3D12_ELEMENTS_LAYOUT_ARRAY; 158 blas_inputs.DescsLayout = D3D12_ELEMENTS_LAYOUT_ARRAY;
157 blas_inputs.NumDescs = 2; 159 blas_inputs.NumDescs = 2;
158 blas_inputs.pGeometryDescs = geometries; 160 blas_inputs.pGeometryDescs = geometries;
@@ -239,7 +241,7 @@ int main(int argc, char** argv) {
239 ID3D12CommandList* lists[] = {list.p}; 241 ID3D12CommandList* lists[] = {list.p};
240 queue->ExecuteCommandLists(1, lists); 242 queue->ExecuteCommandLists(1, lists);
241 if (FAILED(queue->Signal(fence.p, 1))) return fail("Signal"); 243 if (FAILED(queue->Signal(fence.p, 1))) return fail("Signal");
242 HANDLE event = CreateEventW(nullptr, FALSE, FALSE, nullptr); 244 HANDLE event = CreateEventW(nullptr, FALSE, FALSE, nullptr); // reused for the update below
243 const bool done = event && SUCCEEDED(fence->SetEventOnCompletion(1, event)) && 245 const bool done = event && SUCCEEDED(fence->SetEventOnCompletion(1, event)) &&
244 WaitForSingleObject(event, 10000) == WAIT_OBJECT_0; 246 WaitForSingleObject(event, 10000) == WAIT_OBJECT_0;
245 if (event) CloseHandle(event); 247 if (event) CloseHandle(event);
@@ -258,31 +260,35 @@ int main(int argc, char** argv) {
258 rb->Unmap(0, nullptr); 260 rb->Unmap(0, nullptr);
259 return ok; 261 return ok;
260 }; 262 };
261 std::string tris = "["; 263 // The BLAS's triangles as the reference sees them, for the soup's current positions.
262 bool first = true; 264 auto triangles_json = [&](const std::vector<float>& soup_now) {
263 auto add_tri = [&](const float v[3][3], int geometry, UINT primitive) { 265 std::string tris = "[";
264 tris += first ? "\n [" : ",\n ["; 266 bool first = true;
265 first = false; 267 auto add_tri = [&](const float v[3][3], int geometry, UINT primitive) {
266 for (int k = 0; k < 3; ++k) 268 tris += first ? "\n [" : ",\n [";
267 tris += (k ? ", [" : "[") + num(v[k][0]) + ", " + num(v[k][1]) + ", " + num(v[k][2]) + "]"; 269 first = false;
268 tris += ", " + std::to_string(geometry) + ", " + std::to_string(primitive) + "]"; 270 for (int k = 0; k < 3; ++k)
269 }; 271 tris += (k ? ", [" : "[") + num(v[k][0]) + ", " + num(v[k][1]) + ", " + num(v[k][2]) + "]";
270 for (UINT t = 0; t < soup_tris; ++t) { 272 tris += ", " + std::to_string(geometry) + ", " + std::to_string(primitive) + "]";
271 float v[3][3]; 273 };
272 for (int k = 0; k < 9; ++k) v[k / 3][k % 3] = soup[9 * t + k]; 274 for (UINT t = 0; t < soup_tris; ++t) {
273 add_tri(v, 0, t); 275 float v[3][3];
274 } 276 for (int k = 0; k < 9; ++k) v[k / 3][k % 3] = soup_now[9 * t + k];
275 for (UINT t = 0; t < indices.size() / 3; ++t) { 277 add_tri(v, 0, t);
276 float v[3][3];
277 for (int k = 0; k < 3; ++k) {
278 const float* p = &grid[4 * indices[3 * t + k]];
279 for (int r = 0; r < 3; ++r)
280 v[k][r] = transform[4 * r] * p[0] + transform[4 * r + 1] * p[1] + transform[4 * r + 2] * p[2] +
281 transform[4 * r + 3];
282 } 278 }
283 add_tri(v, 1, t); 279 for (UINT t = 0; t < indices.size() / 3; ++t) {
284 } 280 float v[3][3];
285 tris += "]"; 281 for (int k = 0; k < 3; ++k) {
282 const float* p = &grid[4 * indices[3 * t + k]];
283 for (int r = 0; r < 3; ++r)
284 v[k][r] = transform[4 * r] * p[0] + transform[4 * r + 1] * p[1] + transform[4 * r + 2] * p[2] +
285 transform[4 * r + 3];
286 }
287 add_tri(v, 1, t);
288 }
289 return tris + "]";
290 };
291 const std::string tris = triangles_json(soup);
286 if (!dump(blas_rb.p, blas_info.ResultDataMaxSizeInBytes, "d3d12_blas", 292 if (!dump(blas_rb.p, blas_info.ResultDataMaxSizeInBytes, "d3d12_blas",
287 "{\"kind\": \"blas\", \"address\": " + std::to_string(blas->GetGPUVirtualAddress()) + 293 "{\"kind\": \"blas\", \"address\": " + std::to_string(blas->GetGPUVirtualAddress()) +
288 ", \"triangles\": " + tris + "}\n")) 294 ", \"triangles\": " + tris + "}\n"))
@@ -298,6 +304,38 @@ int main(int argc, char** argv) {
298 "{\"kind\": \"tlas\", \"address\": " + std::to_string(tlas->GetGPUVirtualAddress()) + 304 "{\"kind\": \"tlas\", \"address\": " + std::to_string(tlas->GetGPUVirtualAddress()) +
299 ", \"bias\": 0, \"blas\": [\"d3d12_blas\"], \"instances\": " + inst + "}\n")) 305 ", \"bias\": 0, \"blas\": [\"d3d12_blas\"], \"instances\": " + inst + "}\n"))
300 return fail("TLAS readback"); 306 return fail("TLAS readback");
307
308 // ---- PERFORM_UPDATE in place: the soup moves (every vertex), the grid stays; the BLAS is refitted ----
309 std::vector<float> moved = soup;
310 std::uniform_real_distribution<float> nudge(-1.0f, 1.0f);
311 for (std::size_t v = 0; v < moved.size(); v += 3) {
312 moved[v] = moved[v] * 1.3f + nudge(rng);
313 moved[v + 1] = moved[v + 1] * 0.7f + nudge(rng);
314 moved[v + 2] += nudge(rng);
315 }
316 if (FAILED(upload->Map(0, nullptr, reinterpret_cast<void**>(&mapped)))) return fail("Map upload for the update");
317 std::memcpy(mapped + (soup_va - upload->GetGPUVirtualAddress()), moved.data(), std::size_t(soup_bytes));
318 upload->Unmap(0, nullptr);
319 if (FAILED(allocator->Reset()) || FAILED(list->Reset(allocator.p, nullptr))) return fail("Reset for the update");
320 build.Inputs = blas_inputs;
321 build.Inputs.Flags |= D3D12_RAYTRACING_ACCELERATION_STRUCTURE_BUILD_FLAG_PERFORM_UPDATE;
322 build.DestAccelerationStructureData = blas->GetGPUVirtualAddress();
323 build.SourceAccelerationStructureData = blas->GetGPUVirtualAddress();
324 list->BuildRaytracingAccelerationStructure(&build, 0, nullptr);
325 list->ResourceBarrier(1, &barrier);
326 list->CopyBufferRegion(blas_rb.p, 0, blas.p, 0, blas_info.ResultDataMaxSizeInBytes);
327 if (FAILED(hr = list->Close())) return fail("Close (update)", hr);
328 queue->ExecuteCommandLists(1, lists);
329 if (FAILED(queue->Signal(fence.p, 2))) return fail("Signal (update)");
330 event = CreateEventW(nullptr, FALSE, FALSE, nullptr);
331 const bool updated = event && SUCCEEDED(fence->SetEventOnCompletion(2, event)) &&
332 WaitForSingleObject(event, 10000) == WAIT_OBJECT_0;
333 if (event) CloseHandle(event);
334 if (!updated) return fail("the update did not complete");
335 if (!dump(blas_rb.p, blas_info.ResultDataMaxSizeInBytes, "d3d12_blas_update",
336 "{\"kind\": \"blas\", \"address\": " + std::to_string(blas->GetGPUVirtualAddress()) +
337 ", \"triangles\": " + triangles_json(moved) + "}\n"))
338 return fail("BLAS readback after the update");
301 std::printf("d3d12_xdxr_rt: BLAS %llu bytes (prebuild %llu), TLAS (prebuild %llu), written to %s\n", 339 std::printf("d3d12_xdxr_rt: BLAS %llu bytes (prebuild %llu), TLAS (prebuild %llu), written to %s\n",
302 static_cast<unsigned long long>(blas_info.ResultDataMaxSizeInBytes), 340 static_cast<unsigned long long>(blas_info.ResultDataMaxSizeInBytes),
303 static_cast<unsigned long long>(blas_info.ResultDataMaxSizeInBytes), 341 static_cast<unsigned long long>(blas_info.ResultDataMaxSizeInBytes),
diff --git a/runtime/test/depth24_convert_test.cpp b/runtime/test/depth24_convert_test.cpp
index 365628519..89e98b091 100644
--- a/runtime/test/depth24_convert_test.cpp
+++ b/runtime/test/depth24_convert_test.cpp
@@ -673,6 +673,97 @@ int main() {
673 std::printf("depth24: 96-bit texels repack both ways, split into rows and into slices\n"); 673 std::printf("depth24: 96-bit texels repack both ways, split into rows and into slices\n");
674 } 674 }
675 675
676 // 7. ScratchBuffers::collect() must check VkResult from vkGetSemaphoreCounterValue() (leaving in-flight
677 // chunks retired if the query fails even when *pValue is overwritten with UINT64_MAX) and reclaim
678 // ticket-0 batches without querying the timeline semaphore.
679 {
680 struct MockVk {
681 std::uint64_t next_handle = 1;
682 VkResult sem_result = VK_ERROR_DEVICE_LOST;
683 std::uint64_t sem_value = UINT64_MAX;
684 unsigned sem_queries = 0;
685 unsigned destroyed_buffers = 0;
686
687 static MockVk*& state() {
688 static MockVk* s = nullptr;
689 return s;
690 }
691 static VKAPI_ATTR VkResult VKAPI_CALL create_buf(VkDevice, const VkBufferCreateInfo*,
692 const VkAllocationCallbacks*, VkBuffer* out) {
693 *out = reinterpret_cast<VkBuffer>(state()->next_handle++);
694 return VK_SUCCESS;
695 }
696 static VKAPI_ATTR void VKAPI_CALL destroy_buf(VkDevice, VkBuffer, const VkAllocationCallbacks*) {
697 ++state()->destroyed_buffers;
698 }
699 static VKAPI_ATTR void VKAPI_CALL mem_req(VkDevice, VkBuffer, VkMemoryRequirements* req) {
700 *req = {};
701 req->size = 4096;
702 req->alignment = 256;
703 req->memoryTypeBits = 1;
704 }
705 static VKAPI_ATTR VkResult VKAPI_CALL bind_buf(VkDevice, VkBuffer, VkDeviceMemory, VkDeviceSize) {
706 return VK_SUCCESS;
707 }
708 static VKAPI_ATTR void VKAPI_CALL free_mem(VkDevice, VkDeviceMemory, const VkAllocationCallbacks*) {}
709 static VKAPI_ATTR VkResult VKAPI_CALL get_sem(VkDevice, VkSemaphore, std::uint64_t* out) {
710 ++state()->sem_queries;
711 if (out) *out = state()->sem_value;
712 return state()->sem_result;
713 }
714 static VKAPI_ATTR VkResult VKAPI_CALL wait_idle(VkDevice) { return VK_SUCCESS; }
715 static VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL gdpa(VkDevice, const char* name) {
716 if (std::strcmp(name, "vkCreateBuffer") == 0) return reinterpret_cast<PFN_vkVoidFunction>(create_buf);
717 if (std::strcmp(name, "vkDestroyBuffer") == 0)
718 return reinterpret_cast<PFN_vkVoidFunction>(destroy_buf);
719 if (std::strcmp(name, "vkGetBufferMemoryRequirements") == 0)
720 return reinterpret_cast<PFN_vkVoidFunction>(mem_req);
721 if (std::strcmp(name, "vkBindBufferMemory") == 0)
722 return reinterpret_cast<PFN_vkVoidFunction>(bind_buf);
723 if (std::strcmp(name, "vkFreeMemory") == 0) return reinterpret_cast<PFN_vkVoidFunction>(free_mem);
724 if (std::strcmp(name, "vkGetSemaphoreCounterValue") == 0)
725 return reinterpret_cast<PFN_vkVoidFunction>(get_sem);
726 if (std::strcmp(name, "vkDeviceWaitIdle") == 0) return reinterpret_cast<PFN_vkVoidFunction>(wait_idle);
727 return nullptr;
728 }
729 };
730 MockVk mock{};
731 MockVk::state() = &mock;
732 const VkSemaphore fake_sem = reinterpret_cast<VkSemaphore>(std::uintptr_t(0x1234));
733 {
734 ScratchBuffers scratch(&MockVk::gdpa, reinterpret_cast<VkDevice>(std::uintptr_t(1)),
735 [&](const VkMemoryRequirements&) {
736 return reinterpret_cast<VkDeviceMemory>(mock.next_handle++);
737 });
738 EXPECT(scratch.loaded());
739 VkBuffer b1 = VK_NULL_HANDLE, b2 = VK_NULL_HANDLE;
740 VkDeviceSize off = 0;
741 EXPECT(scratch.get(1024, b1, off));
742 scratch.retire(fake_sem, 1);
743 // Query fails with VK_ERROR_DEVICE_LOST while writing UINT64_MAX to *pValue: chunk must NOT be recycled!
744 scratch.collect();
745 EXPECT(scratch.get(1024, b2, off));
746 EXPECT(b2 != b1); // b1 is still in flight; must not have been reclaimed into spare_
747 // Unsubmitted batch (ticket == 0): must reclaim without calling vkGetSemaphoreCounterValue.
748 const unsigned queries_before = mock.sem_queries;
749 scratch.retire(fake_sem, 0);
750 mock.sem_result = VK_SUCCESS;
751 mock.sem_value = 0;
752 scratch.collect();
753 EXPECT(mock.sem_queries == queries_before + 1); // only queried for b1 (ticket 1), not b2 (ticket 0)
754 VkBuffer b3 = VK_NULL_HANDLE;
755 EXPECT(scratch.get(1024, b3, off));
756 EXPECT(b3 == b2); // b2 was reclaimed cleanly from ticket 0
757 // Now b1's ticket completes cleanly.
758 mock.sem_value = 1;
759 scratch.collect();
760 scratch.retire(fake_sem, 0);
761 }
762 EXPECT(mock.destroyed_buffers == 2);
763 MockVk::state() = nullptr;
764 std::printf("depth24: ScratchBuffers::collect() checks vkGetSemaphoreCounterValue VkResult and ticket 0 ok\n");
765 }
766
676 EXPECT(gpu.validation_errors() == 0); 767 EXPECT(gpu.validation_errors() == 0);
677 std::printf("depth24_convert_test: ok\n"); 768 std::printf("depth24_convert_test: ok\n");
678 return 0; 769 return 0;
diff --git a/runtime/test/device_proxy_test.cpp b/runtime/test/device_proxy_test.cpp
index e414f155b..70cae9a89 100644
--- a/runtime/test/device_proxy_test.cpp
+++ b/runtime/test/device_proxy_test.cpp
@@ -151,19 +151,19 @@ int main() {
151 unsigned slots = rt::d3d12_xs::device_proxy_slot_count(device.Get()); 151 unsigned slots = rt::d3d12_xs::device_proxy_slot_count(device.Get());
152 std::printf("proxy forwards %u PC vtable slots (ID3D12Device..Device14 max is 83)\n", slots); 152 std::printf("proxy forwards %u PC vtable slots (ID3D12Device..Device14 max is 83)\n", slots);
153 check(slots >= 44, "proxy forwards at least the base ID3D12Device vtable"); 153 check(slots >= 44, "proxy forwards at least the base ID3D12Device vtable");
154 check(!rt::d3d12_xs::device_slot_overridden(9), "device slot 9 is forwarded (PC CreateCommandAllocator)"); 154 check(rt::d3d12_xs::device_slot_overridden(9), "device slot 9 is CreateCommandAllocator (allocator proxies)");
155 check(!rt::d3d12_xs::device_slot_overridden(10), "device slot 10 is forwarded (PC CreateGraphicsPipelineState)"); 155 check(!rt::d3d12_xs::device_slot_overridden(10), "device slot 10 is forwarded (PC CreateGraphicsPipelineState)");
156 check(rt::d3d12_xs::device_slot_overridden(14), "device slot 14 is the descriptor-heap override"); 156 check(rt::d3d12_xs::device_slot_overridden(14), "device slot 14 is the descriptor-heap override");
157 check(rt::d3d12_xs::device_slot_overridden(62), "device slot 62 is the compute-PSO override"); 157 check(rt::d3d12_xs::device_slot_overridden(62), "device slot 62 is the compute-PSO override");
158 check(rt::d3d12_xs::device_slot_overridden(76), "device slot 76 is the resource override"); 158 check(rt::d3d12_xs::device_slot_overridden(76), "device slot 76 is the resource override");
159 check(rt::d3d12_xs::device_slot_overridden(67), 159 check(rt::d3d12_xs::device_slot_overridden(67),
160 "device slot 67 is refused (console DeserializeComputePipelineStateX, " 160 "device slot 67 is the DeserializeComputePipelineStateX override (console native-code compute pipeline, not PC CreateProtectedResourceSession1)");
161 "not PC CreateProtectedResourceSession1)");
162 161
163 void** proxy_vtbl = *reinterpret_cast<void***>(device.Get()); 162 void** proxy_vtbl = *reinterpret_cast<void***>(device.Get());
164 void** real_vtbl = real ? *reinterpret_cast<void***>(real) : nullptr; 163 void** real_vtbl = real ? *reinterpret_cast<void***>(real) : nullptr;
165 check(proxy_vtbl != nullptr && proxy_vtbl[14] != real_vtbl[14], "slot 14 thunk differs from the PC entry"); 164 check(proxy_vtbl != nullptr && proxy_vtbl[14] != real_vtbl[14], "slot 14 thunk differs from the PC entry");
166 if (slots > 62) check(proxy_vtbl[62] != real_vtbl[62], "slot 62 thunk differs from PC CreateStateObject"); 165 if (slots > 62) check(proxy_vtbl[62] != real_vtbl[62], "slot 62 thunk differs from PC CreateStateObject");
166 if (slots > 67) check(proxy_vtbl[67] != real_vtbl[67], "slot 67 thunk differs from PC CreateProtectedResourceSession1");
167 if (slots > 76) check(proxy_vtbl[76] != real_vtbl[76], "slot 76 thunk differs from PC CreateCommittedResource3"); 167 if (slots > 76) check(proxy_vtbl[76] != real_vtbl[76], "slot 76 thunk differs from PC CreateCommittedResource3");
168 168
169 rt::d3d12_xs::reset_device_proxy_stats(); 169 rt::d3d12_xs::reset_device_proxy_stats();
@@ -278,6 +278,8 @@ int main() {
278 ComPtr<ID3D12CommandAllocator> allocator; 278 ComPtr<ID3D12CommandAllocator> allocator;
279 hr = device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(allocator.GetAddressOf())); 279 hr = device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(allocator.GetAddressOf()));
280 check(SUCCEEDED(hr) && allocator != nullptr, "device slot 9 forwards CreateCommandAllocator"); 280 check(SUCCEEDED(hr) && allocator != nullptr, "device slot 9 forwards CreateCommandAllocator");
281 // A PC runtime allocator is not wrapped: the PC runtime's lists could not resolve an allocator proxy.
282 check(!rt::d3d12_xs::is_allocator_proxy(allocator.Get()), "slot 9 hands out the PC allocator unwrapped");
281 check(rt::d3d12_xs::device_slot_hits(9) == 1, "slot 9 hit counter is 1"); 283 check(rt::d3d12_xs::device_slot_hits(9) == 1, "slot 9 hit counter is 1");
282 284
283 // Slot 76: buffer resource with the measured Xbox layout word 0x101; PC committed resources take ROW_MAJOR. 285 // Slot 76: buffer resource with the measured Xbox layout word 0x101; PC committed resources take ROW_MAJOR.
@@ -342,6 +344,31 @@ int main() {
342 check(SUCCEEDED(hr) && pso != nullptr, "slot 62 creates a compute PSO via CreateComputePipelineState"); 344 check(SUCCEEDED(hr) && pso != nullptr, "slot 62 creates a compute PSO via CreateComputePipelineState");
343 check(rt::d3d12_xs::device_slot_hits(62) == 1, "slot 62 hit counter is 1"); 345 check(rt::d3d12_xs::device_slot_hits(62) == 1, "slot 62 hit counter is 1");
344 check(rt::d3d12_xs::device_slot_first_call_seen(62), "slot 62 first-call flag is set"); 346 check(rt::d3d12_xs::device_slot_first_call_seen(62), "slot 62 first-call flag is set");
347
348 // Slot 67: Xbox native compute pipeline creation. Maps the console descriptor (+0x00 root signature,
349 // +0x28 kind 6 code blob, +0x30 code size) to D3D12_COMPUTE_PIPELINE_STATE_DESC and calls CreateComputePipelineState.
350 struct XboxNativeComputeDesc {
351 ID3D12RootSignature* root_signature;
352 const void* kind0;
353 std::uint64_t kind0_size;
354 const void* kind1;
355 std::uint64_t kind1_size;
356 const void* kind6;
357 std::uint64_t kind6_size;
358 const void* kind7;
359 std::uint64_t kind7_size;
360 } xbox_desc{};
361 xbox_desc.root_signature = root_signature.Get();
362 xbox_desc.kind6 = bytecode->GetBufferPointer();
363 xbox_desc.kind6_size = bytecode->GetBufferSize();
364
365 using XboxCreateNativeComputePsoFn = HRESULT(WINAPI*)(void*, const void*, const IID*, void**);
366 auto create_native_pso = reinterpret_cast<XboxCreateNativeComputePsoFn>(proxy_vtbl[67]);
367 ComPtr<ID3D12PipelineState> pso67;
368 hr = create_native_pso(device.Get(), &xbox_desc, &iid_pso, reinterpret_cast<void**>(pso67.GetAddressOf()));
369 check(SUCCEEDED(hr) && pso67 != nullptr, "slot 67 creates a compute PSO via CreateComputePipelineState");
370 check(rt::d3d12_xs::device_slot_hits(67) == 1, "slot 67 hit counter is 1");
371 check(rt::d3d12_xs::device_slot_first_call_seen(67), "slot 67 first-call flag is set");
345 } 372 }
346 373
347 // _COM_Outptr_ (d3d12.h): a failed create leaves NULL in the output. WARP accepts invalid heap descriptions, 374 // _COM_Outptr_ (d3d12.h): a failed create leaves NULL in the output. WARP accepts invalid heap descriptions,
@@ -357,6 +384,14 @@ int main() {
357 D3D12_COMPUTE_PIPELINE_STATE_DESC empty_pso{}; 384 D3D12_COMPUTE_PIPELINE_STATE_DESC empty_pso{};
358 hr = reinterpret_cast<Slot62Fn>(proxy_vtbl[62])(device.Get(), &empty_pso, 0, 0, nullptr, &proxy_out); 385 hr = reinterpret_cast<Slot62Fn>(proxy_vtbl[62])(device.Get(), &empty_pso, 0, 0, nullptr, &proxy_out);
359 check(FAILED(hr) && proxy_out == nullptr, "slot 62 nulls its output for a null IID"); 386 check(FAILED(hr) && proxy_out == nullptr, "slot 62 nulls its output for a null IID");
387 using Slot67Fn = HRESULT(WINAPI*)(void*, const void*, const IID*, void**);
388 proxy_out = reinterpret_cast<void*>(0x1111);
389 const IID iid_pso = __uuidof(ID3D12PipelineState);
390 hr = reinterpret_cast<Slot67Fn>(proxy_vtbl[67])(device.Get(), nullptr, &iid_pso, &proxy_out);
391 check(FAILED(hr) && proxy_out == nullptr, "slot 67 nulls its output for a null description");
392 proxy_out = reinterpret_cast<void*>(0x1111);
393 hr = reinterpret_cast<Slot67Fn>(proxy_vtbl[67])(device.Get(), &root_desc, nullptr, &proxy_out);
394 check(FAILED(hr) && proxy_out == nullptr, "slot 67 nulls its output for a null IID");
360 using Slot76Fn = HRESULT(WINAPI*)(void*, const D3D12_HEAP_PROPERTIES*, D3D12_HEAP_FLAGS, 395 using Slot76Fn = HRESULT(WINAPI*)(void*, const D3D12_HEAP_PROPERTIES*, D3D12_HEAP_FLAGS,
361 const D3D12_RESOURCE_DESC*, D3D12_RESOURCE_STATES, 396 const D3D12_RESOURCE_DESC*, D3D12_RESOURCE_STATES,
362 const D3D12_CLEAR_VALUE*, const IID*, void**); 397 const D3D12_CLEAR_VALUE*, const IID*, void**);
diff --git a/runtime/test/dxgi_swapchain_test.cpp b/runtime/test/dxgi_swapchain_test.cpp
index 86129852e..c42707640 100644
--- a/runtime/test/dxgi_swapchain_test.cpp
+++ b/runtime/test/dxgi_swapchain_test.cpp
@@ -77,6 +77,19 @@ HWND create_test_window(int width, int height) {
77 nullptr); 77 nullptr);
78} 78}
79 79
80// Native DXGI on NVIDIA and WARP reports DISJOINT once after creation or ResizeBuffers, including when the
81// first query follows a Present. A null output must not consume that notification (D3D-211).
82bool check_statistics_disjoint(IDXGISwapChain* swapchain) {
83 if (swapchain->GetFrameStatistics(nullptr) != DXGI_ERROR_INVALID_CALL) return false;
84 DXGI_FRAME_STATISTICS stats;
85 std::memset(&stats, 0xcd, sizeof(stats));
86 if (swapchain->GetFrameStatistics(&stats) != DXGI_ERROR_FRAME_STATISTICS_DISJOINT) return false;
87 if (stats.PresentCount || stats.PresentRefreshCount || stats.SyncRefreshCount ||
88 stats.SyncQPCTime.QuadPart || stats.SyncGPUTime.QuadPart)
89 return false;
90 return swapchain->GetFrameStatistics(&stats) == S_OK;
91}
92
80} // namespace 93} // namespace
81 94
82int main() { 95int main() {
@@ -263,6 +276,18 @@ int main() {
263 scd.BufferCount = 2; 276 scd.BufferCount = 2;
264 scd.SwapEffect = DXGI_SWAP_EFFECT_FLIP_DISCARD; 277 scd.SwapEffect = DXGI_SWAP_EFFECT_FLIP_DISCARD;
265 278
279 for (const UINT count : {0u, 1u, DXGI_MAX_SWAP_CHAIN_BUFFERS + 1u}) {
280 DXGI_SWAP_CHAIN_DESC1 invalid = scd;
281 invalid.BufferCount = count;
282 IDXGISwapChain1* rejected = nullptr;
283 const HRESULT hr = factory->CreateSwapChainForHwnd(queue, hwnd, &invalid, nullptr, nullptr, &rejected);
284 if (rejected) {
285 rejected->Release();
286 return fail("CreateSwapChainForHwnd returned a swapchain for an invalid buffer count");
287 }
288 if (hr != DXGI_ERROR_INVALID_CALL) return fail("CreateSwapChainForHwnd invalid buffer count HRESULT");
289 }
290
266 IDXGISwapChain1* sc1 = nullptr; 291 IDXGISwapChain1* sc1 = nullptr;
267 if (FAILED(factory->CreateSwapChainForHwnd(queue, hwnd, &scd, nullptr, nullptr, &sc1)) || !sc1) 292 if (FAILED(factory->CreateSwapChainForHwnd(queue, hwnd, &scd, nullptr, nullptr, &sc1)) || !sc1)
268 return fail("CreateSwapChainForHwnd"); 293 return fail("CreateSwapChainForHwnd");
@@ -270,6 +295,8 @@ int main() {
270 if (FAILED(sc1->QueryInterface(IID_PPV_ARGS(&sc))) || !sc) return fail("QI IDXGISwapChain3"); 295 if (FAILED(sc1->QueryInterface(IID_PPV_ARGS(&sc))) || !sc) return fail("QI IDXGISwapChain3");
271 sc1->Release(); 296 sc1->Release();
272 297
298 if (!check_statistics_disjoint(sc)) return fail("initial frame-statistics disjoint notification");
299
273 ID3D12CommandQueue* got_queue = nullptr; 300 ID3D12CommandQueue* got_queue = nullptr;
274 if (FAILED(sc->GetDevice(IID_PPV_ARGS(&got_queue))) || got_queue != queue) { 301 if (FAILED(sc->GetDevice(IID_PPV_ARGS(&got_queue))) || got_queue != queue) {
275 if (got_queue) got_queue->Release(); 302 if (got_queue) got_queue->Release();
@@ -406,6 +433,25 @@ int main() {
406 return 0; 433 return 0;
407 }; 434 };
408 435
436 // Invalid counts must leave the initial back buffers usable for the first frame.
437 {
438 DXGI_SWAP_CHAIN_DESC1 before_resize{};
439 if (FAILED(sc->GetDesc1(&before_resize))) return fail("GetDesc1 before invalid resizes");
440 const std::vector<UINT> node_masks(DXGI_MAX_SWAP_CHAIN_BUFFERS + 1, 1);
441 const std::vector<IUnknown*> present_queues(DXGI_MAX_SWAP_CHAIN_BUFFERS + 1, queue);
442 for (const UINT count : {1u, DXGI_MAX_SWAP_CHAIN_BUFFERS + 1u}) {
443 if (sc->ResizeBuffers(count, 64, 64, DXGI_FORMAT_UNKNOWN, 0) != E_INVALIDARG)
444 return fail("ResizeBuffers invalid buffer count HRESULT");
445 if (sc->ResizeBuffers1(count, 64, 64, DXGI_FORMAT_UNKNOWN, 0, node_masks.data(), present_queues.data()) !=
446 E_INVALIDARG)
447 return fail("ResizeBuffers1 invalid buffer count HRESULT");
448 }
449 DXGI_SWAP_CHAIN_DESC1 after_resize{};
450 if (FAILED(sc->GetDesc1(&after_resize)) || after_resize.BufferCount != before_resize.BufferCount ||
451 after_resize.Width != before_resize.Width || after_resize.Height != before_resize.Height)
452 return fail("Invalid resize changed swapchain buffers");
453 }
454
409 // Frame 1: 128x128 clear to (64, 128, 255, 255), read back all 16,384 pixels, Present. 455 // Frame 1: 128x128 clear to (64, 128, 255, 255), read back all 16,384 pixels, Present.
410 const float blue_ish[4] = {64.0f / 255.0f, 128.0f / 255.0f, 1.0f, 1.0f}; 456 const float blue_ish[4] = {64.0f / 255.0f, 128.0f / 255.0f, 1.0f, 1.0f};
411 if (run_clear_readback_present(128, 128, blue_ish, 64, 128, 255) != 0) return 1; 457 if (run_clear_readback_present(128, 128, blue_ish, 64, 128, 255) != 0) return 1;
@@ -593,13 +639,14 @@ int main() {
593 if (sc->GetLastPresentCount(nullptr) != E_INVALIDARG) 639 if (sc->GetLastPresentCount(nullptr) != E_INVALIDARG)
594 return fail("GetLastPresentCount(nullptr) should return E_INVALIDARG"); 640 return fail("GetLastPresentCount(nullptr) should return E_INVALIDARG");
595 641
642 if (!check_statistics_disjoint(sc)) return fail("post-resize frame-statistics disjoint notification");
596 DXGI_FRAME_STATISTICS stats{}; 643 DXGI_FRAME_STATISTICS stats{};
597 if (FAILED(sc->GetFrameStatistics(&stats)) || stats.PresentCount != count_before || 644 if (FAILED(sc->GetFrameStatistics(&stats)) || stats.PresentCount != count_before ||
598 stats.PresentRefreshCount != count_before || stats.SyncRefreshCount != count_before || 645 stats.PresentRefreshCount != count_before || stats.SyncRefreshCount != count_before ||
599 stats.SyncQPCTime.QuadPart == 0) 646 stats.SyncQPCTime.QuadPart == 0)
600 return fail("GetFrameStatistics values"); 647 return fail("GetFrameStatistics values");
601 if (sc->GetFrameStatistics(nullptr) != E_INVALIDARG) 648 if (sc->GetFrameStatistics(nullptr) != DXGI_ERROR_INVALID_CALL)
602 return fail("GetFrameStatistics(nullptr) should return E_INVALIDARG"); 649 return fail("GetFrameStatistics(nullptr) should return DXGI_ERROR_INVALID_CALL");
603 } 650 }
604 651
605 // SwapChain::GetParent and non-waitable SetMaximumFrameLatency/GetMaximumFrameLatency (host DXGI returns 652 // SwapChain::GetParent and non-waitable SetMaximumFrameLatency/GetMaximumFrameLatency (host DXGI returns
@@ -731,6 +778,8 @@ int main() {
731 // Zero width or height means the window's client area, in ResizeBuffers (the usual WM_SIZE call) and at 778 // Zero width or height means the window's client area, in ResizeBuffers (the usual WM_SIZE call) and at
732 // creation; host DXGI: ResizeBuffers(0, 0, 0) after resizing the window gives the new client size. 779 // creation; host DXGI: ResizeBuffers(0, 0, 0) after resizing the window gives the new client size.
733 { 780 {
781 DXGI_SWAP_CHAIN_DESC1 before_zero{};
782 if (FAILED(sc->GetDesc1(&before_zero))) return fail("GetDesc1 before zero-count resize");
734 RECT wr{0, 0, 300, 200}; 783 RECT wr{0, 0, 300, 200};
735 AdjustWindowRect(&wr, WS_OVERLAPPEDWINDOW, FALSE); 784 AdjustWindowRect(&wr, WS_OVERLAPPEDWINDOW, FALSE);
736 SetWindowPos(hwnd, nullptr, 0, 0, wr.right - wr.left, wr.bottom - wr.top, SWP_NOMOVE | SWP_NOZORDER); 785 SetWindowPos(hwnd, nullptr, 0, 0, wr.right - wr.left, wr.bottom - wr.top, SWP_NOMOVE | SWP_NOZORDER);
@@ -738,7 +787,8 @@ int main() {
738 GetClientRect(hwnd, &cr); 787 GetClientRect(hwnd, &cr);
739 if (FAILED(sc->ResizeBuffers(0, 0, 0, DXGI_FORMAT_UNKNOWN, 0))) return fail("ResizeBuffers(0, 0, 0)"); 788 if (FAILED(sc->ResizeBuffers(0, 0, 0, DXGI_FORMAT_UNKNOWN, 0))) return fail("ResizeBuffers(0, 0, 0)");
740 DXGI_SWAP_CHAIN_DESC1 d{}; 789 DXGI_SWAP_CHAIN_DESC1 d{};
741 sc->GetDesc1(&d); 790 if (FAILED(sc->GetDesc1(&d)) || d.BufferCount != before_zero.BufferCount)
791 return fail("ResizeBuffers(0, 0, 0) changed the buffer count");
742 if (d.Width != UINT(cr.right) || d.Height != UINT(cr.bottom)) { 792 if (d.Width != UINT(cr.right) || d.Height != UINT(cr.bottom)) {
743 std::fprintf(stderr, "FAIL: ResizeBuffers(0, 0, 0) gave %ux%u, client area is %ldx%ld\n", d.Width, d.Height, 793 std::fprintf(stderr, "FAIL: ResizeBuffers(0, 0, 0) gave %ux%u, client area is %ldx%ld\n", d.Width, d.Height,
744 cr.right, cr.bottom); 794 cr.right, cr.bottom);
@@ -778,11 +828,31 @@ int main() {
778 return fail("CheckFeatureSupport should reject null data or wrong size with E_INVALIDARG"); 828 return fail("CheckFeatureSupport should reject null data or wrong size with E_INVALIDARG");
779 factory5->Release(); 829 factory5->Release();
780 830
831 constexpr UINT tearing_flag = DXGI_SWAP_CHAIN_FLAG_ALLOW_TEARING;
832 constexpr UINT waitable_flag = DXGI_SWAP_CHAIN_FLAG_FRAME_LATENCY_WAITABLE_OBJECT;
833 constexpr UINT both_flags = tearing_flag | waitable_flag;
834 const UINT node_masks[2] = {1, 1};
835 IUnknown* const present_queues[2] = {queue, queue};
836 const auto rejects_flag_change = [&](IDXGISwapChain3* chain, UINT flags) {
837 DXGI_SWAP_CHAIN_DESC1 before{}, after{};
838 if (FAILED(chain->GetDesc1(&before))) return false;
839 const UINT width = before.Width + 1;
840 return chain->ResizeBuffers(0, width, before.Height, DXGI_FORMAT_UNKNOWN, flags) == E_INVALIDARG &&
841 chain->ResizeBuffers1(2, width, before.Height, DXGI_FORMAT_UNKNOWN, flags,
842 node_masks, present_queues) == E_INVALIDARG &&
843 SUCCEEDED(chain->GetDesc1(&after)) && after.Flags == before.Flags &&
844 after.BufferCount == before.BufferCount && after.Width == before.Width &&
845 after.Height == before.Height;
846 };
847
781 // Non-waitable, non-tearing swapchain: GetFrameLatencyWaitableObject is null and ALLOW_TEARING is rejected. 848 // Non-waitable, non-tearing swapchain: GetFrameLatencyWaitableObject is null and ALLOW_TEARING is rejected.
849 for (UINT flags : {waitable_flag, tearing_flag, both_flags})
850 if (!rejects_flag_change(sc, flags)) return fail("Resize accepted adding a creation-only flag");
782 if (sc->GetFrameLatencyWaitableObject() != nullptr) 851 if (sc->GetFrameLatencyWaitableObject() != nullptr)
783 return fail("Non-waitable swapchain should return nullptr from GetFrameLatencyWaitableObject"); 852 return fail("Non-waitable swapchain should return nullptr from GetFrameLatencyWaitableObject");
784 if (sc->Present(0, DXGI_PRESENT_ALLOW_TEARING) != DXGI_ERROR_INVALID_CALL) 853 if (sc->Present(0, DXGI_PRESENT_ALLOW_TEARING) != DXGI_ERROR_INVALID_CALL)
785 return fail("Present(ALLOW_TEARING) on non-tearing swapchain should return DXGI_ERROR_INVALID_CALL"); 854 return fail("Present(ALLOW_TEARING) on non-tearing swapchain should return DXGI_ERROR_INVALID_CALL");
855 if (FAILED(sc->Present(0, 0))) return fail("Present after rejected resize on a plain swapchain");
786 856
787 HWND hwnd3 = create_test_window(128, 96); 857 HWND hwnd3 = create_test_window(128, 96);
788 if (!hwnd3) return fail("CreateWindowExW (third)"); 858 if (!hwnd3) return fail("CreateWindowExW (third)");
@@ -790,7 +860,7 @@ int main() {
790 wdesc.Width = 128; 860 wdesc.Width = 128;
791 wdesc.Height = 96; 861 wdesc.Height = 96;
792 wdesc.Format = DXGI_FORMAT_R10G10B10A2_UNORM; // also tests presenting an untouched offscreen backbuffer 862 wdesc.Format = DXGI_FORMAT_R10G10B10A2_UNORM; // also tests presenting an untouched offscreen backbuffer
793 wdesc.Flags = DXGI_SWAP_CHAIN_FLAG_ALLOW_TEARING | DXGI_SWAP_CHAIN_FLAG_FRAME_LATENCY_WAITABLE_OBJECT; 863 wdesc.Flags = both_flags;
794 IDXGISwapChain1* wsc1 = nullptr; 864 IDXGISwapChain1* wsc1 = nullptr;
795 if (FAILED(factory->CreateSwapChainForHwnd(queue, hwnd3, &wdesc, nullptr, nullptr, &wsc1)) || !wsc1) 865 if (FAILED(factory->CreateSwapChainForHwnd(queue, hwnd3, &wdesc, nullptr, nullptr, &wsc1)) || !wsc1)
796 return fail("CreateSwapChainForHwnd (tearing + waitable)"); 866 return fail("CreateSwapChainForHwnd (tearing + waitable)");
@@ -798,6 +868,8 @@ int main() {
798 if (FAILED(wsc1->QueryInterface(IID_PPV_ARGS(&wsc))) || !wsc) return fail("QI IDXGISwapChain3 (waitable)"); 868 if (FAILED(wsc1->QueryInterface(IID_PPV_ARGS(&wsc))) || !wsc) return fail("QI IDXGISwapChain3 (waitable)");
799 wsc1->Release(); 869 wsc1->Release();
800 870
871 for (UINT flags : {0u, waitable_flag, tearing_flag})
872 if (!rejects_flag_change(wsc, flags)) return fail("Resize accepted removing a creation-only flag");
801 DXGI_SWAP_CHAIN_DESC1 got_desc{}; 873 DXGI_SWAP_CHAIN_DESC1 got_desc{};
802 if (FAILED(wsc->GetDesc1(&got_desc)) || got_desc.Flags != wdesc.Flags) 874 if (FAILED(wsc->GetDesc1(&got_desc)) || got_desc.Flags != wdesc.Flags)
803 return fail("Waitable swapchain GetDesc1 did not preserve Flags"); 875 return fail("Waitable swapchain GetDesc1 did not preserve Flags");
@@ -817,13 +889,134 @@ int main() {
817 return fail("Present(1, ALLOW_TEARING) should return DXGI_ERROR_INVALID_CALL"); 889 return fail("Present(1, ALLOW_TEARING) should return DXGI_ERROR_INVALID_CALL");
818 if (FAILED(wsc->Present(0, DXGI_PRESENT_ALLOW_TEARING))) 890 if (FAILED(wsc->Present(0, DXGI_PRESENT_ALLOW_TEARING)))
819 return fail("Present(0, ALLOW_TEARING) on untouched 10-bit offscreen swapchain failed"); 891 return fail("Present(0, ALLOW_TEARING) on untouched 10-bit offscreen swapchain failed");
892 if (!check_statistics_disjoint(wsc)) return fail("first statistics query after Present should be disjoint");
820 if (WaitForSingleObject(waitable, 5000) != WAIT_OBJECT_0) 893 if (WaitForSingleObject(waitable, 5000) != WAIT_OBJECT_0)
821 return fail("Post-Present WaitForSingleObject on waitable swapchain failed"); 894 return fail("Post-Present WaitForSingleObject on waitable swapchain failed");
895 if (FAILED(wsc->ResizeBuffers(0, wdesc.Width + 1, wdesc.Height, DXGI_FORMAT_UNKNOWN, both_flags)) ||
896 FAILED(wsc->GetDesc1(&got_desc)) || got_desc.Width != wdesc.Width + 1 || got_desc.Flags != both_flags)
897 return fail("ResizeBuffers with matching creation flags failed");
898 if (FAILED(wsc->Present(0, DXGI_PRESENT_ALLOW_TEARING)) ||
899 WaitForSingleObject(waitable, 5000) != WAIT_OBJECT_0)
900 return fail("Present or wait after resizing the waitable swapchain failed");
822 CloseHandle(waitable); 901 CloseHandle(waitable);
823 wsc->Release(); 902 wsc->Release();
824 DestroyWindow(hwnd3); 903 DestroyWindow(hwnd3);
825 } 904 }
826 905
906 // CreateSwapChainForCoreWindow & Occlusion status registration
907 {
908 // 1. Parameter validation
909 IDXGISwapChain1* sc_dummy = nullptr;
910 if (factory->CreateSwapChainForCoreWindow(queue, nullptr, &scd, nullptr, &sc_dummy) != E_INVALIDARG)
911 return fail("CreateSwapChainForCoreWindow(null window) should return E_INVALIDARG");
912 if (factory->CreateSwapChainForCoreWindow(nullptr, queue, &scd, nullptr, &sc_dummy) != E_INVALIDARG)
913 return fail("CreateSwapChainForCoreWindow(null device) should return E_INVALIDARG");
914 if (factory->CreateSwapChainForCoreWindow(queue, queue, nullptr, nullptr, &sc_dummy) != E_INVALIDARG)
915 return fail("CreateSwapChainForCoreWindow(null desc) should return E_INVALIDARG");
916 if (factory->CreateSwapChainForCoreWindow(queue, queue, &scd, nullptr, nullptr) != E_POINTER)
917 return fail("CreateSwapChainForCoreWindow(null out) should return E_POINTER");
918
919 // Non-CoreWindow IUnknown
920 if (factory->CreateSwapChainForCoreWindow(queue, queue, &scd, nullptr, &sc_dummy) != DXGI_ERROR_INVALID_CALL)
921 return fail("CreateSwapChainForCoreWindow with non-CoreWindow should return DXGI_ERROR_INVALID_CALL");
922
923 // 2. Mock ICoreWindow with ICoreWindowInterop
924 static constexpr GUID kIID_ICoreWindowInterop = {
925 0x45D64A29, 0xA63E, 0x4CB6, {0xB4, 0x98, 0x57, 0x81, 0xD2, 0x98, 0xCB, 0x4F}};
926 struct MockCoreWindow final : public IUnknown {
927 HWND window_handle = nullptr;
928 std::atomic<ULONG> refs{1};
929
930 HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void** out) override {
931 if (!out) return E_POINTER;
932 if (riid == IID_IUnknown || riid == kIID_ICoreWindowInterop) {
933 *out = this;
934 AddRef();
935 return S_OK;
936 }
937 *out = nullptr;
938 return E_NOINTERFACE;
939 }
940 ULONG STDMETHODCALLTYPE AddRef() override { return ++refs; }
941 ULONG STDMETHODCALLTYPE Release() override {
942 ULONG r = --refs;
943 if (!r) delete this;
944 return r;
945 }
946 virtual HRESULT STDMETHODCALLTYPE get_WindowHandle(HWND* hwnd) {
947 if (!hwnd) return E_POINTER;
948 *hwnd = window_handle;
949 return S_OK;
950 }
951 virtual HRESULT STDMETHODCALLTYPE put_MessageHandled(unsigned char) { return S_OK; }
952 };
953
954 auto* mock_cw = new MockCoreWindow();
955 // Null HWND in interop
956 if (factory->CreateSwapChainForCoreWindow(queue, mock_cw, &scd, nullptr, &sc_dummy) != DXGI_ERROR_INVALID_CALL) {
957 mock_cw->Release();
958 return fail("CreateSwapChainForCoreWindow with null HWND should return DXGI_ERROR_INVALID_CALL");
959 }
960
961 // Valid HWND in mock CoreWindow
962 HWND hwnd4 = create_test_window(160, 120);
963 if (!hwnd4) {
964 mock_cw->Release();
965 return fail("CreateWindowExW (fourth)");
966 }
967 mock_cw->window_handle = hwnd4;
968 IDXGISwapChain1* cw_sc1 = nullptr;
969 if (FAILED(factory->CreateSwapChainForCoreWindow(queue, mock_cw, &scd, nullptr, &cw_sc1)) || !cw_sc1) {
970 mock_cw->Release();
971 DestroyWindow(hwnd4);
972 return fail("CreateSwapChainForCoreWindow with valid MockCoreWindow failed");
973 }
974 IDXGISwapChain3* cw_sc = nullptr;
975 if (FAILED(cw_sc1->QueryInterface(IID_PPV_ARGS(&cw_sc))) || !cw_sc) {
976 cw_sc1->Release();
977 mock_cw->Release();
978 DestroyWindow(hwnd4);
979 return fail("QI IDXGISwapChain3 on CoreWindow swapchain failed");
980 }
981 cw_sc1->Release();
982 DXGI_SWAP_CHAIN_DESC1 cw_desc{};
983 if (FAILED(cw_sc->GetDesc1(&cw_desc)) || cw_desc.Width != scd.Width || cw_desc.Height != scd.Height) {
984 cw_sc->Release();
985 mock_cw->Release();
986 DestroyWindow(hwnd4);
987 return fail("GetDesc1 on CoreWindow swapchain mismatch");
988 }
989 if (FAILED(cw_sc->Present(0, 0))) {
990 cw_sc->Release();
991 mock_cw->Release();
992 DestroyWindow(hwnd4);
993 return fail("Present on CoreWindow swapchain failed");
994 }
995 cw_sc->Release();
996 mock_cw->Release();
997 DestroyWindow(hwnd4);
998
999 // 3. Occlusion status registration
1000 DWORD cookie1 = 0, cookie2 = 0;
1001 if (factory->RegisterOcclusionStatusWindow(nullptr, WM_USER, &cookie1) != DXGI_ERROR_INVALID_CALL)
1002 return fail("RegisterOcclusionStatusWindow(null hwnd) should return DXGI_ERROR_INVALID_CALL");
1003 if (factory->RegisterOcclusionStatusWindow(hwnd, WM_USER, nullptr) != DXGI_ERROR_INVALID_CALL)
1004 return fail("RegisterOcclusionStatusWindow(null cookie) should return DXGI_ERROR_INVALID_CALL");
1005 if (FAILED(factory->RegisterOcclusionStatusWindow(hwnd, WM_USER, &cookie1)) || cookie1 == 0)
1006 return fail("RegisterOcclusionStatusWindow failed");
1007
1008 HANDLE ev = CreateEventW(nullptr, FALSE, FALSE, nullptr);
1009 if (factory->RegisterOcclusionStatusEvent(nullptr, &cookie2) != DXGI_ERROR_INVALID_CALL)
1010 return fail("RegisterOcclusionStatusEvent(null event) should return DXGI_ERROR_INVALID_CALL");
1011 if (factory->RegisterOcclusionStatusEvent(ev, nullptr) != DXGI_ERROR_INVALID_CALL)
1012 return fail("RegisterOcclusionStatusEvent(null cookie) should return DXGI_ERROR_INVALID_CALL");
1013 if (FAILED(factory->RegisterOcclusionStatusEvent(ev, &cookie2)) || cookie2 == 0 || cookie2 == cookie1)
1014 return fail("RegisterOcclusionStatusEvent failed or duplicated cookie");
1015 factory->UnregisterOcclusionStatus(cookie1);
1016 factory->UnregisterOcclusionStatus(cookie2);
1017 CloseHandle(ev);
1018 }
1019
827 rtv_heap->Release(); 1020 rtv_heap->Release();
828 sc->Release(); 1021 sc->Release();
829 fence->Release(); 1022 fence->Release();
@@ -843,7 +1036,7 @@ int main() {
843 return 1; 1036 return 1;
844 } 1037 }
845 std::printf("device: %s (validation %s)\n", chosen.deviceName, val_active ? "on" : "off"); 1038 std::printf("device: %s (validation %s)\n", chosen.deviceName, val_active ? "on" : "off");
846 std::printf("dxgi_swapchain_test: PASS (CreateSwapChainForHwnd, GetBuffer+GetDesc, clear+readback, Present, " 1039 std::printf("dxgi_swapchain_test: PASS (CreateSwapChainForHwnd, CreateSwapChainForCoreWindow, occlusion status, "
847 "ResizeBuffers; 0 validation errors)\n"); 1040 "GetBuffer+GetDesc, clear+readback, Present, ResizeBuffers; 0 validation errors)\n");
848 return 0; 1041 return 0;
849} 1042}
diff --git a/runtime/test/file_system_test.cpp b/runtime/test/file_system_test.cpp
index c33098d2a..1fcaf6710 100644
--- a/runtime/test/file_system_test.cpp
+++ b/runtime/test/file_system_test.cpp
@@ -99,7 +99,7 @@ int main() {
99 write_path(package / "data" / "hello.txt", "package"); 99 write_path(package / "data" / "hello.txt", "package");
100 write_path(package / "data" / "dup.txt", "package"); 100 write_path(package / "data" / "dup.txt", "package");
101 write_path(package / "data" / "bye.txt", "package"); 101 write_path(package / "data" / "bye.txt", "package");
102 std::filesystem::create_directories(package / "data" / "sub"); 102 write_path(package / "data" / "sub" / "nested.txt", "nested");
103 103
104 rt::fs::configure(package, overlay); 104 rt::fs::configure(package, overlay);
105 check(rt::fs::game_dir() == package, "configure() sets the game folder"); 105 check(rt::fs::game_dir() == package, "configure() sets the game folder");
@@ -249,6 +249,15 @@ int main() {
249 SetLastError(0); 249 SetLastError(0);
250 check(delete_w(L"GAME:\\nope\\missing.txt") == FALSE && GetLastError() == ERROR_FILE_NOT_FOUND, 250 check(delete_w(L"GAME:\\nope\\missing.txt") == FALSE && GetLastError() == ERROR_FILE_NOT_FOUND,
251 "deleting a file that never existed reports ERROR_FILE_NOT_FOUND"); 251 "deleting a file that never existed reports ERROR_FILE_NOT_FOUND");
252
253 // Deleting a nested package file creates parent directories inside .gta6rt-deleted/; those marker parent
254 // directories must not hide the corresponding ancestor directories in the package.
255 check(delete_w(L"GAME:\\data\\sub\\nested.txt") != FALSE, "DeleteFileW accepts a nested package file");
256 const DWORD sub_attrs = attributes_w(L"GAME:\\data\\sub");
257 check(sub_attrs != INVALID_FILE_ATTRIBUTES && (sub_attrs & FILE_ATTRIBUTE_DIRECTORY) != 0,
258 "deleting a nested package file does not hide its parent folder");
259 check(contains(list(first_w, next_w, find_close, L"GAME:\\data\\*"), L"sub"),
260 "the parent folder stays listed after deleting a nested package file");
252 } 261 }
253 262
254 // Nothing leaves the package and the overlay. 263 // Nothing leaves the package and the overlay.
diff --git a/runtime/test/fsr_dispatch_test.cpp b/runtime/test/fsr_dispatch_test.cpp
index 7affaee7a..9a66071ac 100644
--- a/runtime/test/fsr_dispatch_test.cpp
+++ b/runtime/test/fsr_dispatch_test.cpp
@@ -28,7 +28,7 @@
28// driver refuses one of its textures (DXGI_FORMAT_R9G9B9E5_SHAREDEXP with ALLOW_UNORDERED_ACCESS); on WARP the 28// driver refuses one of its textures (DXGI_FORMAT_R9G9B9E5_SHAREDEXP with ALLOW_UNORDERED_ACCESS); on WARP the
29// context is created as is. The other backend ids are controls: they end in FFX_API_RETURN_ERROR before the device 29// context is created as is. The other backend ids are controls: they end in FFX_API_RETURN_ERROR before the device
30// is touched. In step 7 the dispatch is recorded up to the DLL's compute pipeline, which a PC device cannot create 30// is touched. In step 7 the dispatch is recorded up to the DLL's compute pipeline, which a PC device cannot create
31// (slot 67 is console-only and refused; slot 62's code is not a PC shader). The INFO lines are the measurement; the 31// (slot 67 and 62 codes are not PC shaders). The INFO lines are the measurement; the
32// PASS/FAIL checks only cover what is known to work. 32// PASS/FAIL checks only cover what is known to work.
33#include <windows.h> 33#include <windows.h>
34 34
@@ -958,7 +958,7 @@ int main() {
958 note(" device slot 62 (compute pipeline from a D3D12_COMPUTE_PIPELINE_STATE_DESC) called " + 958 note(" device slot 62 (compute pipeline from a D3D12_COMPUTE_PIPELINE_STATE_DESC) called " +
959 std::to_string(g_slot62_calls) + "x, last HRESULT " + hex(static_cast<uint32_t>(g_slot62_hr))); 959 std::to_string(g_slot62_calls) + "x, last HRESULT " + hex(static_cast<uint32_t>(g_slot62_hr)));
960 if (g_formatted) note(" the DLL formatted HRESULT " + hex(g_first_formatted)); 960 if (g_formatted) note(" the DLL formatted HRESULT " + hex(g_first_formatted));
961 // On a PC device both pipeline paths fail (67 is refused, 62's code is not a PC shader); on the 961 // On a PC device both pipeline paths fail (neither slot 67's nor 62's code is a PC shader); on the
962 // Vulkan device CreateRootSignature (slot 16) is not implemented yet. Either way the dispatch goes 962 // Vulkan device CreateRootSignature (slot 16) is not implemented yet. Either way the dispatch goes
963 // on with a null pipeline and faults when it records it (RVA 0x65ff reads the pipeline's +0x10, 963 // on with a null pipeline and faults when it records it (RVA 0x65ff reads the pipeline's +0x10,
964 // the same pointer it passes to SetPipelineState): a documented stop, not a test failure. 964 // the same pointer it passes to SetPipelineState): a documented stop, not a test failure.
diff --git a/runtime/test/gameinput_probe.cpp b/runtime/test/gameinput_probe.cpp
index aa077b257..32ddf5d91 100644
--- a/runtime/test/gameinput_probe.cpp
+++ b/runtime/test/gameinput_probe.cpp
@@ -85,12 +85,17 @@ int main(int argc, char** argv) {
85 if (input->GetCurrentReading(GameInputKindGamepad, nullptr, &r) == S_OK) { 85 if (input->GetCurrentReading(GameInputKindGamepad, nullptr, &r) == S_OK) {
86 GameInputGamepadState s{}; 86 GameInputGamepadState s{};
87 GameInputUiNavigationState ui{}; 87 GameInputUiNavigationState ui{};
88 GameInputMotionState m{};
89 const bool motion = r->GetMotionState(&m);
88 r->GetGamepadState(&s); 90 r->GetGamepadState(&s);
89 r->GetUiNavigationState(&ui); 91 r->GetUiNavigationState(&ui);
90 std::printf("\rbuttons=%04x ui=%06x LT=%.2f RT=%.2f L=(%+.2f,%+.2f) R=(%+.2f,%+.2f) seq=%llu ", s.buttons, 92 std::printf("\rbuttons=%04x ui=%06x LT=%.2f RT=%.2f L=(%+.2f,%+.2f) R=(%+.2f,%+.2f) seq=%llu ", s.buttons,
91 ui.buttons, s.leftTrigger, s.rightTrigger, s.leftThumbstickX, s.leftThumbstickY, 93 ui.buttons, s.leftTrigger, s.rightTrigger, s.leftThumbstickX, s.leftThumbstickY,
92 s.rightThumbstickX, s.rightThumbstickY, 94 s.rightThumbstickX, s.rightThumbstickY,
93 static_cast<unsigned long long>(r->GetSequenceNumber(GameInputKindGamepad))); 95 static_cast<unsigned long long>(r->GetSequenceNumber(GameInputKindGamepad)));
96 if (motion) // fractions of motionInfo's maxima: accel includes gravity, so a resting pad shows ~0.5 g
97 std::printf("\n[a]=(%+.2f,%+.2f,%+.2f) [w]=(%+.2f,%+.2f,%+.2f) ", m.accelerationX, m.accelerationY,
98 m.accelerationZ, m.angularVelocityX, m.angularVelocityY, m.angularVelocityZ);
94 std::fflush(stdout); 99 std::fflush(stdout);
95 r->Release(); 100 r->Release();
96 } 101 }
diff --git a/runtime/test/gameinput_test.cpp b/runtime/test/gameinput_test.cpp
index a0bcaf444..d1923ceaf 100644
--- a/runtime/test/gameinput_test.cpp
+++ b/runtime/test/gameinput_test.cpp
@@ -80,7 +80,7 @@ bool SDLCALL on_effect(void* u, const void* data, int size) {
80} 80}
81void SDLCALL on_player(void* u, int index) { static_cast<Pad*>(u)->player = index; } 81void SDLCALL on_player(void* u, int index) { static_cast<Pad*>(u)->player = index; }
82 82
83void attach(Pad& pad, const char* name, uint16_t vendor, uint16_t product, bool trigger_motors) { 83void attach(Pad& pad, const char* name, uint16_t vendor, uint16_t product, bool trigger_motors, bool sensors = false) {
84 SDL_VirtualJoystickDesc d; 84 SDL_VirtualJoystickDesc d;
85 SDL_INIT_INTERFACE(&d); 85 SDL_INIT_INTERFACE(&d);
86 d.type = SDL_JOYSTICK_TYPE_GAMEPAD; 86 d.type = SDL_JOYSTICK_TYPE_GAMEPAD;
@@ -97,6 +97,11 @@ void attach(Pad& pad, const char* name, uint16_t vendor, uint16_t product, bool
97 d.SetLED = on_led; 97 d.SetLED = on_led;
98 d.SendEffect = on_effect; 98 d.SendEffect = on_effect;
99 d.SetPlayerIndex = on_player; 99 d.SetPlayerIndex = on_player;
100 static const SDL_VirtualJoystickSensorDesc kSensors[] = {{SDL_SENSOR_GYRO, 250.0f}, {SDL_SENSOR_ACCEL, 250.0f}};
101 if (sensors) {
102 d.nsensors = 2;
103 d.sensors = kSensors;
104 }
100 pad.id = SDL_AttachVirtualJoystick(&d); 105 pad.id = SDL_AttachVirtualJoystick(&d);
101 pad.js = pad.id ? SDL_OpenJoystick(pad.id) : nullptr; 106 pad.js = pad.id ? SDL_OpenJoystick(pad.id) : nullptr;
102 if (pad.js) { // triggers at rest: the full-range virtual axis maps -32768 to 0 107 if (pad.js) { // triggers at rest: the full-range virtual axis maps -32768 to 0
@@ -206,6 +211,134 @@ bool sticks_at_rest(const GameInputGamepadState& st) {
206 st.rightThumbstickY == 0 && st.leftTrigger == 0 && st.rightTrigger == 0; 211 st.rightThumbstickY == 0 && st.leftTrigger == 0 && st.rightTrigger == 0;
207} 212}
208 213
214// ---- motion: SDL sensors through the shim ----
215void send_motion(Pad& pad, float ax, float ay, float az, float gx, float gy, float gz) {
216 const Uint64 ts = SDL_GetTicksNS();
217 const float accel[3] = {ax, ay, az};
218 const float gyro[3] = {gx, gy, gz};
219 SDL_SendJoystickVirtualSensorData(pad.js, SDL_SENSOR_ACCEL, ts, accel, 3);
220 SDL_SendJoystickVirtualSensorData(pad.js, SDL_SENSOR_GYRO, ts, gyro, 3);
221}
222
223GameInputMotionState motion_state(IGameInput* input, IGameInputDevice* dev, bool* ok = nullptr) {
224 GameInputMotionState ms{};
225 IGameInputReading* r = nullptr;
226 const bool got = input->GetCurrentReading(GameInputKindMotion, dev, &r) == S_OK && r && r->GetMotionState(&ms);
227 if (r) r->Release();
228 if (ok) *ok = got;
229 return ms;
230}
231
232void test_motion(IGameInput* input) {
233 const size_t events_before = g_device_events.size(); // other tests' events are still queued in the vector
234 Pad gyro_pad, plain;
235 attach(gyro_pad, "Leonida virtual gyro pad", 0x054C, 0x0CE6, false, true); // Sony ids, sensors on
236 attach(plain, "Leonida virtual plain pad", 0x045E, 0x02FF, false);
237 rt::gameinput::poll();
238 check(rt::gameinput::connected_count() == 2, "motion: both pads connected");
239 // The connect events for these two pads are the first two CONNECTED events after `events_before`, deduplicated
240 // by device: earlier test sections leave their device callbacks registered, so every connect is delivered more
241 // than once, and a disconnect from a previous test may be queued in between.
242 std::vector<IGameInputDevice*> found;
243 for (size_t i = events_before; i < g_device_events.size() && found.size() < 2; ++i) {
244 const DeviceEvent& e = g_device_events[i];
245 if (!(e.current & GameInputDeviceConnected)) continue;
246 if (std::find(found.begin(), found.end(), e.device) != found.end()) continue;
247 found.push_back(e.device);
248 }
249 IGameInputDevice* mdev = found.size() > 0 ? found[0] : nullptr; // attach order: gyro pad first
250 IGameInputDevice* pdev = found.size() > 1 ? found[1] : nullptr;
251 if (mdev) mdev->AddRef();
252 if (pdev) pdev->AddRef();
253 check(mdev && pdev, "motion: both device objects arrived");
254 if (!mdev || !pdev) return;
255
256 const GameInputDeviceInfo* mi = mdev->GetDeviceInfo();
257 const GameInputDeviceInfo* pi = pdev->GetDeviceInfo();
258 check((mi->supportedInput & GameInputKindMotion) != 0, "motion: the gyro pad reports GameInputKindMotion");
259 check((pi->supportedInput & GameInputKindMotion) == 0, "motion: the plain pad does not");
260 const GameInputMotionInfo* mmotion = static_cast<const GameInputMotionInfo*>(mi->motionInfo);
261 check(mmotion != nullptr && mmotion->maxAcceleration == 19.6133f && mmotion->maxAngularVelocity == 34.9066f &&
262 mmotion->maxMagneticFieldStrength == 0.0f,
263 "motion: motionInfo carries the shim's maxima (magnetometer unavailable)");
264 check(pi->motionInfo == nullptr, "motion: the plain pad's motionInfo is null");
265
266 // Before the first sensor sample arrives, SDL answers reads with zeros and the shim reports no motion at all.
267 IGameInputReading* r = nullptr;
268 GameInputMotionState unused{};
269 check(input->GetCurrentReading(GameInputKindGamepad, mdev, &r) == S_OK && r && !r->GetMotionState(&unused),
270 "motion: before the first sample, GetMotionState is false even on a sensor pad");
271 if (r) r->Release();
272
273 // 9.80665 m/s^2 is half of the 2 g maximum; 17.4533 rad/s is half of 2000 deg/s. A reading with the sample needs
274 // either a gamepad change or the ~8 ms motion cadence, so the test waits out the window before polling.
275 send_motion(gyro_pad, 0.0f, 0.0f, 9.80665f, 17.4533f, 0.0f, 0.0f);
276 Sleep(12);
277 rt::gameinput::poll();
278 bool got = false;
279 const GameInputMotionState ms = motion_state(input, mdev, &got);
280 check(got, "motion: GetMotionState true on a motion reading");
281 check(approx(ms.accelerationZ, 0.5f) && approx(ms.angularVelocityX, 0.5f),
282 "motion: accel and gyro normalised against the motionInfo maxima");
283 check(ms.accelerometerAccuracy == GameInputMotionAccuracyHigh && ms.gyroscopeAccuracy == GameInputMotionAccuracyHigh,
284 "motion: live sensors report High accuracy");
285 check(ms.magnetometerAccuracy == GameInputMotionAccuracyUnknown &&
286 ms.orientationAccuracy == GameInputMotionAccuracyUnknown,
287 "motion: sensors the shim does not provide report Unknown");
288
289 r = nullptr;
290 check(input->GetCurrentReading(GameInputKindMotion, pdev, &r) == GAMEINPUT_E_READING_NOT_FOUND && !r,
291 "motion: a motion query on the plain pad is READING_NOT_FOUND");
292 check(input->GetCurrentReading(GameInputKindGamepad, mdev, &r) == S_OK && r && !r->GetMotionState(nullptr) &&
293 (r->GetInputKind() & GameInputKindMotion),
294 "motion: GetMotionState(nullptr) is false; the gyro pad's reading kind includes Motion");
295 if (r) r->Release();
296 unused = {};
297 check(input->GetCurrentReading(GameInputKindGamepad, pdev, &r) == S_OK && r &&
298 !(r->GetInputKind() & GameInputKindMotion) && !r->GetMotionState(&unused),
299 "motion: the plain pad's reading has no motion kind and GetMotionState is false");
300 if (r) r->Release();
301
302 send_motion(gyro_pad, 100.0f, -100.0f, 0.0f, 0.0f, 0.0f, -100.0f);
303 Sleep(12);
304 rt::gameinput::poll();
305 const GameInputMotionState sat = motion_state(input, mdev);
306 check(sat.accelerationX == 1.0f && sat.accelerationY == -1.0f && sat.angularVelocityZ == -1.0f,
307 "motion: out-of-range sensor values clamp to the +-1 fraction range");
308
309 // The cadence: with the buttons idle, a changed gyro yields a new reading only once per ~8 ms window, not one
310 // per poll, so the history still spans the half second it is documented for.
311 send_motion(gyro_pad, 0.0f, 0.0f, 9.80665f, 0.0f, 0.0f, 0.0f);
312 rt::gameinput::poll();
313 IGameInputReading* first = nullptr;
314 check(input->GetCurrentReading(GameInputKindMotion, mdev, &first) == S_OK && first,
315 "motion: a reading exists after a sensor update");
316 send_motion(gyro_pad, 0.0f, 0.0f, 9.80665f, 34.9066f, 0.0f, 0.0f); // gravity stays: zero accel means "no sample"
317 rt::gameinput::poll();
318 IGameInputReading* none = nullptr;
319 check(input->GetNextReading(first, GameInputKindMotion, mdev, &none) == GAMEINPUT_E_READING_NOT_FOUND && !none,
320 "motion: no new reading within the 8 ms cadence window");
321 Sleep(12);
322 rt::gameinput::poll();
323 IGameInputReading* next = nullptr;
324 check(input->GetNextReading(first, GameInputKindMotion, mdev, &next) == S_OK && next,
325 "motion: after the window the latest sensor state is in a new reading");
326 if (next) {
327 GameInputMotionState later{};
328 check(next->GetMotionState(&later) && approx(later.angularVelocityX, 1.0f),
329 "motion: the new reading carries the newest gyro sample");
330 next->Release();
331 }
332 if (first) first->Release();
333
334 detach(gyro_pad);
335 detach(plain);
336 rt::gameinput::poll();
337 if (mdev) mdev->Release();
338 if (pdev) pdev->Release();
339 check(rt::gameinput::connected_count() == 0, "motion: both pads closed again");
340}
341
209// WASD, the mouse and its buttons. Runs in the focused mode with focus and nothing held. 342// WASD, the mouse and its buttons. Runs in the focused mode with focus and nothing held.
210void test_keyboard_pad_sticks(IGameInput* input, IGameInputDevice* kb) { 343void test_keyboard_pad_sticks(IGameInput* input, IGameInputDevice* kb) {
211 rt::gameinput::poll(); 344 rt::gameinput::poll();
@@ -965,6 +1098,7 @@ int main() {
965 1098
966 test_twins(input); 1099 test_twins(input);
967 test_keyboard_pad(input); 1100 test_keyboard_pad(input);
1101 test_motion(input);
968 input->Release(); 1102 input->Release();
969 1103
970 std::printf("%d checks, %d failures\n", g_checks, g_failures); 1104 std::printf("%d checks, %d failures\n", g_checks, g_failures);
diff --git a/runtime/test/glsl/cs_set0_sample.comp b/runtime/test/glsl/cs_set0_sample.comp
new file mode 100644
index 000000000..f007da556
--- /dev/null
+++ b/runtime/test/glsl/cs_set0_sample.comp
@@ -0,0 +1,77 @@
1#version 460
2// A compute shader that samples through set 0 the way translated shaders do, written to the translator's runtime
3// contract (docs/design.md, "User data", "Xbox GPU addresses" and "Images"; the lookup is tools/rdna2spirv.py
4// desc_probe), standing in for a translated one in d3d12_set0_compute_test. Its root arguments:
5// s0 a root constant: where the view slot to sample starts inside the view table, in dwords
6// s1 a root constant: the first element of the output it writes
7// s2:s3 a root UAV: the console VA of the output buffer
8// s4:s5 a descriptor table of views: a T# in the first eight dwords of each slot
9// s6:s7 a descriptor table of samplers: the S# of its first slot, four dwords
10// It loads the T# and the S# from the tables at heap base + VA, looks both up in the hash table at set 0 binding 2
11// (FNV-1a over the eight key dwords, eight probes, a miss is index 0; an S# key is its four dwords and four of
12// 0xFFFFFFFF), samples the 2D image array at binding 0 with the sampler array at binding 1, and writes
13// out[s1 + i] = the texel at ((i % 8) + 0.5, (i / 8) + 0.5) / 8 + (1, 0), as RGBA8 with red in the low byte.
14// The whole tile to the right in U: a sampler that wraps in U gives the texel at the same place in the image, one
15// that clamps gives the image's right edge. So the result depends on the S# as well as on the T#.
16// Set 0 is the device's bindless set. The D3D12 layer has it in the pipeline layout and binds it at the dispatch,
17// because the index lists bindings for this shader; nothing else in the test binds it.
18#extension GL_EXT_nonuniform_qualifier : require
19#extension GL_EXT_buffer_reference : require
20#extension GL_EXT_buffer_reference_uvec2 : require
21
22layout(local_size_x = 64) in;
23
24layout(buffer_reference, std430, buffer_reference_align = 4) buffer Words {
25 uint w[];
26};
27
28layout(push_constant) uniform UserData {
29 uint s[32];
30 uvec2 heap_base;
31 uvec2 code_base;
32} pc;
33
34layout(set = 0, binding = 0) uniform texture2D images[];
35layout(set = 0, binding = 1) uniform sampler samplers[];
36layout(set = 0, binding = 2, std430) readonly buffer DescriptorMap {
37 uint map[]; // mask, then 10 uints per slot: key[8], index, pad
38};
39
40uvec2 add64(uvec2 a, uvec2 b) {
41 uint carry;
42 const uint low = uaddCarry(a.x, b.x, carry);
43 return uvec2(low, a.y + b.y + carry);
44}
45
46Words at(uvec2 va) {
47 return Words(add64(pc.heap_base, va));
48}
49
50uint lookup(uint key[8]) {
51 uint h = 2166136261u;
52 for (int i = 0; i < 8; ++i) h = (h ^ key[i]) * 16777619u;
53 const uint mask = map[0];
54 for (uint k = 0; k < 8; ++k) {
55 const uint slot = 1 + ((h + k) & mask) * 10;
56 bool same = true;
57 for (int i = 0; i < 8; ++i) same = same && map[slot + i] == key[i];
58 if (same) return map[slot + 8];
59 }
60 return 0;
61}
62
63void main() {
64 const uint i = gl_GlobalInvocationID.x;
65 Words views = at(uvec2(pc.s[4], pc.s[5]));
66 Words sampler_table = at(uvec2(pc.s[6], pc.s[7]));
67 uint image_key[8], sampler_key[8];
68 for (int k = 0; k < 8; ++k) {
69 image_key[k] = views.w[pc.s[0] + k];
70 sampler_key[k] = k < 4 ? sampler_table.w[k] : 0xffffffffu;
71 }
72 const uint image = lookup(image_key), smp = lookup(sampler_key);
73 const vec2 uv = (vec2(i % 8, i / 8) + 0.5) / 8.0 + vec2(1.0, 0.0);
74 const vec4 texel = textureLod(sampler2D(images[image], samplers[smp]), uv, 0.0);
75 Words result = at(uvec2(pc.s[2], pc.s[3]));
76 result.w[pc.s[1] + i] = packUnorm4x8(texel);
77}
diff --git a/runtime/test/glsl/cs_sg_probe.comp b/runtime/test/glsl/cs_sg_probe.comp
new file mode 100644
index 000000000..921cf1a49
--- /dev/null
+++ b/runtime/test/glsl/cs_sg_probe.comp
@@ -0,0 +1,29 @@
1#version 460
2// A compute shader written to the translator's runtime contract that stores the subgroup size the driver ran it
3// with (gl_SubgroupSize) in out[0], for d3d12_subgroup_test. s0:s1 is a root UAV: the console VA of the output.
4#extension GL_EXT_buffer_reference : require
5#extension GL_EXT_buffer_reference_uvec2 : require
6#extension GL_KHR_shader_subgroup_basic : require
7
8layout(local_size_x = 64) in;
9
10layout(buffer_reference, std430, buffer_reference_align = 4) buffer Words {
11 uint w[];
12};
13
14layout(push_constant) uniform UserData {
15 uint s[32];
16 uvec2 heap_base;
17 uvec2 code_base;
18} pc;
19
20uvec2 add64(uvec2 a, uvec2 b) {
21 uint carry;
22 const uint low = uaddCarry(a.x, b.x, carry);
23 return uvec2(low, a.y + b.y + carry);
24}
25
26void main() {
27 Words out_words = Words(add64(pc.heap_base, uvec2(pc.s[0], pc.s[1])));
28 if (gl_LocalInvocationIndex == 0u) out_words.w[0] = gl_SubgroupSize;
29}
diff --git a/runtime/test/glsl/cs_user_data.comp b/runtime/test/glsl/cs_user_data.comp
index a932cc086..82779ccb1 100644
--- a/runtime/test/glsl/cs_user_data.comp
+++ b/runtime/test/glsl/cs_user_data.comp
@@ -36,8 +36,20 @@ Words at(uvec2 va) {
36void main() { 36void main() {
37 const uint i = gl_GlobalInvocationID.x; 37 const uint i = gl_GlobalInvocationID.x;
38 Words table = at(uvec2(pc.s[4], pc.s[5])); 38 Words table = at(uvec2(pc.s[4], pc.s[5]));
39 Words result = at(uvec2(pc.s[2], pc.s[3]));
40 if (pc.s[1] == 0u) {
41 // CBV V# mode: table holds a 16-byte GFX10 raw buffer descriptor written by CreateConstantBufferView.
42 const uint num_records = table.w[2];
43 const uint byte_off = pc.s[0] + i * 4u;
44 if (byte_off + 4u <= num_records) {
45 Words cbv = at(uvec2(table.w[0], table.w[1] & 0xFFFFu));
46 result.w[i] = cbv.w[byte_off >> 2u];
47 } else {
48 result.w[i] = 0u;
49 }
50 return;
51 }
39 Words constants = at(uvec2(table.w[0], table.w[1])); 52 Words constants = at(uvec2(table.w[0], table.w[1]));
40 Words code = at(pc.code_base); 53 Words code = at(pc.code_base);
41 Words result = at(uvec2(pc.s[2], pc.s[3]));
42 result.w[i] = pc.s[0] + pc.s[1] * i + constants.w[i % 4] + code.w[1]; 54 result.w[i] = pc.s[0] + pc.s[1] * i + constants.w[i % 4] + code.w[1];
43} 55}
diff --git a/runtime/test/glsl/ps_sg_probe.frag b/runtime/test/glsl/ps_sg_probe.frag
new file mode 100644
index 000000000..7b4f74e1a
--- /dev/null
+++ b/runtime/test/glsl/ps_sg_probe.frag
@@ -0,0 +1,11 @@
1#version 460
2// A pixel shader that outputs the subgroup size the driver ran it with, (0x40000000 | gl_SubgroupSize, 0x40000000 |
3// gl_SubgroupInvocationID, ...) as float bit patterns (the or keeps them normal floats), for d3d12_subgroup_test.
4#extension GL_KHR_shader_subgroup_basic : require
5
6layout(location = 0) out vec4 target;
7
8void main() {
9 target = uintBitsToFloat(uvec4(0x40000000u | gl_SubgroupSize, 0x40000000u | gl_SubgroupInvocationID, 0x40000000u,
10 0x40000000u));
11}
diff --git a/runtime/test/glsl/vs_sg_fullscreen.vert b/runtime/test/glsl/vs_sg_fullscreen.vert
new file mode 100644
index 000000000..80e4b203a
--- /dev/null
+++ b/runtime/test/glsl/vs_sg_fullscreen.vert
@@ -0,0 +1,6 @@
1#version 460
2// One triangle that covers the whole viewport, from gl_VertexIndex alone, for d3d12_subgroup_test.
3void main() {
4 const vec2 p = vec2(float((gl_VertexIndex << 1) & 2), float(gl_VertexIndex & 2));
5 gl_Position = vec4(p * 2.0 - 1.0, 0.0, 1.0);
6}
diff --git a/runtime/test/process_cmdline_test.cpp b/runtime/test/process_cmdline_test.cpp
index 4c78835bb..8f35a8ef7 100644
--- a/runtime/test/process_cmdline_test.cpp
+++ b/runtime/test/process_cmdline_test.cpp
@@ -1,10 +1,14 @@
1// The process shim's command line round-trips: what GetCommandLineW says must parse with CommandLineToArgvW (the 1// The process shim's command line round-trips: what GetCommandLineW says must parse with CommandLineToArgvW (the
2// documented rules the CRT's argv parser shares) back to the __wargv the shim hands out, and __wargv must hold what 2// documented rules the CRT's argv parser shares) back to the __wargv the shim hands out, and __wargv must hold what
3// main.cpp passed, whatever the system code page (RT-84). No game files. 3// main.cpp passed, whatever the system code page (RT-84). The WinMain line (lpCmdLine) is the game's too, and the
4// command line and ExitProcess are served under kernelbase.dll and the API-set names as well as kernel32.dll.
5// No game files.
4#include <windows.h> 6#include <windows.h>
5#include <shellapi.h> 7#include <shellapi.h>
6 8
7#include <cstdio> 9#include <cstdio>
10#include <cstring>
11#include <cwchar>
8#include <string> 12#include <string>
9#include <vector> 13#include <vector>
10 14
@@ -54,6 +58,60 @@ void check_non_ascii(const std::wstring& want, const char* what) {
54 ++failures; 58 ++failures;
55 } 59 }
56} 60}
61
62// An executable can import GetCommandLineA/W and ExitProcess from kernel32.dll, kernelbase.dll or the API set its
63// umbrella library names, and the loader matches the DLL name exactly: every name must hand out the same shim.
64void check_import_names() {
65 for (const char* dll : {"kernelbase.dll", "api-ms-win-core-processenvironment-l1-1-0.dll"})
66 for (const char* name : {"GetCommandLineA", "GetCommandLineW"}) {
67 void* fn = rt::shims::find(dll, name);
68 if (!fn || fn != rt::shims::find("kernel32.dll", name)) {
69 std::fprintf(stderr, "FAIL %s!%s is not the kernel32.dll shim\n", dll, name);
70 ++failures;
71 }
72 }
73 for (const char* dll : {"kernelbase.dll", "api-ms-win-core-processthreads-l1-1-0.dll"}) {
74 void* fn = rt::shims::find(dll, "ExitProcess");
75 if (!fn || fn != rt::shims::find("kernel32.dll", "ExitProcess")) {
76 std::fprintf(stderr, "FAIL %s!ExitProcess is not the kernel32.dll shim\n", dll);
77 ++failures;
78 }
79 }
80 for (const char* dll : {"api-ms-win-crt-runtime-l1-1-0.dll", "ucrtbase.dll", "ucrtbased.dll"})
81 for (const char* name : {"_get_narrow_winmain_command_line", "_get_wide_winmain_command_line"})
82 if (!rt::shims::find(dll, name)) {
83 std::fprintf(stderr, "FAIL %s!%s is not shimmed\n", dll, name);
84 ++failures;
85 }
86}
87
88// lpCmdLine as the CRT's WinMain startup gets it from _get_wide/_get_narrow_winmain_command_line: the game's command
89// line after the program name and the blanks that follow it (the narrow one in the ANSI code page).
90void check_winmain(const std::wstring& program, const std::vector<std::wstring>& args, const wchar_t* want,
91 const char* what) {
92 rt::process::set_command_line(program, args);
93 using Wide = wchar_t*(__cdecl*)();
94 using Narrow = char*(__cdecl*)();
95 for (const char* dll : {"api-ms-win-crt-runtime-l1-1-0.dll", "ucrtbase.dll"}) {
96 const auto wide_fn = reinterpret_cast<Wide>(rt::shims::find(dll, "_get_wide_winmain_command_line"));
97 const auto narrow_fn = reinterpret_cast<Narrow>(rt::shims::find(dll, "_get_narrow_winmain_command_line"));
98 if (!wide_fn || !narrow_fn) continue; // check_import_names has reported the missing shim
99 const wchar_t* wide = wide_fn();
100 const char* line = narrow_fn();
101 char expected[256] = {};
102 WideCharToMultiByte(CP_ACP, 0, want, -1, expected, sizeof(expected), nullptr, nullptr);
103 if (!wide || std::wcscmp(wide, want) != 0) {
104 std::fwprintf(stderr, L"FAIL %hs (%hs): the wide WinMain line is [%ls], want [%ls]\n", what, dll,
105 wide ? wide : L"(null)", want);
106 ++failures;
107 }
108 if (!line || std::strcmp(line, expected) != 0) {
109 std::fprintf(stderr, "FAIL %s (%s): the narrow WinMain line is [%s], want [%s]\n", what, dll,
110 line ? line : "(null)", expected);
111 ++failures;
112 }
113 }
114}
57} // namespace 115} // namespace
58 116
59int main() { 117int main() {
@@ -67,8 +125,16 @@ int main() {
67 // Greek, Cyrillic and CJK together: no single-byte code page holds all of them, so this covers every PC. 125 // Greek, Cyrillic and CJK together: no single-byte code page holds all of them, so this covers every PC.
68 check_non_ascii(L"\u0394\u0416\u6F22 x", "an argument outside any single-byte code page"); 126 check_non_ascii(L"\u0394\u0416\u6F22 x", "an argument outside any single-byte code page");
69 127
128 check_import_names();
129 check_winmain(L"game.exe", {L"-foo", L"with space"}, L"-foo \"with space\"", "arguments after a plain name");
130 check_winmain(L"C:\\My Games\\game.exe", {L"-x"}, L"-x", "a quoted program name with a space");
131 check_winmain(L"game.exe", {}, L"", "no arguments");
132 // A byte above 0x7f in the narrow program name is part of the name, not the end of it.
133 check_winmain(L"caf\u00e9.exe", {L"-x"}, L"-x", "a non-ASCII program name");
134
70 if (failures) return 1; 135 if (failures) return 1;
71 std::printf("process_cmdline: GetCommandLineW parses back to __wargv, non-ASCII arguments intact (code page %u)\n", 136 std::printf("process_cmdline: GetCommandLineW parses back to __wargv, non-ASCII arguments intact (code page %u); "
137 "the WinMain line and the kernelbase/API-set names are the game's\n",
72 GetACP()); 138 GetACP());
73 return 0; 139 return 0;
74} 140}
diff --git a/runtime/test/queue_proxy_test.cpp b/runtime/test/queue_proxy_test.cpp
index 23a550685..69c1c26bd 100644
--- a/runtime/test/queue_proxy_test.cpp
+++ b/runtime/test/queue_proxy_test.cpp
@@ -33,6 +33,7 @@
33#include <cstring> 33#include <cstring>
34#include <cwchar> 34#include <cwchar>
35#include <iterator> 35#include <iterator>
36#include <mutex>
36#include <string> 37#include <string>
37#include <system_error> 38#include <system_error>
38#include <thread> 39#include <thread>
@@ -822,29 +823,37 @@ ChildRun run_process(const wchar_t* exe, const wchar_t* arguments, DWORD limit_m
822 RunnerFault fault = RunnerFault::none) { 823 RunnerFault fault = RunnerFault::none) {
823 ChildRun run; 824 ChildRun run;
824 std::wstring command = L"\"" + std::wstring(exe) + L"\" " + arguments; 825 std::wstring command = L"\"" + std::wstring(exe) + L"\" " + arguments;
825 SECURITY_ATTRIBUTES inherit{sizeof(inherit), nullptr, TRUE}; 826 // Both ends are made uninheritable. The write end becomes inheritable only while the start lock is held, just for
827 // its own child's CreateProcessW: children are started from several threads at once (check_differential), and a
828 // write end inheritable at any other time would also go to a sibling started meanwhile, which would then keep this
829 // pipe open after this child ended.
826 HANDLE read_end = nullptr, write_end = nullptr; 830 HANDLE read_end = nullptr, write_end = nullptr;
827 if (fault == RunnerFault::pipe) SetLastError(ERROR_NOT_ENOUGH_MEMORY); 831 if (fault == RunnerFault::pipe) SetLastError(ERROR_NOT_ENOUGH_MEMORY);
828 if (fault == RunnerFault::pipe || !CreatePipe(&read_end, &write_end, &inherit, 0)) { 832 if (fault == RunnerFault::pipe || !CreatePipe(&read_end, &write_end, nullptr, 0)) {
829 report_runner_error("CreatePipe"); 833 report_runner_error("CreatePipe");
830 return run; 834 return run;
831 } 835 }
832 if (!SetHandleInformation(read_end, HANDLE_FLAG_INHERIT, 0)) {
833 report_runner_error("SetHandleInformation");
834 CloseHandle(read_end);
835 CloseHandle(write_end);
836 return run;
837 }
838 STARTUPINFOW startup{sizeof(startup)}; 836 STARTUPINFOW startup{sizeof(startup)};
839 startup.dwFlags = STARTF_USESTDHANDLES; 837 startup.dwFlags = STARTF_USESTDHANDLES;
840 startup.hStdOutput = write_end; 838 startup.hStdOutput = write_end;
841 startup.hStdError = GetStdHandle(STD_ERROR_HANDLE); 839 startup.hStdError = GetStdHandle(STD_ERROR_HANDLE);
842 startup.hStdInput = GetStdHandle(STD_INPUT_HANDLE); 840 startup.hStdInput = GetStdHandle(STD_INPUT_HANDLE);
843 PROCESS_INFORMATION process{}; 841 PROCESS_INFORMATION process{};
844 const BOOL started = 842 BOOL started = FALSE;
845 CreateProcessW(exe, command.data(), nullptr, nullptr, TRUE, 0, nullptr, nullptr, &startup, &process); 843 DWORD start_error = 0;
846 const DWORD start_error = GetLastError(); 844 {
847 CloseHandle(write_end); // the child holds the only write end now: the reader sees the pipe end when it is gone 845 static std::mutex start_lock;
846 const std::lock_guard<std::mutex> hold(start_lock);
847 if (!SetHandleInformation(write_end, HANDLE_FLAG_INHERIT, HANDLE_FLAG_INHERIT)) {
848 report_runner_error("SetHandleInformation");
849 CloseHandle(read_end);
850 CloseHandle(write_end);
851 return run;
852 }
853 started = CreateProcessW(exe, command.data(), nullptr, nullptr, TRUE, 0, nullptr, nullptr, &startup, &process);
854 start_error = GetLastError();
855 CloseHandle(write_end); // the child holds the only write end now: the reader sees the pipe end when it is gone
856 }
848 if (!started) { 857 if (!started) {
849 std::fprintf(stderr, "child runner: CreateProcessW \"%ls\" failed (error %lu)\n", exe, start_error); 858 std::fprintf(stderr, "child runner: CreateProcessW \"%ls\" failed (error %lu)\n", exe, start_error);
850 CloseHandle(read_end); 859 CloseHandle(read_end);
@@ -1044,14 +1053,49 @@ int check_child_runner() {
1044 return 0; 1053 return 0;
1045} 1054}
1046 1055
1056// How many differential children run at once: LEONIDA_QUEUE_PROXY_JOBS when set (1 = one after another, as before),
1057// else half the logical processors, from 1 to 8. Each child pays its own device start-up (about 5 s each on an AMD
1058// RDNA2 iGPU, TEST-242), and that waiting is what running them side by side hides.
1059unsigned differential_jobs() {
1060 char value[16] = {};
1061 const DWORD length = GetEnvironmentVariableA("LEONIDA_QUEUE_PROXY_JOBS", value, sizeof(value));
1062 if (length > 0 && length < sizeof(value)) { // set, and short enough to be a number
1063 const unsigned long jobs = std::strtoul(value, nullptr, 10);
1064 if (jobs >= 1 && jobs <= 64) return static_cast<unsigned>(jobs);
1065 }
1066 const unsigned half = std::thread::hardware_concurrency() / 2;
1067 return half < 1 ? 1 : half > 8 ? 8 : half;
1068}
1069
1047// Each case, in a child process for the real object and in another for the proxy: the same HRESULT, the device 1070// Each case, in a child process for the real object and in another for the proxy: the same HRESULT, the device
1048// removed (or not) alike, and no validation errors. A case the real runtime faults on is reported, not compared. 1071// removed (or not) alike, and no validation errors. A case the real runtime faults on is reported, not compared.
1072// The children run differential_jobs() at a time; the results are judged afterwards in case order, so the report is
1073// the same as one child after another would give (a proxy child whose real one faulted is run but not judged).
1049int check_differential(const Backend& b) { 1074int check_differential(const Backend& b) {
1050 const char* label = b.label; 1075 const char* label = b.label;
1051 int compared = 0, faulting = 0; 1076 int compared = 0, faulting = 0;
1052 for (int i = 0; i < static_cast<int>(std::size(kDiffCases)); ++i) { 1077 constexpr int kCases = static_cast<int>(std::size(kDiffCases));
1078 std::vector<ChildResult> results(2 * kCases); // [2 * case] real, [2 * case + 1] proxy
1079 {
1080 std::atomic<int> next{0};
1081 const auto work = [&] {
1082 for (int job; (job = next.fetch_add(1)) < 2 * kCases;)
1083 results[job] = run_child(b.kind, job / 2, job % 2 == 1);
1084 };
1085 const unsigned jobs = differential_jobs();
1086 std::vector<std::thread> pool;
1087 try {
1088 for (unsigned t = 1; t < jobs; ++t) pool.emplace_back(work);
1089 } catch (const std::system_error& e) { // fewer helpers; this thread still runs every job left
1090 std::fprintf(stderr, "%s: %zu of %u differential runner threads (%s)\n", label, pool.size() + 1, jobs,
1091 e.what());
1092 }
1093 work();
1094 for (std::thread& t : pool) t.join();
1095 }
1096 for (int i = 0; i < kCases; ++i) {
1053 const char* name = kDiffCases[i].name; 1097 const char* name = kDiffCases[i].name;
1054 const ChildResult want = run_child(b.kind, i, false); 1098 const ChildResult& want = results[2 * i];
1055 if (!want.ok) { 1099 if (!want.ok) {
1056 std::fprintf(stderr, "%s: %s: the real-object child did not report\n", label, name); 1100 std::fprintf(stderr, "%s: %s: the real-object child did not report\n", label, name);
1057 return 1; 1101 return 1;
@@ -1061,7 +1105,7 @@ int check_differential(const Backend& b) {
1061 ++faulting; 1105 ++faulting;
1062 continue; 1106 continue;
1063 } 1107 }
1064 const ChildResult got = run_child(b.kind, i, true); 1108 const ChildResult& got = results[2 * i + 1];
1065 if (!got.ok || !got.ran || got.hr != want.hr || got.removed != want.removed || got.validation || 1109 if (!got.ok || !got.ran || got.hr != want.hr || got.removed != want.removed || got.validation ||
1066 want.validation) { 1110 want.validation) {
1067 std::fprintf(stderr, 1111 std::fprintf(stderr,
diff --git a/runtime/test/resource_tiling_test.cpp b/runtime/test/resource_tiling_test.cpp
index 4634f6830..4e0f39d48 100644
--- a/runtime/test/resource_tiling_test.cpp
+++ b/runtime/test/resource_tiling_test.cpp
@@ -6,6 +6,7 @@
6#include "../src/resource_tiling.h" 6#include "../src/resource_tiling.h"
7 7
8#include <cstdio> 8#include <cstdio>
9#include <tuple>
9 10
10#define CHECK(condition) do { \ 11#define CHECK(condition) do { \
11 if (!(condition)) { \ 12 if (!(condition)) { \
@@ -176,6 +177,20 @@ int main() {
176 } 177 }
177 } 178 }
178 179
180 // 2D 4x MSAA: tile shape divides by 4 in texels, 1 mip only, unsupported sample counts fail.
181 for (const auto& ms : {std::tuple{1u, 128u, 128u, 4u}, std::tuple{2u, 128u, 64u, 8u},
182 std::tuple{4u, 64u, 64u, 16u}, std::tuple{8u, 64u, 32u, 32u},
183 std::tuple{16u, 32u, 32u, 64u}}) {
184 const auto [bytes, sw, sh, want_tiles] = ms;
185 CHECK(resource_tiling({TiledKind::texture2d, 256, 256, 1, 1, bytes, 1, 4}, t));
186 CHECK(t.shape.width == sw && t.shape.height == sh && t.shape.depth == 1 && t.total_tiles == want_tiles);
187 }
188 CHECK(resource_tiling({TiledKind::texture2d, 64, 64, 1, 1, 1, 1, 4}, t) && t.total_tiles == 1);
189 CHECK(!resource_tiling({TiledKind::texture2d, 256, 256, 1, 1, 4, 1, 2}, t));
190 CHECK(!resource_tiling({TiledKind::texture2d, 256, 256, 1, 1, 4, 1, 8}, t));
191 CHECK(!resource_tiling({TiledKind::texture2d, 256, 256, 1, 2, 4, 1, 4}, t));
192 CHECK(!resource_tiling({TiledKind::texture3d, 64, 64, 16, 1, 4, 1, 4}, t));
193
179 // Element sizes that have no tile shape, and empty descriptions. 194 // Element sizes that have no tile shape, and empty descriptions.
180 CHECK(!resource_tiling({TiledKind::texture2d, 64, 64, 1, 1, 12, 1}, t)); 195 CHECK(!resource_tiling({TiledKind::texture2d, 64, 64, 1, 1, 12, 1}, t));
181 CHECK(!resource_tiling({TiledKind::texture2d, 64, 64, 1, 0, 4, 1}, t)); 196 CHECK(!resource_tiling({TiledKind::texture2d, 64, 64, 1, 0, 4, 1}, t));
diff --git a/runtime/test/root_signature_oracle_test.cpp b/runtime/test/root_signature_oracle_test.cpp
index d0794ddbd..261004328 100644
--- a/runtime/test/root_signature_oracle_test.cpp
+++ b/runtime/test/root_signature_oracle_test.cpp
@@ -120,6 +120,48 @@ int main() {
120 const PackResult packed = pack(model); 120 const PackResult packed = pack(model);
121 check(packed.ok && packed.dword_count == 6, "oracle model packs to 6 dwords"); 121 check(packed.ok && packed.dword_count == 6, "oracle model packs to 6 dwords");
122 122
123 // The descriptor count and range offset are independent. The final SRV range is unbounded
124 // and begins immediately after the fixed range, but the whole table still occupies one GPU address.
125 {
126 D3D12_DESCRIPTOR_RANGE1 ranges[] = {
127 {D3D12_DESCRIPTOR_RANGE_TYPE_SRV, 2, 3, 0, D3D12_DESCRIPTOR_RANGE_FLAG_DATA_STATIC, 0},
128 {D3D12_DESCRIPTOR_RANGE_TYPE_SRV, UINT32_MAX, 7, 1,
129 D3D12_DESCRIPTOR_RANGE_FLAG_DESCRIPTORS_VOLATILE, D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND},
130 };
131 D3D12_ROOT_PARAMETER1 table_and_constants[2] = {{}, params[0]};
132 auto& table = table_and_constants[0];
133 table.ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE;
134 table.ShaderVisibility = D3D12_SHADER_VISIBILITY_PIXEL;
135 table.DescriptorTable = {2, ranges};
136 const auto unbounded_desc = make_desc(table_and_constants, 2);
137 Blobs unbounded;
138 const HRESULT result =
139 D3D12SerializeVersionedRootSignature(&unbounded_desc, &unbounded.blob, &unbounded.error);
140 check(result == S_OK, "Microsoft serializer accepts an unbounded SRV range");
141 RootSignature table_model;
142 if (SUCCEEDED(result) && unbounded.blob &&
143 parse_blob(unbounded.blob, table_model) && table_model.params.size() == 2 &&
144 table_model.params[0].ranges.size() == 2) {
145 const auto& fixed = table_model.params[0].ranges[0];
146 const auto& tail = table_model.params[0].ranges[1];
147 check(table_model.params[0].type == ParamType::Table &&
148 table_model.params[0].visibility == Visibility::Pixel &&
149 fixed.num_descriptors == 2 && fixed.offset_in_table == 0 &&
150 tail.range_type == D3D12_DESCRIPTOR_RANGE_TYPE_SRV &&
151 tail.num_descriptors == UINT32_MAX && tail.base_shader_register == 7 &&
152 tail.register_space == 1 && tail.flags == D3D12_DESCRIPTOR_RANGE_FLAG_DESCRIPTORS_VOLATILE &&
153 tail.offset_in_table == kRangeOffsetAppend,
154 "fixed and unbounded SRV ranges survive native serialization");
155 const auto table_pack = pack(table_model);
156 check(table_pack.ok && table_pack.d3d12_cost == 5 && table_pack.dword_count == 6 &&
157 table_pack.provenance.size() == 6 &&
158 table_pack.provenance[1].param_index == 0 && table_pack.provenance[2].param_index == 1,
159 "unbounded SRV table occupies two SGPRs before the following constants");
160 } else {
161 check(false, "native unbounded table parses with two ranges and two parameters");
162 }
163 }
164
123 // Static samplers, one signature per version: every field round-trips through the real serializer, and 1.2 165 // Static samplers, one signature per version: every field round-trips through the real serializer, and 1.2
124 // adds D3D12_STATIC_SAMPLER_DESC1::Flags (a 14th dword) to each sampler record. Each also carries a table and a 166 // adds D3D12_STATIC_SAMPLER_DESC1::Flags (a 14th dword) to each sampler record. Each also carries a table and a
125 // root descriptor, so the 1.1/1.2 descriptor and range flags sit between the samplers and the header. 167 // root descriptor, so the 1.1/1.2 descriptor and range flags sit between the samplers and the header.
diff --git a/runtime/test/shader_library_corpus_test.cpp b/runtime/test/shader_library_corpus_test.cpp
new file mode 100644
index 000000000..6e3e6be94
--- /dev/null
+++ b/runtime/test/shader_library_corpus_test.cpp
@@ -0,0 +1,159 @@
1// The runtime's shader lookup (src/shader_library.h) over a translated corpus from the player's own copy.
2//
3// LEONIDA_SHADERS=<work>/shaders/spirv the translator's output (index.json and the .spv modules)
4// LEONIDA_SHADER_DXBC=<work>/shaders/dxbc optional; the carved DXBC containers, default <spirv>/../dxbc
5//
6// For every container the test does what d3d12_vulkan_device.cpp does with a PSO's bytecode: inflate the FSSM program
7// from the DXIL/XDAT/XBCH entry, hash it and look it up under the container's stage. The stage comes from the DXIL
8// part's program header, not from index.json. Every container has to resolve to its own entry (the one named after
9// the file, or one of its `~N` duplicates) with a readable SPIR-V module, and every index entry has to be reached by
10// a container. Containers with more than one 0x0D payload are counted, and their first payload must not stand in for
11// the last: that is the rule fssm_program follows, so a regression to the first payload fails here.
12//
13// Without LEONIDA_SHADERS it prints SKIP and exits 77 (SKIP_RETURN_CODE). It reads the work folder in place, writes
14// nothing, and prints counts; on a failure it names at most a few shaders, which stay on your machine.
15#include "../src/shader_library.h"
16
17#include <cstdio>
18#include <cstdlib>
19#include <filesystem>
20#include <fstream>
21#include <set>
22#include <string>
23#include <vector>
24
25namespace {
26
27namespace fs = std::filesystem;
28
29std::string env(const char* name) {
30 const char* value = std::getenv(name);
31 return value ? value : "";
32}
33
34std::vector<std::uint8_t> read_file(const fs::path& path) {
35 std::ifstream file(path, std::ios::binary);
36 return {std::istreambuf_iterator<char>(file), std::istreambuf_iterator<char>()};
37}
38
39std::uint32_t u32(std::span<const std::uint8_t> data, std::size_t at) {
40 if (at + 4 > data.size()) return 0;
41 std::uint32_t v;
42 std::memcpy(&v, data.data() + at, 4);
43 return v;
44}
45
46// The stage the DXIL program header names (DxilProgramHeader::ProgramVersion, kind in bits 31:16; D3D12's
47// D3D12_SHADER_VERSION_TYPE), in the translator's spelling. Empty for a kind the corpus has no translation for.
48std::string dxil_stage(std::span<const std::uint8_t> container) {
49 const auto dxil = leonida::dxbc_part(container, "DXIL");
50 if (dxil.size() < 4) return {};
51 switch (u32(dxil, 0) >> 16) {
52 case 0: return "ps";
53 case 1: return "vs";
54 case 2: return "gs";
55 case 5: return "cs";
56 case 13: return "ms";
57 default: return {};
58 }
59}
60
61// Every 0x0D (XBCH) payload of the container's XDAT table, in table order, inflated. fssm_program keeps the last.
62std::vector<std::vector<std::uint8_t>> all_programs(std::span<const std::uint8_t> container) {
63 std::vector<std::vector<std::uint8_t>> out;
64 const auto dxil = leonida::dxbc_part(container, "DXIL");
65 std::size_t xdat = 0;
66 while (xdat + 4 <= dxil.size() && std::memcmp(dxil.data() + xdat, "XDAT", 4) != 0) ++xdat;
67 const std::uint32_t count = u32(dxil, xdat + 4);
68 for (std::uint32_t i = 0; i < count; ++i) {
69 const std::size_t entry = xdat + 12 + 12 * std::size_t(i);
70 if (entry + 12 > dxil.size()) break;
71 const std::uint32_t tag = u32(dxil, entry), offset = u32(dxil, entry + 4), size = u32(dxil, entry + 8);
72 if (tag != 0x0d || size < 24 || std::size_t(offset) + size > dxil.size()) continue;
73 const auto blob = dxil.subspan(offset, size);
74 std::vector<std::uint8_t> program;
75 if (std::memcmp(blob.data(), "XBCH", 4) == 0 && leonida::zlib_inflate(blob.subspan(24), program, u32(blob, 16)))
76 out.push_back(std::move(program));
77 }
78 return out;
79}
80
81bool own_entry(const leonida::ShaderEntry& entry, const std::string& stem) {
82 return entry.name == stem || entry.name.rfind(stem + "~", 0) == 0;
83}
84
85} // namespace
86
87int main() {
88 const std::string spirv_dir = env("LEONIDA_SHADERS");
89 if (spirv_dir.empty()) {
90 std::printf("SKIP (no translated corpus: set LEONIDA_SHADERS to <work>/shaders/spirv)\n");
91 return 77;
92 }
93 std::string dxbc_dir = env("LEONIDA_SHADER_DXBC");
94 if (dxbc_dir.empty()) dxbc_dir = (fs::path(spirv_dir) / ".." / "dxbc").lexically_normal().string();
95
96 int failures = 0, named = 0;
97 const auto fail = [&](const std::string& what, const std::string& shader) {
98 ++failures;
99 if (named++ < 8) std::fprintf(stderr, "FAIL %s: %s\n", what.c_str(), shader.c_str());
100 };
101
102 leonida::ShaderLibrary library;
103 std::string error;
104 if (!library.load(spirv_dir, &error)) {
105 std::fprintf(stderr, "FAIL loading %s: %s\n", spirv_dir.c_str(), error.c_str());
106 return 1;
107 }
108 std::error_code ec;
109 if (!fs::is_directory(dxbc_dir, ec)) {
110 std::fprintf(stderr, "FAIL no DXBC folder %s (set LEONIDA_SHADER_DXBC)\n", dxbc_dir.c_str());
111 return 1;
112 }
113
114 std::size_t containers = 0, multi = 0;
115 std::set<std::string> reached;
116 for (const auto& item : fs::directory_iterator(dxbc_dir)) {
117 if (!item.is_regular_file() || item.path().extension() != ".dxbc") continue;
118 ++containers;
119 const std::string stem = item.path().stem().string();
120 const auto bytes = read_file(item.path());
121 const std::string stage = dxil_stage(bytes);
122 if (stage.empty()) {
123 fail("no shader stage in the DXIL program header", stem);
124 continue;
125 }
126 const auto program = leonida::fssm_program(bytes);
127 if (program.size() < 4 || std::memcmp(program.data(), "FSSM", 4) != 0) {
128 fail("no FSSM program", stem);
129 continue;
130 }
131 bool found = false;
132 for (const leonida::ShaderEntry* entry : library.candidates(stage, leonida::sha256_hex(program))) {
133 if (!own_entry(*entry, stem)) continue;
134 found = true;
135 reached.insert(entry->name);
136 if (library.spirv(*entry).empty()) fail("no SPIR-V module for", entry->name);
137 }
138 if (!found) fail("not found under its " + stage + " stage", stem);
139
140 // The 0x0D payloads that differ from the last: none of them may be what the index has for this container.
141 const auto programs = all_programs(bytes);
142 if (programs.empty() || programs.back() != program) fail("fssm_program is not the last 0x0D payload", stem);
143 bool differs = false;
144 for (std::size_t i = 0; i + 1 < programs.size(); ++i) {
145 if (programs[i] == program) continue;
146 differs = true;
147 for (const leonida::ShaderEntry* entry : library.candidates(stage, leonida::sha256_hex(programs[i])))
148 if (own_entry(*entry, stem)) fail("an earlier 0x0D payload is the indexed program", stem);
149 }
150 multi += differs;
151 }
152
153 if (containers == 0) fail("no .dxbc containers in", dxbc_dir);
154 if (reached.size() != library.size())
155 fail(std::to_string(library.size() - reached.size()) + " index entries reached by no container", spirv_dir);
156 std::printf("%zu containers, %zu index entries, %zu reached; %zu containers with more than one program; "
157 "%d failures\n", containers, library.size(), reached.size(), multi, failures);
158 return failures ? 1 : 0;
159}
diff --git a/runtime/test/shader_library_test.cpp b/runtime/test/shader_library_test.cpp
index 1fecf1205..49189f69c 100644
--- a/runtime/test/shader_library_test.cpp
+++ b/runtime/test/shader_library_test.cpp
@@ -194,6 +194,7 @@ int main() {
194 const auto dir = std::filesystem::temp_directory_path() / "leonida_shader_library_test"; 194 const auto dir = std::filesystem::temp_directory_path() / "leonida_shader_library_test";
195 std::filesystem::create_directories(dir); 195 std::filesystem::create_directories(dir);
196 const std::string hash = sha256_hex(skewed(600)); 196 const std::string hash = sha256_hex(skewed(600));
197 const std::string hash2 = sha256_hex(bytes("another program"));
197 { 198 {
198 std::ofstream index(dir / "index.json", std::ios::binary); 199 std::ofstream index(dir / "index.json", std::ios::binary);
199 index << "{\"cs_test\": {\"stage\": \"cs\", \"fssm_sha256\": \"" << hash 200 index << "{\"cs_test\": {\"stage\": \"cs\", \"fssm_sha256\": \"" << hash
@@ -208,6 +209,10 @@ int main() {
208 "{\"semantic\": \"TEXCOORD\", \"semantic_index\": 3, \"register\": -1, \"system_value\": 0, " 209 "{\"semantic\": \"TEXCOORD\", \"semantic_index\": 3, \"register\": -1, \"system_value\": 0, "
209 "\"component_type\": \"float\"}]},\n" 210 "\"component_type\": \"float\"}]},\n"
210 " \"ps_out\": {\"stage\": \"ps\", \"fssm_sha256\": \"" << hash << "\", \"outputs\": [0, 2]},\n" 211 " \"ps_out\": {\"stage\": \"ps\", \"fssm_sha256\": \"" << hash << "\", \"outputs\": [0, 2]},\n"
212 " \"ps_native\": {\"stage\": \"ps\", \"fssm_sha256\": \"" << hash2 << "\", \"wave64\": true, "
213 "\"subgroup_size\": 64},\n"
214 " \"cs_emulated\": {\"stage\": \"cs\", \"fssm_sha256\": \"" << hash2 << "\", \"wave64\": true, "
215 "\"subgroup_size\": null, \"wave64_exchange\": \"workgroup\"},\n"
211 " \"ps_unhashed\": {\"stage\": \"ps\", \"bindings\": []}}"; 216 " \"ps_unhashed\": {\"stage\": \"ps\", \"bindings\": []}}";
212 std::ofstream spv(dir / "cs_test.spv", std::ios::binary); 217 std::ofstream spv(dir / "cs_test.spv", std::ios::binary);
213 const std::uint32_t words[5] = {0x07230203, 0x00010500, 0, 1, 0}; 218 const std::uint32_t words[5] = {0x07230203, 0x00010500, 0, 1, 0};
@@ -215,7 +220,7 @@ int main() {
215 } 220 }
216 ShaderLibrary library; 221 ShaderLibrary library;
217 std::string error; 222 std::string error;
218 CHECK(library.load(dir.string(), &error) && library.size() == 4); 223 CHECK(library.load(dir.string(), &error) && library.size() == 6);
219 const ShaderEntry* vs = library.find("vs", hash); 224 const ShaderEntry* vs = library.find("vs", hash);
220 CHECK(vs && vs->input_signature.size() == 2 && vs->input_signature[0].semantic == "COLOR"); 225 CHECK(vs && vs->input_signature.size() == 2 && vs->input_signature[0].semantic == "COLOR");
221 CHECK(vs->input_signature[1].register_index == 2 && vs->input_signature[1].system_value == 6 && 226 CHECK(vs->input_signature[1].register_index == 2 && vs->input_signature[1].system_value == 6 &&
@@ -232,6 +237,13 @@ int main() {
232 CHECK(entry && entry->name == "cs_test" && entry->binding_count == 1 && entry->push_constant_bytes == 144); 237 CHECK(entry && entry->name == "cs_test" && entry->binding_count == 1 && entry->push_constant_bytes == 144);
233 CHECK(entry->local_size[0] == 64 && entry->uses_code_base && !entry->wave64); 238 CHECK(entry->local_size[0] == 64 && entry->uses_code_base && !entry->wave64);
234 CHECK(!library.find("ms", hash)); // no mesh shader with this hash 239 CHECK(!library.find("ms", hash)); // no mesh shader with this hash
240 // The subgroup fields of the index (wave64 / subgroup_size / wave64_exchange): absent, native and emulated.
241 CHECK(!entry->subgroup_size && entry->wave64_exchange.empty() && !entry->emulated());
242 const ShaderEntry* native = library.find("ps", hash2);
243 CHECK(native && native->wave64 && native->subgroup_size == 64 && !native->emulated());
244 const ShaderEntry* emulated = library.find("cs", hash2);
245 CHECK(emulated && emulated->wave64 && emulated->subgroup_size == 0 && emulated->wave64_exchange == "workgroup" &&
246 emulated->emulated());
235 CHECK(library.spirv(*entry).size() == 5); 247 CHECK(library.spirv(*entry).size() == 5);
236 CHECK(!library.load((dir / "missing").string(), &error) && !error.empty()); 248 CHECK(!library.load((dir / "missing").string(), &error) && !error.empty());
237 { 249 {
diff --git a/runtime/test/shaders/build.py b/runtime/test/shaders/build.py
index f7979ee69..c9796f244 100644
--- a/runtime/test/shaders/build.py
+++ b/runtime/test/shaders/build.py
@@ -135,6 +135,10 @@ def translate_tests(work, names):
135def main(): 135def main():
136 if len(sys.argv) < 2: 136 if len(sys.argv) < 2:
137 sys.exit(__doc__) 137 sys.exit(__doc__)
138 # The CMake test targets name the spirv-as/spirv-val folder here instead of passing a whole PATH, which the Visual
139 # Studio generator's command line can't carry intact (a PATH entry ending in a backslash escapes the next quote).
140 if os.environ.get("LEONIDA_SPIRV_TOOLS"):
141 os.environ["PATH"] = os.environ["LEONIDA_SPIRV_TOOLS"] + os.pathsep + os.environ.get("PATH", "")
138 out = Path(sys.argv[1]) 142 out = Path(sys.argv[1])
139 available = sorted({p.stem for p in Path(HERE).glob("*.asm")} | CLIP_CASES.keys()) 143 available = sorted({p.stem for p in Path(HERE).glob("*.asm")} | CLIP_CASES.keys())
140 names = sys.argv[2:] or available 144 names = sys.argv[2:] or available
diff --git a/runtime/test/shaders/check.py b/runtime/test/shaders/check.py
index 5b4fa43c8..585d208e6 100644
--- a/runtime/test/shaders/check.py
+++ b/runtime/test/shaders/check.py
@@ -81,7 +81,7 @@ CS_SMEM = [0x5eed0024, 0x5eed0028, 0x5eed002c, 0x5eed0030, 0x5eed0010, 0x5eed001
81WAVE32_DUMPS = ("cs_store", "cs_smem_soffset_imm", "cs_wqm_w32", "cs_w32_lane_wrap", "cs_movrelsd_2", "cs_w32_permute", 81WAVE32_DUMPS = ("cs_store", "cs_smem_soffset_imm", "cs_wqm_w32", "cs_w32_lane_wrap", "cs_movrelsd_2", "cs_w32_permute",
82 "cs_barrier_divergent", "cs_barrier_early_end", "cs_barrier_loop", "cs_w32_lds_u8_d16", "cs_bpermute32", 82 "cs_barrier_divergent", "cs_barrier_early_end", "cs_barrier_loop", "cs_w32_lds_u8_d16", "cs_bpermute32",
83 "cs_w32_partial_scmp", "cs_exec_const", "cs_w32_mask_imm", "cs_w32_int_ext", 83 "cs_w32_partial_scmp", "cs_exec_const", "cs_w32_mask_imm", "cs_w32_int_ext",
84 "cs_w32_salu64", "cs_w32_misc_ext", "cs_w32_new_ops") 84 "cs_w32_salu64", "cs_w32_misc_ext", "cs_w32_new_ops", "cs_w32_sincos")
85# Wave32 lane-mask dumps: their EXEC/VCC masks and lane selects cover 32 lanes, so a device whose widest subgroup is 85# Wave32 lane-mask dumps: their EXEC/VCC masks and lane selects cover 32 lanes, so a device whose widest subgroup is
86# narrower (Mesa llvmpipe: 8) can't produce their words. They are skipped there, as ps_bitmask_perm is. They run with 86# narrower (Mesa llvmpipe: 8) can't produce their words. They are skipped there, as ps_bitmask_perm is. They run with
87# 32 lanes requested (WAVE32_LANE_ENV), as run_gpu_tests.py does: a device with a range like 8..32 (Intel ANV) may 87# 32 lanes requested (WAVE32_LANE_ENV), as run_gpu_tests.py does: a device with a range like 8..32 (Intel ANV) may
@@ -130,6 +130,8 @@ CS_DUMPS = [*CS_DPP, ("cs_store", CS_STORE), ("cs_smem_soffset_imm", CS_SMEM),
130 ("cs_wqm_w64", [20, 4, 12, 8, 1, 0, 15728895, 20]), ("cs_wqm_w32", [12, 1, 4, 0, 8, 15728880, 4, 32]), 130 ("cs_wqm_w64", [20, 4, 12, 8, 1, 0, 15728895, 20]), ("cs_wqm_w32", [12, 1, 4, 0, 8, 15728880, 4, 32]),
131 ("cs_bpermute32", [0, 50, 162, 99, 36, 218, 183, 15]), 131 ("cs_bpermute32", [0, 50, 162, 99, 36, 218, 183, 15]),
132 ("cs_w32_partial_scmp", [0, 1, 1, 0, 1, 1, 1, 1]), # a 20-thread wave32: s_cmp mask, -1 132 ("cs_w32_partial_scmp", [0, 1, 1, 0, 1, 1, 1, 1]), # a 20-thread wave32: s_cmp mask, -1
133 # SHADER-88: v_sin/v_cos reduce the angle in turns (a regression guard, tolerance 1e-3)
134 ("cs_w32_sincos", [1, 1, 1, 1, 1, 1]),
133 ("cs_wqm_w64_half", [11, 14, 0, 1, 6, 8, 12, 2]), 135 ("cs_wqm_w64_half", [11, 14, 0, 1, 6, 8, 12, 2]),
134 # SHADER-91: two s_barrier sites in wave-uniform branches meet like one barrier; wave 0 reads wave 3 136 # SHADER-91: two s_barrier sites in wave-uniform branches meet like one barrier; wave 0 reads wave 3
135 ("cs_barrier_divergent", [127, 126, 125, 124, 123, 122, 121, 120]), 137 ("cs_barrier_divergent", [127, 126, 125, 124, 123, 122, 121, 120]),
@@ -156,6 +158,22 @@ CMPX_CLASS_WORDS = [0xEEEEEEEE] * 3 + [0x22] + [0x11] * 4
156# cs_fmt_1010102.asm: descriptor loads, immediate-format load, raw input words and the two packed stores. 158# cs_fmt_1010102.asm: descriptor loads, immediate-format load, raw input words and the two packed stores.
157FMT_1010102_WORDS = [0, 0x3F800000, 0, 0x3F800000, 0x3F800000, 0, 0x3F800000, 0, 159FMT_1010102_WORDS = [0, 0x3F800000, 0, 0x3F800000, 0x3F800000, 0, 0x3F800000, 0,
158 0, 0x3F800000, 0, 0x3F800000, 0xC00FFC00, 0x003FF003, 0xE00003FF, 0xFFE00003] 160 0, 0x3F800000, 0, 0x3F800000, 0xC00FFC00, 0x003FF003, 0xE00003FF, 0xFFE00003]
161# cs_fmt_sint32.asm: hand-derived full-width and D16 load results, inputs, stores, and untouched words.
162FMT_SINT32_WORDS = [
163 0x80000000, 0x7FFFFFFF, 0x80000000, 1,
164 0x80000000, 0x7FFFFFFF, 0xFFFFFFFD, 0x80000000,
165 0x80000000, 0x7FFFFFFF, 0xFFFFFFFD, 17,
166 0x80000000, 0x7FFFFFFF, 0, 0,
167 0x80000000, 0x7FFFFFFF, 0xFFFFFFFD, 0,
168 0x80000000, 0x7FFFFFFF, 0xFFFFFFFD, 17,
169 0x7FFF8000, 0x0011FFFD, 0x7FFF8000, 0x0011FFFD,
170 0xFFFFFFFD, 0xFFFFFFFD, 0xEEEEEEEE, 0xEEEEEEEE,
171 0x80000000, 0x7FFFFFFF, 0xFFFFFFFD, 17,
172 0x80000000, 0x7FFFFFFF, 0xEEEEEEEE, 0xEEEEEEEE,
173 0x80000000, 0x7FFFFFFF, 0xFFFFFFFD, 0xEEEEEEEE,
174 0x80000000, 0x7FFFFFFF, 0xFFFFFFFD, 17,
175 0xFFFFFFFD, 0xFFFF8000, 0xFFFFFFFD, *[0xEEEEEEEE] * 13,
176]
159# cs_fmt_xy_xyz.asm (TEST-185): 12 xy/xyz loads, then the 9 store regions read back, as a Radeon 680M (gfx1035) gives 177# cs_fmt_xy_xyz.asm (TEST-185): 12 xy/xyz loads, then the 9 store regions read back, as a Radeon 680M (gfx1035) gives
160# them natively, with the updated UINT saturation case checked on gfx1036. Layout and rules in the .asm header. 178# them natively, with the updated UINT saturation case checked on gfx1036. Layout and rules in the .asm header.
161FMT_XY_XYZ_WORDS = [ 179FMT_XY_XYZ_WORDS = [
@@ -197,6 +215,9 @@ W64_EMULATED = os.environ.get("LEONIDA_W64_EMULATE") == "1"
197# LEONIDA_BARY_FALLBACK=1 (set for build.py too): a pixel shader that reads raw barycentrics was translated with 215# LEONIDA_BARY_FALLBACK=1 (set for build.py too): a pixel shader that reads raw barycentrics was translated with
198# --bary-fallback and is drawn through its pass-through geometry shader, <name>.bary_gs.spv. 216# --bary-fallback and is drawn through its pass-through geometry shader, <name>.bary_gs.spv.
199BARY_FALLBACK = os.environ.get("LEONIDA_BARY_FALLBACK") == "1" 217BARY_FALLBACK = os.environ.get("LEONIDA_BARY_FALLBACK") == "1"
218# LEONIDA_F16_INTERP_FALLBACK=1 (as build.py reads it): *_f16 interps were translated from decoded-half inputs, with no
219# PerVertexKHR inputs at all, so the translator refuses a computed I/J pair (ps_ij_computed) there.
220F16_HALVES = os.environ.get("LEONIDA_F16_INTERP_FALLBACK") == "1"
200W64X_DUMPS = [("cs_dpp_w64", [1, 0, 3, 2, 5, 4, 7, 6]), 221W64X_DUMPS = [("cs_dpp_w64", [1, 0, 3, 2, 5, 4, 7, 6]),
201 ("cs_w64x_readlane", [121, 121, 16, 97, 16, 100, 100, 121]), 222 ("cs_w64x_readlane", [121, 121, 16, 97, 16, 100, 100, 121]),
202 ("cs_w64x_writelane", [4660, 77, 99, 2748, 0, 0, 4660, 99]), 223 ("cs_w64x_writelane", [4660, 77, 99, 2748, 0, 0, 4660, 99]),
@@ -236,6 +257,8 @@ PIXEL_BITS = {"ps_clip_color": (0x3e800000, 0x3f000000, 0x3f400000, 0x3f800000),
236 "ps_vcmpx_forms": (0xf05b2a48, 0xf05e8a12, 0xb174be18, 0x15550000), 257 "ps_vcmpx_forms": (0xf05b2a48, 0xf05e8a12, 0xb174be18, 0x15550000),
237 "ps_med3_mods": (0x3f800000, 0x40400000, 0x40c00000, 0x3f400000), 258 "ps_med3_mods": (0x3f800000, 0x40400000, 0x40c00000, 0x3f400000),
238 "ps_scc_minmax": (0x00030205, 0x00030207, 0x00030209, 0x00030203), 259 "ps_scc_minmax": (0x00030205, 0x00030207, 0x00030209, 0x00030203),
260 "ps_scc_logic32": (0x0fff0fff, 0x000f000f, 0xf00ff00f, 0x36),
261 "ps_scc_logic64": (0x0fff0fff, 0xff000000, 0xff0000ff, 0x16),
239 "ps_fma_literal": (0x41b80000, 0x41800000, 0x40e00000, 0x41a40000), 262 "ps_fma_literal": (0x41b80000, 0x41800000, 0x40e00000, 0x41a40000),
240 "ps_f64_mods": (0x40040000, 0x3ff00000, 0x3fe40000, 0x3ff00000), 263 "ps_f64_mods": (0x40040000, 0x3ff00000, 0x3fe40000, 0x3ff00000),
241 # f16 op_sel, partial writes, inline constants: words measured on RDNA2 hardware (.asm headers) 264 # f16 op_sel, partial writes, inline constants: words measured on RDNA2 hardware (.asm headers)
@@ -248,6 +271,8 @@ PIXEL_BITS = {"ps_clip_color": (0x3e800000, 0x3f000000, 0x3f400000, 0x3f800000),
248 "ps_f16_const": (0xaaaa3d00, 0x38005555, 0xaaaa3800, 0x3f000000), 271 "ps_f16_const": (0xaaaa3d00, 0x38005555, 0xaaaa3800, 0x3f000000),
249 "ps_f16_const2": (0x42003d00, 0x3d004200, 0xaaaabc00, 3), 272 "ps_f16_const2": (0x42003d00, 0x3d004200, 0xaaaabc00, 3),
250 "ps_f16_pack": (0x34003c00, 0x38003400, 0x34000000, 0x44004200), 273 "ps_f16_pack": (0x34003c00, 0x38003400, 0x34000000, 0x44004200),
274 # v_pack_b32_f16 neg/abs on the selected half: a sign flip / clear before packing (SHADER-260)
275 "ps_f16_pack_mods": (0x4400b400, 0xc4003400, 0x4400c200, 0xb400b400),
251 "ps_sff_imm": (2, 1, 20, 16), 276 "ps_sff_imm": (2, 1, 20, 16),
252 "ps_fnan_med3": (0x40a00000, 0xc0200000, 0xc0200000, 0x40600000), 277 "ps_fnan_med3": (0x40a00000, 0xc0200000, 0xc0200000, 0x40600000),
253 "ps_fnan_fract": (0x3f7fffff, 0x00003bff, 0xc0200000, 0xc0200000), 278 "ps_fnan_fract": (0x3f7fffff, 0x00003bff, 0xc0200000, 0xc0200000),
@@ -267,7 +292,13 @@ PIXEL_BITS = {"ps_clip_color": (0x3e800000, 0x3f000000, 0x3f400000, 0x3f800000),
267 "ps_vint_bits": (0xfffffffe, 0x40000000, 0x1e6a2c48, 0x000001d5), 292 "ps_vint_bits": (0xfffffffe, 0x40000000, 0x1e6a2c48, 0x000001d5),
268 "ps_vint_mul24": (0x13345678, 0xfffffffd, 0x00007fff, 0x0000ffff), 293 "ps_vint_mul24": (0x13345678, 0xfffffffd, 0x00007fff, 0x0000ffff),
269 "ps_vint_minmax": (0x7ffffffe, 0x80000001, 0x80000001, 0x7ffffffe), 294 "ps_vint_minmax": (0x7ffffffe, 0x80000001, 0x80000001, 0x7ffffffe),
270 "ps_vint_minmax3": (0xf0f0f0f0, 0xab800000, 0xf0f0f0f0, 0xab800000)} 295 "ps_vint_minmax3": (0xf0f0f0f0, 0xab800000, 0xf0f0f0f0, 0xab800000),
296 # v_readlane_b32 across both halves of a wave64 (the .asm header derives the words)
297 "ps_w64x_readlane": (0x40000079, 0x40000010, 0x40000064, 0x400000be)}
298# Pixel shaders that are exact only when the pixel stage really ran 64 lanes wide. vk_harness says so when it chained
299# a required subgroup size onto the fragment stage ("fragment subgroup size: N required"). A device that cannot
300# require 64 there (NVIDIA: 32 only; llvmpipe: 8) has no frame to judge: the test is skipped, not failed.
301WIDE_PIXEL_TESTS = {"ps_w64x_readlane": 64}
271# h0..h7 of the ps_vint_* fixtures: 24-bit fields with bit 23 set and garbage above, 33 (a shift of 32+), a 302# h0..h7 of the ps_vint_* fixtures: 24-bit fields with bit 23 set and garbage above, 33 (a shift of 32+), a
272# negative i32 that is a large u32, and plain bit patterns. 303# negative i32 that is a large u32, and plain bit patterns.
273VINT_ENV = {"VKH_SGPRS": "0x1000,0,32,0", 304VINT_ENV = {"VKH_SGPRS": "0x1000,0,32,0",
@@ -444,6 +475,10 @@ def fmt_1010102_test(tools, spirv, env=None):
444 return dump_test(tools, spirv, "cs_fmt_1010102", FMT_1010102_WORDS + [0xEEEEEEEE] * 48, 64, env) 475 return dump_test(tools, spirv, "cs_fmt_1010102", FMT_1010102_WORDS + [0xEEEEEEEE] * 48, 64, env)
445 476
446 477
478def fmt_sint32_test(tools, spirv, env=None):
479 return dump_test(tools, spirv, "cs_fmt_sint32", FMT_SINT32_WORDS, len(FMT_SINT32_WORDS), env)
480
481
447def fmt_xy_xyz_test(tools, spirv, env=None): 482def fmt_xy_xyz_test(tools, spirv, env=None):
448 """TEST-185: the 84 result words and the untouched words after them, up to the inputs at 0x200. The heap needs 483 """TEST-185: the 84 result words and the untouched words after them, up to the inputs at 0x200. The heap needs
449 0x2d0 bytes, so it is 192 words.""" 484 0x2d0 bytes, so it is 192 words."""
@@ -692,9 +727,10 @@ def subgroup_size(spirv, name):
692 return None 727 return None
693 728
694 729
695def bindless_test(tools, spirv): 730def bindless_test(tools, spirv, pixel="ps_tex"):
696 """ps_tex: a texture found through the descriptor hash table and the bindless set (vk_bindless_test).""" 731 """ps_tex: a texture found through the descriptor hash table and the bindless set (vk_bindless_test).
697 shaders = [os.path.join(spirv, name + ".spv") for name in ("vs_ids", "ps_tex")] 732 ps_imgatomic: image atomics in a pixel shader through the set's r32ui storage arrays, checked per texel."""
733 shaders = [os.path.join(spirv, name + ".spv") for name in ("vs_ids", pixel)]
698 for path in shaders: 734 for path in shaders:
699 if not os.path.isfile(path): 735 if not os.path.isfile(path):
700 return f"missing {os.path.basename(path)}" 736 return f"missing {os.path.basename(path)}"
@@ -702,6 +738,9 @@ def bindless_test(tools, spirv):
702 if code == UNSUPPORTED: 738 if code == UNSUPPORTED:
703 m = re.search(r"unsupported: .*", out) 739 m = re.search(r"unsupported: .*", out)
704 return Skip(f"SKIP ({m.group(0) if m else 'unsupported device'})") 740 return Skip(f"SKIP ({m.group(0) if m else 'unsupported device'})")
741 if pixel == "ps_imgatomic":
742 m = re.search(r"ps_imgatomic: (\d+) of \d+ texels wrong.*; (\d+) of \d+ render-target pixels wrong", out)
743 return "" if code == 0 and m and m.group(1) == "0" and m.group(2) == "0" else failure(code, out, 3)
705 m = re.search(r"(\d+) draws read back, (\d+) bad pixels", out) 744 m = re.search(r"(\d+) draws read back, (\d+) bad pixels", out)
706 return "" if code == 0 and m and m.group(2) == "0" else failure(code, out, 3) 745 return "" if code == 0 and m and m.group(2) == "0" else failure(code, out, 3)
707 746
@@ -1072,13 +1111,27 @@ def interp_f16_high_problem(px):
1072 return "" if err < 2e-3 else f"f16 halves off by {err:.3g}" 1111 return "" if err < 2e-3 else f"f16 halves off by {err:.3g}"
1073 1112
1074 1113
1114def wide_pixel_skip(name, out):
1115 """A Skip when `name` needs a 64-wide pixel stage (WIDE_PIXEL_TESTS) and vk_harness's output does not say that size
1116 was required of the fragment stage, else None."""
1117 want = WIDE_PIXEL_TESTS.get(name)
1118 if not want or re.search(rf"^fragment subgroup size: {want} required$", out, re.MULTILINE):
1119 return None
1120 m = re.search(r"subgroup (\d+)\.\.(\d+)", out)
1121 seen = f": subgroup {m.group(1)}..{m.group(2)}" if m else ""
1122 return Skip(f"SKIP (this device cannot require a {want}-wide fragment subgroup{seen})")
1123
1124
1075def pixel_test(tools, spirv, name): 1125def pixel_test(tools, spirv, name):
1076 path = os.path.join(spirv, name + ".spv") 1126 path = os.path.join(spirv, name + ".spv")
1127 if name == "ps_ij_computed" and (BARY_FALLBACK or F16_HALVES):
1128 # Before the .spv check: without PerVertexKHR inputs the translator refuses a computed I/J pair (no .spv).
1129 return Skip("SKIP (computed I/J pairs need PerVertexKHR inputs: no --bary-fallback / --f16-interp-fallback)")
1077 if not os.path.isfile(path): 1130 if not os.path.isfile(path):
1078 return f"missing {name}.spv" 1131 return f"missing {name}.spv"
1079 if name in ("ps_texoff", "ps_texoff_implicit"): 1132 if name in ("ps_texoff", "ps_texoff_implicit"):
1080 return texoff_test(tools, spirv, name) 1133 return texoff_test(tools, spirv, name)
1081 if name in ("ps_interp_f16_high", "ps_ij_computed") and BARY_FALLBACK: 1134 if name == "ps_interp_f16_high" and BARY_FALLBACK:
1082 return Skip("SKIP (per-vertex interpolants need VK_KHR_fragment_shader_barycentric)") 1135 return Skip("SKIP (per-vertex interpolants need VK_KHR_fragment_shader_barycentric)")
1083 fmt = "<4f" if name == "ps_bary" else "<2I2f" if name in ("ps_flat", "ps_uniform_branch", "ps_scc_mask32") else "<4I" 1136 fmt = "<4f" if name == "ps_bary" else "<2I2f" if name in ("ps_flat", "ps_uniform_branch", "ps_scc_mask32") else "<4I"
1084 px, out = pixels(tools, spirv, name, fmt, PIXEL_VERTEX.get(name, "vs_ids")) 1137 px, out = pixels(tools, spirv, name, fmt, PIXEL_VERTEX.get(name, "vs_ids"))
@@ -1093,6 +1146,8 @@ def pixel_test(tools, spirv, name):
1093 return Skip("SKIP (vk_harness reported no subgroup width)") 1146 return Skip("SKIP (vk_harness reported no subgroup width)")
1094 if int(m.group(1)) < 32: 1147 if int(m.group(1)) < 32:
1095 return Skip(f"SKIP (subgroup {m.group(1)} is narrower than 32 lanes)") 1148 return Skip(f"SKIP (subgroup {m.group(1)} is narrower than 32 lanes)")
1149 if skip := wide_pixel_skip(name, out):
1150 return skip
1096 if name == "ps_vcmpx_forms": 1151 if name == "ps_vcmpx_forms":
1097 if skip := vcmpx_forms_narrow_skip(out): 1152 if skip := vcmpx_forms_narrow_skip(out):
1098 return skip 1153 return skip
@@ -1184,6 +1239,7 @@ def main():
1184 results.append(("cs_cmpx_class_f32", compute_test(tools, spirv, "cs_cmpx_class_f32", "1", "dump", 1239 results.append(("cs_cmpx_class_f32", compute_test(tools, spirv, "cs_cmpx_class_f32", "1", "dump",
1185 expected_words=CMPX_CLASS_WORDS))) 1240 expected_words=CMPX_CLASS_WORDS)))
1186 results.append(("cs_fmt_1010102", fmt_1010102_test(tools, spirv))) 1241 results.append(("cs_fmt_1010102", fmt_1010102_test(tools, spirv)))
1242 results.append(("cs_fmt_sint32", fmt_sint32_test(tools, spirv)))
1187 results.append(("cs_fmt_xy_xyz", fmt_xy_xyz_test(tools, spirv))) 1243 results.append(("cs_fmt_xy_xyz", fmt_xy_xyz_test(tools, spirv)))
1188 for name, groups, want in GLOBAL_OFFSET: 1244 for name, groups, want in GLOBAL_OFFSET:
1189 results.append((name, compute_test(tools, spirv, name, groups, "dump", expected_words=want))) 1245 results.append((name, compute_test(tools, spirv, name, groups, "dump", expected_words=want)))
@@ -1222,6 +1278,7 @@ def main():
1222 results.append((name, texture_constant_test(tools, spirv, name))) 1278 results.append((name, texture_constant_test(tools, spirv, name)))
1223 results.append(("ps_tex", bindless_test(tools, spirv))) 1279 results.append(("ps_tex", bindless_test(tools, spirv)))
1224 results.append(("ps_ssharp", sampler_test(tools, spirv))) 1280 results.append(("ps_ssharp", sampler_test(tools, spirv)))
1281 results.append(("ps_imgatomic", bindless_test(tools, spirv, "ps_imgatomic")))
1225 for name in MIP_TEST_PASSES: 1282 for name in MIP_TEST_PASSES:
1226 results.append((name, texture_mip_test(tools, spirv, name))) 1283 results.append((name, texture_mip_test(tools, spirv, name)))
1227 for name in GRADIENT_TESTS: 1284 for name in GRADIENT_TESTS:
diff --git a/runtime/test/shaders/cs_fmt_sint32.asm b/runtime/test/shaders/cs_fmt_sint32.asm
new file mode 100644
index 000000000..a444421ce
--- /dev/null
+++ b/runtime/test/shaders/cs_fmt_sint32.asm
@@ -0,0 +1,90 @@
1; SHADER-257: GFX10 32-bit signed typed buffers. Lane 0 writes [-2147483648, 2147483647, -3, 17] at 0x80.
2; MUBUF loads at out[0..11] test integer DST_SEL=1 for format 63 (X,Y,X,1) and raw words for 73/76.
3; MTBUF loads at out[12..23] use a bound 32_FLOAT descriptor and take width and identity selectors from the
4; instruction (XY00, XYZ0, XYZW). D16 loads at out[24..27] check signed saturation, including -3, for both forms.
5; Single-channel SINT MUBUF/MTBUF loads place -3 in out[28..29].
6; MUBUF stores at 0x90/0xa0/0xb0 write the low 2/3/4 original words. The D16 store at 0xc0 sign-extends
7; 0xfffd and 0x8000 to dwords. The single-channel store at 0xc8 writes -3. Unwritten words retain 0xeeeeeeee.
8v_cmpx_eq_u32_e32 0, v0
9v_mov_b32_e32 v1, 0x80000000
10v_mov_b32_e32 v2, 0x7fffffff
11v_mov_b32_e32 v3, -3
12v_mov_b32_e32 v4, 17
13v_mov_b32_e32 v5, 0x80
14buffer_store_dwordx4 v[1:4], v5, s[0:3], 0 offen
15s_mov_b32 s4, s0
16s_mov_b32 s5, s1
17s_mov_b32 s6, s2
18
19; MUBUF load via format 63.
20s_mov_b32 s7, 0x3103f32c
21buffer_load_format_xyzw v[8:11], v5, s[4:7], 0 offen
22v_mov_b32_e32 v6, 0x0
23buffer_store_dwordx4 v[8:11], v6, s[0:3], 0 offen
24
25; MUBUF load via format 73.
26s_mov_b32 s7, 0x31049fac
27buffer_load_format_xyzw v[8:11], v5, s[4:7], 0 offen
28v_mov_b32_e32 v6, 0x10
29buffer_store_dwordx4 v[8:11], v6, s[0:3], 0 offen
30
31; MUBUF load via format 76.
32s_mov_b32 s7, 0x3104cfac
33buffer_load_format_xyzw v[8:11], v5, s[4:7], 0 offen
34v_mov_b32_e32 v6, 0x20
35buffer_store_dwordx4 v[8:11], v6, s[0:3], 0 offen
36
37; A bound FLOAT descriptor with a different size and selectors from each instruction.
38s_mov_b32 s7, 0x31016000
39tbuffer_load_format_xyzw v[8:11], v5, s[4:7], 0 format:[BUF_FMT_32_32_SINT] offen
40v_mov_b32_e32 v6, 0x30
41buffer_store_dwordx4 v[8:11], v6, s[0:3], 0 offen
42tbuffer_load_format_xyzw v[8:11], v5, s[4:7], 0 format:[BUF_FMT_32_32_32_SINT] offen
43v_mov_b32_e32 v6, 0x40
44buffer_store_dwordx4 v[8:11], v6, s[0:3], 0 offen
45tbuffer_load_format_xyzw v[8:11], v5, s[4:7], 0 format:[BUF_FMT_32_32_32_32_SINT] offen
46v_mov_b32_e32 v6, 0x50
47buffer_store_dwordx4 v[8:11], v6, s[0:3], 0 offen
48
49; Packs (0x8000, 0x7fff) and (0xfffd, 0x0011).
50s_mov_b32 s7, 0x3104cfac
51buffer_load_format_d16_xyzw v[8:9], v5, s[4:7], 0 offen
52v_mov_b32_e32 v6, 0x60
53buffer_store_dwordx2 v[8:9], v6, s[0:3], 0 offen
54s_mov_b32 s7, 0x31016000
55tbuffer_load_format_d16_xyzw v[8:9], v5, s[4:7], 0 format:[BUF_FMT_32_32_32_32_SINT] offen
56v_mov_b32_e32 v6, 0x68
57buffer_store_dwordx2 v[8:9], v6, s[0:3], 0 offen
58
59; Single-component 32_SINT at 0x88, with a bound FLOAT descriptor for the MTBUF case.
60s_mov_b32 s7, 0x31015004
61buffer_load_format_x v8, v5, s[4:7], 0 offen offset:8
62s_mov_b32 s7, 0x31016000
63tbuffer_load_format_x v9, v5, s[4:7], 0 format:[BUF_FMT_32_SINT] offen offset:8
64v_mov_b32_e32 v6, 0x70
65buffer_store_dwordx2 v[8:9], v6, s[0:3], 0 offen
66
67; MUBUF store via format 63.
68s_mov_b32 s7, 0x3103ffac
69v_mov_b32_e32 v6, 0x90
70buffer_store_format_xy v[1:2], v6, s[4:7], 0 offen
71
72; MUBUF store via format 73.
73s_mov_b32 s7, 0x31049fac
74v_mov_b32_e32 v6, 0xa0
75buffer_store_format_xyz v[1:3], v6, s[4:7], 0 offen
76
77; MUBUF store via format 76.
78s_mov_b32 s7, 0x3104cfac
79v_mov_b32_e32 v6, 0xb0
80buffer_store_format_xyzw v[1:4], v6, s[4:7], 0 offen
81
82; A signed packed store must extend both halves.
83s_mov_b32 s7, 0x3103ffac
84v_mov_b32_e32 v6, 0xc0
85v_mov_b32_e32 v7, 0x8000fffd
86buffer_store_format_d16_xy v7, v6, s[4:7], 0 offen
87s_mov_b32 s7, 0x31015004
88v_mov_b32_e32 v6, 0xc8
89buffer_store_format_x v3, v6, s[4:7], 0 offen
90s_endpgm
diff --git a/runtime/test/shaders/cs_w32_sincos.asm b/runtime/test/shaders/cs_w32_sincos.asm
new file mode 100644
index 000000000..6777867da
--- /dev/null
+++ b/runtime/test/shaders/cs_w32_sincos.asm
@@ -0,0 +1,60 @@
1; SHADER-88: v_sin_f32 / v_cos_f32 take the angle in turns and must reduce it in turns before scaling by 2*pi.
2; Six large-angle cases (254.25, 254.5, -200.75, 100.3, 254.51, -254.51 turns); each stores 1 when
3; |result - reference| < 1e-3 (the reference is sin/cos(2*pi*x) in double; a Vulkan Sin/Cos is only guaranteed to
4; 2^-11 = 4.9e-4 in [-pi, pi], so the shader compares with a tolerance and stores a flag, not the float).
5; Lane 0 stores out[0..5] = 1 1 1 1 1 1. (Expected references, f32 bits: 1.0, -1.0, 1.0, 0xbe9e39de,
6; 0xbd808642, 0xbf7f7ed2.)
7; group: 32,1,1
8; Run: vk_compute_test cs_w32_sincos.spv 1 dump -> out[0..5] = 1 1 1 1 1 1
9; mattr: +wavefrontsize32,-wavefrontsize64
10v_mov_b32_e32 v9, 0x3a83126f
11v_cmpx_eq_u32_e32 0, v0
12v_mov_b32_e32 v1, 0x437e4000
13v_sin_f32_e32 v2, v1
14v_sub_f32_e32 v2, 0x3f800000, v2
15v_and_b32_e32 v2, 0x7fffffff, v2
16v_cmp_gt_f32_e32 vcc_lo, v9, v2
17v_cndmask_b32_e64 v20, 0, 1, vcc_lo
18v_mov_b32_e32 v21, 0
19buffer_store_dword v20, v21, s[0:3], 0 offen
20v_mov_b32_e32 v1, 0x437e8000
21v_cos_f32_e32 v2, v1
22v_sub_f32_e32 v2, 0xbf800000, v2
23v_and_b32_e32 v2, 0x7fffffff, v2
24v_cmp_gt_f32_e32 vcc_lo, v9, v2
25v_cndmask_b32_e64 v20, 0, 1, vcc_lo
26v_mov_b32_e32 v21, 4
27buffer_store_dword v20, v21, s[0:3], 0 offen
28v_mov_b32_e32 v1, 0xc348c000
29v_sin_f32_e32 v2, v1
30v_sub_f32_e32 v2, 0x3f800000, v2
31v_and_b32_e32 v2, 0x7fffffff, v2
32v_cmp_gt_f32_e32 vcc_lo, v9, v2
33v_cndmask_b32_e64 v20, 0, 1, vcc_lo
34v_mov_b32_e32 v21, 8
35buffer_store_dword v20, v21, s[0:3], 0 offen
36v_mov_b32_e32 v1, 0x42c8999a
37v_cos_f32_e32 v2, v1
38v_sub_f32_e32 v2, 0xbe9e39de, v2
39v_and_b32_e32 v2, 0x7fffffff, v2
40v_cmp_gt_f32_e32 vcc_lo, v9, v2
41v_cndmask_b32_e64 v20, 0, 1, vcc_lo
42v_mov_b32_e32 v21, 12
43buffer_store_dword v20, v21, s[0:3], 0 offen
44v_mov_b32_e32 v1, 0x437e828f
45v_sin_f32_e32 v2, v1
46v_sub_f32_e32 v2, 0xbd808642, v2
47v_and_b32_e32 v2, 0x7fffffff, v2
48v_cmp_gt_f32_e32 vcc_lo, v9, v2
49v_cndmask_b32_e64 v20, 0, 1, vcc_lo
50v_mov_b32_e32 v21, 16
51buffer_store_dword v20, v21, s[0:3], 0 offen
52v_mov_b32_e32 v1, 0xc37e828f
53v_cos_f32_e32 v2, v1
54v_sub_f32_e32 v2, 0xbf7f7ed2, v2
55v_and_b32_e32 v2, 0x7fffffff, v2
56v_cmp_gt_f32_e32 vcc_lo, v9, v2
57v_cndmask_b32_e64 v20, 0, 1, vcc_lo
58v_mov_b32_e32 v21, 20
59buffer_store_dword v20, v21, s[0:3], 0 offen
60s_endpgm
diff --git a/runtime/test/shaders/ps_f16_pack_mods.asm b/runtime/test/shaders/ps_f16_pack_mods.asm
new file mode 100644
index 000000000..1ef415ee9
--- /dev/null
+++ b/runtime/test/shaders/ps_f16_pack_mods.asm
@@ -0,0 +1,19 @@
1; v_pack_b32_f16 with NEG and ABS on a source: each acts on the selected 16-bit half as a plain bit move
2; (ABS clears bit 15, NEG flips it, ABS first), before the half is packed. The rule and its words were measured
3; on a Radeon 680M (gfx1036, RDNA2 iGPU, AMD Windows driver 32.0.21044.64) with raw kernels: -v0 turned 0x7c01
4; into 0xfe01 under IEEE mode 1 and 0xfc01 under mode 0, in either half and with op_sel (#1548 SHADER-260).
5; Quieting an sNaN half under IEEE mode 1 is not modelled (SHADER-190); the values below are not NaNs.
6; v0 = 0.25 | 3.0 << 16, v1 = 4.0 | 0.25 << 16 (low | high half).
7; -v0, |v1|: -0x3400 | 0x4400 << 16
8; v0, -v1: 0x3400 | -0x4400 << 16
9; -|v0|, v1 op_sel:[1,0,0]: -(0x4200) | 0x4400 << 16
10; -v0, -|v1| op_sel:[0,1,0]: -0x3400 | -(0x3400) << 16
11; Expected mrt0 bits: 0x4400b400, 0xc4003400, 0x4400c200, 0xb400b400
12v_mov_b32 v0, 0x42003400
13v_mov_b32 v1, 0x34004400
14v_pack_b32_f16 v2, -v0, |v1|
15v_pack_b32_f16 v3, v0, -v1
16v_pack_b32_f16 v4, -|v0|, v1 op_sel:[1,0,0]
17v_pack_b32_f16 v5, -v0, -|v1| op_sel:[0,1,0]
18exp mrt0 v2, v3, v4, v5 done vm
19s_endpgm
diff --git a/runtime/test/shaders/ps_imgatomic.asm b/runtime/test/shaders/ps_imgatomic.asm
new file mode 100644
index 000000000..b8f888c13
--- /dev/null
+++ b/runtime/test/shaders/ps_imgatomic.asm
@@ -0,0 +1,44 @@
1; Image atomics in a pixel shader, the forms the game uses (1,018 of its 1,038 image-atomic shaders are pixel shaders:
2; image_atomic_or / umin / umax on a 2D image and umax on a 3D one), through the descriptor table and the set-0
3; r32ui storage arrays (binding 4 for 2D, 7 for 3D). User data s2:s3 is the console VA of a table of four T#s:
4; +0x00 the 2D umax image, +0x20 the 2D umin image, +0x40 the 2D or image, +0x60 the 3D umax image (any 8 dwords:
5; only the key matters). Each of the 64x64 pixels computes px, py from attr0 (vs_ids runs it 0..1 over the target),
6; its id = px + 64 * py, and its texel tx = px >> 3, ty = py >> 3, so 64 pixels contend for each texel of the 8x8
7; images:
8; umax2d[ty][tx] = max(id), umin2d[ty][tx] = min(id), or2d[ty][tx] |= 1 << (id & 31),
9; umax3d[px & 3][ty >> 1][tx >> 1] = max(id) (a 4x4x4 image)
10; After its atomics, every odd px is discarded (v_cmpx). The atomics of a pixel that is discarded afterwards still
11; count, as on hardware: the expected values above are over all 4096 pixels. Even pixels export 1.0.
12; Run: vk_bindless_test vs_ids.spv ps_imgatomic.spv (images cleared to 0, umin to 0xffffffff; checked per texel)
13s_load_dwordx8 s[8:15], s[2:3], 0x0
14s_load_dwordx8 s[16:23], s[2:3], 0x20
15s_load_dwordx8 s[24:31], s[2:3], 0x40
16s_load_dwordx8 s[32:39], s[2:3], 0x60
17s_waitcnt lgkmcnt(0)
18v_interp_p1_f32_e32 v2, v0, attr0.x
19v_interp_p2_f32_e32 v2, v1, attr0.x
20v_interp_p1_f32_e32 v3, v0, attr0.y
21v_interp_p2_f32_e32 v3, v1, attr0.y
22v_mul_f32_e32 v2, 0x42800000, v2
23v_mul_f32_e32 v3, 0x42800000, v3
24v_cvt_u32_f32_e32 v4, v2
25v_cvt_u32_f32_e32 v5, v3
26v_lshlrev_b32_e32 v6, 6, v5
27v_add_nc_u32_e32 v6, v6, v4
28v_lshrrev_b32_e32 v7, 3, v4
29v_lshrrev_b32_e32 v8, 3, v5
30image_atomic_umax v6, v[7:8], s[8:15] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm
31image_atomic_umin v6, v[7:8], s[16:23] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm
32v_and_b32_e32 v9, 31, v6
33v_lshlrev_b32_e64 v9, v9, 1
34image_atomic_or v9, v[7:8], s[24:31] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm
35v_lshrrev_b32_e32 v10, 1, v7
36v_lshrrev_b32_e32 v11, 1, v8
37v_and_b32_e32 v12, 3, v4
38image_atomic_umax v6, v[10:12], s[32:39] dmask:0x1 dim:SQ_RSRC_IMG_3D unorm
39s_waitcnt vmcnt(0)
40v_and_b32_e32 v13, 1, v4
41v_cmpx_eq_u32_e32 0, v13
42v_mov_b32_e32 v14, 1.0
43exp mrt0 v14, v14, v14, v14 done vm
44s_endpgm
diff --git a/runtime/test/shaders/ps_m2_uoff.asm b/runtime/test/shaders/ps_m2_uoff.asm
index 7f1167944..1c96f50d5 100644
--- a/runtime/test/shaders/ps_m2_uoff.asm
+++ b/runtime/test/shaders/ps_m2_uoff.asm
@@ -2,9 +2,12 @@
2; and the fallback sampler give the same pixels; with U + 1 the CLAMP sampler returns the last column and the WRAP one 2; and the fallback sampler give the same pixels; with U + 1 the CLAMP sampler returns the last column and the WRAP one
3; the same texel as without the offset, so the pixels tell which sampler the draw used. Idea and measurements by 3; the same texel as without the offset, so the pixels tell which sampler the draw used. Idea and measurements by
4; @Vonsek (#1489). Run: d3d12_m2_textured_test. 4; @Vonsek (#1489). Run: d3d12_m2_textured_test.
5; The same unbounded SRV table stays bound across both draws. Root constants s4 and s5 hold
6; the descriptor index and byte stride, respectively.
5; fssm-at: 0x10 7; fssm-at: 0x10
6; fssm-data: 0x324d5350 0x4f465520 8; fssm-data: 0x324d5350 0x4f465520
7s_load_dwordx8 s[8:15], s[0:1], 0x0 9s_mul_i32 s20, s4, s5
10s_load_dwordx8 s[8:15], s[0:1], s20
8s_load_dwordx4 s[16:19], s[2:3], 0x0 11s_load_dwordx4 s[16:19], s[2:3], 0x0
9s_waitcnt lgkmcnt(0) 12s_waitcnt lgkmcnt(0)
10v_interp_p1_f32_e32 v2, v0, attr0.x 13v_interp_p1_f32_e32 v2, v0, attr0.x
diff --git a/runtime/test/shaders/ps_scc_logic32.asm b/runtime/test/shaders/ps_scc_logic32.asm
new file mode 100644
index 000000000..3b36f1362
--- /dev/null
+++ b/runtime/test/shaders/ps_scc_logic32.asm
@@ -0,0 +1,44 @@
1; s_nand_b32, s_nor_b32, s_xnor_b32: D = ~(S0 op S1), SCC = (D != 0). Values by hand from the RDNA2 ISA SOP2 text.
2; s2 = 0xf0f0f0f0, s3 = 0xff00ff00: and = 0xf000f000, or = 0xfff0fff0, xor = 0x0ff00ff0.
3; Expected mrt0 bits: nand 0x0fff0fff, nor 0x000f000f, xnor 0xf00ff00f, and an SCC word, bit n = SCC after case n:
4; 0 nand(-1, -1) = 0 -> 0 1 nor(0, 0) = -1 -> 1 2 xnor(x, x) = -1 -> 1
5; 3 xnor(x, ~x) = 0 -> 0 4 nor(0xfffffff0, 0) = 0xf -> 1 5 nand(0x80000000, -1) = 0x7fffffff -> 1
6; so the SCC word is 0x36.
7s_mov_b32 s2, 0xf0f0f0f0
8s_mov_b32 s3, 0xff00ff00
9s_nand_b32 s4, s2, s3
10s_nor_b32 s5, s2, s3
11s_xnor_b32 s6, s2, s3
12s_mov_b32 s8, -1
13s_mov_b32 s9, 0
14s_mov_b32 s10, 0x0f0f0f0f
15s_mov_b32 s11, 0xfffffff0
16s_mov_b32 s12, 0x80000000
17s_nand_b32 s13, s8, s8
18s_cselect_b32 s20, 1, 0
19s_nor_b32 s13, s9, s9
20s_cselect_b32 s21, 1, 0
21s_xnor_b32 s13, s2, s2
22s_cselect_b32 s22, 1, 0
23s_xnor_b32 s13, s2, s10
24s_cselect_b32 s23, 1, 0
25s_nor_b32 s13, s11, s9
26s_cselect_b32 s24, 1, 0
27s_nand_b32 s13, s12, s8
28s_cselect_b32 s25, 1, 0
29s_lshl_b32 s21, s21, 1
30s_lshl_b32 s22, s22, 2
31s_lshl_b32 s23, s23, 3
32s_lshl_b32 s24, s24, 4
33s_lshl_b32 s25, s25, 5
34s_or_b32 s20, s20, s21
35s_or_b32 s20, s20, s22
36s_or_b32 s20, s20, s23
37s_or_b32 s20, s20, s24
38s_or_b32 s20, s20, s25
39v_mov_b32_e32 v0, s4
40v_mov_b32_e32 v1, s5
41v_mov_b32_e32 v2, s6
42v_mov_b32_e32 v3, s20
43exp mrt0 v0, v1, v2, v3 done vm
44s_endpgm
diff --git a/runtime/test/shaders/ps_scc_logic64.asm b/runtime/test/shaders/ps_scc_logic64.asm
new file mode 100644
index 000000000..3ffb677ae
--- /dev/null
+++ b/runtime/test/shaders/ps_scc_logic64.asm
@@ -0,0 +1,49 @@
1; s_nand_b64, s_nor_b64, s_xnor_b64 on plain SGPR pairs: D = ~(S0 op S1), SCC = ((D.lo | D.hi) != 0). By hand from the RDNA2 ISA.
2; A = s[2:3] = (lo 0xf0f0f0f0, hi 0x0000ffff), B = s[4:5] = (lo 0xff00ff00, hi 0x00ff00ff).
3; Expected mrt0 bits: nand.lo 0x0fff0fff, nor.hi 0xff000000 (A.hi | B.hi = 0x00ffffff), xnor.hi 0xff0000ff (A.hi ^ B.hi = 0x00ffff00),
4; and an SCC word, bit n = SCC after case n (X = (-1, 0), Y = (0, -1)):
5; 0 nand(ones, ones) = 0 -> 0 1 nor(X, 0) = (0, -1), only the high dword set -> 1
6; 2 xnor(X, X) = all ones -> 1 3 xnor(X, Y) = 0 -> 0
7; 4 nor(Y, (0xfffffff0, 0)) = (0xf, 0), only the low dword set -> 1
8; so the SCC word is 0x16.
9s_mov_b32 s2, 0xf0f0f0f0
10s_mov_b32 s3, 0x0000ffff
11s_mov_b32 s4, 0xff00ff00
12s_mov_b32 s5, 0x00ff00ff
13s_nand_b64 s[6:7], s[2:3], s[4:5]
14s_nor_b64 s[8:9], s[2:3], s[4:5]
15s_xnor_b64 s[10:11], s[2:3], s[4:5]
16s_mov_b32 s12, -1
17s_mov_b32 s13, -1
18s_mov_b32 s14, -1
19s_mov_b32 s15, 0
20s_mov_b32 s16, 0
21s_mov_b32 s17, -1
22s_mov_b32 s18, 0
23s_mov_b32 s19, 0
24s_mov_b32 s24, 0xfffffff0
25s_mov_b32 s25, 0
26s_nand_b64 s[30:31], s[12:13], s[12:13]
27s_cselect_b32 s40, 1, 0
28s_nor_b64 s[30:31], s[14:15], s[18:19]
29s_cselect_b32 s41, 1, 0
30s_xnor_b64 s[30:31], s[14:15], s[14:15]
31s_cselect_b32 s42, 1, 0
32s_xnor_b64 s[30:31], s[14:15], s[16:17]
33s_cselect_b32 s43, 1, 0
34s_nor_b64 s[30:31], s[16:17], s[24:25]
35s_cselect_b32 s44, 1, 0
36s_lshl_b32 s41, s41, 1
37s_lshl_b32 s42, s42, 2
38s_lshl_b32 s43, s43, 3
39s_lshl_b32 s44, s44, 4
40s_or_b32 s40, s40, s41
41s_or_b32 s40, s40, s42
42s_or_b32 s40, s40, s43
43s_or_b32 s40, s40, s44
44v_mov_b32_e32 v0, s6
45v_mov_b32_e32 v1, s9
46v_mov_b32_e32 v2, s11
47v_mov_b32_e32 v3, s40
48exp mrt0 v0, v1, v2, v3 done vm
49s_endpgm
diff --git a/runtime/test/shaders/ps_w64x_readlane.asm b/runtime/test/shaders/ps_w64x_readlane.asm
new file mode 100644
index 000000000..895254471
--- /dev/null
+++ b/runtime/test/shaders/ps_w64x_readlane.asm
@@ -0,0 +1,27 @@
1; Wave64 pixel shader with v_readlane_b32 across both halves of the wave (RDNA2 ISA: lane = S1 % 64, EXEC ignored).
2; The translator's pixel path takes the lane from SubgroupLocalInvocationId, which is the hardware lane only in a
3; 64-wide subgroup; in a 32-wide one the lane select wraps (lane 40 reads lane 8), so the words below differ.
4; v2 = 3 * lane + 1. Every lane of a full wave reads the same scalars:
5; s6 = v2[40] = 121, s7 = v2[5] = 16, s8 = v2[33] = 100, s9 = v2[63] = 190
6; Each is or'ed with 0x40000000 so the export is a normal float (a float render target keeps bit patterns, but a
7; denormal could be flushed). Export mrt0 = (0x40000079, 0x40000010, 0x40000064, 0x400000be) for every covered
8; pixel of a full wave; draw a triangle that covers the whole target so every wave is full.
9; Run: d3d12_subgroup_test (the PS through a D3D12 graphics PSO, R32G32B32A32_FLOAT target).
10; mattr: +wavefrontsize64,-wavefrontsize32
11v_mbcnt_lo_u32_b32 v1, -1, 0
12v_mbcnt_hi_u32_b32 v1, -1, v1
13v_mad_u32_u24 v2, v1, 3, 1
14v_readlane_b32 s6, v2, 40
15v_readlane_b32 s7, v2, 5
16v_readlane_b32 s8, v2, 33
17v_readlane_b32 s9, v2, 63
18s_or_b32 s6, s6, 0x40000000
19s_or_b32 s7, s7, 0x40000000
20s_or_b32 s8, s8, 0x40000000
21s_or_b32 s9, s9, 0x40000000
22v_mov_b32 v3, s6
23v_mov_b32 v4, s7
24v_mov_b32 v5, s8
25v_mov_b32 v6, s9
26exp mrt0 v3, v4, v5, v6 done vm
27s_endpgm
diff --git a/runtime/test/subgroup_size_test.cpp b/runtime/test/subgroup_size_test.cpp
new file mode 100644
index 000000000..e61387e07
--- /dev/null
+++ b/runtime/test/subgroup_size_test.cpp
@@ -0,0 +1,256 @@
1// The subgroup-size decision of pipeline creation (src/subgroup_size.h) without a GPU: synthetic shader index
2// entries against synthetic device properties, and the VkPipelineShaderStageCreateInfo chain that results.
3// The devices are the three shapes known so far:
4// - AMD, Windows driver (measured on a Radeon 880M, 26.11.2) and current Mesa RADV on GFX10+: sizes 32..64, the
5// stages FRAGMENT | COMPUTE | TASK | MESH can be required;
6// - NVIDIA: every stage can be required, but the only size is 32;
7// - an old RADV: sizes 32..64, COMPUTE only.
8// No game data.
9#include "../src/subgroup_size.h"
10
11#include <cstdio>
12#include <string>
13
14#define CHECK(condition) do { \
15 if (!(condition)) { \
16 std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); \
17 return 1; \
18 } \
19} while (0)
20
21using namespace leonida;
22
23namespace {
24
25constexpr VkShaderStageFlags amd_stages = VK_SHADER_STAGE_FRAGMENT_BIT | VK_SHADER_STAGE_COMPUTE_BIT |
26 VK_SHADER_STAGE_TASK_BIT_EXT | VK_SHADER_STAGE_MESH_BIT_EXT;
27constexpr VkShaderStageFlags all_stages = VK_SHADER_STAGE_ALL_GRAPHICS | VK_SHADER_STAGE_COMPUTE_BIT |
28 VK_SHADER_STAGE_TASK_BIT_EXT | VK_SHADER_STAGE_MESH_BIT_EXT;
29
30SubgroupSizeCaps amd() {
31 SubgroupSizeCaps c;
32 c.subgroup_size_control = c.compute_full_subgroups = true;
33 c.min_size = 32;
34 c.max_size = 64;
35 c.default_size = 64;
36 c.max_compute_workgroup_subgroups = 16;
37 c.required_stages = amd_stages;
38 return c;
39}
40
41SubgroupSizeCaps nvidia() {
42 SubgroupSizeCaps c;
43 c.subgroup_size_control = c.compute_full_subgroups = true;
44 c.min_size = c.max_size = c.default_size = 32;
45 c.max_compute_workgroup_subgroups = 32;
46 c.required_stages = all_stages;
47 return c;
48}
49
50SubgroupSizeCaps old_radv() {
51 SubgroupSizeCaps c = amd();
52 c.required_stages = VK_SHADER_STAGE_COMPUTE_BIT;
53 return c;
54}
55
56// An index entry as the translator writes it: `wave64` shaders carry subgroup_size 64, the rest 32, and a shader
57// translated with --wave64-emulate has no size and a wave64_exchange.
58ShaderEntry entry(const char* stage, bool wave64, std::array<std::uint32_t, 3> local = {64, 1, 1},
59 bool emulated = false) {
60 ShaderEntry e;
61 e.name = std::string(stage) + (wave64 ? "_w64" : "_w32") + (emulated ? "_emu" : "");
62 e.stage = stage;
63 e.wave64 = wave64;
64 e.subgroup_size = emulated ? 0 : (wave64 ? 64 : 32);
65 if (emulated) e.wave64_exchange = "workgroup";
66 e.local_size = local;
67 return e;
68}
69
70} // namespace
71
72int main() {
73 // --- AMD-like -------------------------------------------------------------------------------------------
74 {
75 const SubgroupSizeCaps caps = amd();
76 // Native wave64 compute: 64, plus full subgroups when X is a multiple of 64.
77 auto r = decide_subgroup_size(entry("cs", true), caps);
78 CHECK(r.outcome == SubgroupOutcome::required && r.size == 64 && r.wanted == 64);
79 CHECK(r.stage == VK_SHADER_STAGE_COMPUTE_BIT);
80 CHECK(r.flags == VK_PIPELINE_SHADER_STAGE_CREATE_REQUIRE_FULL_SUBGROUPS_BIT);
81 r = decide_subgroup_size(entry("cs", true, {128, 2, 1}), caps);
82 CHECK(r.size == 64 && (r.flags & VK_PIPELINE_SHADER_STAGE_CREATE_REQUIRE_FULL_SUBGROUPS_BIT));
83 // X not a multiple of 64 (32x2): 64 is still required, full subgroups are not (-pNext-02757).
84 r = decide_subgroup_size(entry("cs", true, {32, 2, 1}), caps);
85 CHECK(r.outcome == SubgroupOutcome::required && r.size == 64 && r.flags == 0);
86 r = decide_subgroup_size(entry("cs", true, {96, 1, 1}), caps);
87 CHECK(r.size == 64 && r.flags == 0);
88 // A wave32 compute shader on a 32..64 device: 32 (the default is 64 here), full subgroups when X % 32 == 0.
89 r = decide_subgroup_size(entry("cs", false, {96, 1, 1}), caps);
90 CHECK(r.outcome == SubgroupOutcome::required && r.size == 32 &&
91 r.flags == VK_PIPELINE_SHADER_STAGE_CREATE_REQUIRE_FULL_SUBGROUPS_BIT);
92 r = decide_subgroup_size(entry("cs", false, {48, 1, 1}), caps);
93 CHECK(r.size == 32 && r.flags == 0);
94 // Pixel shaders can be required on AMD: wave64 gets 64, wave32 gets 32, never a full-subgroups flag.
95 r = decide_subgroup_size(entry("ps", true), caps);
96 CHECK(r.outcome == SubgroupOutcome::required && r.size == 64 && r.flags == 0 &&
97 r.stage == VK_SHADER_STAGE_FRAGMENT_BIT);
98 r = decide_subgroup_size(entry("ps", false), caps);
99 CHECK(r.outcome == SubgroupOutcome::required && r.size == 32 && r.flags == 0);
100 // Mesh: wave64 by construction, 64 and no flag (the flag is only asked of compute).
101 r = decide_subgroup_size(entry("ms", true, {128, 1, 1}), caps);
102 CHECK(r.outcome == SubgroupOutcome::required && r.size == 64 && r.flags == 0 &&
103 r.stage == VK_SHADER_STAGE_MESH_BIT_EXT);
104 // Vertex and geometry stages are not in the list: a wave64 VS cannot be given 64, but the default is 64, so it
105 // works as it is (device_default); there is no emulation for it.
106 r = decide_subgroup_size(entry("vs", true), caps);
107 CHECK(r.outcome == SubgroupOutcome::device_default && r.size == 0 && r.wanted == 64);
108 r = decide_subgroup_size(entry("gs", true), caps);
109 CHECK(r.outcome == SubgroupOutcome::device_default);
110 // A wave32 VS on a 64-wide default is wrong too.
111 r = decide_subgroup_size(entry("vs", false), caps);
112 CHECK(r.outcome == SubgroupOutcome::unavailable && r.wanted == 32);
113 // Emulated shaders ask for nothing, whatever the stage.
114 r = decide_subgroup_size(entry("cs", true, {64, 1, 1}, true), caps);
115 CHECK(r.outcome == SubgroupOutcome::emulated && r.size == 0 && r.flags == 0);
116 r = decide_subgroup_size(entry("ms", true, {128, 1, 1}, true), caps);
117 CHECK(r.outcome == SubgroupOutcome::emulated && r.size == 0 && r.flags == 0);
118 }
119
120 // --- NVIDIA-like: 32 only ----------------------------------------------------------------------------------
121 {
122 const SubgroupSizeCaps caps = nvidia();
123 // Wave32 is what the device does: nothing to chain, in any stage.
124 for (const char* stage : {"cs", "ps", "vs", "gs", "ms"}) {
125 const auto r = decide_subgroup_size(entry(stage, false), caps);
126 CHECK(r.outcome == SubgroupOutcome::device_fixed && r.size == 0 && r.flags == 0);
127 }
128 // Wave64 cannot be had (64 > max): native wave64 is reported in every stage, emulated is fine.
129 for (const char* stage : {"cs", "ps", "vs", "gs", "ms"}) {
130 const auto r = decide_subgroup_size(entry(stage, true), caps);
131 CHECK(r.outcome == SubgroupOutcome::unavailable && r.size == 0 && r.flags == 0 && r.wanted == 64);
132 }
133 const auto emulated = decide_subgroup_size(entry("cs", true, {64, 1, 1}, true), caps);
134 CHECK(emulated.outcome == SubgroupOutcome::emulated && emulated.size == 0);
135 }
136
137 // --- An old RADV: COMPUTE only ----------------------------------------------------------------------------------
138 {
139 const SubgroupSizeCaps caps = old_radv();
140 auto r = decide_subgroup_size(entry("cs", true), caps);
141 CHECK(r.outcome == SubgroupOutcome::required && r.size == 64 &&
142 r.flags == VK_PIPELINE_SHADER_STAGE_CREATE_REQUIRE_FULL_SUBGROUPS_BIT);
143 // Pixel shaders cannot be required, and the default is 64: a wave32 PS is wrong, a wave64 PS works as it is
144 // (device_default: nothing guarantees the default, min != max).
145 r = decide_subgroup_size(entry("ps", false), caps);
146 CHECK(r.outcome == SubgroupOutcome::unavailable && r.size == 0);
147 r = decide_subgroup_size(entry("ps", true), caps);
148 CHECK(r.outcome == SubgroupOutcome::device_default && r.size == 0);
149 r = decide_subgroup_size(entry("ms", true, {128, 1, 1}), caps);
150 CHECK(r.outcome == SubgroupOutcome::device_default);
151 }
152
153 // --- Feature, limit and index edge cases -------------------------------------------------------------------------
154 {
155 SubgroupSizeCaps caps = amd();
156 // computeFullSubgroups off: the size is still required, the flag is not set.
157 caps.compute_full_subgroups = false;
158 auto r = decide_subgroup_size(entry("cs", true), caps);
159 CHECK(r.outcome == SubgroupOutcome::required && r.size == 64 && r.flags == 0);
160 // subgroupSizeControl not enabled: the chain would break VUID -pNext-02755, so it is not asked for.
161 caps = amd();
162 caps.subgroup_size_control = false;
163 r = decide_subgroup_size(entry("cs", true), caps);
164 CHECK(r.outcome == SubgroupOutcome::device_default && r.size == 0 && r.flags == 0);
165 // The workgroup must fit size * maxComputeWorkgroupSubgroups (-pNext-02756): 1024 > 64 * 8.
166 caps = amd();
167 caps.max_compute_workgroup_subgroups = 8;
168 r = decide_subgroup_size(entry("cs", true, {1024, 1, 1}), caps);
169 CHECK(r.outcome == SubgroupOutcome::device_default);
170 r = decide_subgroup_size(entry("cs", true, {512, 1, 1}), caps);
171 CHECK(r.outcome == SubgroupOutcome::required && r.size == 64);
172 r = decide_subgroup_size(entry("cs", true, {16, 8, 8}), caps); // 1024 invocations too
173 CHECK(r.outcome == SubgroupOutcome::device_default);
174 // The limit is for compute and mesh; a pixel shader is not subject to it.
175 r = decide_subgroup_size(entry("ps", true), caps);
176 CHECK(r.outcome == SubgroupOutcome::required);
177 // A size that is not a power of two, or outside [min, max], is not chained.
178 caps = amd();
179 ShaderEntry odd = entry("cs", true);
180 odd.subgroup_size = 48;
181 CHECK(decide_subgroup_size(odd, caps).outcome == SubgroupOutcome::unavailable);
182 odd.subgroup_size = 128;
183 CHECK(decide_subgroup_size(odd, caps).outcome == SubgroupOutcome::unavailable);
184 odd.subgroup_size = 16;
185 CHECK(decide_subgroup_size(odd, caps).outcome == SubgroupOutcome::unavailable);
186 // An entry without subgroup_size (an index from an older translator) follows `wave64`.
187 ShaderEntry bare = entry("cs", true);
188 bare.subgroup_size = 0;
189 CHECK(decide_subgroup_size(bare, amd()).size == 64);
190 bare.wave64 = false;
191 CHECK(decide_subgroup_size(bare, amd()).size == 32);
192 // Device sizes that were never queried: nothing is asked for and nothing is reported.
193 CHECK(decide_subgroup_size(entry("cs", true), SubgroupSizeCaps{}).outcome == SubgroupOutcome::unknown_device);
194 // A stage this layer has no pipeline for.
195 CHECK(decide_subgroup_size(entry("rt", true), amd()).outcome == SubgroupOutcome::unknown_stage);
196 // A device that only has 64 runs a wave64 shader as it is.
197 caps = amd();
198 caps.min_size = caps.max_size = caps.default_size = 64;
199 CHECK(decide_subgroup_size(entry("ps", true), caps).outcome == SubgroupOutcome::device_fixed);
200 CHECK(decide_subgroup_size(entry("ps", false), caps).outcome == SubgroupOutcome::unavailable);
201 }
202
203 // --- The create-info chain -------------------------------------------------------------------------------------
204 {
205 const SubgroupSizeCaps caps = amd();
206 VkPipelineShaderStageRequiredSubgroupSizeCreateInfo storage{};
207 VkPipelineShaderStageCreateInfo stage{VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO};
208 stage.stage = VK_SHADER_STAGE_COMPUTE_BIT;
209 apply_subgroup_request(decide_subgroup_size(entry("cs", true), caps), storage, stage);
210 CHECK(stage.flags == VK_PIPELINE_SHADER_STAGE_CREATE_REQUIRE_FULL_SUBGROUPS_BIT);
211 CHECK(stage.pNext == &storage);
212 CHECK(storage.sType == VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_REQUIRED_SUBGROUP_SIZE_CREATE_INFO);
213 CHECK(storage.requiredSubgroupSize == 64 && storage.pNext == nullptr);
214
215 // It goes in front of what the stage already chains.
216 VkPipelineShaderStageRequiredSubgroupSizeCreateInfo other{};
217 VkPipelineShaderStageCreateInfo chained{VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO};
218 chained.pNext = &other;
219 apply_subgroup_request(decide_subgroup_size(entry("ps", false), caps), storage, chained);
220 CHECK(chained.pNext == &storage && storage.pNext == &other && storage.requiredSubgroupSize == 32);
221 CHECK(chained.flags == 0);
222
223 // A request for nothing leaves the stage alone, whatever the reason.
224 for (const auto& e : {entry("cs", true, {64, 1, 1}, true), entry("vs", true)}) {
225 VkPipelineShaderStageCreateInfo untouched{VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO};
226 VkPipelineShaderStageRequiredSubgroupSizeCreateInfo unused{};
227 apply_subgroup_request(decide_subgroup_size(e, caps), unused, untouched);
228 CHECK(untouched.pNext == nullptr && untouched.flags == 0 && unused.sType == 0);
229 }
230 }
231
232 // --- Querying the device ----------------------------------------------------------------------------------------
233 {
234 VkPhysicalDevice device = reinterpret_cast<VkPhysicalDevice>(std::uintptr_t(0x1000));
235 VkPhysicalDevice seen = VK_NULL_HANDLE;
236 const auto fake = [&](VkPhysicalDevice physical, VkPhysicalDeviceProperties2* properties) {
237 seen = physical;
238 auto* subgroup = static_cast<VkPhysicalDeviceSubgroupProperties*>(properties->pNext);
239 auto* control = static_cast<VkPhysicalDeviceSubgroupSizeControlProperties*>(subgroup->pNext);
240 subgroup->subgroupSize = 64;
241 control->minSubgroupSize = 32;
242 control->maxSubgroupSize = 64;
243 control->maxComputeWorkgroupSubgroups = 16;
244 control->requiredSubgroupSizeStages = amd_stages;
245 };
246 SubgroupSizeCaps caps;
247 CHECK(query_subgroup_size_caps(fake, device, true, false, caps));
248 CHECK(seen == device);
249 CHECK(caps.default_size == 64 && caps.min_size == 32 && caps.max_size == 64 &&
250 caps.max_compute_workgroup_subgroups == 16 && caps.required_stages == amd_stages);
251 CHECK(caps.subgroup_size_control && !caps.compute_full_subgroups);
252 }
253
254 std::printf("subgroup size decision: AMD-like, NVIDIA-like, old RADV, limits, create-info chain and query OK\n");
255 return 0;
256}
diff --git a/runtime/test/vk_bc_zero_init_test.cpp b/runtime/test/vk_bc_zero_init_test.cpp
new file mode 100644
index 000000000..6edc36fcb
--- /dev/null
+++ b/runtime/test/vk_bc_zero_init_test.cpp
@@ -0,0 +1,388 @@
1// Committed block-compressed (BC*) texture zero-initialization regression (D3D-220, #1725):
2// D3D12 committed textures start zeroed unless D3D12_HEAP_FLAG_CREATE_NOT_ZEROED is set. Vulkan forbids
3// vkCmdClearColorImage on BC formats, so detail::initialize() must zero-fill them via vkCmdCopyBufferToImage
4// from either the device zero page (vk.zero_buffer) or a zeroed transfer-scratch chunk (vk.copy_scratch).
5//
6// Cases (all on explicitly poisoned 0x5A backing memory when host-visible, plus default device memory):
7// 1. Path A (vk.zero_buffer): CopyTextureRegion R32G32_UINT 2x2 -> BC1 16x16 at (8, 4) — untouched blocks are 0x00.
8// 2. Path A (vk.zero_buffer): CopyResource R32G32_UINT 3x2 -> BC1 12x8, 2 mips — mip 1 untouched block (bytes 56..63) is 0x00.
9// 3. Path A (tiny 32-byte vk.zero_buffer): 32x32 BC7 image tiled in multiple row/column chunks — all 1024 bytes are 0x00.
10// 4. Path B (enable_copy_scratch, no zero_buffer — matches d3d12_copy_xfmt): both D3D-220 cases match bit for bit.
11// 5. not_zeroed = true (CREATE_NOT_ZEROED): zero-fill is skipped.
12// Skips with exit code 77 when no Vulkan 1.3 device with textureCompressionBC is available. No game data.
13#include "vk_test_device.h"
14#include "../src/vulkan_backend.h"
15
16#include <algorithm>
17#include <cstdint>
18#include <cstdio>
19#include <cstring>
20#include <vector>
21
22#define EXPECT(condition) do { \
23 if (!(condition)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); return 1; } \
24} while (0)
25
26namespace {
27
28struct OwnedImage {
29 VkDevice device = VK_NULL_HANDLE;
30 PFN_vkDestroyImage destroy_image = nullptr;
31 PFN_vkFreeMemory free_memory = nullptr;
32 VkImage image = VK_NULL_HANDLE;
33 VkDeviceMemory memory = VK_NULL_HANDLE;
34 bool poisoned = false;
35
36 ~OwnedImage() {
37 if (image && destroy_image) destroy_image(device, image, nullptr);
38 if (memory && free_memory) free_memory(device, memory, nullptr);
39 }
40 OwnedImage(const OwnedImage&) = delete;
41 OwnedImage& operator=(const OwnedImage&) = delete;
42 OwnedImage() = default;
43};
44
45bool create_image(const vktest::Device& d, VkFormat format, std::uint32_t width, std::uint32_t height,
46 std::uint32_t mips, VkBuffer poison_buf, OwnedImage& out) {
47 out.device = d.device;
48 out.destroy_image = d.fn<PFN_vkDestroyImage>("vkDestroyImage");
49 out.free_memory = d.fn<PFN_vkFreeMemory>("vkFreeMemory");
50
51 VkImageCreateInfo info{VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO};
52 info.imageType = VK_IMAGE_TYPE_2D;
53 info.format = format;
54 info.extent = {width, height, 1};
55 info.mipLevels = mips;
56 info.arrayLayers = 1;
57 info.samples = VK_SAMPLE_COUNT_1_BIT;
58 info.tiling = VK_IMAGE_TILING_OPTIMAL;
59 info.usage = VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_SAMPLED_BIT;
60 if (d.fn<PFN_vkCreateImage>("vkCreateImage")(d.device, &info, nullptr, &out.image) != VK_SUCCESS) return false;
61
62 VkMemoryRequirements req{};
63 d.fn<PFN_vkGetImageMemoryRequirements>("vkGetImageMemoryRequirements")(d.device, out.image, &req);
64 VkPhysicalDeviceMemoryProperties mp{};
65 d.instance_fn<PFN_vkGetPhysicalDeviceMemoryProperties>("vkGetPhysicalDeviceMemoryProperties")(d.physical, &mp);
66
67 std::uint32_t type = UINT32_MAX;
68 for (std::uint32_t i = 0; i < mp.memoryTypeCount; ++i) {
69 if (!(req.memoryTypeBits & (1u << i))) continue;
70 if (type == UINT32_MAX) type = i;
71 if (mp.memoryTypes[i].propertyFlags & VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT) {
72 type = i;
73 break;
74 }
75 }
76 if (type == UINT32_MAX) return false;
77
78 VkMemoryAllocateInfo alloc{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO};
79 alloc.allocationSize = req.size;
80 alloc.memoryTypeIndex = type;
81 if (d.fn<PFN_vkAllocateMemory>("vkAllocateMemory")(d.device, &alloc, nullptr, &out.memory) != VK_SUCCESS)
82 return false;
83 if (d.fn<PFN_vkBindImageMemory>("vkBindImageMemory")(d.device, out.image, out.memory, 0) != VK_SUCCESS)
84 return false;
85
86 // Pre-fill every mip on the GPU with 0x5A so stale recycled VRAM is modeled deterministically on every GPU
87 // (discrete and integrated alike), before registering the image in LayoutTracker as UNDEFINED.
88 if (poison_buf) {
89 const bool ok = const_cast<vktest::Device&>(d).run([&](VkCommandBuffer cb) {
90 VkImageMemoryBarrier to_dst{VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER};
91 to_dst.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
92 to_dst.oldLayout = VK_IMAGE_LAYOUT_UNDEFINED;
93 to_dst.newLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
94 to_dst.srcQueueFamilyIndex = to_dst.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
95 to_dst.image = out.image;
96 to_dst.subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, mips, 0, 1};
97 d.fn<PFN_vkCmdPipelineBarrier>("vkCmdPipelineBarrier")(cb, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT,
98 VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, nullptr, 0,
99 nullptr, 1, &to_dst);
100 std::vector<VkBufferImageCopy> regions;
101 for (std::uint32_t m = 0; m < mips; ++m) {
102 VkBufferImageCopy r{};
103 r.imageSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, m, 0, 1};
104 r.imageExtent = {std::max(1u, width >> m), std::max(1u, height >> m), 1};
105 regions.push_back(r);
106 }
107 d.fn<PFN_vkCmdCopyBufferToImage>("vkCmdCopyBufferToImage")(
108 cb, poison_buf, out.image, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, std::uint32_t(regions.size()),
109 regions.data());
110 return true;
111 });
112 if (!ok) return false;
113 out.poisoned = true;
114 }
115 return true;
116}
117
118VkDeviceMemory allocate_device_local(const vktest::Device& d, const VkMemoryRequirements& req) {
119 VkPhysicalDeviceMemoryProperties mp{};
120 d.instance_fn<PFN_vkGetPhysicalDeviceMemoryProperties>("vkGetPhysicalDeviceMemoryProperties")(d.physical, &mp);
121 std::uint32_t chosen = UINT32_MAX;
122 for (std::uint32_t i = 0; i < mp.memoryTypeCount; ++i) {
123 if (!(req.memoryTypeBits & (1u << i))) continue;
124 if (chosen == UINT32_MAX) chosen = i;
125 if (mp.memoryTypes[i].propertyFlags & VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT) {
126 chosen = i;
127 break;
128 }
129 }
130 if (chosen == UINT32_MAX) return VK_NULL_HANDLE;
131 VkMemoryAllocateInfo info{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO};
132 info.allocationSize = req.size;
133 info.memoryTypeIndex = chosen;
134 VkDeviceMemory mem = VK_NULL_HANDLE;
135 if (d.fn<PFN_vkAllocateMemory>("vkAllocateMemory")(d.device, &info, nullptr, &mem) != VK_SUCCESS)
136 return VK_NULL_HANDLE;
137 return mem;
138}
139
140// Runs the two D3D-220 partial uncompressed -> BC1 copies on a given context/queue:
141// (a) CopyTextureRegion R32G32_UINT 2x2 -> BC1 16x16 at (8, 4)
142// (b) CopyResource R32G32_UINT 3x2 -> BC1 12x8, 2 mips
143int run_d3d220_cases(const vktest::Device& d, leonida::VulkanContext& ctx, leonida::VulkanQueue& q,
144 VkBuffer poison_buf, VkBuffer up_buf, void* up_ptr, VkBuffer rb_buf, void* rb_ptr,
145 const char* label) {
146 using namespace leonida;
147
148 auto* up = static_cast<std::uint8_t*>(up_ptr);
149 auto* rb = static_cast<std::uint8_t*>(rb_ptr);
150 for (std::size_t i = 0; i < 4096; ++i) up[i] = static_cast<std::uint8_t>(i * 7 + 3);
151
152 // Case (a): CopyTextureRegion R32G32_UINT 2x2 -> BC1 16x16 at (8, 4).
153 // Destination has 4x4 BC1 blocks (8 bytes/block). Only blocks (2,1), (3,1), (2,2), (3,2) are written;
154 // the other 12 blocks (including block (0,0) at byte 0) must be 0x00.
155 {
156 OwnedImage src_img, dst_img;
157 EXPECT(create_image(d, VK_FORMAT_R32G32_UINT, 2, 2, 1, VK_NULL_HANDLE, src_img));
158 EXPECT(create_image(d, VK_FORMAT_BC1_RGBA_UNORM_BLOCK, 16, 16, 1, poison_buf, dst_img));
159
160 ResourceBinding src_rb{};
161 src_rb.image = src_img.image;
162 src_rb.format = VK_FORMAT_R32G32_UINT;
163 src_rb.aspects = VK_IMAGE_ASPECT_COLOR_BIT;
164 src_rb.width = 2; src_rb.height = 2; src_rb.mip_levels = 1; src_rb.array_layers = 1; src_rb.depth = 1; src_rb.samples = 1;
165
166 ResourceBinding dst_rb{};
167 dst_rb.image = dst_img.image;
168 dst_rb.format = VK_FORMAT_BC1_RGBA_UNORM_BLOCK;
169 dst_rb.aspects = VK_IMAGE_ASPECT_COLOR_BIT;
170 dst_rb.width = 16; dst_rb.height = 16; dst_rb.mip_levels = 1; dst_rb.array_layers = 1; dst_rb.depth = 1; dst_rb.samples = 1;
171
172 ctx.add_resource(10, src_rb, VK_IMAGE_LAYOUT_UNDEFINED);
173 ctx.add_resource(11, dst_rb, VK_IMAGE_LAYOUT_UNDEFINED);
174 std::memset(rb, 0xCD, 4096);
175
176 CommandList list;
177 CopyLocation up_loc{1, true, 0, 0, 2, 2, 1, 256};
178 CopyLocation src_loc{10, false, 0, 0, 0, 0, 0, 0};
179 CopyLocation dst_loc{11, false, 0, 0, 0, 0, 0, 0};
180 CopyLocation rb_loc{2, true, 0, 0, 16, 16, 1, 256};
181 EXPECT(list.copy_texture({src_loc, 0, 0, 0, up_loc, false, {}}));
182 EXPECT(list.transition({10, all_subresources, d3d12_state::copy_dest, d3d12_state::copy_source}));
183 EXPECT(list.copy_texture({dst_loc, 8, 4, 0, src_loc, false, {}}));
184 EXPECT(list.transition({11, all_subresources, d3d12_state::copy_dest, d3d12_state::copy_source}));
185 EXPECT(list.copy_texture({rb_loc, 0, 0, 0, dst_loc, false, {}}));
186 EXPECT(list.close());
187
188 const CommandList* ptr = &list;
189 EXPECT(q.execute({&ptr, 1}) == ReplayResult::success);
190 EXPECT(q.idle());
191
192 // Check every 8-byte block across the 4x4 block grid (row pitch 256).
193 for (std::uint32_t by = 0; by < 4; ++by) {
194 for (std::uint32_t bx = 0; bx < 4; ++bx) {
195 const std::uint8_t* got = rb + std::size_t(by) * 256 + std::size_t(bx) * 8;
196 if (bx >= 2 && bx < 4 && by >= 1 && by < 3) {
197 const std::uint8_t* want = up + std::size_t(by - 1) * 256 + std::size_t(bx - 2) * 8;
198 EXPECT(std::memcmp(got, want, 8) == 0);
199 } else {
200 for (int k = 0; k < 8; ++k) EXPECT(got[k] == 0x00);
201 }
202 }
203 }
204 ctx.remove_resource(10);
205 ctx.remove_resource(11);
206 }
207
208 // Case (b): CopyResource R32G32_UINT 3x2 -> BC1 12x8, 2 mips.
209 // Mip 0: 3x2 -> 12x8 (3x2 = 6 blocks written).
210 // Mip 1: 1x1 -> 6x4 (2x1 = 2 blocks; block 0 is written, block 1 at bytes 8..15 of mip 1 is untouched -> 0x00).
211 {
212 OwnedImage src_img, dst_img;
213 EXPECT(create_image(d, VK_FORMAT_R32G32_UINT, 3, 2, 2, VK_NULL_HANDLE, src_img));
214 EXPECT(create_image(d, VK_FORMAT_BC1_RGBA_UNORM_BLOCK, 12, 8, 2, poison_buf, dst_img));
215
216 ResourceBinding src_rb{};
217 src_rb.image = src_img.image;
218 src_rb.format = VK_FORMAT_R32G32_UINT;
219 src_rb.aspects = VK_IMAGE_ASPECT_COLOR_BIT;
220 src_rb.width = 3; src_rb.height = 2; src_rb.mip_levels = 2; src_rb.array_layers = 1; src_rb.depth = 1; src_rb.samples = 1;
221
222 ResourceBinding dst_rb{};
223 dst_rb.image = dst_img.image;
224 dst_rb.format = VK_FORMAT_BC1_RGBA_UNORM_BLOCK;
225 dst_rb.aspects = VK_IMAGE_ASPECT_COLOR_BIT;
226 dst_rb.width = 12; dst_rb.height = 8; dst_rb.mip_levels = 2; dst_rb.array_layers = 1; dst_rb.depth = 1; dst_rb.samples = 1;
227
228 ctx.add_resource(12, src_rb, VK_IMAGE_LAYOUT_UNDEFINED);
229 ctx.add_resource(13, dst_rb, VK_IMAGE_LAYOUT_UNDEFINED);
230 std::memset(rb, 0xCD, 4096);
231
232 // Upload mip 0 at offset 0 (2 rows * 256 = 512 bytes) and mip 1 at offset 512 (1 row * 256).
233 CommandList list;
234 CopyLocation up0{1, true, 0, 0, 3, 2, 1, 256};
235 CopyLocation up1{1, true, 0, 512, 1, 1, 1, 256};
236 CopyLocation src0{12, false, 0, 0, 0, 0, 0, 0};
237 CopyLocation src1{12, false, 1, 0, 0, 0, 0, 0};
238 CopyLocation dst0{13, false, 0, 0, 0, 0, 0, 0};
239 CopyLocation dst1{13, false, 1, 0, 0, 0, 0, 0};
240 CopyLocation rb0{2, true, 0, 0, 12, 8, 1, 256};
241 CopyLocation rb1{2, true, 0, 512, 6, 4, 1, 256};
242 EXPECT(list.copy_texture({src0, 0, 0, 0, up0, false, {}}));
243 EXPECT(list.copy_texture({src1, 0, 0, 0, up1, false, {}}));
244 EXPECT(list.transition({12, all_subresources, d3d12_state::copy_dest, d3d12_state::copy_source}));
245 EXPECT(list.copy_resource({13, 12}));
246 EXPECT(list.transition({13, all_subresources, d3d12_state::copy_dest, d3d12_state::copy_source}));
247 EXPECT(list.copy_texture({rb0, 0, 0, 0, dst0, false, {}}));
248 EXPECT(list.copy_texture({rb1, 0, 0, 0, dst1, false, {}}));
249 EXPECT(list.close());
250
251 const CommandList* ptr = &list;
252 EXPECT(q.execute({&ptr, 1}) == ReplayResult::success);
253 EXPECT(q.idle());
254
255 // Mip 0: 2 rows of 3 blocks (24 bytes per row).
256 EXPECT(std::memcmp(rb + 0, up + 0, 24) == 0);
257 EXPECT(std::memcmp(rb + 256, up + 256, 24) == 0);
258 // Mip 1: block 0 (bytes 0..7) matches up + 512; untouched block 1 (bytes 8..15) must be 0x00.
259 EXPECT(std::memcmp(rb + 512, up + 512, 8) == 0);
260 for (int k = 8; k < 16; ++k) EXPECT(rb[512 + k] == 0x00);
261
262 ctx.remove_resource(12);
263 ctx.remove_resource(13);
264 }
265
266 (void)up_buf;
267 (void)rb_buf;
268 std::printf("bc zero-init (%s): partial CopyTextureRegion and 2-mip CopyResource ok\n", label);
269 return 0;
270}
271
272} // namespace
273
274int main() {
275 using namespace leonida;
276
277 vktest::Device d;
278 if (!d.create(false) || !d.bc) {
279 std::fprintf(stderr, "vk_bc_zero_init_test: no Vulkan 1.3 device with BC support, skipped\n");
280 return 77;
281 }
282
283 void* up_ptr = nullptr;
284 void* rb_ptr = nullptr;
285 void* zero_ptr = nullptr;
286 void* poison_ptr = nullptr;
287 const VkBuffer up_buf = d.buffer(4096, VK_BUFFER_USAGE_TRANSFER_SRC_BIT, &up_ptr);
288 const VkBuffer rb_buf = d.buffer(8192, VK_BUFFER_USAGE_TRANSFER_DST_BIT, &rb_ptr);
289 const VkBuffer zero_buf = d.buffer(65536, VK_BUFFER_USAGE_TRANSFER_SRC_BIT, &zero_ptr);
290 const VkBuffer poison_buf = d.buffer(4096, VK_BUFFER_USAGE_TRANSFER_SRC_BIT, &poison_ptr);
291 EXPECT(up_buf && rb_buf && zero_buf && poison_buf);
292 std::memset(zero_ptr, 0, 65536);
293 std::memset(poison_ptr, 0x5A, 4096);
294
295 ResourceBinding up_rb{};
296 up_rb.buffer = up_buf;
297 up_rb.size = 4096;
298 ResourceBinding rb_rb{};
299 rb_rb.buffer = rb_buf;
300 rb_rb.size = 8192;
301 rb_rb.host_readable = true;
302
303 // Path A: device arena zero page (vk.zero_buffer).
304 {
305 VulkanContext ctx(d.device_proc, d.device, true);
306 EXPECT(ctx.loaded());
307 ctx.set_zero_page(zero_buf, 0, 65536);
308 ctx.add_resource(1, up_rb);
309 ctx.add_resource(2, rb_rb);
310 VulkanQueue q(ctx, d.queue, d.family);
311 EXPECT(q.ok());
312 EXPECT(run_d3d220_cases(d, ctx, q, poison_buf, up_buf, up_ptr, rb_buf, rb_ptr, "zero_buffer") == 0);
313
314 // Multi-tile chunking: shrink zero_page to 32 bytes (2 BC7 blocks) and zero-init a 32x32 BC7 image (64 blocks).
315 ctx.set_zero_page(zero_buf, 16, 32);
316 OwnedImage bc7_img;
317 EXPECT(create_image(d, VK_FORMAT_BC7_UNORM_BLOCK, 32, 32, 1, poison_buf, bc7_img));
318 ResourceBinding bc7_rb{};
319 bc7_rb.image = bc7_img.image;
320 bc7_rb.format = VK_FORMAT_BC7_UNORM_BLOCK;
321 bc7_rb.aspects = VK_IMAGE_ASPECT_COLOR_BIT;
322 bc7_rb.width = 32; bc7_rb.height = 32; bc7_rb.mip_levels = 1; bc7_rb.array_layers = 1; bc7_rb.depth = 1; bc7_rb.samples = 1;
323 ctx.add_resource(20, bc7_rb, VK_IMAGE_LAYOUT_UNDEFINED);
324 std::memset(rb_ptr, 0xCD, 8192);
325
326 CommandList list;
327 EXPECT(list.transition({20, all_subresources, d3d12_state::copy_dest, d3d12_state::copy_source}));
328 CopyLocation bc7_loc{20, false, 0, 0, 0, 0, 0, 0};
329 CopyLocation rb_loc{2, true, 0, 0, 32, 32, 1, 256};
330 EXPECT(list.copy_texture({rb_loc, 0, 0, 0, bc7_loc, false, {}}));
331 EXPECT(list.close());
332 const CommandList* ptr = &list;
333 EXPECT(q.execute({&ptr, 1}) == ReplayResult::success);
334 EXPECT(q.idle());
335
336 auto* rb = static_cast<std::uint8_t*>(rb_ptr);
337 for (std::uint32_t row = 0; row < 8; ++row)
338 for (std::uint32_t x = 0; x < 8 * 16; ++x)
339 EXPECT(rb[row * 256 + x] == 0x00);
340 ctx.remove_resource(20);
341 std::printf("bc zero-init (tiny 32-byte zero_buffer chunking on 32x32 BC7): ok\n");
342
343 // CREATE_NOT_ZEROED (not_zeroed = true) must skip zero-fill.
344 ctx.set_zero_page(zero_buf, 0, 65536);
345 OwnedImage nz_img;
346 EXPECT(create_image(d, VK_FORMAT_BC1_RGBA_UNORM_BLOCK, 16, 16, 1, poison_buf, nz_img));
347 EXPECT(nz_img.poisoned);
348 ResourceBinding nz_rb{};
349 nz_rb.image = nz_img.image;
350 nz_rb.format = VK_FORMAT_BC1_RGBA_UNORM_BLOCK;
351 nz_rb.aspects = VK_IMAGE_ASPECT_COLOR_BIT;
352 nz_rb.width = 16; nz_rb.height = 16; nz_rb.mip_levels = 1; nz_rb.array_layers = 1; nz_rb.depth = 1; nz_rb.samples = 1;
353 nz_rb.not_zeroed = true;
354 ctx.add_resource(21, nz_rb, VK_IMAGE_LAYOUT_UNDEFINED);
355 std::memset(rb_ptr, 0xCD, 8192);
356
357 CommandList nz_list;
358 EXPECT(nz_list.transition({21, all_subresources, d3d12_state::copy_dest, d3d12_state::copy_source}));
359 CopyLocation nz_loc{21, false, 0, 0, 0, 0, 0, 0};
360 CopyLocation nz_rb_loc{2, true, 0, 0, 16, 16, 1, 256};
361 EXPECT(nz_list.copy_texture({nz_rb_loc, 0, 0, 0, nz_loc, false, {}}));
362 EXPECT(nz_list.close());
363 const CommandList* nz_ptr = &nz_list;
364 EXPECT(q.execute({&nz_ptr, 1}) == ReplayResult::success);
365 EXPECT(q.idle());
366 EXPECT(rb[0] == 0x5A);
367 ctx.remove_resource(21);
368 std::printf("bc zero-init (not_zeroed = true skips zero-fill): ok\n");
369 }
370
371 // Path B: copy_scratch + vkCmdFillBuffer fallback (no zero_buffer, matching d3d12_copy_xfmt without BDA).
372 {
373 VulkanContext ctx(d.device_proc, d.device, true);
374 EXPECT(ctx.loaded());
375 ctx.enable_copy_scratch(d.device_proc, [&](const VkMemoryRequirements& req) {
376 return allocate_device_local(d, req);
377 });
378 ctx.add_resource(1, up_rb);
379 ctx.add_resource(2, rb_rb);
380 VulkanQueue q(ctx, d.queue, d.family);
381 EXPECT(q.ok());
382 EXPECT(run_d3d220_cases(d, ctx, q, poison_buf, up_buf, up_ptr, rb_buf, rb_ptr, "copy_scratch") == 0);
383 }
384
385 EXPECT(d.validation_errors() == 0);
386 std::printf("vk_bc_zero_init_test: ok\n");
387 return 0;
388}
diff --git a/runtime/test/vk_bindless_test.cpp b/runtime/test/vk_bindless_test.cpp
index 73ac39013..419a1dda4 100644
--- a/runtime/test/vk_bindless_test.cpp
+++ b/runtime/test/vk_bindless_test.cpp
@@ -24,6 +24,7 @@
24#include "vk_shader_fma.h" 24#include "vk_shader_fma.h"
25#include "../src/vulkan_bindless.h" 25#include "../src/vulkan_bindless.h"
26 26
27#include <algorithm>
27#include <array> 28#include <array>
28#include <cmath> 29#include <cmath>
29#include <cstdio> 30#include <cstdio>
@@ -105,7 +106,7 @@ std::uint32_t probe_depth(std::span<const std::uint32_t> table, const Descriptor
105 106
106int main(int argc, char** argv) { 107int main(int argc, char** argv) {
107 if (argc < 3) { 108 if (argc < 3) {
108 std::fprintf(stderr, "usage: vk_bindless_test <vs_ids.spv> <ps_tex.spv>\n"); 109 std::fprintf(stderr, "usage: vk_bindless_test <vs_ids.spv> <ps_tex.spv | ps_imgatomic.spv>\n");
109 return 2; 110 return 2;
110 } 111 }
111 // A bad readback in a single channel must still fail when all three others match. 112 // A bad readback in a single channel must still fail when all three others match.
@@ -225,6 +226,15 @@ int main(int argc, char** argv) {
225 VkPhysicalDeviceFeatures2 enable{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, &enable12}; 226 VkPhysicalDeviceFeatures2 enable{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, &enable12};
226 enable.features.shaderInt64 = VK_TRUE; 227 enable.features.shaderInt64 = VK_TRUE;
227 enable.features.shaderSampledImageArrayDynamicIndexing = VK_TRUE; 228 enable.features.shaderSampledImageArrayDynamicIndexing = VK_TRUE;
229 // ps_imgatomic: image atomics in a pixel shader need fragment stores and atomics.
230 const bool atomic_mode = std::strstr(argv[2], "imgatomic") != nullptr;
231 if (atomic_mode) {
232 if (!have.features.fragmentStoresAndAtomics) {
233 std::printf("unsupported: fragmentStoresAndAtomics (image atomics in a pixel shader)\n");
234 return unsupported;
235 }
236 enable.features.fragmentStoresAndAtomics = VK_TRUE;
237 }
228 238
229 std::uint32_t qn = 0; 239 std::uint32_t qn = 0;
230 vkGetPhysicalDeviceQueueFamilyProperties(pd, &qn, nullptr); 240 vkGetPhysicalDeviceQueueFamilyProperties(pd, &qn, nullptr);
@@ -260,7 +270,7 @@ int main(int argc, char** argv) {
260 LD(vkDeviceWaitIdle); LD(vkDestroyPipeline); LD(vkDestroyPipelineLayout); 270 LD(vkDeviceWaitIdle); LD(vkDestroyPipeline); LD(vkDestroyPipelineLayout);
261 LD(vkDestroyCommandPool); LD(vkDestroyShaderModule); LD(vkDestroyFramebuffer); LD(vkDestroyRenderPass); 271 LD(vkDestroyCommandPool); LD(vkDestroyShaderModule); LD(vkDestroyFramebuffer); LD(vkDestroyRenderPass);
262 LD(vkDestroySampler); LD(vkDestroyImageView); LD(vkDestroyImage); LD(vkDestroyBuffer); 272 LD(vkDestroySampler); LD(vkDestroyImageView); LD(vkDestroyImage); LD(vkDestroyBuffer);
263 LD(vkFreeMemory); LD(vkDestroyDevice); 273 LD(vkFreeMemory); LD(vkDestroyDevice); LD(vkCmdClearColorImage);
264 VkQueue queue = VK_NULL_HANDLE; 274 VkQueue queue = VK_NULL_HANDLE;
265 vkGetDeviceQueue(dev, qi, 0, &queue); 275 vkGetDeviceQueue(dev, qi, 0, &queue);
266 VkPhysicalDeviceMemoryProperties mp; 276 VkPhysicalDeviceMemoryProperties mp;
@@ -663,6 +673,171 @@ int main(int argc, char** argv) {
663 const std::uint32_t sampler_index = set.add_sampler(nearest); 673 const std::uint32_t sampler_index = set.add_sampler(nearest);
664 EXPECT(decoy_sampler == 1 && sampler_index == 2); 674 EXPECT(decoy_sampler == 1 && sampler_index == 2);
665 675
676 if (atomic_mode) {
677 // ps_imgatomic.asm: image_atomic_umax/umin/or on three 8x8 r32ui images and umax on a 4x4x4 one, from
678 // every pixel of the 64x64 draw (64 pixels per 2D texel), each found through its own T# key. Odd
679 // pixels are discarded after their atomics, which still count.
680 constexpr std::uint32_t atomic_va = 1024, AW = 8, A3 = 4;
681 const std::array<DescriptorKey, 4> keys{{{0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, 0xa8},
682 {0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, 0xb8},
683 {0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, 0xc8},
684 {0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8}}};
685 for (std::uint32_t k = 0; k < 4; ++k)
686 std::memcpy(static_cast<char*>(heap_map) + atomic_va + 32 * k, keys[k].data(), 32);
687 const VkImageUsageFlags atomic_usage =
688 VK_IMAGE_USAGE_STORAGE_BIT | VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT |
689 VK_IMAGE_USAGE_TRANSFER_DST_BIT;
690 VkImage images[4];
691 VkImageView views[4];
692 for (int k = 0; k < 3; ++k) CHECK(make_image(VK_FORMAT_R32_UINT, AW, AW, atomic_usage, &images[k], &views[k]));
693 { // the 3D image
694 VkImageCreateInfo ii{VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO};
695 ii.imageType = VK_IMAGE_TYPE_3D;
696 ii.format = VK_FORMAT_R32_UINT;
697 ii.extent = {A3, A3, A3};
698 ii.mipLevels = 1;
699 ii.arrayLayers = 1;
700 ii.samples = VK_SAMPLE_COUNT_1_BIT;
701 ii.usage = atomic_usage;
702 CHECK(vkCreateImage(dev, &ii, nullptr, &images[3]));
703 VkMemoryRequirements mr;
704 vkGetImageMemoryRequirements(dev, images[3], &mr);
705 VkMemoryAllocateInfo ai{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO};
706 ai.allocationSize = mr.size;
707 ai.memoryTypeIndex = memtype(mr.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT);
708 VkDeviceMemory m;
709 CHECK(vkAllocateMemory(dev, &ai, nullptr, &m));
710 allocations.push_back(m);
711 CHECK(vkBindImageMemory(dev, images[3], m, 0));
712 VkImageViewCreateInfo vi{VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO};
713 vi.image = images[3];
714 vi.viewType = VK_IMAGE_VIEW_TYPE_3D;
715 vi.format = VK_FORMAT_R32_UINT;
716 vi.subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1};
717 CHECK(vkCreateImageView(dev, &vi, nullptr, &views[3]));
718 }
719 std::uint32_t indices[4];
720 for (int k = 0; k < 4; ++k) {
721 StorageViews storage;
722 storage.as_uint = views[k];
723 storage.r32ui = views[k];
724 indices[k] = set.add_image(k == 3 ? ImageDimension::dim_3d : ImageDimension::dim_2d, views[k],
725 VK_IMAGE_LAYOUT_GENERAL, storage);
726 EXPECT(indices[k] != 0);
727 EXPECT(set.insert_key(keys[k], indices[k]));
728 }
729 EXPECT(flush());
730
731 // Clear: umax and or start at 0, umin at all ones; then GENERAL for the shader's atomics.
732 CHECK(vkResetCommandBuffer(cmd, 0));
733 CHECK(vkBeginCommandBuffer(cmd, &begin));
734 if (!set.fallbacks_ready()) set.record_fallback_init(cmd);
735 for (int k = 0; k < 4; ++k) {
736 VkImageMemoryBarrier b{VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER};
737 b.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
738 b.oldLayout = VK_IMAGE_LAYOUT_UNDEFINED;
739 b.newLayout = VK_IMAGE_LAYOUT_GENERAL;
740 b.srcQueueFamilyIndex = b.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
741 b.image = images[k];
742 b.subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1};
743 vkCmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0,
744 nullptr, 0, nullptr, 1, &b);
745 VkClearColorValue value{};
746 for (auto& c : value.uint32) c = k == 1 ? 0xFFFFFFFFu : 0u;
747 vkCmdClearColorImage(cmd, images[k], VK_IMAGE_LAYOUT_GENERAL, &value, 1, &b.subresourceRange);
748 b.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
749 b.dstAccessMask = VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT;
750 b.oldLayout = b.newLayout = VK_IMAGE_LAYOUT_GENERAL;
751 vkCmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, 0, 0,
752 nullptr, 0, nullptr, 1, &b);
753 }
754 CHECK(submit());
755
756 // The draw, then the images and the render target read back.
757 const VkDeviceSize image_bytes = 3 * AW * AW * 4 + A3 * A3 * A3 * 4;
758 VkBuffer atomic_readback;
759 void* atomic_map;
760 CHECK(make_buffer(image_bytes, VK_BUFFER_USAGE_TRANSFER_DST_BIT, &atomic_readback, &atomic_map));
761 CHECK(vkResetCommandBuffer(cmd, 0));
762 CHECK(vkBeginCommandBuffer(cmd, &begin));
763 VkClearValue clear{};
764 for (float& channel : clear.color.float32) channel = 0.25f;
765 VkRenderPassBeginInfo rbi{VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO};
766 rbi.renderPass = pass;
767 rbi.framebuffer = framebuffer;
768 rbi.renderArea = scissor;
769 rbi.clearValueCount = 1;
770 rbi.pClearValues = &clear;
771 vkCmdBeginRenderPass(cmd, &rbi, VK_SUBPASS_CONTENTS_INLINE);
772 vkCmdBindPipeline(cmd, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline);
773 const VkDescriptorSet bound = set.set();
774 vkCmdBindDescriptorSets(cmd, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline_layout, 0, 1, &bound, 0, nullptr);
775 std::uint32_t block[36] = {};
776 block[2] = atomic_va;
777 block[32] = std::uint32_t(heap_base);
778 block[33] = std::uint32_t(heap_base >> 32);
779 vkCmdPushConstants(cmd, pipeline_layout, VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_FRAGMENT_BIT, 0,
780 sizeof(block), block);
781 vkCmdDraw(cmd, 3, 1, 0, 0);
782 vkCmdEndRenderPass(cmd);
783 VkMemoryBarrier after{VK_STRUCTURE_TYPE_MEMORY_BARRIER};
784 after.srcAccessMask = VK_ACCESS_SHADER_WRITE_BIT;
785 after.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT;
786 vkCmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 1, &after,
787 0, nullptr, 0, nullptr);
788 VkDeviceSize offset = 0;
789 for (int k = 0; k < 4; ++k) {
790 VkBufferImageCopy rc{};
791 rc.bufferOffset = offset;
792 rc.imageSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1};
793 rc.imageExtent = k == 3 ? VkExtent3D{A3, A3, A3} : VkExtent3D{AW, AW, 1};
794 vkCmdCopyImageToBuffer(cmd, images[k], VK_IMAGE_LAYOUT_GENERAL, atomic_readback, 1, &rc);
795 offset += k == 3 ? A3 * A3 * A3 * 4 : AW * AW * 4;
796 }
797 VkBufferImageCopy tc{};
798 tc.imageSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1};
799 tc.imageExtent = {W, H, 1};
800 vkCmdCopyImageToBuffer(cmd, target, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, readback, 1, &tc);
801 CHECK(submit());
802
803 // The model: every pixel's atomics, discarded or not.
804 std::vector<std::uint32_t> want(3 * AW * AW + A3 * A3 * A3, 0);
805 for (std::uint32_t t = 0; t < AW * AW; ++t) want[AW * AW + t] = 0xFFFFFFFFu;
806 for (std::uint32_t py = 0; py < H; ++py)
807 for (std::uint32_t px = 0; px < W; ++px) {
808 const std::uint32_t id = px + 64 * py, t = (py >> 3) * AW + (px >> 3);
809 want[t] = std::max(want[t], id);
810 want[AW * AW + t] = std::min(want[AW * AW + t], id);
811 want[2 * AW * AW + t] |= 1u << (id & 31);
812 const std::uint32_t v = ((px & 3) * A3 + (py >> 4)) * A3 + (px >> 4);
813 want[3 * AW * AW + v] = std::max(want[3 * AW * AW + v], id);
814 }
815 const auto* got = static_cast<const std::uint32_t*>(atomic_map);
816 const char* names[] = {"2D umax", "2D umin", "2D or", "3D umax"};
817 unsigned wrong = 0;
818 for (std::size_t i = 0; i < want.size(); ++i) {
819 if (got[i] == want[i]) continue;
820 const int k = i < 3 * AW * AW ? int(i / (AW * AW)) : 3;
821 if (wrong++ < 8)
822 std::printf(" %s texel %zu: got 0x%08x, want 0x%08x\n", names[k],
823 k == 3 ? i - 3 * AW * AW : i % (AW * AW), got[i], want[i]);
824 }
825 const float* rt = static_cast<const float*>(readback_map);
826 unsigned bad_rt = 0;
827 for (std::uint32_t py = 0; py < H; ++py)
828 for (std::uint32_t px = 0; px < W; ++px)
829 bad_rt += rt[(py * W + px) * 4] != ((px & 1) ? 0.25f : 1.0f);
830 std::printf("ps_imgatomic: %u of %zu texels wrong (2D umax/umin/or 8x8 each, 3D umax 4x4x4); "
831 "%u of %u render-target pixels wrong (odd columns discarded)\n",
832 wrong, want.size(), bad_rt, W * H);
833 vkDeviceWaitIdle(dev);
834 if (g_validation_errors) {
835 std::printf("ps_imgatomic: %u validation errors\n", g_validation_errors);
836 return 1;
837 }
838 return wrong || bad_rt ? 1 : 0;
839 }
840
666 // A view that comes and goes before the set is flushed is never written: a texture created and destroyed 841 // A view that comes and goes before the set is flushed is never written: a texture created and destroyed
667 // between two submissions. Its slots are written once, with the fallback; a write of the destroyed view 842 // between two submissions. Its slots are written once, with the fallback; a write of the destroyed view
668 // would be a validation error. 843 // would be a validation error.
diff --git a/runtime/test/vk_pipeline_check.cpp b/runtime/test/vk_pipeline_check.cpp
index bdefac894..a8fe0eaeb 100644
--- a/runtime/test/vk_pipeline_check.cpp
+++ b/runtime/test/vk_pipeline_check.cpp
@@ -32,6 +32,7 @@
32#include <cctype> 32#include <cctype>
33#include <charconv> 33#include <charconv>
34#include <chrono> 34#include <chrono>
35#include <cmath>
35#include <condition_variable> 36#include <condition_variable>
36#include <cstdio> 37#include <cstdio>
37#include <cstring> 38#include <cstring>
@@ -395,27 +396,36 @@ int main(int argc, char** argv) {
395 bool cache_feedback = false; 396 bool cache_feedback = false;
396 for (int i = 2; i < argc; i++) { 397 for (int i = 2; i < argc; i++) {
397 std::string a = argv[i]; 398 std::string a = argv[i];
398 auto val = [&] { return i + 1 < argc ? std::string(argv[++i]) : std::string("0"); }; 399 auto value = [&]() -> std::string_view {
399 if (a == "--jobs") jobs = std::max(1u, uint32_t(std::stoul(val()))); 400 if (i + 1 == argc || std::string_view(argv[i + 1]).starts_with("--")) return {};
400 else if (a == "--start") start = std::stoull(val()); 401 return argv[++i];
401 else if (a == "--count") count = std::stoull(val()); 402 };
402 else if (a == "--slow") slow = std::stod(val()); 403 auto number = [&](auto& dest) {
403 else if (a == "--stage") stage_filter = val(); 404 const auto text = value();
405 if (text.empty()) return false;
406 const auto end = text.data() + text.size();
407 const auto [ptr, ec] = std::from_chars(text.data(), end, dest);
408 return ec == std::errc{} && ptr == end;
409 };
410 bool valid = true;
411 if (a == "--jobs") {
412 valid = number(jobs);
413 jobs = std::max(1u, jobs);
414 } else if (a == "--start") valid = number(start);
415 else if (a == "--count") valid = number(count);
416 else if (a == "--slow") valid = number(slow) && std::isfinite(slow) && slow >= 0.0;
417 else if (a == "--stage") valid = !(stage_filter = value()).empty();
404 else if (a == "--compute-only") stage_filter = "cs"; 418 else if (a == "--compute-only") stage_filter = "cs";
405 else if (a == "--graphics-only") stage_filter = "graphics"; 419 else if (a == "--graphics-only") stage_filter = "graphics";
406 else if (a == "--max-bytes") max_bytes = std::stoull(val()); 420 else if (a == "--max-bytes") valid = number(max_bytes);
407 else if (a == "--large-module-bytes") { 421 else if (a == "--large-module-bytes") valid = number(large_module_bytes);
408 const std::string_view value = i + 1 < argc ? argv[++i] : ""; 422 else if (a == "--stats") valid = !(stats_path = value()).empty();
409 const auto end = value.data() + value.size();
410 const auto [ptr, ec] = std::from_chars(value.data(), end, large_module_bytes);
411 if (ec != std::errc{} || ptr != end) {
412 std::fprintf(stderr, "--large-module-bytes requires a non-negative byte count\n");
413 return 2;
414 }
415 }
416 else if (a == "--stats") stats_path = val();
417 else if (a == "--cache-feedback") cache_feedback = true; 423 else if (a == "--cache-feedback") cache_feedback = true;
418 else cache_path = a; 424 else cache_path = a;
425 if (!valid) {
426 std::fprintf(stderr, "%s requires a valid value\n", a.c_str());
427 return 2;
428 }
419 } 429 }
420 if (stage_filter != "all" && stage_filter != "cs" && stage_filter != "graphics") { 430 if (stage_filter != "all" && stage_filter != "cs" && stage_filter != "graphics") {
421 std::fprintf(stderr, "unknown --stage '%s' (expected: all, cs, graphics)\n", stage_filter.c_str()); 431 std::fprintf(stderr, "unknown --stage '%s' (expected: all, cs, graphics)\n", stage_filter.c_str());
diff --git a/runtime/test/vk_presenter_sync_test.cpp b/runtime/test/vk_presenter_sync_test.cpp
index 3748aeec7..46a2531ef 100644
--- a/runtime/test/vk_presenter_sync_test.cpp
+++ b/runtime/test/vk_presenter_sync_test.cpp
@@ -19,10 +19,12 @@
19#include "../src/vulkan_present.h" 19#include "../src/vulkan_present.h"
20 20
21#include <atomic> 21#include <atomic>
22#include <chrono>
22#include <cmath> 23#include <cmath>
23#include <cstdint> 24#include <cstdint>
24#include <cstdio> 25#include <cstdio>
25#include <cstdlib> 26#include <cstdlib>
27#include <functional>
26#include <string_view> 28#include <string_view>
27#include <thread> 29#include <thread>
28#include <vector> 30#include <vector>
@@ -49,10 +51,12 @@ namespace driver {
49PFN_vkGetInstanceProcAddr real_get_instance = nullptr; 51PFN_vkGetInstanceProcAddr real_get_instance = nullptr;
50PFN_vkGetDeviceProcAddr real_get_device = nullptr; 52PFN_vkGetDeviceProcAddr real_get_device = nullptr;
51PFN_vkQueueSubmit real_submit = nullptr; 53PFN_vkQueueSubmit real_submit = nullptr;
54PFN_vkQueuePresentKHR real_present = nullptr;
52PFN_vkCmdPipelineBarrier real_barrier = nullptr; 55PFN_vkCmdPipelineBarrier real_barrier = nullptr;
53PFN_vkCmdCopyImageToBuffer real_copy_i2b = nullptr; 56PFN_vkCmdCopyImageToBuffer real_copy_i2b = nullptr;
54 57
55std::atomic<VkResult> fail_next_submit{VK_SUCCESS}; 58std::atomic<VkResult> fail_next_submit{VK_SUCCESS};
59std::function<void()> on_next_present;
56std::atomic<bool> observe_capture{false}; 60std::atomic<bool> observe_capture{false};
57std::atomic<bool> saw_capture_waw{false}; 61std::atomic<bool> saw_capture_waw{false};
58std::atomic<std::uint32_t> capture_copies{0}; 62std::atomic<std::uint32_t> capture_copies{0};
@@ -65,6 +69,15 @@ VKAPI_ATTR VkResult VKAPI_CALL queue_submit(VkQueue queue, std::uint32_t count,
65 return real_submit(queue, count, submits, fence); 69 return real_submit(queue, count, submits, fence);
66} 70}
67 71
72VKAPI_ATTR VkResult VKAPI_CALL queue_present(VkQueue queue, const VkPresentInfoKHR* info) {
73 if (on_next_present) {
74 auto cb = std::move(on_next_present);
75 on_next_present = {};
76 cb();
77 }
78 return real_present(queue, info);
79}
80
68VKAPI_ATTR void VKAPI_CALL cmd_pipeline_barrier(VkCommandBuffer cb, VkPipelineStageFlags src_stage, 81VKAPI_ATTR void VKAPI_CALL cmd_pipeline_barrier(VkCommandBuffer cb, VkPipelineStageFlags src_stage,
69 VkPipelineStageFlags dst_stage, VkDependencyFlags flags, 82 VkPipelineStageFlags dst_stage, VkDependencyFlags flags,
70 std::uint32_t mem_count, const VkMemoryBarrier* mem, 83 std::uint32_t mem_count, const VkMemoryBarrier* mem,
@@ -100,6 +113,7 @@ VKAPI_ATTR void VKAPI_CALL cmd_copy_image_to_buffer(VkCommandBuffer cb, VkImage
100VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL get_device(VkDevice device, const char* name) { 113VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL get_device(VkDevice device, const char* name) {
101 const std::string_view n = name; 114 const std::string_view n = name;
102 if (n == "vkQueueSubmit") return reinterpret_cast<PFN_vkVoidFunction>(queue_submit); 115 if (n == "vkQueueSubmit") return reinterpret_cast<PFN_vkVoidFunction>(queue_submit);
116 if (n == "vkQueuePresentKHR") return reinterpret_cast<PFN_vkVoidFunction>(queue_present);
103 if (n == "vkCmdPipelineBarrier") return reinterpret_cast<PFN_vkVoidFunction>(cmd_pipeline_barrier); 117 if (n == "vkCmdPipelineBarrier") return reinterpret_cast<PFN_vkVoidFunction>(cmd_pipeline_barrier);
104 if (n == "vkCmdCopyImageToBuffer") return reinterpret_cast<PFN_vkVoidFunction>(cmd_copy_image_to_buffer); 118 if (n == "vkCmdCopyImageToBuffer") return reinterpret_cast<PFN_vkVoidFunction>(cmd_copy_image_to_buffer);
105 return real_get_device(device, name); 119 return real_get_device(device, name);
@@ -114,6 +128,7 @@ void install(PFN_vkGetInstanceProcAddr instance_proc, VkInstance instance, VkDev
114 real_get_instance = instance_proc; 128 real_get_instance = instance_proc;
115 real_get_device = reinterpret_cast<PFN_vkGetDeviceProcAddr>(instance_proc(instance, "vkGetDeviceProcAddr")); 129 real_get_device = reinterpret_cast<PFN_vkGetDeviceProcAddr>(instance_proc(instance, "vkGetDeviceProcAddr"));
116 real_submit = reinterpret_cast<PFN_vkQueueSubmit>(real_get_device(device, "vkQueueSubmit")); 130 real_submit = reinterpret_cast<PFN_vkQueueSubmit>(real_get_device(device, "vkQueueSubmit"));
131 real_present = reinterpret_cast<PFN_vkQueuePresentKHR>(real_get_device(device, "vkQueuePresentKHR"));
117 real_barrier = reinterpret_cast<PFN_vkCmdPipelineBarrier>(real_get_device(device, "vkCmdPipelineBarrier")); 132 real_barrier = reinterpret_cast<PFN_vkCmdPipelineBarrier>(real_get_device(device, "vkCmdPipelineBarrier"));
118 real_copy_i2b = reinterpret_cast<PFN_vkCmdCopyImageToBuffer>(real_get_device(device, "vkCmdCopyImageToBuffer")); 133 real_copy_i2b = reinterpret_cast<PFN_vkCmdCopyImageToBuffer>(real_get_device(device, "vkCmdCopyImageToBuffer"));
119} 134}
@@ -193,15 +208,36 @@ int main() {
193 EXPECT(presenter.ok()); 208 EXPECT(presenter.ok());
194 EXPECT(presenter.enable_capture()); 209 EXPECT(presenter.enable_capture());
195 210
196 // 1. Failed vkQueueSubmit must NOT commit the UNDEFINED -> GENERAL transition in LayoutTracker. 211 // 1. Failed vkQueueSubmit must NOT commit the UNDEFINED -> GENERAL transition in LayoutTracker (O(1) rollback
212 // even with many live tracked textures), and tracker_mutex_ must be released before vkQueuePresentKHR.
213 for (ResourceId extra = 1000; extra < 1512; ++extra)
214 context.add_resource(extra, side_rb, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL);
197 EXPECT(context.layout(1, 0) == VK_IMAGE_LAYOUT_UNDEFINED); 215 EXPECT(context.layout(1, 0) == VK_IMAGE_LAYOUT_UNDEFINED);
198 driver::fail_next_submit.store(VK_ERROR_OUT_OF_HOST_MEMORY); 216 driver::fail_next_submit.store(VK_ERROR_OUT_OF_HOST_MEMORY);
199 EXPECT(presenter.present(1, true) == VK_ERROR_OUT_OF_HOST_MEMORY); 217 EXPECT(presenter.present(1, true) == VK_ERROR_OUT_OF_HOST_MEMORY);
200 EXPECT(context.layout(1, 0) == VK_IMAGE_LAYOUT_UNDEFINED); 218 EXPECT(context.layout(1, 0) == VK_IMAGE_LAYOUT_UNDEFINED);
201 219 EXPECT(context.layout(1000, 0) == VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL);
202 // Next present succeeds, runs the deferred zero-fill, and commits GENERAL. 220
221 // Next present succeeds, runs the deferred zero-fill, commits GENERAL, and unlocks tracker_mutex_ before
222 // vkQueuePresentKHR so other threads' emit() / layout() calls are not blocked by presentation.
223 std::atomic<bool> read_done{false};
224 VkImageLayout seen_during_present = VK_IMAGE_LAYOUT_UNDEFINED;
225 bool unblocked_during_present = false;
226 std::thread reader;
227 driver::on_next_present = [&] {
228 reader = std::thread([&] {
229 seen_during_present = context.layout(1, 0);
230 read_done.store(true, std::memory_order_release);
231 });
232 std::this_thread::sleep_for(std::chrono::milliseconds(30));
233 unblocked_during_present = read_done.load(std::memory_order_acquire);
234 };
203 EXPECT(presenter.present(1, true) == VK_SUCCESS); 235 EXPECT(presenter.present(1, true) == VK_SUCCESS);
236 if (reader.joinable()) reader.join();
237 EXPECT(unblocked_during_present);
238 EXPECT(seen_during_present == VK_IMAGE_LAYOUT_GENERAL);
204 EXPECT(context.layout(1, 0) == VK_IMAGE_LAYOUT_GENERAL); 239 EXPECT(context.layout(1, 0) == VK_IMAGE_LAYOUT_GENERAL);
240 for (ResourceId extra = 1000; extra < 1512; ++extra) context.remove_resource(extra);
205 std::vector<std::uint8_t> pixels; 241 std::vector<std::uint8_t> pixels;
206 VkExtent2D ext{}; 242 VkExtent2D ext{};
207 VkFormat fmt = VK_FORMAT_UNDEFINED; 243 VkFormat fmt = VK_FORMAT_UNDEFINED;
diff --git a/runtime/test/vk_queue_query_sync_test.cpp b/runtime/test/vk_queue_query_sync_test.cpp
new file mode 100644
index 000000000..a9daf6477
--- /dev/null
+++ b/runtime/test/vk_queue_query_sync_test.cpp
@@ -0,0 +1,351 @@
1// VulkanQueue / VulkanContext query-state synchronization and failed-submit wait preservation regressions
2// (runtime/src/vulkan_backend.h):
3// 1. VulkanContext::remove_query_pool() must serialize with tracker_mutex_ so an in-flight VulkanQueue::execute()
4// that already unlocked resource_mutex_ cannot suffer a use-after-free in QueryReplay::commit().
5// 2. VulkanQueue::execute() must acquire tracker_mutex_ before QueryReplay::plan() so concurrent queues see
6// submission-order query state (no data race on QueryPool::ended / QueryPool::occlusion and no stale zero-fill).
7// 3. A transient vkQueueSubmit failure must preserve pending VulkanQueue::wait() timeline semaphores for the retry.
8// 4. Concurrent multi-queue query End/Resolve + add/remove_query_pool stress with zero Vulkan validation errors.
9// Skips with exit code 77 when no Vulkan 1.3 device is available. No game data.
10#include "vk_test_device.h"
11#include "../src/vulkan_backend.h"
12
13#include <atomic>
14#include <chrono>
15#include <cstdint>
16#include <cstdio>
17#include <cstring>
18#include <functional>
19#include <string_view>
20#include <thread>
21#include <vector>
22
23#define EXPECT(condition) do { \
24 if (!(condition)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); return 1; } \
25} while (0)
26
27namespace {
28
29namespace driver {
30PFN_vkGetDeviceProcAddr real_get_device = nullptr;
31PFN_vkQueueSubmit real_submit = nullptr;
32PFN_vkCmdCopyQueryPoolResults real_copy_queries = nullptr;
33PFN_vkCmdFillBuffer real_fill_buffer = nullptr;
34
35std::atomic<VkResult> fail_next_submit{VK_SUCCESS};
36std::atomic<bool> capture_next_waits{false};
37std::atomic<std::uint32_t> captured_wait_count{0};
38std::atomic<std::uintptr_t> captured_wait_sem{0};
39std::atomic<std::uint64_t> captured_wait_val{0};
40
41std::atomic<bool> count_resolves{false};
42std::atomic<std::uint32_t> copy_query_calls{0};
43std::atomic<std::uint32_t> fill_buffer_calls{0};
44
45// Optional one-shot callback invoked inside vkQueueSubmit right before calling the real driver.
46// Returning non-VK_SUCCESS short-circuits the submit with that status.
47std::function<VkResult()> on_next_submit;
48
49VKAPI_ATTR VkResult VKAPI_CALL queue_submit(VkQueue queue, std::uint32_t count, const VkSubmitInfo* submits,
50 VkFence fence) {
51 if (on_next_submit) {
52 auto cb = std::move(on_next_submit);
53 on_next_submit = {};
54 const VkResult override_res = cb();
55 if (override_res != VK_SUCCESS) return override_res;
56 }
57 const VkResult armed = fail_next_submit.exchange(VK_SUCCESS);
58 if (armed != VK_SUCCESS) return armed;
59 if (capture_next_waits.exchange(false) && count > 0 && submits) {
60 captured_wait_count.store(submits[0].waitSemaphoreCount);
61 if (submits[0].waitSemaphoreCount > 0 && submits[0].pWaitSemaphores) {
62 captured_wait_sem.store(reinterpret_cast<std::uintptr_t>(submits[0].pWaitSemaphores[0]));
63 const auto* timeline = reinterpret_cast<const VkTimelineSemaphoreSubmitInfo*>(submits[0].pNext);
64 if (timeline && timeline->sType == VK_STRUCTURE_TYPE_TIMELINE_SEMAPHORE_SUBMIT_INFO &&
65 timeline->waitSemaphoreValueCount > 0 && timeline->pWaitSemaphoreValues) {
66 captured_wait_val.store(timeline->pWaitSemaphoreValues[0]);
67 }
68 }
69 }
70 return real_submit(queue, count, submits, fence);
71}
72
73VKAPI_ATTR void VKAPI_CALL cmd_copy_query_pool_results(VkCommandBuffer cb, VkQueryPool pool, std::uint32_t first,
74 std::uint32_t count, VkBuffer dst, VkDeviceSize offset,
75 VkDeviceSize stride, VkQueryResultFlags flags) {
76 if (count_resolves.load(std::memory_order_relaxed)) copy_query_calls.fetch_add(1, std::memory_order_relaxed);
77 real_copy_queries(cb, pool, first, count, dst, offset, stride, flags);
78}
79
80VKAPI_ATTR void VKAPI_CALL cmd_fill_buffer(VkCommandBuffer cb, VkBuffer dst, VkDeviceSize offset, VkDeviceSize size,
81 std::uint32_t data) {
82 if (count_resolves.load(std::memory_order_relaxed)) fill_buffer_calls.fetch_add(1, std::memory_order_relaxed);
83 real_fill_buffer(cb, dst, offset, size, data);
84}
85
86VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL get_device(VkDevice device, const char* name) {
87 const std::string_view n = name;
88 if (n == "vkQueueSubmit") return reinterpret_cast<PFN_vkVoidFunction>(queue_submit);
89 if (n == "vkCmdCopyQueryPoolResults") return reinterpret_cast<PFN_vkVoidFunction>(cmd_copy_query_pool_results);
90 if (n == "vkCmdFillBuffer") return reinterpret_cast<PFN_vkVoidFunction>(cmd_fill_buffer);
91 return real_get_device(device, name);
92}
93
94void install(PFN_vkGetDeviceProcAddr device_proc, VkDevice device) {
95 real_get_device = device_proc;
96 real_submit = reinterpret_cast<PFN_vkQueueSubmit>(device_proc(device, "vkQueueSubmit"));
97 real_copy_queries =
98 reinterpret_cast<PFN_vkCmdCopyQueryPoolResults>(device_proc(device, "vkCmdCopyQueryPoolResults"));
99 real_fill_buffer = reinterpret_cast<PFN_vkCmdFillBuffer>(device_proc(device, "vkCmdFillBuffer"));
100}
101} // namespace driver
102
103} // namespace
104
105int main() {
106 using namespace leonida;
107
108 vktest::Device d;
109 if (!d.create(false)) {
110 std::fprintf(stderr, "vk_queue_query_sync_test: no Vulkan 1.3 device, skipped\n");
111 return 77;
112 }
113 driver::install(d.device_proc, d.device);
114
115 const auto create_query_pool = d.fn<PFN_vkCreateQueryPool>("vkCreateQueryPool");
116 const auto destroy_query_pool = d.fn<PFN_vkDestroyQueryPool>("vkDestroyQueryPool");
117 EXPECT(create_query_pool && destroy_query_pool);
118
119 auto make_occlusion_pool = [&](std::uint32_t count) -> VkQueryPool {
120 VkQueryPoolCreateInfo info{VK_STRUCTURE_TYPE_QUERY_POOL_CREATE_INFO};
121 info.queryType = VK_QUERY_TYPE_OCCLUSION;
122 info.queryCount = count;
123 VkQueryPool pool = VK_NULL_HANDLE;
124 if (create_query_pool(d.device, &info, nullptr, &pool) != VK_SUCCESS) return VK_NULL_HANDLE;
125 return pool;
126 };
127
128 const VkQueryPool pool_uaf = make_occlusion_pool(2);
129 const VkQueryPool pool_race = make_occlusion_pool(2);
130 const VkQueryPool pool_stress = make_occlusion_pool(32);
131 EXPECT(pool_uaf && pool_race && pool_stress);
132
133 {
134 VulkanContext context(driver::get_device, d.device, true);
135 EXPECT(context.loaded());
136 VulkanQueue queue_a(context, d.queue, d.family);
137 VulkanQueue queue_b(context, d.queue, d.family);
138 EXPECT(queue_a.ok() && queue_b.ok());
139
140 void* src_ptr = nullptr;
141 void* dst_ptr = nullptr;
142 void* res_ptr = nullptr;
143 const VkBuffer src_buf = d.buffer(64, VK_BUFFER_USAGE_TRANSFER_SRC_BIT, &src_ptr);
144 const VkBuffer dst_buf = d.buffer(64, VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_TRANSFER_SRC_BIT, &dst_ptr);
145 const VkBuffer res_buf = d.buffer(64, VK_BUFFER_USAGE_TRANSFER_DST_BIT, &res_ptr);
146 EXPECT(src_buf && dst_buf && res_buf);
147
148 ResourceBinding src_rb{};
149 src_rb.buffer = src_buf;
150 src_rb.size = 64;
151 ResourceBinding dst_rb{};
152 dst_rb.buffer = dst_buf;
153 dst_rb.size = 64;
154 dst_rb.host_readable = true;
155 ResourceBinding res_rb{};
156 res_rb.buffer = res_buf;
157 res_rb.size = 64;
158 res_rb.host_readable = true;
159 context.add_resource(1, src_rb);
160 context.add_resource(2, dst_rb);
161 context.add_resource(3, res_rb);
162
163 // 1. remove_query_pool() must block on tracker_mutex_ while execute() is between resource_lock.unlock() and
164 // QueryReplay::commit(), preventing a use-after-free on the QueryPool* stored in QueryReplay::pending_.
165 {
166 constexpr QueryHeapId heap_id = 77;
167 QueryPool qp{};
168 qp.pool = pool_uaf;
169 qp.heap_type = d3d12_query_heap::occlusion;
170 qp.count = 2;
171 qp.ended.assign(2, false);
172 context.add_query_pool(heap_id, qp);
173
174 CommandList list;
175 EXPECT(list.begin_query({heap_id, d3d12_query::occlusion, 0}));
176 EXPECT(list.end_query({heap_id, d3d12_query::occlusion, 0}));
177 EXPECT(list.close());
178 const CommandList* ptr = &list;
179
180 std::atomic<bool> removed{false};
181 bool removed_during_submit = false;
182 std::thread remover;
183 driver::on_next_submit = [&]() -> VkResult {
184 remover = std::thread([&] {
185 context.remove_query_pool(heap_id);
186 removed.store(true, std::memory_order_release);
187 });
188 std::this_thread::sleep_for(std::chrono::milliseconds(30));
189 removed_during_submit = removed.load(std::memory_order_acquire);
190 // If remove_query_pool already erased the node, abort the submit so queries.commit() does not
191 // corrupt the heap before the EXPECT below reports the failure cleanly.
192 return removed_during_submit ? VK_ERROR_OUT_OF_HOST_MEMORY : VK_SUCCESS;
193 };
194 const ReplayResult exec_res = queue_a.execute({&ptr, 1});
195 if (remover.joinable()) remover.join();
196 EXPECT(!removed_during_submit);
197 EXPECT(exec_res == ReplayResult::success);
198 EXPECT(removed.load(std::memory_order_acquire));
199 EXPECT(context.query_heap_type(heap_id) == ~0u);
200 EXPECT(queue_a.idle());
201 std::printf("queue/query sync: remove_query_pool serialized with QueryReplay::commit ok\n");
202 }
203
204 // 2. Concurrent queue_b.execute(ResolveQueries) must not run QueryReplay::plan() before queue_a commits
205 // EndQuery; otherwise queue_b sees ended[0] == false and emits vkCmdFillBuffer(0) instead of copying.
206 {
207 constexpr QueryHeapId heap_id = 88;
208 QueryPool qp{};
209 qp.pool = pool_race;
210 qp.heap_type = d3d12_query_heap::occlusion;
211 qp.count = 2;
212 qp.ended.assign(2, false);
213 context.add_query_pool(heap_id, qp);
214
215 CommandList end_list;
216 EXPECT(end_list.begin_query({heap_id, d3d12_query::occlusion, 0}));
217 EXPECT(end_list.end_query({heap_id, d3d12_query::occlusion, 0}));
218 EXPECT(end_list.close());
219 const CommandList* end_ptr = &end_list;
220
221 CommandList resolve_list;
222 EXPECT(resolve_list.resolve_queries({heap_id, d3d12_query::occlusion, 0, 1, 3, 0}));
223 EXPECT(resolve_list.close());
224 const CommandList* resolve_ptr = &resolve_list;
225
226 std::memset(res_ptr, 0xAB, 64);
227 driver::copy_query_calls.store(0);
228 driver::fill_buffer_calls.store(0);
229 driver::count_resolves.store(true);
230
231 std::thread resolver;
232 ReplayResult resolve_res = ReplayResult::unsupported;
233 driver::on_next_submit = [&]() -> VkResult {
234 resolver = std::thread([&] { resolve_res = queue_b.execute({&resolve_ptr, 1}); });
235 // Give queue_b ample time to run prepare() and reach QueryReplay::plan() while queue_a holds
236 // tracker_mutex_ (and has already unlocked resource_mutex_).
237 std::this_thread::sleep_for(std::chrono::milliseconds(40));
238 return VK_SUCCESS;
239 };
240
241 const ReplayResult end_res = queue_a.execute({&end_ptr, 1});
242 if (resolver.joinable()) resolver.join();
243 driver::count_resolves.store(false);
244 EXPECT(end_res == ReplayResult::success);
245 EXPECT(resolve_res == ReplayResult::success);
246 EXPECT(queue_a.idle() && queue_b.idle());
247 EXPECT(driver::copy_query_calls.load() == 1);
248 EXPECT(driver::fill_buffer_calls.load() == 0);
249 std::uint64_t resolved = 0xDEADBEEFULL;
250 std::memcpy(&resolved, res_ptr, sizeof(resolved));
251 EXPECT(resolved == 0); // empty occlusion query resolves 0 via vkCmdCopyQueryPoolResults
252 context.remove_query_pool(heap_id);
253 std::printf("queue/query sync: cross-queue QueryReplay::plan serialized with commit ok\n");
254 }
255
256 // 3. A transient vkQueueSubmit failure must preserve pending VulkanQueue::wait() semaphores for the retry.
257 {
258 VulkanFence fence(context, 0);
259 EXPECT(fence.semaphore() != VK_NULL_HANDLE);
260
261 const std::uint64_t pattern = 0x1122334455667788ULL;
262 std::memcpy(src_ptr, &pattern, sizeof(pattern));
263 std::memset(dst_ptr, 0, sizeof(pattern));
264
265 CommandList copy_list;
266 EXPECT(copy_list.copy_buffer({2, 0, 1, 0, sizeof(pattern)}));
267 EXPECT(copy_list.close());
268 const CommandList* ptr = &copy_list;
269
270 queue_a.wait(fence.semaphore(), 1);
271 driver::fail_next_submit.store(VK_ERROR_OUT_OF_HOST_MEMORY);
272 EXPECT(queue_a.execute({&ptr, 1}) == ReplayResult::unsupported);
273
274 // Retry: the pending wait on (fence, 1) must still be attached to the next vkQueueSubmit.
275 EXPECT(fence.signal(1));
276 driver::captured_wait_count.store(0);
277 driver::captured_wait_sem.store(0);
278 driver::captured_wait_val.store(0);
279 driver::capture_next_waits.store(true);
280 EXPECT(queue_a.execute({&ptr, 1}) == ReplayResult::success);
281 EXPECT(queue_a.idle());
282 EXPECT(driver::captured_wait_count.load() == 1);
283 EXPECT(driver::captured_wait_sem.load() == reinterpret_cast<std::uintptr_t>(fence.semaphore()));
284 EXPECT(driver::captured_wait_val.load() == 1);
285
286 std::uint64_t got = 0;
287 std::memcpy(&got, dst_ptr, sizeof(got));
288 EXPECT(got == pattern);
289 std::printf("queue/query sync: pending Wait() preserved across failed vkQueueSubmit ok\n");
290 }
291
292 // 4. Concurrent multi-queue EndQuery + ResolveQueries + temporary query pool add/remove stress.
293 // Each iteration uses a distinct query slot so no slot is reset while another submission resolves it.
294 {
295 constexpr QueryHeapId main_heap = 99;
296 QueryPool qp{};
297 qp.pool = pool_stress;
298 qp.heap_type = d3d12_query_heap::occlusion;
299 qp.count = 32;
300 qp.ended.assign(32, false);
301 context.add_query_pool(main_heap, qp);
302
303 CommandList res_list;
304 EXPECT(res_list.resolve_queries({main_heap, d3d12_query::occlusion, 0, 1, 3, 0}));
305 EXPECT(res_list.close());
306 const CommandList* res_ptr_cmd = &res_list;
307
308 std::atomic<bool> stop{false};
309 std::atomic<bool> worker_err{false};
310 std::thread worker([&] {
311 for (std::uint64_t round = 0; !stop.load(std::memory_order_relaxed); ++round) {
312 if (queue_b.execute({&res_ptr_cmd, 1}) != ReplayResult::success || !queue_b.idle()) {
313 worker_err.store(true);
314 break;
315 }
316 const QueryHeapId temp_id = 1000 + (round % 16);
317 context.add_query_pool(temp_id, qp);
318 context.remove_query_pool(temp_id);
319 }
320 });
321
322 ReplayResult main_err = ReplayResult::success;
323 for (std::uint32_t i = 0; i < 32; ++i) {
324 CommandList end_list;
325 if (!end_list.begin_query({main_heap, d3d12_query::occlusion, i}) ||
326 !end_list.end_query({main_heap, d3d12_query::occlusion, i}) || !end_list.close()) {
327 main_err = ReplayResult::invalid_query;
328 break;
329 }
330 const CommandList* end_ptr = &end_list;
331 main_err = queue_a.execute({&end_ptr, 1});
332 if (main_err != ReplayResult::success) break;
333 }
334 stop.store(true, std::memory_order_relaxed);
335 worker.join();
336 EXPECT(main_err == ReplayResult::success);
337 EXPECT(!worker_err.load());
338 EXPECT(queue_a.idle() && queue_b.idle());
339 context.remove_query_pool(main_heap);
340 std::printf("queue/query sync: concurrent multi-queue query stress ok\n");
341 }
342 }
343
344 destroy_query_pool(d.device, pool_uaf, nullptr);
345 destroy_query_pool(d.device, pool_race, nullptr);
346 destroy_query_pool(d.device, pool_stress, nullptr);
347
348 EXPECT(d.validation_errors() == 0);
349 std::printf("vk_queue_query_sync_test: ok\n");
350 return 0;
351}
diff --git a/runtime/test/vk_sync_validation_selftest.cpp b/runtime/test/vk_sync_validation_selftest.cpp
new file mode 100644
index 000000000..6b6cf380f
--- /dev/null
+++ b/runtime/test/vk_sync_validation_selftest.cpp
@@ -0,0 +1,93 @@
1// Proves that Vulkan synchronization validation reports hazards on this machine when LEONIDA_VK_VALIDATION=1, so a
2// "0 validation errors" from the GPU tests means the layer looked, not that it was absent or silent.
3//
4// vk_test_device.h asks for VK_VALIDATION_FEATURE_ENABLE_SYNCHRONIZATION_VALIDATION_EXT whenever validation is on.
5// This test records two vkCmdCopyBuffer into the same bytes:
6// - without a barrier between them, synchronization validation must report the write-after-write hazard;
7// - with a transfer -> transfer memory barrier, it must report nothing.
8// The second half keeps the first honest: a layer that reported every copy would fail it.
9//
10// Exit codes: 0 pass; 1 the hazard was not reported, the barrier case was, or the device failed;
11// 77 (ctest skip) when validation is not requested or there is no Vulkan device. No game files, no runtime code.
12#include "vk_test_device.h"
13
14#include <cstdio>
15#include <cstdlib>
16#include <cstring>
17
18namespace {
19
20// Validation errors reported while recording and submitting the two copies, or ~0u when the copies could not run.
21unsigned copy_twice(vktest::Device& d, bool barrier) {
22 void* mapped = nullptr;
23 const VkBuffer src = d.buffer(4096, VK_BUFFER_USAGE_TRANSFER_SRC_BIT, &mapped);
24 const VkBuffer dst = d.buffer(4096, VK_BUFFER_USAGE_TRANSFER_DST_BIT, &mapped);
25 if (!src || !dst) return ~0u;
26 const auto copy = d.fn<PFN_vkCmdCopyBuffer>("vkCmdCopyBuffer");
27 const auto pipeline_barrier = d.fn<PFN_vkCmdPipelineBarrier>("vkCmdPipelineBarrier");
28 const unsigned before = d.validation_errors();
29 const bool ran = d.run([&](VkCommandBuffer cb) {
30 const VkBufferCopy region{0, 0, 4096};
31 copy(cb, src, dst, 1, &region);
32 if (barrier) {
33 VkMemoryBarrier memory{VK_STRUCTURE_TYPE_MEMORY_BARRIER};
34 memory.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
35 memory.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
36 pipeline_barrier(cb, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 1, &memory, 0,
37 nullptr, 0, nullptr);
38 }
39 copy(cb, src, dst, 1, &region);
40 return true;
41 });
42 return ran ? d.validation_errors() - before : ~0u;
43}
44
45bool validation_requested() {
46#ifdef _MSC_VER
47#pragma warning(push)
48#pragma warning(disable : 4996) // getenv: read once, as vk_test_device.h does
49#endif
50 const char* env = std::getenv("LEONIDA_VK_VALIDATION");
51#ifdef _MSC_VER
52#pragma warning(pop)
53#endif
54 return env && std::strcmp(env, "0") != 0;
55}
56
57} // namespace
58
59int main() {
60 if (!validation_requested()) {
61 std::printf("SKIP vk_sync_validation_selftest: LEONIDA_VK_VALIDATION is not set, nothing to prove\n");
62 return 77;
63 }
64 vktest::Device d;
65 const auto status = d.initialize(); // fails, with a message, when the Khronos layer is not installed
66 if (status == vktest::DeviceStatus::unavailable) {
67 std::printf("SKIP vk_sync_validation_selftest: no Vulkan device\n");
68 return 77;
69 }
70 if (status != vktest::DeviceStatus::ready || !d.validation) {
71 std::fprintf(stderr, "vk_sync_validation_selftest: no validated Vulkan device\n");
72 return 1;
73 }
74 const unsigned hazard = copy_twice(d, false);
75 const unsigned clean = copy_twice(d, true);
76 if (hazard == ~0u || clean == ~0u) {
77 std::fprintf(stderr, "vk_sync_validation_selftest: the copies could not be recorded or submitted\n");
78 return 1;
79 }
80 std::printf("two copies into the same bytes: %u validation error(s) without a barrier, %u with one\n", hazard,
81 clean);
82 if (hazard == 0) {
83 std::fprintf(stderr, "vk_sync_validation_selftest: FAIL, the write-after-write hazard was not reported: "
84 "synchronization validation is not active, so 0 errors elsewhere proves nothing\n");
85 return 1;
86 }
87 if (clean != 0) {
88 std::fprintf(stderr, "vk_sync_validation_selftest: FAIL, the synchronized copies were reported too\n");
89 return 1;
90 }
91 std::printf("vk_sync_validation_selftest: PASS, synchronization validation is active\n");
92 return 0;
93}
diff --git a/runtime/test/vk_test_device.h b/runtime/test/vk_test_device.h
index 0fb490d18..635a3107b 100644
--- a/runtime/test/vk_test_device.h
+++ b/runtime/test/vk_test_device.h
@@ -6,6 +6,7 @@
6#include "vulkan_loader.h" 6#include "vulkan_loader.h"
7#include "../src/vulkan_device_filter.h" 7#include "../src/vulkan_device_filter.h"
8#include "vk_device_pick.h" 8#include "vk_device_pick.h"
9#include "../src/subgroup_size.h"
9 10
10#include <algorithm> 11#include <algorithm>
11#include <cstdint> 12#include <cstdint>
@@ -101,6 +102,8 @@ public:
101 bool request_buffer_device_address = false; // set before create(): enable bufferDeviceAddress where supported 102 bool request_buffer_device_address = false; // set before create(): enable bufferDeviceAddress where supported
102 bool buffer_device_address = false; // enabled: buffer() memory and buffers can be addressed (device_address()) 103 bool buffer_device_address = false; // enabled: buffer() memory and buffers can be addressed (device_address())
103 bool debug_utils = false; // VK_EXT_debug_utils is enabled on the instance 104 bool debug_utils = false; // VK_EXT_debug_utils is enabled on the instance
105 // The subgroup sizes of the device, with subgroupSizeControl and computeFullSubgroups enabled where it has them.
106 leonida::SubgroupSizeCaps subgroup;
104 107
105 Device() = default; 108 Device() = default;
106 Device(const Device&) = delete; 109 Device(const Device&) = delete;
@@ -328,6 +331,15 @@ public:
328 conditional_rendering ? &enable_conditional : nullptr}; 331 conditional_rendering ? &enable_conditional : nullptr};
329 enable13.dynamicRendering = VK_TRUE; 332 enable13.dynamicRendering = VK_TRUE;
330 enable13.synchronization2 = VK_TRUE; 333 enable13.synchronization2 = VK_TRUE;
334 enable13.subgroupSizeControl = features13.subgroupSizeControl;
335 enable13.computeFullSubgroups = features13.computeFullSubgroups;
336 leonida::query_subgroup_size_caps(instance_fn<PFN_vkGetPhysicalDeviceProperties2>("vkGetPhysicalDeviceProperties2"),
337 physical, features13.subgroupSizeControl, features13.computeFullSubgroups,
338 subgroup);
339 std::printf("subgroup sizes: %u..%u (default %u), requirable in stages 0x%x, subgroupSizeControl %s, "
340 "computeFullSubgroups %s\n",
341 subgroup.min_size, subgroup.max_size, subgroup.default_size, unsigned(subgroup.required_stages),
342 subgroup.subgroup_size_control ? "on" : "off", subgroup.compute_full_subgroups ? "on" : "off");
331 // shaderDrawParameters, where available: translated vertex shaders will read BaseVertex and BaseInstance once PR 436 343 // shaderDrawParameters, where available: translated vertex shaders will read BaseVertex and BaseInstance once PR 436
332 // (zero-based VS ids) is in; harmless before. 344 // (zero-based VS ids) is in; harmless before.
333 VkPhysicalDeviceVulkan11Features enable11{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_FEATURES, &enable13}; 345 VkPhysicalDeviceVulkan11Features enable11{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_FEATURES, &enable13};
@@ -364,6 +376,7 @@ public:
364 queue_info.pQueuePriorities = &priority; 376 queue_info.pQueuePriorities = &priority;
365 VkPhysicalDeviceFeatures enable{}; 377 VkPhysicalDeviceFeatures enable{};
366 enable.textureCompressionBC = features.features.textureCompressionBC; // BC uploads, where available 378 enable.textureCompressionBC = features.features.textureCompressionBC; // BC uploads, where available
379 enable.shaderInt64 = features.features.shaderInt64; // translated shaders declare Int64 (index features)
367 bc = features.features.textureCompressionBC == VK_TRUE; 380 bc = features.features.textureCompressionBC == VK_TRUE;
368 enable.shaderSampledImageArrayDynamicIndexing = bindless; 381 enable.shaderSampledImageArrayDynamicIndexing = bindless;
369 enable.shaderStorageImageArrayDynamicIndexing = bindless; 382 enable.shaderStorageImageArrayDynamicIndexing = bindless;
@@ -434,6 +447,7 @@ public:
434 if (host_image_copy) device_extensions.push_back(host_image_copy_name); 447 if (host_image_copy) device_extensions.push_back(host_image_copy_name);
435 const char* swapchain = "VK_KHR_swapchain"; 448 const char* swapchain = "VK_KHR_swapchain";
436 if (presentation) device_extensions.push_back(swapchain); 449 if (presentation) device_extensions.push_back(swapchain);
450#if defined(VK_KHR_swapchain_maintenance1)
437 VkPhysicalDeviceSwapchainMaintenance1FeaturesKHR swapchain_m1{ 451 VkPhysicalDeviceSwapchainMaintenance1FeaturesKHR swapchain_m1{
438 VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SWAPCHAIN_MAINTENANCE_1_FEATURES_KHR}; 452 VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SWAPCHAIN_MAINTENANCE_1_FEATURES_KHR};
439 if (presentation) { 453 if (presentation) {
@@ -455,6 +469,7 @@ public:
455 } 469 }
456 } 470 }
457 } 471 }
472#endif
458#ifdef VK_KHR_SHADER_FMA_EXTENSION_NAME 473#ifdef VK_KHR_SHADER_FMA_EXTENSION_NAME
459 if (shader_fma) device_extensions.push_back(VK_KHR_SHADER_FMA_EXTENSION_NAME); 474 if (shader_fma) device_extensions.push_back(VK_KHR_SHADER_FMA_EXTENSION_NAME);
460#endif 475#endif
diff --git a/runtime/test/vk_xdxr_build_test.cpp b/runtime/test/vk_xdxr_build_test.cpp
index 136f49f68..6f354b2b2 100644
--- a/runtime/test/vk_xdxr_build_test.cpp
+++ b/runtime/test/vk_xdxr_build_test.cpp
@@ -6,10 +6,11 @@
6// 6//
7// Cases: one triangle; five (two levels); 1000 random triangles; an indexed R16 grid with a 16-byte vertex stride; 7// Cases: one triangle; five (two levels); 1000 random triangles; an indexed R16 grid with a 16-byte vertex stride;
8// R32 indices with R32G32 vertices; a geometry transform; two geometries with an inactive (NaN) triangle; no 8// R32 indices with R32G32 vertices; a geometry transform; two geometries with an inactive (NaN) triangle; no
9// triangles; 5000 triangles (three radix-sort tiles); and a TLAS of four instances (rotated and scaled, one with mask 0, one with no BLAS). 9// triangles; 5000 triangles (many radix-sort tiles); updates (refits) in place and into another buffer; a TLAS of four instances (rotated and scaled, one with mask 0, one with no BLAS).
10// Exit 77 when there is no Vulkan device with bufferDeviceAddress. 10// Exit 77 when there is no Vulkan device with bufferDeviceAddress.
11// `vk_xdxr_build_test <out dir> <triangles>` instead times BLAS builds of that many random triangles (wall clock of 11// `vk_xdxr_build_test <out dir> <triangles>` instead times BLAS builds of that many random triangles (wall clock of
12// one submission each, after one warm-up; result and scratch in device-local memory) and writes nothing. 12// one submission each, after one warm-up; result and scratch in device-local memory), then in-place updates
13// (refits) of the same structure, and writes nothing.
13#include "vk_test_device.h" 14#include "vk_test_device.h"
14#include "../src/xdxr_build.h" 15#include "../src/xdxr_build.h"
15 16
@@ -117,9 +118,12 @@ struct Built {
117 std::vector<Tri> tris; 118 std::vector<Tri> tris;
118}; 119};
119 120
121// With `moved` (the same geometries with new vertex positions) the BLAS is then updated: refitted in place, or with
122// `into_other` into a second buffer, in which case the untouched source is written too, as <name>_source.
120int build_blas(vktest::Device& gpu, XdxrBuilder& builder, const std::string& dir, const std::string& name, 123int build_blas(vktest::Device& gpu, XdxrBuilder& builder, const std::string& dir, const std::string& name,
121 const std::vector<Geometry>& geometries, Built& built, unsigned rays = 0) { 124 const std::vector<Geometry>& geometries, Built& built, unsigned rays = 0,
122 std::vector<Buffer> keep; 125 const std::vector<Geometry>* moved = nullptr, bool into_other = false) {
126 std::vector<Buffer> keep, vertex_buffers;
123 std::vector<XdxrTriangles> descs; 127 std::vector<XdxrTriangles> descs;
124 std::uint32_t total = 0; 128 std::uint32_t total = 0;
125 for (std::size_t g = 0; g < geometries.size(); ++g) { 129 for (std::size_t g = 0; g < geometries.size(); ++g) {
@@ -134,6 +138,7 @@ int build_blas(vktest::Device& gpu, XdxrBuilder& builder, const std::string& dir
134 d.triangle_count = geo.triangle_count; 138 d.triangle_count = geo.triangle_count;
135 d.flags = 1; 139 d.flags = 1;
136 keep.push_back(v); 140 keep.push_back(v);
141 vertex_buffers.push_back(v);
137 if (!geo.indices.empty()) { 142 if (!geo.indices.empty()) {
138 Buffer ib = make(gpu, geo.indices.size() * 4); 143 Buffer ib = make(gpu, geo.indices.size() * 4);
139 EXPECT(ib.buffer); 144 EXPECT(ib.buffer);
@@ -170,13 +175,41 @@ int build_blas(vktest::Device& gpu, XdxrBuilder& builder, const std::string& dir
170 return recorded; 175 return recorded;
171 })); 176 }));
172 built.address = base; 177 built.address = base;
173 const auto* bytes = static_cast<const char*>(dst.map) + (base - dst.address); 178 auto dump = [&](const std::string& case_name, const Buffer& buffer, std::uint64_t at, const std::vector<Tri>& tris) {
174 EXPECT(write_file(dir + "/" + name + ".bin", bytes, layout.size)); 179 const auto* bytes = static_cast<const char*>(buffer.map) + (at - buffer.address);
175 const std::string json = "{\"kind\": \"blas\", \"address\": " + std::to_string(base) + 180 const std::string json = "{\"kind\": \"blas\", \"address\": " + std::to_string(at) +
176 (rays ? ", \"rays\": " + std::to_string(rays) : std::string()) + 181 (rays ? ", \"rays\": " + std::to_string(rays) : std::string()) +
177 ", \"triangles\": " + tris_json(built.tris) + "}\n"; 182 ", \"triangles\": " + tris_json(tris) + "}\n";
178 EXPECT(write_file(dir + "/" + name + ".json", json.data(), json.size())); 183 return write_file(dir + "/" + case_name + ".bin", bytes, layout.size) &&
179 std::printf("%s: %u triangles, %u bytes, %u nodes\n", name.c_str(), total, layout.size, layout.nodes); 184 write_file(dir + "/" + case_name + ".json", json.data(), json.size());
185 };
186 if (!moved) {
187 EXPECT(dump(name, dst, base, built.tris));
188 std::printf("%s: %u triangles, %u bytes, %u nodes\n", name.c_str(), total, layout.size, layout.nodes);
189 return 0;
190 }
191 // the update: new positions in the same vertex buffers, then a refit of the structure just built
192 EXPECT(moved->size() == geometries.size());
193 std::vector<Tri> moved_tris;
194 for (std::size_t g = 0; g < moved->size(); ++g) {
195 EXPECT((*moved)[g].vertex_data.size() == geometries[g].vertex_data.size());
196 std::memcpy(vertex_buffers[g].map, (*moved)[g].vertex_data.data(), (*moved)[g].vertex_data.size() * 4);
197 expand((*moved)[g], std::uint32_t(g), moved_tris);
198 }
199 Buffer other = into_other ? make(gpu, layout.size + 256) : Buffer{};
200 const std::uint64_t target = into_other ? (other.address + 255) & ~std::uint64_t(255) : base;
201 EXPECT(!into_other || other.buffer);
202 EXPECT(gpu.run([&](VkCommandBuffer cb) {
203 recorded = builder.record_blas(cb, layout, descs, target, scratch.address, base);
204 barrier_to_host(gpu, cb);
205 return recorded;
206 }));
207 if (into_other) EXPECT(dump(name + "_source", dst, base, built.tris)); // a refit must not touch its source
208 EXPECT(dump(name, into_other ? other : dst, target, moved_tris));
209 built.tris = moved_tris;
210 built.address = target;
211 std::printf("%s: %u triangles refitted %s, %u bytes\n", name.c_str(), total,
212 into_other ? "into another buffer" : "in place", layout.size);
180 return 0; 213 return 0;
181} 214}
182 215
@@ -234,8 +267,17 @@ int main(int argc, char** argv) {
234 const double ms = std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - t0).count(); 267 const double ms = std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - t0).count();
235 if (rep) best = std::min(best, ms); 268 if (rep) best = std::min(best, ms);
236 } 269 }
237 std::printf("%u triangles: %.2f ms (best of 3), result %u bytes, scratch %llu bytes, sort size %u\n", n, best, 270 double refit = 1e30; // an update of the structure just built, in place
238 layout.size, static_cast<unsigned long long>(layout.scratch), layout.sort_size); 271 for (int rep = 0; rep < 4; ++rep) {
272 const auto t0 = std::chrono::steady_clock::now();
273 EXPECT(gpu.run([&](VkCommandBuffer cb) {
274 return builder.record_blas(cb, layout, {d}, dst.address, scratch.address, dst.address);
275 }));
276 const double ms = std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - t0).count();
277 if (rep) refit = std::min(refit, ms);
278 }
279 std::printf("%u triangles: %.2f ms (best of 3), refit %.2f ms, result %u bytes, scratch %llu bytes, sort size %u\n",
280 n, best, refit, layout.size, static_cast<unsigned long long>(layout.scratch), layout.sort_size);
239 return 0; 281 return 0;
240 } 282 }
241 283
@@ -287,10 +329,33 @@ int main(int argc, char** argv) {
287 b.vertex_data[3 * 3 * 7] = std::nanf(""); // triangle 7 of geometry 1: inactive 329 b.vertex_data[3 * 3 * 7] = std::nanf(""); // triangle 7 of geometry 1: inactive
288 if (build_blas(gpu, builder, dir, "blas_two_geometries", {a, b}, multi)) return 1; 330 if (build_blas(gpu, builder, dir, "blas_two_geometries", {a, b}, multi)) return 1;
289 if (build_blas(gpu, builder, dir, "blas_empty", {}, empty)) return 1; 331 if (build_blas(gpu, builder, dir, "blas_empty", {}, empty)) return 1;
290 // three radix-sort tiles of 2048, the last one partial (fewer rays: the reference's brute force is slow) 332 // many radix-sort tiles (RADIX_TILE elements each), the last one partial (fewer rays: the brute force is slow)
291 Built tiles; 333 Built tiles;
292 if (build_blas(gpu, builder, dir, "blas_three_sort_tiles", {soup(5000)}, tiles, 200)) return 1; 334 if (build_blas(gpu, builder, dir, "blas_three_sort_tiles", {soup(5000)}, tiles, 200)) return 1;
293 335
336 // Updates. Every triangle moves (its own offset, and a stretch), so each box changes; the tree is kept.
337 auto move = [&](Geometry g, float amount) {
338 std::uniform_real_distribution<float> d(-amount, amount);
339 const std::uint32_t floats = g.stride / 4;
340 for (std::size_t v = 0; v + 2 < g.vertex_data.size(); v += floats) {
341 const float dx = d(rng), dy = d(rng);
342 g.vertex_data[v] = g.vertex_data[v] * 1.25f + dx;
343 g.vertex_data[v + 1] = g.vertex_data[v + 1] * 0.8f + dy;
344 if (!g.xy) g.vertex_data[v + 2] += d(rng);
345 }
346 return g;
347 };
348 {
349 Built refitted;
350 const Geometry big = soup(3000); // the radix-sort path
351 const std::vector<Geometry> after = {move(big, 1.5f)};
352 if (build_blas(gpu, builder, dir, "blas_refit_in_place", {big}, refitted, 300, &after)) return 1;
353 Built copied;
354 const Geometry g = grid(12, 4, false); // R32 indices, stride 16; the small-sort path
355 const std::vector<Geometry> after_grid = {move(g, 0.3f)};
356 if (build_blas(gpu, builder, dir, "blas_refit_into_other", {g}, copied, 0, &after_grid, true)) return 1;
357 }
358
294 // TLAS: instances over blas_random and blas_grid_u16_stride16. An instance names its BLAS by a 40-bit address 359 // TLAS: instances over blas_random and blas_grid_u16_stride16. An instance names its BLAS by a 40-bit address
295 // (256-byte units in 32 bits), as on the console; device addresses can be wider (llvmpipe's are host pointers). 360 // (256-byte units in 32 bits), as on the console; device addresses can be wider (llvmpipe's are host pointers).
296 // The instances hold application-style addresses, device address - bias, as the layer's address window does. 361 // The instances hold application-style addresses, device address - bias, as the layer's address window does.
@@ -338,6 +403,34 @@ int main(int argc, char** argv) {
338 } 403 }
339 json += "]}\n"; 404 json += "]}\n";
340 EXPECT(write_file(dir + "/tlas.json", json.data(), json.size())); 405 EXPECT(write_file(dir + "/tlas.json", json.data(), json.size()));
406
407 // The TLAS updated in place: every instance moves and turns; the masked and the BLAS-less ones stay so.
408 Inst moved_insts[sizeof insts / sizeof insts[0]];
409 std::memcpy(moved_insts, insts, sizeof insts);
410 const float c2 = std::cos(1.9f), s2 = std::sin(1.9f);
411 const float turned[12] = {c2, 0, s2, 4, 0, 1, 0, -3, -s2, 0, c2, 2};
412 std::memcpy(moved_insts[0].m, turned, sizeof turned);
413 moved_insts[1].m[3] -= 7;
414 moved_insts[1].m[7] += 5;
415 moved_insts[2].m[11] -= 4;
416 for (std::uint32_t i = 0; i < count; ++i) std::memcpy(static_cast<char*>(descs.map) + 64 * i, moved_insts[i].m, 48);
417 EXPECT(gpu.run([&](VkCommandBuffer cb) {
418 recorded = builder.record_tlas(cb, layout, descs.address, base, scratch.address, bias, base);
419 barrier_to_host(gpu, cb);
420 return recorded;
421 }));
422 EXPECT(write_file(dir + "/tlas_refit.bin", static_cast<const char*>(dst.map) + (base - dst.address), layout.size));
423 std::string json2 = "{\"kind\": \"tlas\", \"address\": " + std::to_string(base) + ", \"bias\": " +
424 std::to_string(bias) + ", \"blas\": [\"blas_random\", \"blas_grid_u16_stride16\"], \"instances\": [";
425 for (std::uint32_t i = 0; i < count; ++i) {
426 json2 += i ? ", {" : "{";
427 json2 += "\"transform\": [";
428 for (int k = 0; k < 12; ++k) json2 += (k ? ", " : "") + num(moved_insts[i].m[k]);
429 json2 += "], \"mask\": " + std::to_string(moved_insts[i].id_mask >> 24) + ", \"blas\": " +
430 std::to_string(moved_insts[i].which) + "}";
431 }
432 json2 += "]}\n";
433 EXPECT(write_file(dir + "/tlas_refit.json", json2.data(), json2.size()));
341 std::printf("tlas: %u instances, %u bytes\nvk_xdxr_build_test: built every case\n", count, layout.size); 434 std::printf("tlas: %u instances, %u bytes\nvk_xdxr_build_test: built every case\n", count, layout.size);
342 return 0; 435 return 0;
343} 436}
diff --git a/runtime/test/xgameruntime_test.cpp b/runtime/test/xgameruntime_test.cpp
index 755b64381..ac36f40d9 100644
--- a/runtime/test/xgameruntime_test.cpp
+++ b/runtime/test/xgameruntime_test.cpp
@@ -10,6 +10,7 @@
10#include <atomic> 10#include <atomic>
11#include <cstdint> 11#include <cstdint>
12#include <cstdio> 12#include <cstdio>
13#include <cstdlib>
13#include <cstring> 14#include <cstring>
14 15
15#include <XAsync.h> 16#include <XAsync.h>
@@ -98,6 +99,31 @@ HRESULT CALLBACK provider(XAsyncOp op, const XAsyncProviderData* data) {
98 } 99 }
99} 100}
100 101
102HMODULE g_teardown_rt_mod = nullptr;
103FARPROC(WINAPI* g_teardown_get_proc)(HMODULE, LPCSTR) = nullptr;
104BOOL(WINAPI* g_teardown_free_lib)(HMODULE) = nullptr;
105
106// Registered with std::atexit before check_run_time_load() constructs any function-local statics in library_loader.
107// LIFO atexit order means this runs after those statics would have been destroyed, simulating mapped-DLL
108// DLL_PROCESS_DETACH or earlier atexit handlers calling GetProcAddress/FreeLibrary on a pseudo-handle during exit.
109void check_late_teardown() {
110 if (!g_teardown_rt_mod || !g_teardown_get_proc || !g_teardown_free_lib) return;
111 if (g_teardown_get_proc(g_teardown_rt_mod, "UninitializeApiImpl") == nullptr) {
112 std::fprintf(stderr, "FAIL late teardown GetProcAddress on pseudo-handle\n");
113 std::_Exit(1);
114 }
115 SetLastError(0);
116 if (g_teardown_get_proc(g_teardown_rt_mod, "LateTeardownMissingSymbol") != nullptr ||
117 GetLastError() != ERROR_PROC_NOT_FOUND) {
118 std::fprintf(stderr, "FAIL late teardown unserved GetProcAddress on pseudo-handle\n");
119 std::_Exit(1);
120 }
121 if (g_teardown_free_lib(g_teardown_rt_mod) != TRUE) {
122 std::fprintf(stderr, "FAIL late teardown FreeLibrary on pseudo-handle\n");
123 std::_Exit(1);
124 }
125}
126
101// xgameruntime.lib's thunks don't import the runtime: they LoadLibraryW(L"xgameruntime.dll") and GetProcAddress five 127// xgameruntime.lib's thunks don't import the runtime: they LoadLibraryW(L"xgameruntime.dll") and GetProcAddress five
102// names (measured in the package's libHttpClient.GDK.dll and XCurl.dll). Drive that path through the loader shims, 128// names (measured in the package's libHttpClient.GDK.dll and XCurl.dll). Drive that path through the loader shims,
103// bound by the api set XCurl.dll imports them from, as a mapped image would be. 129// bound by the api set XCurl.dll imports them from, as a mapped image would be.
@@ -136,6 +162,9 @@ void check_run_time_load() {
136 SetLastError(0); 162 SetLastError(0);
137 check(get_proc(rt_mod, "NoSuchRuntimeFunction") == nullptr && GetLastError() == ERROR_PROC_NOT_FOUND, 163 check(get_proc(rt_mod, "NoSuchRuntimeFunction") == nullptr && GetLastError() == ERROR_PROC_NOT_FOUND,
138 "an unserved name is NULL with ERROR_PROC_NOT_FOUND, as from a real module"); 164 "an unserved name is NULL with ERROR_PROC_NOT_FOUND, as from a real module");
165 SetLastError(0);
166 check(get_proc(rt_mod, nullptr) == nullptr && GetLastError() == ERROR_PROC_NOT_FOUND,
167 "a null proc name is NULL with ERROR_PROC_NOT_FOUND");
139 168
140 struct Options { 169 struct Options {
141 uint32_t unknown; 170 uint32_t unknown;
@@ -162,6 +191,10 @@ void check_run_time_load() {
162 "GetProcAddress on a host module is the host's"); 191 "GetProcAddress on a host module is the host's");
163 check(free_lib(rt_mod) == TRUE && load_w(L"xgameruntime.dll") == rt_mod, 192 check(free_lib(rt_mod) == TRUE && load_w(L"xgameruntime.dll") == rt_mod,
164 "FreeLibrary on the runtime succeeds and keeps it loaded"); 193 "FreeLibrary on the runtime succeeds and keeps it loaded");
194
195 g_teardown_rt_mod = rt_mod;
196 g_teardown_get_proc = get_proc;
197 g_teardown_free_lib = free_lib;
165} 198}
166 199
167} // namespace 200} // namespace
@@ -262,6 +295,7 @@ int main() {
262 check(init() == S_OK, "XGameRuntimeInitialize works again after balanced uninitialize calls"); 295 check(init() == S_OK, "XGameRuntimeInitialize works again after balanced uninitialize calls");
263 uninit(); 296 uninit();
264 297
298 std::atexit(check_late_teardown);
265 check_run_time_load(); 299 check_run_time_load();
266 300
267 if (g_failures) { 301 if (g_failures) {
diff --git a/runtime/test/xs_proxy_mock_test.cpp b/runtime/test/xs_proxy_mock_test.cpp
index 429261e98..f115b6655 100644
--- a/runtime/test/xs_proxy_mock_test.cpp
+++ b/runtime/test/xs_proxy_mock_test.cpp
@@ -70,7 +70,7 @@ namespace xs = rt::d3d12_xs;
70 70
71// ---- Mocks ---- 71// ---- Mocks ----
72 72
73enum class Kind { device, queue, fence, resource }; 73enum class Kind { device, queue, fence, resource, allocator };
74 74
75constexpr unsigned kMockSlots = 128; 75constexpr unsigned kMockSlots = 128;
76constexpr std::uint64_t kFenceHandle = 0x1000, kResourceHandle = 0x2000; // the handles the mock device opens 76constexpr std::uint64_t kFenceHandle = 0x1000, kResourceHandle = 0x2000; // the handles the mock device opens
@@ -84,6 +84,7 @@ struct Mock {
84 long refs; 84 long refs;
85 int device_level; // device: highest ID3D12DeviceN it answers (0 = ID3D12Device only) 85 int device_level; // device: highest ID3D12DeviceN it answers (0 = ID3D12Device only)
86 bool fence1; // fence: answers ID3D12Fence1; device: the fences it makes do 86 bool fence1; // fence: answers ID3D12Fence1; device: the fences it makes do
87 bool allocator_tag; // allocator: answers kLeonidaCommandAllocatorTag; device: the allocators it makes do
87 bool create_null; // device: creation returns create_result with no object 88 bool create_null; // device: creation returns create_result with no object
88 HRESULT create_result; // device: what creation returns (S_OK makes the object) 89 HRESULT create_result; // device: what creation returns (S_OK makes the object)
89 Mock* last_child; // device: the object its last creation or open made 90 Mock* last_child; // device: the object its last creation or open made
@@ -126,6 +127,9 @@ bool mock_has(const Mock* m, REFIID iid) {
126 case Kind::fence: 127 case Kind::fence:
127 return IsEqualIID(iid, __uuidof(ID3D12Fence)) || (m->fence1 && IsEqualIID(iid, __uuidof(ID3D12Fence1))); 128 return IsEqualIID(iid, __uuidof(ID3D12Fence)) || (m->fence1 && IsEqualIID(iid, __uuidof(ID3D12Fence1)));
128 case Kind::resource: return IsEqualIID(iid, __uuidof(ID3D12Resource)); 129 case Kind::resource: return IsEqualIID(iid, __uuidof(ID3D12Resource));
130 case Kind::allocator:
131 return IsEqualIID(iid, __uuidof(ID3D12CommandAllocator)) ||
132 (m->allocator_tag && IsEqualIID(iid, xs::kLeonidaCommandAllocatorTag));
129 default: return false; 133 default: return false;
130 } 134 }
131} 135}
@@ -148,6 +152,7 @@ HRESULT mock_create(Mock* device, Kind kind, std::uint64_t riid, std::uint64_t o
148 if (device->create_null || FAILED(device->create_result)) return device->create_result; 152 if (device->create_null || FAILED(device->create_result)) return device->create_result;
149 Mock* child = new_mock(kind); 153 Mock* child = new_mock(kind);
150 child->fence1 = device->fence1; 154 child->fence1 = device->fence1;
155 child->allocator_tag = device->allocator_tag;
151 device->last_child = child; 156 device->last_child = child;
152 return mock_query(child, reinterpret_cast<const IID*>(riid), out); 157 return mock_query(child, reinterpret_cast<const IID*>(riid), out);
153} 158}
@@ -163,6 +168,7 @@ std::uint64_t mock_call(Mock* m, unsigned slot, const std::uint64_t* words) {
163 if (m->kind == Kind::device) { 168 if (m->kind == Kind::device) {
164 switch (slot) { 169 switch (slot) {
165 case 8: return static_cast<std::uint32_t>(mock_create(m, Kind::queue, a2, a3)); // CreateCommandQueue 170 case 8: return static_cast<std::uint32_t>(mock_create(m, Kind::queue, a2, a3)); // CreateCommandQueue
171 case 9: return static_cast<std::uint32_t>(mock_create(m, Kind::allocator, a2, a3)); // CreateCmdAllocator
166 case 75: return static_cast<std::uint32_t>(mock_create(m, Kind::queue, a3, a4)); // CreateCommandQueue1 172 case 75: return static_cast<std::uint32_t>(mock_create(m, Kind::queue, a3, a4)); // CreateCommandQueue1
167 case 36: return static_cast<std::uint32_t>(mock_create(m, Kind::fence, a3, a4)); // CreateFence 173 case 36: return static_cast<std::uint32_t>(mock_create(m, Kind::fence, a3, a4)); // CreateFence
168 case 32: // OpenSharedHandle 174 case 32: // OpenSharedHandle
@@ -248,10 +254,11 @@ const IID kDevice1Iid = __uuidof(ID3D12Device1);
248const D3D12_COMMAND_QUEUE_DESC kQueueDesc{}; 254const D3D12_COMMAND_QUEUE_DESC kQueueDesc{};
249 255
250// A device proxy over a new mock device. The proxy takes the mock's one reference. 256// A device proxy over a new mock device. The proxy takes the mock's one reference.
251void* make_device(Mock*& mock, int level, bool fence1) { 257void* make_device(Mock*& mock, int level, bool fence1, bool allocator_tag = true) {
252 mock = new_mock(Kind::device); 258 mock = new_mock(Kind::device);
253 mock->device_level = level; 259 mock->device_level = level;
254 mock->fence1 = fence1; 260 mock->fence1 = fence1;
261 mock->allocator_tag = allocator_tag;
255 mock->refs = 1; 262 mock->refs = 1;
256 void* device = nullptr; 263 void* device = nullptr;
257 if (FAILED(xs::create_device_proxy(reinterpret_cast<ID3D12Device*>(mock), __uuidof(ID3D12Device), &device))) 264 if (FAILED(xs::create_device_proxy(reinterpret_cast<ID3D12Device*>(mock), __uuidof(ID3D12Device), &device)))
@@ -563,7 +570,85 @@ int check_alloc_failures() {
563 return 0; 570 return 0;
564} 571}
565 572
566// ---- 6. The refused tail and the guard region ---- 573// ---- 6. Command allocators (device slot 9) ----
574
575int check_allocators() {
576 const IID allocator_iid = __uuidof(ID3D12CommandAllocator);
577 // An allocator that answers Leonida's tag (its lists resolve a proxy) comes back wrapped.
578 {
579 Mock* mock = nullptr;
580 void* device = make_device(mock, 9, true, true);
581 EXPECT(device);
582 const unsigned long device_refs = xs::device_proxy_ref_count(device);
583 void* allocator = nullptr;
584 EXPECT(hr_of(raw(device, 9, D3D12_COMMAND_LIST_TYPE_DIRECT, word(&allocator_iid), word(&allocator))) == S_OK);
585 Mock* const real = mock->last_child;
586 EXPECT(xs::is_allocator_proxy(allocator) && word(xs::allocator_proxy_real_allocator(allocator)) == word(real));
587 EXPECT(mock->args[9][0] == D3D12_COMMAND_LIST_TYPE_DIRECT && real->refs == 1);
588 EXPECT(xs::allocator_proxy_slot_count(allocator) == 9 && xs::device_proxy_ref_count(device) == device_refs + 1);
589 // Reset (slot 8) reaches the real allocator; every slot past it up to the table end is refused.
590 EXPECT(hr_of(raw(allocator, 8)) == S_OK && real->calls[8] == 1);
591 for (unsigned slot = 9; slot < xs::allocator_proxy_table_size(); ++slot)
592 EXPECT(hr_of(raw(allocator, slot)) == E_NOTIMPL && real->calls[slot] == 0);
593 // The tag and the real object stay hidden: QueryInterface answers only the modelled interfaces.
594 void* found = reinterpret_cast<void*>(1);
595 EXPECT(hr_of(raw(allocator, 0, word(&xs::kLeonidaCommandAllocatorTag), word(&found))) == E_NOINTERFACE &&
596 !found);
597 EXPECT(hr_of(raw(allocator, 0, word(&allocator_iid), word(&found))) == S_OK && found == allocator);
598 EXPECT(release(found) == 1);
599 // An allocator is a pageable: MakeResident gives the real runtime the real allocator.
600 const std::uint64_t objects[1] = {word(allocator)};
601 EXPECT(hr_of(raw(device, 34, 1, word(objects))) == S_OK && mock->array[34][0] == word(real));
602 EXPECT(release(allocator) == 0 && real->refs == 0);
603 EXPECT(xs::device_proxy_ref_count(device) == device_refs);
604 // Null IID, null output, a failing or empty creation, an IID the allocator lacks.
605 void* out = reinterpret_cast<void*>(1);
606 EXPECT(hr_of(raw(device, 9, 0, 0, word(&out))) == E_POINTER && !out);
607 EXPECT(hr_of(raw(device, 9, 0, word(&allocator_iid), 0)) == S_FALSE); // the device's own answer
608 mock->create_result = E_OUTOFMEMORY;
609 out = reinterpret_cast<void*>(1);
610 EXPECT(hr_of(raw(device, 9, 0, word(&allocator_iid), word(&out))) == E_OUTOFMEMORY && !out);
611 mock->create_result = S_OK;
612 mock->create_null = true;
613 out = reinterpret_cast<void*>(1);
614 EXPECT(hr_of(raw(device, 9, 0, word(&allocator_iid), word(&out))) == E_FAIL && !out);
615 mock->create_null = false;
616 const IID fence_iid = __uuidof(ID3D12Fence);
617 out = reinterpret_cast<void*>(1);
618 EXPECT(hr_of(raw(device, 9, 0, word(&fence_iid), word(&out))) == E_NOINTERFACE && !out);
619 EXPECT(mock->last_child->refs == 0);
620 // A refused allocation for the proxy: E_OUTOFMEMORY, and the real allocator is released.
621 g_fail_news = 1;
622 out = reinterpret_cast<void*>(1);
623 const HRESULT starved = hr_of(raw(device, 9, 0, word(&allocator_iid), word(&out)));
624 g_fail_news = 0;
625 EXPECT(starved == E_OUTOFMEMORY && !out && mock->last_child->refs == 0);
626 EXPECT(xs::device_proxy_ref_count(device) == device_refs);
627 EXPECT(release(device) == 0 && mock->refs == 0);
628 }
629 // An allocator without the tag (a PC runtime allocator, whose lists could not resolve a proxy) comes back as it
630 // is, as the interface asked for.
631 {
632 Mock* mock = nullptr;
633 void* device = make_device(mock, 9, true, false);
634 EXPECT(device);
635 void* allocator = nullptr;
636 EXPECT(hr_of(raw(device, 9, 0, word(&allocator_iid), word(&allocator))) == S_OK);
637 EXPECT(allocator == mock->last_child && !xs::is_allocator_proxy(allocator) && mock->last_child->refs == 1);
638 Mock* const real = mock->last_child;
639 EXPECT(release(allocator) == 0 && real->refs == 0);
640 const IID fence_iid = __uuidof(ID3D12Fence);
641 void* out = reinterpret_cast<void*>(1);
642 EXPECT(hr_of(raw(device, 9, 0, word(&fence_iid), word(&out))) == E_NOINTERFACE && !out);
643 EXPECT(mock->last_child->refs == 0);
644 EXPECT(release(device) == 0 && mock->refs == 0);
645 }
646 std::printf("%s: allocators answering Leonida's tag are wrapped (Reset forwarded, tail refused, residency "
647 "unwrapped, references balanced); others come back unwrapped; failures leave no reference\n", g_label);
648 return 0;
649}
650
651// ---- 7. The refused tail and the guard region ----
567 652
568int check_tail(bool want_guarded) { 653int check_tail(bool want_guarded) {
569 Mock* mock = nullptr; 654 Mock* mock = nullptr;
@@ -686,7 +771,7 @@ int main(int argc, char** argv) {
686 if (argc == 2) return run_fault_mode(argv[1]); 771 if (argc == 2) return run_fault_mode(argv[1]);
687 if (argc != 1) return 2; 772 if (argc != 1) return 2;
688 if (check_tail(true) || check_levels() || check_fence1() || check_create_failures() || check_open_shared() || 773 if (check_tail(true) || check_levels() || check_fence1() || check_create_failures() || check_open_shared() ||
689 check_alloc_failures()) 774 check_alloc_failures() || check_allocators())
690 return 1; 775 return 1;
691 std::printf("xs_proxy_mock_test: PASS (%d allocations refused on purpose)\n", g_failed_news); 776 std::printf("xs_proxy_mock_test: PASS (%d allocations refused on purpose)\n", g_failed_news);
692 return 0; 777 return 0;
diff --git a/scripts/build_runtime.ps1 b/scripts/build_runtime.ps1
index e71bcfe27..b251a281c 100644
--- a/scripts/build_runtime.ps1
+++ b/scripts/build_runtime.ps1
@@ -1,4 +1,4 @@
1# Builds runtime\build\gta6rt.exe with MSVC at BelowNormal priority, on half the cores. 1# Builds runtime\build\gta6rt.exe with MSVC at BelowNormal priority, on half the cores.
2# Uses VS's CMake + Ninja when the "C++ CMake tools" component is installed, otherwise calls cl.exe directly. 2# Uses VS's CMake + Ninja when the "C++ CMake tools" component is installed, otherwise calls cl.exe directly.
3# The GameInput controller shim (SDL3, docs/gameinput.md) is built only on the CMake path: with an installed SDL3, or 3# The GameInput controller shim (SDL3, docs/gameinput.md) is built only on the CMake path: with an installed SDL3, or
4# with -FetchSdl3, which lets CMake download the pinned SDL3 release. The cl.exe fallback never builds it. 4# with -FetchSdl3, which lets CMake download the pinned SDL3 release. The cl.exe fallback never builds it.
@@ -58,8 +58,10 @@ if defined VULKAN_SDK cl /nologo /std:c++20 /EHsc /O2 /DWIN32_LEAN_AND_MEAN /DNO
58} 58}
59 59
60# A .cmd file avoids cmd.exe's quote stripping on paths with spaces. 60# A .cmd file avoids cmd.exe's quote stripping on paths with spaces.
61# Switch to UTF-8 (CP 65001) before invoking CMake/Ninja/cl.exe so non-English MSVC /showIncludes prefixes
62# (e.g. Spanish "Nota: inclusión del archivo:") match Ninja's msvc_deps_prefix instead of being mojibaked in OEM CP.
61$bat = Join-Path $out "_build.cmd" 63$bat = Join-Path $out "_build.cmd"
62"@echo off`r`nset `"PATH=$installer;%PATH%`"`r`ncall `"$vcvars`" >nul || exit /b 1`r`n$body" | Set-Content -Encoding ascii $bat 64"@echo off`r`nchcp 65001 >nul`r`nset `"PATH=$installer;%PATH%`"`r`ncall `"$vcvars`" >nul || exit /b 1`r`n$body" | Set-Content -Encoding ascii $bat
63 65
64$p = Start-Process cmd.exe -ArgumentList "/c", "`"$bat`"" -NoNewWindow -PassThru 66$p = Start-Process cmd.exe -ArgumentList "/c", "`"$bat`"" -NoNewWindow -PassThru
65$null = $p.Handle # keeps the exit code readable after WaitForExit 67$null = $p.Handle # keeps the exit code readable after WaitForExit
diff --git a/scripts/run_gpu_tests.py b/scripts/run_gpu_tests.py
index a1e98d40a..9361c1011 100644
--- a/scripts/run_gpu_tests.py
+++ b/scripts/run_gpu_tests.py
@@ -25,7 +25,7 @@ sys.path.insert(0, os.path.join(ROOT, "tools"))
25import mc_command # noqa: E402 25import mc_command # noqa: E402
26sys.path.insert(0, SHADER_DIR) 26sys.path.insert(0, SHADER_DIR)
27from build import CLIP_CASES, clip_container, shader_source 27from build import CLIP_CASES, clip_container, shader_source
28from check import Skip, clip_test, fmt_1010102_test, fmt_xy_xyz_test 28from check import Skip, clip_test, fmt_1010102_test, fmt_sint32_test, fmt_xy_xyz_test
29from compute_fixture import compute_header 29from compute_fixture import compute_header
30from check import SAMPLER_CASES, sampler_test # ps_ssharp: the S#/T# mip fields (vk_sampler_test) 30from check import SAMPLER_CASES, sampler_test # ps_ssharp: the S#/T# mip fields (vk_sampler_test)
31from check import (CMPX_CLASS_WORDS, CVT_F32_SAT_CASES, GRADIENT_TESTS, TEST_PROGRAMS, TEXTURE_MIP_DEPENDENCIES, 31from check import (CMPX_CLASS_WORDS, CVT_F32_SAT_CASES, GRADIENT_TESTS, TEST_PROGRAMS, TEXTURE_MIP_DEPENDENCIES,
@@ -40,6 +40,7 @@ from check import (WAVE32_LANE_DUMPS, WAVE32_LANE_ENV, bitmask_perm_narrow_skip,
40 vcmpx_forms_narrow_skip, wave32_lane_skip) # as in check.py 40 vcmpx_forms_narrow_skip, wave32_lane_skip) # as in check.py
41from check import PIXEL_VERTEX, VINT_ENV, interp_f16_high_problem, ij_computed_problem # pixel producers and checks 41from check import PIXEL_VERTEX, VINT_ENV, interp_f16_high_problem, ij_computed_problem # pixel producers and checks
42from check import GET_LOD_TESTS, STORE_WORDS, get_lod_test, store_words_problem # TEST-184: image atomics and queries 42from check import GET_LOD_TESTS, STORE_WORDS, get_lod_test, store_words_problem # TEST-184: image atomics and queries
43from check import wide_pixel_skip # ps_w64x_readlane: judged only where the fragment stage was required 64-wide
43 44
44 45
45def make_dxbc(chunks: list[tuple[bytes, bytes]]) -> bytes: 46def make_dxbc(chunks: list[tuple[bytes, bytes]]) -> bytes:
@@ -553,7 +554,7 @@ OTHER_HARNESS = {"ps_m15": "d3d12_translated_draw_test", "vs_m15": "d3d12_transl
553# Shaders a selected test draws with, built even when the filter leaves them out (#192). 554# Shaders a selected test draws with, built even when the filter leaves them out (#192).
554DRAWN_WITH = {GATHER_LOD_TEST: "vs_ids.asm", "ps_flat": "vs_ids.asm", "ps_texture_sample": "vs_ids.asm", "ps_cube_sample": "vs_ids.asm", 555DRAWN_WITH = {GATHER_LOD_TEST: "vs_ids.asm", "ps_flat": "vs_ids.asm", "ps_texture_sample": "vs_ids.asm", "ps_cube_sample": "vs_ids.asm",
555 "ps_texture_sample_d16": "vs_ids.asm", "ps_sample_c_lz": "vs_ids.asm", "ps_sample_c_lz_a16": "vs_ids.asm", 556 "ps_texture_sample_d16": "vs_ids.asm", "ps_sample_c_lz": "vs_ids.asm", "ps_sample_c_lz_a16": "vs_ids.asm",
556 **{name: "vs_ids.asm" for name in TEXTURE_CONSTANTS}, "ps_ssharp": "vs_ids.asm", 557 **{name: "vs_ids.asm" for name in TEXTURE_CONSTANTS}, "ps_ssharp": "vs_ids.asm", "ps_imgatomic": "vs_ids.asm",
557 **{name: "vs_ids.asm" for name in GRADIENT_TESTS}, "vs_clip": "ps_clip_color.asm", 558 **{name: "vs_ids.asm" for name in GRADIENT_TESTS}, "vs_clip": "ps_clip_color.asm",
558 "ps_interp_f16_high": "vs_f16_pack.asm", "ms_f16_pack": "ps_interp_f16_high.asm", 559 "ps_interp_f16_high": "vs_f16_pack.asm", "ms_f16_pack": "ps_interp_f16_high.asm",
559 "ps_interp_f32_mods": "vs_interp_consts.asm", "ps_interp_mov_mods": "vs_interp_consts.asm", 560 "ps_interp_f32_mods": "vs_interp_consts.asm", "ps_interp_mov_mods": "vs_interp_consts.asm",
@@ -761,6 +762,12 @@ def run_suite(a, work: str) -> int:
761 for fname in asm_files: 762 for fname in asm_files:
762 name = os.path.splitext(fname)[0] 763 name = os.path.splitext(fname)[0]
763 spv = os.path.join(spirv_dir, f"{name}.spv") 764 spv = os.path.join(spirv_dir, f"{name}.spv")
765 if name == "ps_ij_computed" and (bary_fallback() or f16_interp_fallback()):
766 # Before the .spv check: without PerVertexKHR inputs the translator refuses a computed I/J pair, so there
767 # is no .spv (the f16 fallback is on by default where PerVertexKHR doesn't compile: MoltenVK).
768 results.append((name, None, "SKIP (computed I/J pairs need PerVertexKHR inputs: "
769 "no --bary-fallback / --f16-interp-fallback)"))
770 continue
764 if not os.path.isfile(spv): 771 if not os.path.isfile(spv):
765 results.append((name, False, "missing .spv (translation failed)")) 772 results.append((name, False, "missing .spv (translation failed)"))
766 continue 773 continue
@@ -831,6 +838,9 @@ def run_suite(a, work: str) -> int:
831 elif name == "cs_fmt_1010102": 838 elif name == "cs_fmt_1010102":
832 problem = fmt_1010102_test(a.build, spirv_dir, cs_env) 839 problem = fmt_1010102_test(a.build, spirv_dir, cs_env)
833 results.append((name, not problem, problem or "64/64 dumped words exact")) 840 results.append((name, not problem, problem or "64/64 dumped words exact"))
841 elif name == "cs_fmt_sint32":
842 problem = fmt_sint32_test(a.build, spirv_dir, cs_env)
843 results.append((name, not problem, problem or "64/64 dumped words exact"))
834 elif name == "cs_fmt_xy_xyz": 844 elif name == "cs_fmt_xy_xyz":
835 # TEST-185: xy/xyz format loads and stores, words measured natively on a Radeon 680M (the .asm header) 845 # TEST-185: xy/xyz format loads and stores, words measured natively on a Radeon 680M (the .asm header)
836 problem = fmt_xy_xyz_test(a.build, spirv_dir, cs_env) 846 problem = fmt_xy_xyz_test(a.build, spirv_dir, cs_env)
@@ -866,7 +876,7 @@ def run_suite(a, work: str) -> int:
866 # Whole-wave mask test, as in check.py: needs a 64-wide subgroup, skipped where the device has none. 876 # Whole-wave mask test, as in check.py: needs a 64-wide subgroup, skipped where the device has none.
867 # With LEONIDA_W64_EMULATE=1 it was translated with --wave64-emulate and runs on any subgroup size. 877 # With LEONIDA_W64_EMULATE=1 it was translated with --wave64-emulate and runs on any subgroup size.
868 results.append((name,) + wavemask_check(vk_compute, spv, cs_env, w64_emulated())) 878 results.append((name,) + wavemask_check(vk_compute, spv, cs_env, w64_emulated()))
869 elif name in ("cs_store", "cs_smem_soffset_imm", "cs_w32_lane_wrap", "cs_movrelsd_2", "cs_w32_permute", "cs_exec_const", "cs_w32_mask_imm", "cs_w64_mask_imm", "cs_w32_lds_u8_d16", "cs_w32_int_ext", "cs_w32_salu64", "cs_w32_misc_ext", "cs_w32_new_ops", "cs_wave64_ballot", "cs_wm_half_ops", "cs_wm_half_cmp", "cs_wm_bfm64", "cs_wm_scc_rfl", "cs_wqm_w64", "cs_wqm_w32", "cs_wqm_w64_half", 879 elif name in ("cs_store", "cs_smem_soffset_imm", "cs_w32_lane_wrap", "cs_movrelsd_2", "cs_w32_permute", "cs_w32_sincos", "cs_exec_const", "cs_w32_mask_imm", "cs_w64_mask_imm", "cs_w32_lds_u8_d16", "cs_w32_int_ext", "cs_w32_salu64", "cs_w32_misc_ext", "cs_w32_new_ops", "cs_wave64_ballot", "cs_wm_half_ops", "cs_wm_half_cmp", "cs_wm_bfm64", "cs_wm_scc_rfl", "cs_wqm_w64", "cs_wqm_w32", "cs_wqm_w64_half",
870 "cs_dpp", "cs_dpp_row", "cs_dpp_mask", "cs_dpp8", "cs_dpp_ops", "cs_dpp_bank", "cs_dpp_fi", 880 "cs_dpp", "cs_dpp_row", "cs_dpp_mask", "cs_dpp8", "cs_dpp_ops", "cs_dpp_bank", "cs_dpp_fi",
871 "cs_dpp_bound", "cs_dpp_w64", 881 "cs_dpp_bound", "cs_dpp_w64",
872 "cs_w64_mask_detect", 882 "cs_w64_mask_detect",
@@ -937,6 +947,7 @@ def run_suite(a, work: str) -> int:
937 "cs_w64x_partial": [40, 40, 528, 0, 0, 532, 539, 524820], 947 "cs_w64x_partial": [40, 40, 528, 0, 0, 532, 539, 524820],
938 "cs_w64x_partial_scmp": [0, 1, 0, 1, 1, 1, 1, 0], # s_cmp mask, -1 in a partial wave 948 "cs_w64x_partial_scmp": [0, 1, 0, 1, 1, 1, 1, 0], # s_cmp mask, -1 in a partial wave
939 "cs_w32_partial_scmp": [0, 1, 1, 0, 1, 1, 1, 1], # the same in a 20-thread wave32 949 "cs_w32_partial_scmp": [0, 1, 1, 0, 1, 1, 1, 1], # the same in a 20-thread wave32
950 "cs_w32_sincos": [1, 1, 1, 1, 1, 1], # SHADER-88 (cs_w32_sincos.asm): angles in turns
940 "cs_w64x_sbarrier": [605, 605, 686, 686, 3032, 3013, 3032, 3031], 951 "cs_w64x_sbarrier": [605, 605, 686, 686, 3032, 3013, 3032, 3031],
941 "cs_w64x_load_ballot_load": [43, 74, 75, 42, 42, 18, 41, 32], 952 "cs_w64x_load_ballot_load": [43, 74, 75, 42, 42, 18, 41, 32],
942 "cs_w64x_andn2_exec": [1, 16, 32, 4144, 2052, 3, 8, 1544], # s_andn2_saveexec/wrexec_b64 (.asm header) 953 "cs_w64x_andn2_exec": [1, 16, 32, 4144, 2052, 3, 8, 1544], # s_andn2_saveexec/wrexec_b64 (.asm header)
@@ -951,7 +962,7 @@ def run_suite(a, work: str) -> int:
951 } 962 }
952 want = cs_dump_wants[name] 963 want = cs_dump_wants[name]
953 # Every dump but cs_store / cs_smem_soffset_imm / cs_w32_lane_wrap / cs_movrelsd_2 / cs_w32_permute / 964 # Every dump but cs_store / cs_smem_soffset_imm / cs_w32_lane_wrap / cs_movrelsd_2 / cs_w32_permute /
954 # cs_w32_lds_u8_d16 / cs_w32_int_ext / cs_w32_salu64 / cs_w32_misc_ext / cs_w32_new_ops, the wave32 965 # cs_w32_lds_u8_d16 / cs_w32_sincos / cs_w32_int_ext / cs_w32_salu64 / cs_w32_misc_ext / cs_w32_new_ops, the wave32
955 # cs_wqm_w32 / cs_bpermute32 and the DPP tests is a whole-wave (wave64) mask test: ask for a 64-wide subgroup and skip, 966 # cs_wqm_w32 / cs_bpermute32 and the DPP tests is a whole-wave (wave64) mask test: ask for a 64-wide subgroup and skip,
956 # as check.py does, where the device has none 967 # as check.py does, where the device has none
957 # (vk_compute_test exits 77) instead of reporting a failure. With LEONIDA_W64_EMULATE=1 they were 968 # (vk_compute_test exits 77) instead of reporting a failure. With LEONIDA_W64_EMULATE=1 they were
@@ -963,7 +974,7 @@ def run_suite(a, work: str) -> int:
963 wave64 = name not in ("cs_store", "cs_smem_soffset_imm", "cs_wqm_w32", "cs_w32_lane_wrap", "cs_movrelsd_2", 974 wave64 = name not in ("cs_store", "cs_smem_soffset_imm", "cs_wqm_w32", "cs_w32_lane_wrap", "cs_movrelsd_2",
964 "cs_w32_permute", "cs_barrier_divergent", "cs_barrier_early_end", "cs_barrier_loop", 975 "cs_w32_permute", "cs_barrier_divergent", "cs_barrier_early_end", "cs_barrier_loop",
965 "cs_w32_lds_u8_d16", "cs_w32_int_ext", "cs_w32_salu64", "cs_w32_misc_ext", "cs_w32_new_ops", 976 "cs_w32_lds_u8_d16", "cs_w32_int_ext", "cs_w32_salu64", "cs_w32_misc_ext", "cs_w32_new_ops",
966 "cs_bpermute32", "cs_w32_partial_scmp", 977 "cs_bpermute32", "cs_w32_partial_scmp", "cs_w32_sincos",
967 "cs_exec_const", "cs_w32_mask_imm", "cs_dpp", "cs_dpp_row", "cs_dpp_mask", "cs_dpp8", 978 "cs_exec_const", "cs_w32_mask_imm", "cs_dpp", "cs_dpp_row", "cs_dpp_mask", "cs_dpp8",
968 "cs_dpp_ops", "cs_dpp_bound", "cs_dpp_bank", "cs_dpp_fi") and not emulated and not partial 979 "cs_dpp_ops", "cs_dpp_bound", "cs_dpp_bank", "cs_dpp_fi") and not emulated and not partial
969 if partial and not emulated: 980 if partial and not emulated:
@@ -1037,10 +1048,12 @@ def run_suite(a, work: str) -> int:
1037 else: 1048 else:
1038 results.append((name, rc == 0 and bad == 0, "4096/4096 pixels exact" if bad == 0 else 1049 results.append((name, rc == 0 and bad == 0, "4096/4096 pixels exact" if bad == 0 else
1039 f"{bad} pixels differ from {expected}: {msg.splitlines()[-1] if msg else ''}")) 1050 f"{bad} pixels differ from {expected}: {msg.splitlines()[-1] if msg else ''}"))
1040 elif name == "ps_tex": 1051 elif name in ("ps_tex", "ps_imgatomic"):
1041 # A texture through the descriptor hash table and the bindless set. vk_bindless_test compares the 1052 # A texture through the descriptor hash table and the bindless set (ps_tex), or image atomics in a pixel
1042 # pixels itself, and exits 77 where the device lacks a feature the set or the shader needs. 1053 # shader through the set's r32ui storage arrays (ps_imgatomic, drawn with vs_ids). vk_bindless_test
1043 rc, msg = run_cmd([vk_bindless, vs_tri, spv]) 1054 # compares the result itself, and exits 77 where the device lacks a feature the set or shader needs.
1055 vs = os.path.join(spirv_dir, "vs_ids.spv") if name == "ps_imgatomic" else vs_tri
1056 rc, msg = run_cmd([vk_bindless, vs, spv])
1044 lines = msg.splitlines() 1057 lines = msg.splitlines()
1045 if rc == 77: 1058 if rc == 77:
1046 reason = next((ln for ln in lines if ln.startswith("unsupported:")), "unsupported device") 1059 reason = next((ln for ln in lines if ln.startswith("unsupported:")), "unsupported device")
@@ -1072,7 +1085,7 @@ def run_suite(a, work: str) -> int:
1072 raw = os.path.join(raw_dir, f"{name}.raw") 1085 raw = os.path.join(raw_dir, f"{name}.raw")
1073 vs = os.path.join(spirv_dir, "vs_ids.spv") if name == "ps_flat" else vs_tri # check.py draws ps_flat with vs_ids 1086 vs = os.path.join(spirv_dir, "vs_ids.spv") if name == "ps_flat" else vs_tri # check.py draws ps_flat with vs_ids
1074 if name in PIXEL_VERTEX: 1087 if name in PIXEL_VERTEX:
1075 if bary_fallback() and name in ("ps_interp_f16_high", "ps_ij_computed"): # no PerVertexKHR inputs 1088 if bary_fallback() and name == "ps_interp_f16_high": # no PerVertexKHR inputs under --bary-fallback
1076 results.append((name, None, "SKIP (per-vertex f16 interpolants need barycentrics)")) 1089 results.append((name, None, "SKIP (per-vertex f16 interpolants need barycentrics)"))
1077 continue 1090 continue
1078 vs = os.path.join(spirv_dir, PIXEL_VERTEX[name] + ".spv") 1091 vs = os.path.join(spirv_dir, PIXEL_VERTEX[name] + ".spv")
@@ -1105,6 +1118,8 @@ def run_suite(a, work: str) -> int:
1105 "ps_vcmpx_forms": (0xF05B2A48, 0xF05E8A12, 0xB174BE18, 0x15550000), # 14 v_cmpx forms (.asm header) 1118 "ps_vcmpx_forms": (0xF05B2A48, 0xF05E8A12, 0xB174BE18, 0x15550000), # 14 v_cmpx forms (.asm header)
1106 "ps_med3_mods": (0x3F800000, 0x40400000, 0x40C00000, 0x3F400000), 1119 "ps_med3_mods": (0x3F800000, 0x40400000, 0x40C00000, 0x3F400000),
1107 "ps_scc_minmax": (0x00030205, 0x00030207, 0x00030209, 0x00030203), 1120 "ps_scc_minmax": (0x00030205, 0x00030207, 0x00030209, 0x00030203),
1121 "ps_scc_logic32": (0x0fff0fff, 0x000f000f, 0xf00ff00f, 0x36),
1122 "ps_scc_logic64": (0x0fff0fff, 0xff000000, 0xff0000ff, 0x16),
1108 "ps_fma_literal": (0x41B80000, 0x41800000, 0x40E00000, 0x41A40000), 1123 "ps_fma_literal": (0x41B80000, 0x41800000, 0x40E00000, 0x41A40000),
1109 "ps_f64_mods": (0x40040000, 0x3FF00000, 0x3FE40000, 0x3FF00000), # needs shaderFloat64 1124 "ps_f64_mods": (0x40040000, 0x3FF00000, 0x3FE40000, 0x3FF00000), # needs shaderFloat64
1110 # f16 op_sel / partial writes / inline constants: RDNA2 hardware words (see the .asm headers) 1125 # f16 op_sel / partial writes / inline constants: RDNA2 hardware words (see the .asm headers)
@@ -1117,6 +1132,7 @@ def run_suite(a, work: str) -> int:
1117 "ps_f16_const": (0xAAAA3D00, 0x38005555, 0xAAAA3800, 0x3F000000), 1132 "ps_f16_const": (0xAAAA3D00, 0x38005555, 0xAAAA3800, 0x3F000000),
1118 "ps_f16_const2": (0x42003D00, 0x3D004200, 0xAAAABC00, 3), 1133 "ps_f16_const2": (0x42003D00, 0x3D004200, 0xAAAABC00, 3),
1119 "ps_f16_pack": (0x34003C00, 0x38003400, 0x34000000, 0x44004200), 1134 "ps_f16_pack": (0x34003C00, 0x38003400, 0x34000000, 0x44004200),
1135 "ps_f16_pack_mods": (0x4400B400, 0xC4003400, 0x4400C200, 0xB400B400),
1120 "ps_sff_imm": (2, 1, 20, 16), # SHADER-46: s_ff0/s_ff1 of an immediate 1136 "ps_sff_imm": (2, 1, 20, 16), # SHADER-46: s_ff0/s_ff1 of an immediate
1121 "ps_fnan_med3": (0x40A00000, 0xC0200000, 0xC0200000, 0x40600000), # measured on RDNA2 hardware 1137 "ps_fnan_med3": (0x40A00000, 0xC0200000, 0xC0200000, 0x40600000), # measured on RDNA2 hardware
1122 "ps_fnan_fract": (0x3F7FFFFF, 0x00003BFF, 0xC0200000, 0xC0200000), 1138 "ps_fnan_fract": (0x3F7FFFFF, 0x00003BFF, 0xC0200000, 0xC0200000),
@@ -1136,7 +1152,11 @@ def run_suite(a, work: str) -> int:
1136 "ps_vint_mul24": (0x13345678, 0xFFFFFFFD, 0x00007FFF, 0x0000FFFF), 1152 "ps_vint_mul24": (0x13345678, 0xFFFFFFFD, 0x00007FFF, 0x0000FFFF),
1137 "ps_vint_minmax": (0x7FFFFFFE, 0x80000001, 0x80000001, 0x7FFFFFFE), 1153 "ps_vint_minmax": (0x7FFFFFFE, 0x80000001, 0x80000001, 0x7FFFFFFE),
1138 "ps_vint_minmax3": (0xF0F0F0F0, 0xAB800000, 0xF0F0F0F0, 0xAB800000), 1154 "ps_vint_minmax3": (0xF0F0F0F0, 0xAB800000, 0xF0F0F0F0, 0xAB800000),
1155 "ps_w64x_readlane": (0x40000079, 0x40000010, 0x40000064, 0x400000BE), # same expectation as check.py
1139 } 1156 }
1157 if skip := wide_pixel_skip(name, msg): # a 64-wide pixel stage the device could not give: nothing to judge
1158 results.append((name, None, str(skip)))
1159 continue
1140 if name in const_wants: 1160 if name in const_wants:
1141 if name == "ps_vcmpx_forms" and (skip := vcmpx_forms_narrow_skip(msg)): 1161 if name == "ps_vcmpx_forms" and (skip := vcmpx_forms_narrow_skip(msg)):
1142 ok, detail = None, str(skip) 1162 ok, detail = None, str(skip)
diff --git a/scripts/run_wine_tests.py b/scripts/run_wine_tests.py
index b2736982f..b55ea9b91 100644
--- a/scripts/run_wine_tests.py
+++ b/scripts/run_wine_tests.py
@@ -8,6 +8,10 @@ Usage:
8made in (forward slashes, as `cygpath -m` prints it). Paths under it are mapped to --root, the Linux checkout (default: 8made in (forward slashes, as `cygpath -m` prints it). Paths under it are mapped to --root, the Linux checkout (default:
9this repository), which must hold the Windows build's runtime/build folder at the same place. 9this repository), which must hold the Windows build's runtime/build folder at the same place.
10 10
11Some tests open files through absolute paths compiled into them (the GLSL test shaders, LEONIDA_TEST_*_SPV under
12runtime/build/generated). For those, the drive of --windows-root is pointed at --root in the Wine prefix for the run
13($WINEPREFIX, else ~/.wine), unless that drive is already in use there.
14
11Every test is run and reported. The exit code is 1 if a test named by --require fails or is missing, else 0: the 15Every test is run and reported. The exit code is 1 if a test named by --require fails or is missing, else 0: the
12others show what does and doesn't work under Wine yet without failing the job. 16others show what does and doesn't work under Wine yet without failing the job.
13""" 17"""
@@ -17,8 +21,10 @@ import math
17import os 21import os
18import re 22import re
19import shlex 23import shlex
24import shutil
20import subprocess 25import subprocess
21import sys 26import sys
27import tempfile
22import time 28import time
23 29
24ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) 30ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
@@ -46,6 +52,51 @@ def map_path(arg: str, windows_root: str, root: str) -> str | None:
46 return None 52 return None
47 53
48 54
55class DriveMap:
56 """Points the drive of the Windows checkout at the Linux one inside the Wine prefix, for the run.
57
58 A test that opens D:/a/Leonida/Leonida/runtime/build/generated/x.spv (a path compiled into it) then reads
59 <root>/runtime/build/generated/x.spv. The drive is a dosdevices link to a scratch folder holding a/Leonida/Leonida
60 as a link to the root; both are removed afterwards. A drive the prefix already has (c:, z:, or one set up by
61 hand) is left alone, and so is a root without a drive letter.
62 """
63
64 def __init__(self, windows_root: str, root: str, prefix: str):
65 self.windows_root, self.root, self.prefix = norm(windows_root), os.path.abspath(root), prefix
66 self.link = self.scratch = None
67 self.note = ""
68
69 def __enter__(self):
70 m = re.fullmatch(r"([A-Za-z]):/(.+)", self.windows_root)
71 if not m:
72 self.note = f"{self.windows_root} has no drive letter: no drive mapped"
73 return self
74 drive, rest = m.group(1).lower(), [p for p in m.group(2).split("/") if p]
75 dosdevices = os.path.join(self.prefix, "dosdevices")
76 link = os.path.join(dosdevices, drive + ":")
77 if not os.path.isdir(dosdevices):
78 self.note = f"no Wine prefix at {self.prefix}: drive {drive}: not mapped"
79 return self
80 if os.path.lexists(link):
81 self.note = f"drive {drive}: is already set in {dosdevices}: left as it is"
82 return self
83 self.scratch = tempfile.mkdtemp(prefix="wine-drive-")
84 parent = os.path.join(self.scratch, *rest[:-1])
85 os.makedirs(parent, exist_ok=True)
86 os.symlink(self.root, os.path.join(parent, rest[-1]))
87 os.symlink(self.scratch, link)
88 self.link = link
89 self.note = f"drive {drive}: maps {self.windows_root} to {self.root} for this run"
90 return self
91
92 def __exit__(self, *exc):
93 if self.link and os.path.islink(self.link):
94 os.unlink(self.link)
95 if self.scratch:
96 shutil.rmtree(self.scratch, ignore_errors=True) # removes the links, never what they point to
97 return False
98
99
49def wine_path(path: str) -> str: 100def wine_path(path: str) -> str:
50 """Wine's Z: drive is the Unix root, so a Windows program reads /x/y as Z:\\x\\y.""" 101 """Wine's Z: drive is the Unix root, so a Windows program reads /x/y as Z:\\x\\y."""
51 return "Z:" + os.path.abspath(path).replace("/", "\\") 102 return "Z:" + os.path.abspath(path).replace("/", "\\")
@@ -175,14 +226,17 @@ def main() -> int:
175 return 2 226 return 2
176 wine = args.wine 227 wine = args.wine
177 results = {} 228 results = {}
178 for test in tests: 229 prefix = os.environ.get("WINEPREFIX") or os.path.join(os.path.expanduser("~"), ".wine")
179 name = test.get("name", "?") 230 with DriveMap(args.windows_root, args.root, prefix) as drive:
180 status, detail = run_test(test, args, wine) 231 print(drive.note, flush=True)
181 results[name] = status 232 for test in tests:
182 print(f"[{status.upper()}] {name}", flush=True) 233 name = test.get("name", "?")
183 if status != "pass": 234 status, detail = run_test(test, args, wine)
184 for line in detail.rstrip().splitlines()[-40:]: 235 results[name] = status
185 print(f" {line}") 236 print(f"[{status.upper()}] {name}", flush=True)
237 if status != "pass":
238 for line in detail.rstrip().splitlines()[-40:]:
239 print(f" {line}")
186 240
187 missing = [n for n in args.require if n not in results] 241 missing = [n for n in args.require if n not in results]
188 failed_required = [n for n in args.require if results.get(n) != "pass"] 242 failed_required = [n for n in args.require if results.get(n) != "pass"]
diff --git a/tests/semantic/README.md b/tests/semantic/README.md
index cef5723fc..65b741083 100644
--- a/tests/semantic/README.md
+++ b/tests/semantic/README.md
@@ -85,6 +85,10 @@ What they check (`tools/rdna2spirv.py`, pixel shaders plus one compute shader):
85 undefined in SPIR-V (`UndefinedResult`); a "lane mod 32" model of issue #94 gives the words a 32-wide GPU 85 undefined in SPIR-V (`UndefinedResult`); a "lane mod 32" model of issue #94 gives the words a 32-wide GPU
86 shows (all 24 matched on an RTX 4070 SUPER, driver 610.88, without `--wave64-emulate`). Two SPIR-V sabotages (readlane lane & 31, bpermute without its half base) must change the 86 shows (all 24 matched on an RTX 4070 SUPER, driver 610.88, without `--wave64-emulate`). Two SPIR-V sabotages (readlane lane & 31, bpermute without its half base) must change the
87 64-wide result. 87 64-wide result.
88- `test_w64x_scalar_load_order.py` translates wave64 programs with `--wave64-emulate` and checks the emitted rounds:
89 no case of the round loop's switch reads or writes buffer memory after a write, or writes after a read, so a
90 `buffer_store` and a later `s_load` / `s_buffer_load` of the wave (and a scalar load and a later store) run in
91 different rounds (#1587). Loads alone share a round.
88- `test_wave64_subgroup_ops.py` runs eight more wave64 GPU tests the same way (`cs_w64x_ballot`, 92- `test_wave64_subgroup_ops.py` runs eight more wave64 GPU tests the same way (`cs_w64x_ballot`,
89 `_readfirstlane`, `_load_ballot_load`, `_partial`, `cs_wave64_ballot`, `cs_wm_bfm64`, `cs_wm_half_cmp`, 93 `_readfirstlane`, `_load_ballot_load`, `_partial`, `cs_wave64_ballot`, `cs_wm_bfm64`, `cs_wm_half_cmp`,
90 `cs_wavemask`): on one 64-wide subgroup every word equals the GPU check; on two 32-wide subgroups the 94 `cs_wavemask`): on one 64-wide subgroup every word equals the GPU check; on two 32-wide subgroups the
diff --git a/tests/semantic/fixtures/disasm/cs_fmt_sint32.s b/tests/semantic/fixtures/disasm/cs_fmt_sint32.s
new file mode 100644
index 000000000..ecacaa055
--- /dev/null
+++ b/tests/semantic/fixtures/disasm/cs_fmt_sint32.s
@@ -0,0 +1,64 @@
1; cs_fmt_sint32 test fixture generated by tests/semantic/regen_fixtures.py from runtime/test/shaders/cs_fmt_sint32.asm
2 v_cmpx_eq_u32_e32 0, v0
3 v_mov_b32_e32 v1, 0x80000000
4 v_mov_b32_e32 v2, 0x7fffffff
5 v_mov_b32_e32 v3, -3
6 v_mov_b32_e32 v4, 17
7 v_mov_b32_e32 v5, 0x80
8 buffer_store_dwordx4 v[1:4], v5, s[0:3], 0 offen
9 s_mov_b32 s4, s0
10 s_mov_b32 s5, s1
11 s_mov_b32 s6, s2
12 s_mov_b32 s7, 0x3103f32c
13 buffer_load_format_xyzw v[8:11], v5, s[4:7], 0 offen
14 v_mov_b32_e32 v6, 0x0
15 buffer_store_dwordx4 v[8:11], v6, s[0:3], 0 offen
16 s_mov_b32 s7, 0x31049fac
17 buffer_load_format_xyzw v[8:11], v5, s[4:7], 0 offen
18 v_mov_b32_e32 v6, 0x10
19 buffer_store_dwordx4 v[8:11], v6, s[0:3], 0 offen
20 s_mov_b32 s7, 0x3104cfac
21 buffer_load_format_xyzw v[8:11], v5, s[4:7], 0 offen
22 v_mov_b32_e32 v6, 0x20
23 buffer_store_dwordx4 v[8:11], v6, s[0:3], 0 offen
24 s_mov_b32 s7, 0x31016000
25 tbuffer_load_format_xyzw v[8:11], v5, s[4:7], 0 format:[BUF_FMT_32_32_SINT] offen
26 v_mov_b32_e32 v6, 0x30
27 buffer_store_dwordx4 v[8:11], v6, s[0:3], 0 offen
28 tbuffer_load_format_xyzw v[8:11], v5, s[4:7], 0 format:[BUF_FMT_32_32_32_SINT] offen
29 v_mov_b32_e32 v6, 0x40
30 buffer_store_dwordx4 v[8:11], v6, s[0:3], 0 offen
31 tbuffer_load_format_xyzw v[8:11], v5, s[4:7], 0 format:[BUF_FMT_32_32_32_32_SINT] offen
32 v_mov_b32_e32 v6, 0x50
33 buffer_store_dwordx4 v[8:11], v6, s[0:3], 0 offen
34 s_mov_b32 s7, 0x3104cfac
35 buffer_load_format_d16_xyzw v[8:9], v5, s[4:7], 0 offen
36 v_mov_b32_e32 v6, 0x60
37 buffer_store_dwordx2 v[8:9], v6, s[0:3], 0 offen
38 s_mov_b32 s7, 0x31016000
39 tbuffer_load_format_d16_xyzw v[8:9], v5, s[4:7], 0 format:[BUF_FMT_32_32_32_32_SINT] offen
40 v_mov_b32_e32 v6, 0x68
41 buffer_store_dwordx2 v[8:9], v6, s[0:3], 0 offen
42 s_mov_b32 s7, 0x31015004
43 buffer_load_format_x v8, v5, s[4:7], 0 offen offset:8
44 s_mov_b32 s7, 0x31016000
45 tbuffer_load_format_x v9, v5, s[4:7], 0 format:[BUF_FMT_32_SINT] offen offset:8
46 v_mov_b32_e32 v6, 0x70
47 buffer_store_dwordx2 v[8:9], v6, s[0:3], 0 offen
48 s_mov_b32 s7, 0x3103ffac
49 v_mov_b32_e32 v6, 0x90
50 buffer_store_format_xy v[1:2], v6, s[4:7], 0 offen
51 s_mov_b32 s7, 0x31049fac
52 v_mov_b32_e32 v6, 0xa0
53 buffer_store_format_xyz v[1:3], v6, s[4:7], 0 offen
54 s_mov_b32 s7, 0x3104cfac
55 v_mov_b32_e32 v6, 0xb0
56 buffer_store_format_xyzw v[1:4], v6, s[4:7], 0 offen
57 s_mov_b32 s7, 0x3103ffac
58 v_mov_b32_e32 v6, 0xc0
59 v_mov_b32_e32 v7, 0x8000fffd
60 buffer_store_format_d16_xy v7, v6, s[4:7], 0 offen
61 s_mov_b32 s7, 0x31015004
62 v_mov_b32_e32 v6, 0xc8
63 buffer_store_format_x v3, v6, s[4:7], 0 offen
64 s_endpgm
diff --git a/tests/semantic/fixtures/disasm/ps_f16_pack_mods.s b/tests/semantic/fixtures/disasm/ps_f16_pack_mods.s
new file mode 100644
index 000000000..ad15acda2
--- /dev/null
+++ b/tests/semantic/fixtures/disasm/ps_f16_pack_mods.s
@@ -0,0 +1,9 @@
1; ps_f16_pack_mods test fixture generated by tests/semantic/regen_fixtures.py from runtime/test/shaders/ps_f16_pack_mods.asm
2 v_mov_b32 v0, 0x42003400
3 v_mov_b32 v1, 0x34004400
4 v_pack_b32_f16 v2, -v0, |v1|
5 v_pack_b32_f16 v3, v0, -v1
6 v_pack_b32_f16 v4, -|v0|, v1 op_sel:[1,0,0]
7 v_pack_b32_f16 v5, -v0, -|v1| op_sel:[0,1,0]
8 exp mrt0 v2, v3, v4, v5 done vm
9 s_endpgm
diff --git a/tests/semantic/regen_fixtures.py b/tests/semantic/regen_fixtures.py
index bbd8a2811..eafc903f2 100644
--- a/tests/semantic/regen_fixtures.py
+++ b/tests/semantic/regen_fixtures.py
@@ -19,7 +19,7 @@ FIXTURE_DIR = os.path.join(HERE, "fixtures", "disasm")
19SHADERS = ("cs_smem_bounds", "cs_smem_stride_align", "cs_smem_sload_neg", "cs_buf_tail", # SMEM / raw MUBUF bounds measured on RDNA2 19SHADERS = ("cs_smem_bounds", "cs_smem_stride_align", "cs_smem_sload_neg", "cs_buf_tail", # SMEM / raw MUBUF bounds measured on RDNA2
20 "ps_fnan_med3", "ps_fnan_fract", # float NaN / fract rows measured on RDNA2 hardware 20 "ps_fnan_med3", "ps_fnan_fract", # float NaN / fract rows measured on RDNA2 hardware
21 "ps_sdwa", "ps_ops", "ps_ops2", "ps_ops3", "ps_ops4", "ps_ops5", "ps_ops6", "ps_ops7", "ps_ops8", 21 "ps_sdwa", "ps_ops", "ps_ops2", "ps_ops3", "ps_ops4", "ps_ops5", "ps_ops6", "ps_ops7", "ps_ops8",
22 "ps_legacy_mul", "ps_vcc_x2", "ps_vcmpx_forms", "ps_flat", "cs_bounds", "cs_fmt_1010102", "cs_w64x_readlane", 22 "ps_legacy_mul", "ps_vcc_x2", "ps_vcmpx_forms", "ps_flat", "cs_bounds", "cs_fmt_1010102", "cs_fmt_sint32", "cs_w64x_readlane",
23 "cs_w64x_writelane", "cs_w64x_bpermute", "cs_w32_permute", "cs_w32_int_ext", "cs_w32_salu64", "cs_w32_misc_ext", "cs_w32_new_ops", "cs_w64x_permute", "cs_w64x_ballot", "cs_w64x_readfirstlane", 23 "cs_w64x_writelane", "cs_w64x_bpermute", "cs_w32_permute", "cs_w32_int_ext", "cs_w32_salu64", "cs_w32_misc_ext", "cs_w32_new_ops", "cs_w64x_permute", "cs_w64x_ballot", "cs_w64x_readfirstlane",
24 "cs_w64x_load_ballot_load", "cs_w64x_partial", "cs_wave64_ballot", "cs_wm_bfm64", "cs_wm_half_cmp", 24 "cs_w64x_load_ballot_load", "cs_w64x_partial", "cs_wave64_ballot", "cs_wm_bfm64", "cs_wm_half_cmp",
25 "cs_wavemask", "cs_cvt_f32_sat", "ps_scc_minmax", "ps_fma_literal", "ps_f16_vop2", 25 "cs_wavemask", "cs_cvt_f32_sat", "ps_scc_minmax", "ps_fma_literal", "ps_f16_vop2",
@@ -28,6 +28,7 @@ SHADERS = ("cs_smem_bounds", "cs_smem_stride_align", "cs_smem_sload_neg", "cs_bu
28 "cs_buf_swizzle", # swizzled MUBUF / ADD_TID (test_buffer_swizzle.py) 28 "cs_buf_swizzle", # swizzled MUBUF / ADD_TID (test_buffer_swizzle.py)
29 # TEST-175: GPU fixtures for the docs/design.md rules that were checked on the CPU only 29 # TEST-175: GPU fixtures for the docs/design.md rules that were checked on the CPU only
30 "ps_cmp_nlg", "ps_cvt_off", "ps_fmac_f16_mods", "ps_vop3_const_mods", "ps_interp_f32_mods", "ps_interp_mov_mods", 30 "ps_cmp_nlg", "ps_cvt_off", "ps_fmac_f16_mods", "ps_vop3_const_mods", "ps_interp_f32_mods", "ps_interp_mov_mods",
31 "ps_f16_pack_mods", # v_pack_b32_f16 neg/abs (SHADER-260)
31 "cs_w64x_andn2_exec", # s_andn2_saveexec_b64 / s_andn2_wrexec_b64 (test_andn2_exec_b64.py) 32 "cs_w64x_andn2_exec", # s_andn2_saveexec_b64 / s_andn2_wrexec_b64 (test_andn2_exec_b64.py)
32 "cs_w64x_saveexec_b64", # s_and/s_or/s_andn2_saveexec_b64, s_andn2_wrexec_b64 (test_saveexec_b64.py) 33 "cs_w64x_saveexec_b64", # s_and/s_or/s_andn2_saveexec_b64, s_andn2_wrexec_b64 (test_saveexec_b64.py)
33 "ps_valu16_mad", "ps_valu16_subrev", # v_mad_u32_u16 / v_mad_i32_i16, v_subrev_f16 34 "ps_valu16_mad", "ps_valu16_subrev", # v_mad_u32_u16 / v_mad_i32_i16, v_subrev_f16
diff --git a/tests/semantic/spirv_mini_interp.py b/tests/semantic/spirv_mini_interp.py
index dbc1c4317..05650dec8 100644
--- a/tests/semantic/spirv_mini_interp.py
+++ b/tests/semantic/spirv_mini_interp.py
@@ -37,6 +37,27 @@ class UnsupportedConstruct(NotImplementedError):
37 """The module uses something this interpreter deliberately does not model.""" 37 """The module uses something this interpreter deliberately does not model."""
38 38
39 39
40class InvalidModule(AssertionError):
41 """The module breaks a SPIR-V structural rule spirv-val enforces, so no driver would accept it, even though
42 this interpreter could run it. Raised instead of returning results for a shader that never reaches a GPU."""
43
44
45def check_structure(body):
46 """spirv-val's merge rule (SPIR-V 2.16.2): OpSelectionMerge must be the second-to-last instruction of its block,
47 directly before OpBranchConditional or OpSwitch, and OpLoopMerge directly before OpBranch or
48 OpBranchConditional. Until 2026-11-22 the interpreter skipped merges, so a translator change that put an
49 instruction between a merge and its branch (#1633: OpLoad %active) passed every semantic test while every
50 driver rejected the module. `body` is the list of (result, opcode, operands, line) of a function."""
51 follow = {"OpSelectionMerge": ("OpBranchConditional", "OpSwitch"),
52 "OpLoopMerge": ("OpBranch", "OpBranchConditional")}
53 for k, (_, op, _, line) in enumerate(body):
54 if op in follow:
55 nxt = body[k + 1][1] if k + 1 < len(body) else None
56 if nxt not in follow[op]:
57 raise InvalidModule(f"{line!r} is followed by {body[k + 1][3] if nxt else 'the end of the function'!r}"
58 f", not by {' or '.join(follow[op])}")
59
60
40# Instructions that carry no runtime semantics for a single-entry-point, straight-line module. 61# Instructions that carry no runtime semantics for a single-entry-point, straight-line module.
41_IGNORED = frozenset({ 62_IGNORED = frozenset({
42 "OpCapability", "OpExtension", "OpExtInstImport", "OpMemoryModel", "OpEntryPoint", "OpExecutionMode", 63 "OpCapability", "OpExtension", "OpExtInstImport", "OpMemoryModel", "OpEntryPoint", "OpExecutionMode",
@@ -463,6 +484,7 @@ def _invocation(text, inputs, push_constants, memory, step=False):
463 raise UnsupportedConstruct(f"{op} in module header") 484 raise UnsupportedConstruct(f"{op} in module header")
464 if not in_body: 485 if not in_body:
465 raise UnsupportedConstruct("no function body") 486 raise UnsupportedConstruct("no function body")
487 check_structure(body)
466 488
467 def deref(p): 489 def deref(p):
468 box, i = p 490 box, i = p
@@ -845,18 +867,6 @@ def _invocation(text, inputs, push_constants, memory, step=False):
845 values[res] = fma_f32(x, y, z) 867 values[res] = fma_f32(x, y, z)
846 elif op == "OpFNegate": 868 elif op == "OpFNegate":
847 values[res] = f32(-val(a[1])) 869 values[res] = f32(-val(a[1]))
848 elif op == "OpFDiv":
849 x, y = val(a[1]), val(a[2])
850 if not (isinstance(x, float) and isinstance(y, float)):
851 raise UnsupportedConstruct("OpFDiv on non-float")
852 if y == 0.0:
853 raise UnsupportedConstruct("OpFDiv by zero (undefined in SPIR-V)")
854 if math.isinf(x) and math.isinf(y):
855 values[res] = math.nan
856 elif math.isnan(x) or math.isnan(y):
857 values[res] = math.nan
858 else:
859 values[res] = f32(x / y) # x/inf is a signed zero, as in Python
860 elif op == "OpQuantizeToF16": 870 elif op == "OpQuantizeToF16":
861 # Single-instruction f32 -> f16 -> f32 round to nearest, with the 871 # Single-instruction f32 -> f16 -> f32 round to nearest, with the
862 # SPIR-V subnormal rule: a magnitude too small for a normal f16 872 # SPIR-V subnormal rule: a magnitude too small for a normal f16
diff --git a/tests/semantic/spirv_wave_interp.py b/tests/semantic/spirv_wave_interp.py
index db8f1e950..a3adf6544 100644
--- a/tests/semantic/spirv_wave_interp.py
+++ b/tests/semantic/spirv_wave_interp.py
@@ -38,6 +38,15 @@ class UnsupportedConstruct(NotImplementedError):
38 """The module uses something this interpreter deliberately does not model.""" 38 """The module uses something this interpreter deliberately does not model."""
39 39
40 40
41class InvalidModule(AssertionError):
42 """The module breaks spirv-val's merge rule (see spirv_mini_interp.check_structure): a merge instruction must
43 directly precede its block's branch. Raised instead of running a shader no driver would accept."""
44
45
46_MERGE_FOLLOW = {"OpSelectionMerge": ("OpBranchConditional", "OpSwitch"),
47 "OpLoopMerge": ("OpBranch", "OpBranchConditional")}
48
49
41class F: 50class F:
42 """A 32-bit float carried as its bit pattern.""" 51 """A 32-bit float carried as its bit pattern."""
43 __slots__ = ("bits",) 52 __slots__ = ("bits",)
@@ -120,6 +129,7 @@ class _Module:
120 self.id_type = {} 129 self.id_type = {}
121 cur = None 130 cur = None
122 in_body = False 131 in_body = False
132 merge_line = None # (opcode, line) of a merge whose branch has not been seen yet
123 for raw in text.splitlines(): 133 for raw in text.splitlines():
124 line = raw.strip() 134 line = raw.strip()
125 if not line: 135 if not line:
@@ -130,6 +140,11 @@ class _Module:
130 res, op, rest = m.groups() 140 res, op, rest = m.groups()
131 a = rest.split() 141 a = rest.split()
132 if in_body: 142 if in_body:
143 if merge_line is not None:
144 if op not in _MERGE_FOLLOW[merge_line[0]]:
145 raise InvalidModule(f"{merge_line[1]!r} is followed by {line!r}, not by "
146 f"{' or '.join(_MERGE_FOLLOW[merge_line[0]])}")
147 merge_line = None
133 if op == "OpFunctionEnd": 148 if op == "OpFunctionEnd":
134 in_body = False 149 in_body = False
135 continue 150 continue
@@ -149,6 +164,7 @@ class _Module:
149 cur.phis.append((res, a)) 164 cur.phis.append((res, a))
150 elif op in ("OpSelectionMerge", "OpLoopMerge"): 165 elif op in ("OpSelectionMerge", "OpLoopMerge"):
151 cur.merge = (op, a[0], a[1] if op == "OpLoopMerge" else None) 166 cur.merge = (op, a[0], a[1] if op == "OpLoopMerge" else None)
167 merge_line = (op, line)
152 elif op in _TERMINATORS: 168 elif op in _TERMINATORS:
153 cur.term = (op, a) 169 cur.term = (op, a)
154 cur = None 170 cur = None
diff --git a/tests/semantic/test_alu_bitop_folding.py b/tests/semantic/test_alu_bitop_folding.py
new file mode 100644
index 000000000..42a2bbd9a
--- /dev/null
+++ b/tests/semantic/test_alu_bitop_folding.py
@@ -0,0 +1,159 @@
1from __future__ import annotations
2
3"""Regression and semantic tests for bitwise and shift constant folding in the translator.
4
5Verifies that:
6- Constant and immediate shifts fold the modulo 32 mask at translate time (no runtime OpBitwiseAnd %c31).
7- Constant v_bfe_u32/i32 offset and width fold directly into OpBitField[US]Extract operands (no OpISub/OpULessThan/OpSelect).
8- Constant v_alignbyte_b32 with sel=0 folds directly to the low word; non-zero sel folds into exact shifts and OpBitwiseOr.
9- Constant v_alignbit_b32 with shift=0 folds directly to the low word; non-zero shift folds into exact shifts and OpBitwiseOr.
10- dedupe_types terminates early upon reaching function definitions and correctly renames aliased types across the shader.
11"""
12import os
13import re
14import struct
15import sys
16import tempfile
17import unittest
18import warnings
19
20HERE = os.path.dirname(os.path.abspath(__file__))
21ROOT = os.path.dirname(os.path.dirname(HERE))
22TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools")
23
24sys.dont_write_bytecode = True
25if TOOLS_DIR not in sys.path:
26 sys.path.insert(0, TOOLS_DIR)
27if HERE not in sys.path:
28 sys.path.insert(0, HERE)
29
30import rdna2spirv # noqa: E402
31import spirv_mini_interp as si # noqa: E402
32import support # noqa: E402
33
34STUB_DXBC = b"DXBC" + bytes(24) + struct.pack("<I", 0) + bytes(4)
35
36
37class BitopConstantFoldingTests(unittest.TestCase):
38 def translate_lines(self, lines: list[str]) -> str:
39 body = "\n".join("\t" + line for line in lines)
40 asm = f"; bitop_test\n{body}\n\texp mrt0 v0, v0, v0, v0 done vm\n\ts_endpgm\n"
41 with tempfile.TemporaryDirectory() as tmp:
42 d_dir = os.path.join(tmp, "disasm")
43 os.mkdir(d_dir)
44 s_path = os.path.join(d_dir, "ps_bitop.s")
45 with open(s_path, "w", encoding="utf-8") as f:
46 f.write(asm)
47 with open(os.path.join(tmp, "ps_bitop.dxbc"), "wb") as f:
48 f.write(STUB_DXBC)
49 with warnings.catch_warnings():
50 warnings.simplefilter("ignore", ResourceWarning)
51 return rdna2spirv.translate(s_path)
52
53 def test_constant_shift_eliminates_runtime_mask(self):
54 lines = [
55 "v_mov_b32 v1, 0x1234",
56 "v_lshlrev_b32 v0, 4, v1",
57 ]
58 spv = self.translate_lines(lines)
59 self.assertNotIn("OpBitwiseAnd %uint", spv)
60 self.assertIn("OpShiftLeftLogical %uint", spv)
61 res = si.run_fragment(spv)["%out_mrt0"][0]
62 self.assertEqual(res, 0x12340)
63
64 def test_constant_bfe_eliminates_runtime_bounds(self):
65 lines = [
66 "v_mov_b32 v1, 0x12345678",
67 "v_bfe_u32 v0, v1, 8, 12",
68 ]
69 spv = self.translate_lines(lines)
70 # Should directly emit OpBitFieldUExtract without runtime sub, cmp, or bounds select
71 self.assertNotIn("OpBitwiseAnd %uint", spv)
72 self.assertNotIn("OpISub %uint", spv)
73 self.assertNotIn("OpULessThan %bool", spv)
74 self.assertIn("OpBitFieldUExtract %uint", spv)
75 res = si.run_fragment(spv)["%out_mrt0"][0]
76 self.assertEqual(res, 0x456)
77
78 def test_constant_alignbyte_zero_shift_folds_directly(self):
79 lines = [
80 "v_mov_b32 v1, 0xDEADBEEF",
81 "v_mov_b32 v2, 0x12345678",
82 "v_alignbyte_b32 v0, v1, v2, 0",
83 ]
84 spv = self.translate_lines(lines)
85 self.assertNotIn("OpShiftRightLogical", spv)
86 self.assertNotIn("OpShiftLeftLogical", spv)
87 self.assertNotIn("OpBitwiseOr", spv)
88 res = si.run_fragment(spv)["%out_mrt0"][0]
89 self.assertEqual(res, 0x12345678)
90
91 def test_constant_alignbyte_nonzero_shift_emits_direct_shifts(self):
92 lines = [
93 "v_mov_b32 v1, 0x8899AABB",
94 "v_mov_b32 v2, 0x11223344",
95 "v_alignbyte_b32 v0, v1, v2, 1",
96 ]
97 spv = self.translate_lines(lines)
98 # Shift and or are emitted directly without runtime mask or sub
99 self.assertNotIn("OpBitwiseAnd %uint", spv)
100 self.assertNotIn("OpISub %uint", spv)
101 self.assertIn("OpShiftRightLogical %uint", spv)
102 self.assertIn("OpShiftLeftLogical %uint", spv)
103 self.assertIn("OpBitwiseOr %uint", spv)
104 res = si.run_fragment(spv)["%out_mrt0"][0]
105 self.assertEqual(res, 0xBB112233)
106
107 def test_constant_alignbit_zero_shift_folds_directly(self):
108 lines = [
109 "v_mov_b32 v1, 0xDEADBEEF",
110 "v_mov_b32 v2, 0x12345678",
111 "v_alignbit_b32 v0, v1, v2, 0",
112 ]
113 spv = self.translate_lines(lines)
114 self.assertNotIn("OpShiftRightLogical", spv)
115 self.assertNotIn("OpShiftLeftLogical", spv)
116 self.assertNotIn("OpBitwiseOr", spv)
117 res = si.run_fragment(spv)["%out_mrt0"][0]
118 self.assertEqual(res, 0x12345678)
119
120 def test_constant_alignbit_nonzero_shift_emits_direct_shifts(self):
121 lines = [
122 "v_mov_b32 v1, 0x12345678",
123 "v_mov_b32 v2, 0x9ABCDEF0",
124 "v_alignbit_b32 v0, v1, v2, 16",
125 ]
126 spv = self.translate_lines(lines)
127 self.assertNotIn("OpBitwiseAnd %uint", spv)
128 self.assertNotIn("OpISub %uint", spv)
129 self.assertIn("OpShiftRightLogical %uint", spv)
130 self.assertIn("OpShiftLeftLogical %uint", spv)
131 self.assertIn("OpBitwiseOr %uint", spv)
132 res = si.run_fragment(spv)["%out_mrt0"][0]
133 self.assertEqual(res, 0x56789ABC)
134
135 def test_dedupe_types_merges_duplicate_types_and_substitutes(self):
136 spv_sample = (
137 "OpCapability Shader\n"
138 "%uint = OpTypeInt 32 0\n"
139 "%v4uint = OpTypeVector %uint 4\n"
140 "%v4uint_st = OpTypeVector %uint 4\n"
141 "%ptr_v4uint = OpTypePointer StorageBuffer %v4uint\n"
142 "%ptr_v4uint_st = OpTypePointer StorageBuffer %v4uint_st\n"
143 "%fn = OpTypeFunction %void\n"
144 "%main = OpFunction %void None %fn\n"
145 "%entry = OpLabel\n"
146 "%var = OpVariable %ptr_v4uint_st StorageBuffer\n"
147 "%val = OpLoad %v4uint_st %var\n"
148 "OpReturn\n"
149 "OpFunctionEnd"
150 )
151 deduped = rdna2spirv.dedupe_types(spv_sample)
152 self.assertNotIn("%v4uint_st =", deduped)
153 self.assertNotIn("%ptr_v4uint_st =", deduped)
154 self.assertIn("%var = OpVariable %ptr_v4uint StorageBuffer", deduped)
155 self.assertIn("%val = OpLoad %v4uint %var", deduped)
156
157
158if __name__ == "__main__":
159 unittest.main()
diff --git a/tests/semantic/test_alu_dot4_i8.py b/tests/semantic/test_alu_dot4_i8.py
new file mode 100644
index 000000000..ff60a8508
--- /dev/null
+++ b/tests/semantic/test_alu_dot4_i8.py
@@ -0,0 +1,138 @@
1"""v_dot4_i32_i8 and v_dot4c_i32_i8: the dot product of the signed bytes of two dwords, plus an addend.
2
3ISA rule (RDNA2): D = S0.b0*S1.b0 + S0.b1*S1.b1 + S0.b2*S1.b2 + S0.b3*S1.b3 + addend, every byte sign-extended, the
4sum kept modulo 2^32. The addend is the third source for v_dot4_i32_i8 (VOP3P) and the old value of the destination
5for v_dot4c_i32_i8 (VOP2). The 29 FSPX programs of the package's upscaler DLL (docs/fspx.md) use the pair 27,271
6times.
7
8The expected words below were measured on RDNA2 hardware (gfx1036, the integrated GPU of a Ryzen 9 7950X3D, through
9tools/hw_oracle): each case ran `v_dot4_i32_i8 v8, v1, v2, v3`, `v_dot4c_i32_i8 v10, v1, v2` with v10 holding the
10addend, and the same with the two sources swapped. All three gave the word in the table, which the plain-Python
11reference `ref` reproduces. With `clamp` the hardware saturates v_dot4_i32_i8 to a signed 32-bit value
12(0x7fffffff and 0x80000000 in the two overflowing cases); the translator refuses that form.
13
14op_sel. The plain instruction has op_sel 0 and op_sel_hi 7. 89 words in 8 of those programs are v_dot4_i32_i8 with
15op_sel 2 and op_sel_hi 5, which llvm-mc does not decode (docs/fspx.md). Run on the same hardware as two raw words
16(0xCC165008 0x0C0E0501: v8 = v1 . v2 + v3 with those fields), that form gave the words of MEASURED_OP_SEL: the dot
17product with the two 16-bit halves of the second source exchanged, as op_sel selects halves for the packed 16-bit
18ops. `ref_op_sel` reproduces them; the translator refuses any op_sel on these two instructions until a listing can
19carry it.
20
21 python -m unittest discover -s tests/semantic -p test_alu_dot4_i8.py
22"""
23import os
24import sys
25import unittest
26
27HERE = os.path.dirname(os.path.abspath(__file__))
28if HERE not in sys.path:
29 sys.path.insert(0, HERE)
30
31import support # noqa: E402
32
33rdna2spirv = support.rdna2spirv
34
35# (S0, S1, addend, result measured on gfx1036)
36MEASURED = [
37 (0x01020304, 0x05060708, 0x00000000, 0x00000046), # 4*8 + 3*7 + 2*6 + 1*5 = 70
38 (0x01020304, 0x05060708, 0x000003E8, 0x0000042E), # 70 + 1000
39 (0xFF80017F, 0x7F7F80FF, 0x00000000, 0xFFFFBF02), # 127*-1 + 1*-128 + -128*127 + -1*127 = -16638
40 (0xFF80017F, 0x7F7F80FF, 0x00010000, 0x0000BF02),
41 (0x80808080, 0x80808080, 0x00000000, 0x00010000), # 4 * (-128 * -128)
42 (0x80808080, 0x7F7F7F7F, 0x00000005, 0xFFFF0205), # 4 * (-128 * 127) + 5
43 (0x7F7F7F7F, 0x7F7F7F7F, 0x7FFFFFFF, 0x8000FC03), # wraps upward: no saturation without clamp
44 (0x80808080, 0x7F7F7F7F, 0x80000000, 0x7FFF0200), # wraps downward
45 (0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0x00000003), # 4 * (-1 * -1) - 1
46 (0x00000000, 0x12345678, 0xDEADBEEF, 0xDEADBEEF),
47]
48
49
50# (S0, S1, addend, result measured on gfx1036 with op_sel 2 and op_sel_hi 5)
51MEASURED_OP_SEL = [
52 (0x04030201, 0x08070605, 0x00000000, 62), # the plain form gives 70
53 (0x04030201, 0x08070605, 0x000003E8, 1062),
54 (0x7F01FE80, 0x02FD7F81, 0x00000000, 16382), # the plain form gives 16253
55 (0x11223344, 0x55667788, 0x00010000, 74750), # the plain form gives 68358
56 (0xFFFFFFFF, 0x01020304, 0x00000007, 0xFFFFFFFD), # every byte of S0 the same: the order cannot show
57]
58
59
60def ref(a, b, addend):
61 def s8(x):
62 return x - 256 if x & 0x80 else x
63 total = sum(s8((a >> (8 * i)) & 0xFF) * s8((b >> (8 * i)) & 0xFF) for i in range(4))
64 return (total + addend) & 0xFFFFFFFF
65
66
67def ref_op_sel(a, b, addend):
68 """op_sel 2, op_sel_hi 5: the low half of the product reads the high half of S1 and the high half its low half."""
69 return ref(a, (b & 0xFFFF) << 16 | b >> 16, addend)
70
71
72def program(a, b, addend):
73 """mrt0 = (v_dot4_i32_i8, v_dot4c_i32_i8, v_dot4c_i32_i8 with the sources swapped, v_dot4_i32_i8 with the
74 sources and the addend taken from SGPRs and a literal, as the shaders do)."""
75 return [
76 f"v_mov_b32_e32 v1, 0x{a:08x}",
77 f"v_mov_b32_e32 v2, 0x{b:08x}",
78 f"v_mov_b32_e32 v3, 0x{addend:08x}",
79 f"s_mov_b32 s4, 0x{addend:08x}",
80 "v_dot4_i32_i8 v8, v1, v2, v3",
81 f"v_mov_b32_e32 v9, 0x{addend:08x}",
82 "v_dot4c_i32_i8 v9, v1, v2",
83 f"v_mov_b32_e32 v10, 0x{addend:08x}",
84 "v_dot4c_i32_i8 v10, v2, v1",
85 f"v_dot4_i32_i8 v11, v1, 0x{b:08x}, s4",
86 "exp mrt0 v8, v9, v10, v11 done vm",
87 "s_endpgm",
88 ]
89
90
91class Dot4I8(unittest.TestCase):
92 def test_the_reference_reproduces_the_hardware_words(self):
93 for a, b, addend, measured in MEASURED:
94 self.assertEqual(ref(a, b, addend), measured, f"{a:#x} . {b:#x} + {addend:#x}")
95
96 def test_both_forms_give_the_hardware_words(self):
97 for a, b, addend, measured in MEASURED:
98 with self.subTest(a=f"{a:#010x}", b=f"{b:#010x}", addend=f"{addend:#010x}"):
99 spv = support.translate_lines("ps_dot4_i8", program(a, b, addend))
100 self.assertEqual(support.mrt0_words(spv), [measured] * 4)
101
102 def test_the_accumulating_form_reads_its_destination(self):
103 # v9 is never written before v_dot4c reads it: the old value is then the register's initial 0, not garbage
104 # from an expression that dropped the addend. 70 is the dot product alone.
105 lines = ["v_mov_b32_e32 v1, 0x01020304", "v_mov_b32_e32 v2, 0x05060708", "v_dot4c_i32_i8 v9, v1, v2",
106 "v_dot4c_i32_i8 v9, v1, v2", "exp mrt0 v9, v9, v9, v9 done vm", "s_endpgm"]
107 self.assertEqual(support.mrt0_words(support.translate_lines("ps_dot4c_twice", lines)), [140] * 4)
108
109 def test_the_bytes_are_signed(self):
110 # 0xff * 0x01: -1 as a signed byte, 255 as an unsigned one.
111 lines = ["v_mov_b32_e32 v1, 0x000000ff", "v_mov_b32_e32 v2, 0x00000001", "v_mov_b32_e32 v3, 0",
112 "v_dot4_i32_i8 v8, v1, v2, v3", "exp mrt0 v8, v8, v8, v8 done vm", "s_endpgm"]
113 self.assertEqual(support.mrt0_words(support.translate_lines("ps_dot4_signed", lines)), [0xFFFFFFFF] * 4)
114
115 def test_the_op_sel_reference_reproduces_the_hardware_words(self):
116 for a, b, addend, measured in MEASURED_OP_SEL:
117 self.assertEqual(ref_op_sel(a, b, addend), measured, f"{a:#x} . {b:#x} + {addend:#x}")
118 # The table can tell the two readings apart: the plain rule gives another word in four of the five cases.
119 self.assertEqual(sum(ref(a, b, c) != m for a, b, c, m in MEASURED_OP_SEL), 4)
120
121 def test_op_sel_is_refused(self):
122 lines = ["v_mov_b32_e32 v1, 1", "v_mov_b32_e32 v2, 1", "v_mov_b32_e32 v3, 0",
123 "v_dot4_i32_i8 v8, v1, v2, v3 op_sel:[0,1,0] op_sel_hi:[1,0,1]",
124 "exp mrt0 v8, v8, v8, v8 done vm", "s_endpgm"]
125 with self.assertRaises(rdna2spirv.Unsupported) as refused:
126 support.translate_lines("ps_dot4_op_sel", lines)
127 self.assertEqual(str(refused.exception), "v_dot4_i32_i8 op_sel")
128
129 def test_clamp_is_refused(self):
130 lines = ["v_mov_b32_e32 v1, 1", "v_mov_b32_e32 v2, 1", "v_mov_b32_e32 v3, 0",
131 "v_dot4_i32_i8 v8, v1, v2, v3 clamp", "exp mrt0 v8, v8, v8, v8 done vm", "s_endpgm"]
132 with self.assertRaises(rdna2spirv.Unsupported) as refused:
133 support.translate_lines("ps_dot4_clamp", lines)
134 self.assertEqual(str(refused.exception), "v_dot4_i32_i8 clamp")
135
136
137if __name__ == "__main__":
138 unittest.main()
diff --git a/tests/semantic/test_alu_min3_max3_med3_16.py b/tests/semantic/test_alu_min3_max3_med3_16.py
new file mode 100644
index 000000000..2c1376a62
--- /dev/null
+++ b/tests/semantic/test_alu_min3_max3_med3_16.py
@@ -0,0 +1,537 @@
1"""Semantic interpreter tests for RDNA2 16-bit three-operand min/max/median instructions:
2v_min3_i16, v_min3_u16, v_max3_i16, v_max3_u16, v_med3_i16, v_med3_u16,
3v_min3_f16, and v_max3_f16.
4
5Each test translates a synthetic pixel shader listing with tools/rdna2spirv.py, executes it in
6tests/semantic/spirv_mini_interp.py, and compares the exported mrt0 words against plain-Python references.
7
8Covers:
9- A multi-instruction hand-written .asm fixture exercising all eight opcodes into low and high VGPR halves.
10- Signed vs unsigned 16-bit integer comparisons across boundary values (0x8000, 0xFFFF, 0x7FFF, 0x0000, 0x0001)
11 in all 3! = 6 operand permutations.
12- All 16 op_sel:[s0,s1,s2,dst] bit combinations for every opcode.
13- Unwritten destination-half preservation and destination/source register aliasing.
14- Inline integer/float constants and SGPR operands.
15- Floating-point 16-bit NaN skipping (NMin/NMax), signed-zero ordering (-0.0 < +0.0), neg/abs source modifiers,
16 and VOP3 output modifiers (mul:2, mul:4, div:2, clamp).
17- Unsupported rejections for clamp on integer min3/max3/med3 and non-VGPR op_sel destination.
18- Seeded random sweep over all eight opcodes.
19"""
20from __future__ import annotations
21
22import itertools
23import math
24import os
25import random
26import struct
27import sys
28import tempfile
29import unittest
30import warnings
31
32HERE = os.path.dirname(os.path.abspath(__file__))
33ROOT = os.path.dirname(os.path.dirname(HERE))
34TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools")
35
36sys.dont_write_bytecode = True
37sys.path.insert(0, TOOLS_DIR)
38sys.path.insert(0, HERE)
39
40import rdna2spirv # noqa: E402
41import spirv_mini_interp as si # noqa: E402
42
43MASK16 = 0xFFFF
44MASK32 = 0xFFFFFFFF
45STUB_DXBC = b"DXBC" + bytes(24) + struct.pack("<I", 0) + bytes(4)
46OLD = 0xA55A5AA5
47
48INT_OPS = (
49 "v_min3_i16",
50 "v_min3_u16",
51 "v_max3_i16",
52 "v_max3_u16",
53 "v_med3_i16",
54 "v_med3_u16",
55)
56FLOAT_OPS = ("v_min3_f16", "v_max3_f16")
57ALL_OPS = INT_OPS + FLOAT_OPS
58
59# Hand-written multi-instruction RDNA2 pixel shader fixture covering all 8 opcodes into lo/hi VGPR halves.
60# Register inputs:
61# v10 = 0x80007FFF -> lo = 0x7FFF (+32767 i16 / 32767 u16), hi = 0x8000 (-32768 i16 / 32768 u16)
62# v11 = 0xFFFF0001 -> lo = 0x0001 (+1), hi = 0xFFFF (-1 i16 / 65535 u16)
63# v12 = 0x0005FFFE -> lo = 0xFFFE (-2 i16 / 65534 u16), hi = 0x0005 (+5)
64# v13 = 0x3C00BC00 -> lo = 0xBC00 (-1.0 f16), hi = 0x3C00 (+1.0 f16)
65# v14 = 0x80000000 -> lo = 0x0000 (+0.0 f16), hi = 0x8000 (-0.0 f16)
66# v15 = 0x7E004000 -> lo = 0x4000 (+2.0 f16), hi = 0x7E00 (qNaN f16)
67# Expected mrt0 words:
68# v0: v_min3_i16(32767, -1, -2) = -2 (0xFFFE) | v_max3_i16(-32768, 1, 5) = 5 (0x0005) -> 0x0005FFFE
69# v1: v_med3_i16(32767, -1, 5) = 5 (0x0005) | v_min3_u16(32768, 65535, 65534) = 0x8000 -> 0x80000005
70# v2: v_max3_u16(32767, 65535, 65534) = 0xFFFF | v_med3_u16(32768, 1, 65534) = 0x8000 -> 0x8000FFFF
71# v3: v_min3_f16(+1.0, -0.0, qNaN) = -0.0 (0x8000) | v_max3_f16(-1.0, +0.0, +2.0) = 0x4000 -> 0x40008000
72PS_MIN3_MAX3_MED3_16_ASM = """\
73; test_alu_min3_max3_med3_16 fixture
74\tv_mov_b32 v0, 0xdeadbef0
75\tv_mov_b32 v1, 0xdeadbef1
76\tv_mov_b32 v2, 0xdeadbef2
77\tv_mov_b32 v3, 0xdeadbef3
78\tv_mov_b32 v10, 0x80007fff
79\tv_mov_b32 v11, 0xffff0001
80\tv_mov_b32 v12, 0x0005fffe
81\tv_mov_b32 v13, 0x3c00bc00
82\tv_mov_b32 v14, 0x80000000
83\tv_mov_b32 v15, 0x7e004000
84\tv_min3_i16 v0, v10, v11, v12 op_sel:[0,1,0,0]
85\tv_max3_i16 v0, v10, v11, v12 op_sel:[1,0,1,1]
86\tv_med3_i16 v1, v10, v11, v12 op_sel:[0,1,1,0]
87\tv_min3_u16 v1, v10, v11, v12 op_sel:[1,1,0,1]
88\tv_max3_u16 v2, v10, v11, v12 op_sel:[0,1,0,0]
89\tv_med3_u16 v2, v10, v11, v12 op_sel:[1,0,0,1]
90\tv_min3_f16 v3, v13, v14, v15 op_sel:[1,1,1,0]
91\tv_max3_f16 v3, v13, v14, v15 op_sel:[0,0,0,1]
92\texp mrt0 v0, v1, v2, v3 done vm
93\ts_endpgm
94"""
95PS_MIN3_MAX3_MED3_16_EXPECTED = (0x0005FFFE, 0x80000005, 0x8000FFFF, 0x40008000)
96
97INT_TRIPLES = (
98 (0x0005, 0x8000, 0x0007),
99 (0xFFFF, 0x0000, 0x0001),
100 (0x7FFF, 0x8000, 0xFFFF),
101 (0x8001, 0x8000, 0x7FFE),
102 (0x0001, 0xFFFE, 0xFFFF),
103 (0x0009, 0x0009, 0x8000),
104 (0xFFFF, 0xFFFF, 0x0000),
105 (0x0003, 0x0003, 0x0003),
106)
107
108# f16 bit patterns: -inf, -2.0, -1.0, -0.5, smallest neg subnormal, -0.0, +0.0, subnormal, +0.5, +1.0, +2.0, +inf
109F16_VALS = (
110 0xFC00, # -inf
111 0xC000, # -2.0
112 0xBC00, # -1.0
113 0xB800, # -0.5
114 0x8001, # -2^-24 (negative subnormal)
115 0x8000, # -0.0
116 0x0000, # +0.0
117 0x0001, # +2^-24 (positive subnormal)
118 0x3800, # +0.5
119 0x3C00, # +1.0
120 0x4000, # +2.0
121 0x7C00, # +inf
122)
123
124
125def s16(h: int) -> int:
126 h &= MASK16
127 return h - 0x10000 if h & 0x8000 else h
128
129
130def f16_to_float(h: int) -> float:
131 return struct.unpack("<e", struct.pack("<H", h & MASK16))[0]
132
133
134def float_to_f16_bits(f: float) -> int:
135 try:
136 return struct.unpack("<H", struct.pack("<e", f))[0]
137 except OverflowError:
138 return 0x7C00 if f > 0 else 0xFC00
139
140
141def half_bits(word: int, hi: int) -> int:
142 return ((word >> 16) if hi else word) & MASK16
143
144
145def merge_half(res16: int, dst_hi: int, old: int = OLD) -> int:
146 res16 &= MASK16
147 return ((res16 << 16) | (old & MASK16)) if dst_hi else ((old & 0xFFFF0000) | res16)
148
149
150def ref_int16(op: str, a: int, b: int, c: int) -> int:
151 key = s16 if op.endswith("_i16") else (lambda v: v & MASK16)
152 xs = [a & MASK16, b & MASK16, c & MASK16]
153 if "min3" in op:
154 return min(xs, key=key) & MASK16
155 if "max3" in op:
156 return max(xs, key=key) & MASK16
157 if "med3" in op:
158 return sorted(xs, key=key)[1] & MASK16
159 raise ValueError(op)
160
161
162def ref_f16(op: str, a_bits: int, b_bits: int, c_bits: int, mods: str = "") -> int:
163 vals = [f16_to_float(h) for h in (a_bits, b_bits, c_bits)]
164 non_nan = [v for v in vals if not math.isnan(v)]
165 if not non_nan:
166 return 0x7E00
167 pick = min if "min3" in op else max
168 # RDNA2 orders -0.0 below +0.0.
169 chosen = pick(non_nan, key=lambda v: (v, math.copysign(1.0, v)))
170 if "mul:2" in mods:
171 chosen *= 2.0
172 elif "mul:4" in mods:
173 chosen *= 4.0
174 elif "div:2" in mods:
175 chosen *= 0.5
176 if "clamp" in mods:
177 if math.isnan(chosen):
178 chosen = 0.0
179 else:
180 chosen = max(0.0, min(1.0, chosen))
181 if chosen == 0.0:
182 chosen = 0.0
183 return float_to_f16_bits(chosen)
184
185
186def ref_word(op: str, w1: int, w2: int, w3: int, sel=(0, 0, 0), dst_hi: int = 0, old: int = OLD, mods: str = "") -> int:
187 h1, h2, h3 = half_bits(w1, sel[0]), half_bits(w2, sel[1]), half_bits(w3, sel[2])
188 r16 = ref_f16(op, h1, h2, h3, mods=mods) if op in FLOAT_OPS else ref_int16(op, h1, h2, h3)
189 return merge_half(r16, dst_hi, old=old)
190
191
192_TMP_DIR = None
193_SRC_PATH = None
194
195
196def setUpModule():
197 global _TMP_DIR, _SRC_PATH
198 _TMP_DIR = tempfile.TemporaryDirectory()
199 disasm_dir = os.path.join(_TMP_DIR.name, "disasm")
200 os.mkdir(disasm_dir)
201 _SRC_PATH = os.path.join(disasm_dir, "ps_min3_16.s")
202 with open(os.path.join(_TMP_DIR.name, "ps_min3_16.dxbc"), "wb") as f:
203 f.write(STUB_DXBC)
204
205
206def tearDownModule():
207 global _TMP_DIR
208 if _TMP_DIR is not None:
209 _TMP_DIR.cleanup()
210 _TMP_DIR = None
211
212
213def translate_asm(asm: str) -> str:
214 if _TMP_DIR is None:
215 setUpModule()
216 with open(_SRC_PATH, "w", encoding="utf-8") as f:
217 f.write(asm)
218 with warnings.catch_warnings():
219 warnings.simplefilter("ignore", ResourceWarning)
220 return rdna2spirv.translate(_SRC_PATH)
221
222
223def run_insn(
224 op: str,
225 operands_words: tuple[int | str, int | str, int | str],
226 *,
227 inline: tuple[int, ...] = (),
228 sgpr_idx: tuple[int, ...] = (),
229 src_mods: dict[int, str] | None = None,
230 tail_mods: str = "",
231 old: int = OLD,
232 dst: str = "v0",
233 alias_dst: int | None = None,
234) -> int:
235 lines = [f"\tv_mov_b32 v0, {old & MASK32:#x}"]
236 op_strs = []
237 sgpr_vals: dict[int, int] = {}
238 for i, val in enumerate(operands_words):
239 fmt = (src_mods or {}).get(i, "{}")
240 if i in inline:
241 val_str = str(val) if isinstance(val, str) else (f"{val:#x}" if isinstance(val, int) and val >= 0 else str(val))
242 op_strs.append(fmt.format(val_str))
243 elif i in sgpr_idx:
244 reg = 4 + i
245 sgpr_vals[reg] = int(val) & MASK32
246 lines.append(f"\ts_mov_b32 s{reg}, {sgpr_vals[reg]:#x}")
247 op_strs.append(fmt.format(f"s{reg}"))
248 elif alias_dst == i:
249 lines[0] = f"\tv_mov_b32 v0, {int(val) & MASK32:#x}"
250 op_strs.append(fmt.format("v0"))
251 else:
252 vreg = f"v{i + 1}"
253 lines.append(f"\tv_mov_b32 {vreg}, {int(val) & MASK32:#x}")
254 op_strs.append(fmt.format(vreg))
255 mod_suffix = f" {tail_mods}" if tail_mods else ""
256 lines.append(f"\t{op} {dst}, {', '.join(op_strs)}{mod_suffix}")
257 asm = "; test_alu_min3_max3_med3_16\n" + "\n".join(lines) + "\n\texp mrt0 v0, v0, v0, v0 done vm\n\ts_endpgm\n"
258 spv = translate_asm(asm)
259 return si.run_fragment(spv)["%out_mrt0"][0]
260
261
262class ReferenceTests(unittest.TestCase):
263 """Cross-check plain-Python reference calculations against hand-worked edge cases."""
264
265 def test_int_reference(self):
266 self.assertEqual(ref_int16("v_min3_i16", 0x7FFF, 0xFFFF, 0xFFFE), 0xFFFE)
267 self.assertEqual(ref_int16("v_min3_u16", 0x7FFF, 0xFFFF, 0xFFFE), 0x7FFF)
268 self.assertEqual(ref_int16("v_max3_i16", 0x8000, 0x0001, 0x0005), 0x0005)
269 self.assertEqual(ref_int16("v_max3_u16", 0x8000, 0x0001, 0x0005), 0x8000)
270 self.assertEqual(ref_int16("v_med3_i16", 0x7FFF, 0xFFFF, 0x0005), 0x0005)
271 self.assertEqual(ref_int16("v_med3_u16", 0x8000, 0x0001, 0xFFFE), 0x8000)
272
273 def test_f16_reference(self):
274 self.assertEqual(ref_f16("v_min3_f16", 0x3C00, 0x8000, 0x7E00), 0x8000)
275 self.assertEqual(ref_f16("v_max3_f16", 0xBC00, 0x0000, 0x8000), 0x0000)
276 self.assertEqual(ref_f16("v_min3_f16", 0x0000, 0x8000, 0x3C00), 0x8000)
277
278
279class FixtureTests(unittest.TestCase):
280 """Hand-written multi-instruction RDNA2 .asm fixture for all 8 instructions."""
281
282 def test_ps_min3_max3_med3_16_fixture(self):
283 spv = translate_asm(PS_MIN3_MAX3_MED3_16_ASM)
284 got = si.run_fragment(spv)["%out_mrt0"]
285 self.assertEqual(got, PS_MIN3_MAX3_MED3_16_EXPECTED)
286
287
288class Int16PermutationsTests(unittest.TestCase):
289 """Verify signed vs unsigned ordering across all 3! = 6 operand permutations."""
290
291 def test_boundary_permutations(self):
292 for op in INT_OPS:
293 for triple in INT_TRIPLES:
294 for perm in sorted(set(itertools.permutations(triple))):
295 w1, w2, w3 = (0xBEEF0000 | x for x in perm)
296 with self.subTest(op=op, perm=[hex(x) for x in perm]):
297 self.assertEqual(run_insn(op, (w1, w2, w3)), ref_word(op, w1, w2, w3))
298
299
300class OpselAllPatternsTests(unittest.TestCase):
301 """Test all 16 op_sel:[s0,s1,s2,dst] bit combinations for every opcode."""
302
303 def test_all_sixteen_opsel_patterns_int(self):
304 # Distinct lo/hi values in every register, mixing signed-negative and unsigned-high patterns.
305 w1, w2, w3 = 0x80007FFF, 0xFFFF0001, 0x0005FFFE
306 for op in INT_OPS:
307 for bits in itertools.product((0, 1), repeat=4):
308 mods = f"op_sel:[{bits[0]},{bits[1]},{bits[2]},{bits[3]}]"
309 with self.subTest(op=op, mods=mods):
310 got = run_insn(op, (w1, w2, w3), tail_mods=mods)
311 want = ref_word(op, w1, w2, w3, bits[:3], bits[3])
312 self.assertEqual(got, want)
313
314 def test_all_sixteen_opsel_patterns_f16(self):
315 # v1 = (-1.0 | 4.0), v2 = (0.5 | 2.0), v3 = (1.5 | -3.0)
316 w1 = float_to_f16_bits(4.0) << 16 | float_to_f16_bits(-1.0)
317 w2 = float_to_f16_bits(2.0) << 16 | float_to_f16_bits(0.5)
318 w3 = float_to_f16_bits(-3.0) << 16 | float_to_f16_bits(1.5)
319 for op in FLOAT_OPS:
320 for bits in itertools.product((0, 1), repeat=4):
321 mods = f"op_sel:[{bits[0]},{bits[1]},{bits[2]},{bits[3]}]"
322 with self.subTest(op=op, mods=mods):
323 got = run_insn(op, (w1, w2, w3), tail_mods=mods)
324 want = ref_word(op, w1, w2, w3, bits[:3], bits[3])
325 self.assertEqual(got, want)
326
327
328class HalfPreservationAndAliasingTests(unittest.TestCase):
329 """Unwritten half of dst is preserved, including when dst aliases src0, src1, or src2."""
330
331 def test_preserves_unwritten_half(self):
332 for op in ALL_OPS:
333 w1, w2, w3 = 0x3C003800, 0x4000B800, 0xBC000001
334 for dst_hi in (0, 1):
335 for sentinel in (0x12345678, 0xFEDCBA98):
336 with self.subTest(op=op, dst_hi=dst_hi, sentinel=hex(sentinel)):
337 got = run_insn(op, (w1, w2, w3), tail_mods=f"op_sel:[0,0,0,{dst_hi}]", old=sentinel)
338 self.assertEqual(got, ref_word(op, w1, w2, w3, (0, 0, 0), dst_hi, old=sentinel))
339
340 def test_dst_source_aliasing(self):
341 for op in ALL_OPS:
342 w = [0x80003C00, 0x4000FFFF, 0x38000002]
343 for alias_idx in (0, 1, 2):
344 for dst_hi in (0, 1):
345 mods = f"op_sel:[1,0,1,{dst_hi}]"
346 with self.subTest(op=op, alias_idx=alias_idx, dst_hi=dst_hi):
347 got = run_insn(
348 op,
349 (w[0], w[1], w[2]),
350 tail_mods=mods,
351 alias_dst=alias_idx,
352 )
353 want = ref_word(op, w[0], w[1], w[2], (1, 0, 1), dst_hi, old=w[alias_idx])
354 self.assertEqual(got, want)
355
356
357class ConstantsAndSgprTests(unittest.TestCase):
358 """Inline constants (imm / fimm) and SGPR sources."""
359
360 def test_int_inline_constants_and_sgpr(self):
361 # -16 inline is 0xFFFFFFF0 (lo = 0xFFF0 = -16 i16 / 65520 u16, hi = 0xFFFF = -1 i16 / 65535 u16).
362 cases = [
363 ("v_min3_i16", (-16, 64, 0x00030005), (0, 1), (), "op_sel:[0,0,0,0]"),
364 ("v_min3_u16", (-16, 64, 0x00030005), (0, 1), (), "op_sel:[0,0,0,1]"),
365 ("v_max3_i16", (-1, 0x80000002, 10), (0, 2), (1,), "op_sel:[0,1,0,0]"),
366 ("v_max3_u16", (-16, 0x00010002, 0x80000003), (0,), (1,), "op_sel:[1,0,1,1]"),
367 ("v_med3_i16", (0x7FFF8000, -1, 16), (1, 2), (0,), "op_sel:[0,0,0,0]"),
368 ("v_med3_u16", (0x7FFF8000, -16, 64), (1, 2), (0,), "op_sel:[1,0,0,1]"),
369 ]
370 for op, words, inl, sgprs, mods in cases:
371 with self.subTest(op=op, words=words, mods=mods):
372 sel_parts = [int(x) for x in mods.split("[")[1].rstrip("]").split(",")]
373 norm_words = [
374 (w & MASK32) if isinstance(w, int) else w
375 for w in words
376 ]
377 got = run_insn(op, words, inline=inl, sgpr_idx=sgprs, tail_mods=mods)
378 want = ref_word(op, norm_words[0], norm_words[1], norm_words[2], sel_parts[:3], sel_parts[3])
379 self.assertEqual(got, want)
380
381 def test_f16_fimm_constants_and_sgpr(self):
382 # Inline float constants populate the low half as f16 with high half = +0.0 (docs/design.md).
383 # 1.0 -> 0x00003C00; -2.0 -> 0x0000C000; 0.5 -> 0x00003800
384 got_min = run_insn(
385 "v_min3_f16",
386 ("1.0", 0x40003C00, "-2.0"),
387 inline=(0, 2),
388 sgpr_idx=(1,),
389 tail_mods="op_sel:[0,1,0,0]",
390 )
391 self.assertEqual(got_min, merge_half(0xC000, 0))
392
393 # Selecting the high half of an inline float constant reads +0.0.
394 got_hi_fimm = run_insn(
395 "v_max3_f16",
396 ("1.0", 0xBC00BC00, "-0.5"),
397 inline=(0, 2),
398 tail_mods="op_sel:[1,0,0,1]",
399 )
400 self.assertEqual(got_hi_fimm, merge_half(0x0000, 1))
401
402
403class Float16SpecialsAndModsTests(unittest.TestCase):
404 """f16 NaNs, signed zeros (-0.0 < +0.0), neg/abs, omod, and clamp."""
405
406 def test_signed_zeros_all_orders(self):
407 # -0.0 (0x8000) orders strictly below +0.0 (0x0000) regardless of operand position.
408 for triple in (
409 (0x8000, 0x0000, 0x3C00), # -0, +0, +1 -> min=-0, max=+1
410 (0x8000, 0x0000, 0xBC00), # -0, +0, -1 -> min=-1, max=+0
411 (0x8000, 0x0000, 0x0000), # -0, +0, +0 -> min=-0, max=+0
412 (0x8000, 0x8000, 0x0000), # -0, -0, +0 -> min=-0, max=+0
413 ):
414 for perm in sorted(set(itertools.permutations(triple))):
415 for op in FLOAT_OPS:
416 with self.subTest(op=op, perm=[hex(x) for x in perm]):
417 got = run_insn(op, perm)
418 self.assertEqual(got, ref_word(op, *perm))
419
420 def test_nan_operands(self):
421 for op in FLOAT_OPS:
422 # One quiet or signaling NaN: returns min/max of the remaining finite values.
423 for nan_bits in (0x7E00, 0x7C01, 0xFE01):
424 for perm in sorted(set(itertools.permutations((nan_bits, 0x4000, 0xBC00)))):
425 with self.subTest(op=op, perm=[hex(x) for x in perm]):
426 got = run_insn(op, perm)
427 self.assertEqual(got, ref_word(op, *perm))
428 # Two NaNs: returns the single non-NaN operand.
429 for perm in sorted(set(itertools.permutations((0x7E00, 0xFE01, 0x3800)))):
430 with self.subTest(op=op, two_nans=[hex(x) for x in perm]):
431 got = run_insn(op, perm)
432 self.assertEqual(got, ref_word(op, *perm))
433 # Three NaNs: result is NaN and unwritten high half is preserved.
434 got_all_nan = run_insn(op, (0x7E00, 0x7E01, 0xFE01))
435 self.assertEqual(got_all_nan >> 16, OLD >> 16)
436 self.assertTrue(math.isnan(f16_to_float(got_all_nan & MASK16)))
437
438 def test_source_and_output_modifiers(self):
439 # Input neg/abs apply to the selected half; omod (mul:2/mul:4/div:2) runs before clamp [0, 1].
440 w1 = float_to_f16_bits(-3.0) << 16 | float_to_f16_bits(0.5)
441 w2 = float_to_f16_bits(0.25) << 16 | float_to_f16_bits(-2.0)
442 w3 = float_to_f16_bits(-0.125) << 16 | float_to_f16_bits(4.0)
443
444 # neg(|v1.hi|) = -3.0, |v2.lo| = +2.0, v3.hi = -0.125 -> min = -3.0 -> div:2 = -1.5
445 got_div2 = run_insn(
446 "v_min3_f16",
447 (w1, w2, w3),
448 src_mods={0: "-|{}|", 1: "|{}|"},
449 tail_mods="op_sel:[1,0,1,0] div:2",
450 )
451 self.assertEqual(got_div2, merge_half(float_to_f16_bits(-1.5), 0))
452
453 # min(|v1.lo|=0.5, v2.hi=0.25, -v3.hi=0.125) = 0.125 -> mul:4 = 0.5 -> clamp = 0.5 (hi half)
454 got_mul4_clamp = run_insn(
455 "v_min3_f16",
456 (w1, w2, w3),
457 src_mods={0: "|{}|", 2: "-{}"},
458 tail_mods="op_sel:[0,1,1,1] mul:4 clamp",
459 )
460 self.assertEqual(got_mul4_clamp, merge_half(float_to_f16_bits(0.5), 1))
461
462 # max(v1.lo=0.5, v2.hi=0.25, v3.lo=4.0) = 4.0 -> div:2 = 2.0 -> clamp = 1.0
463 got_max_clamp = run_insn(
464 "v_max3_f16",
465 (w1, w2, w3),
466 tail_mods="op_sel:[0,1,0,0] div:2 clamp",
467 )
468 self.assertEqual(got_max_clamp, merge_half(float_to_f16_bits(1.0), 0))
469
470 # max(v1.hi=-3.0, v2.lo=-2.0, v3.hi=-0.125) = -0.125 -> mul:2 = -0.25 -> clamp = +0.0
471 got_neg_clamp = run_insn(
472 "v_max3_f16",
473 (w1, w2, w3),
474 tail_mods="op_sel:[1,0,1,1] mul:2 clamp",
475 )
476 self.assertEqual(got_neg_clamp, merge_half(0x0000, 1))
477
478
479class UnsupportedTests(unittest.TestCase):
480 """Reject unmodelled integer clamp and non-VGPR op_sel destinations."""
481
482 def test_int_clamp_rejected(self):
483 for op in INT_OPS:
484 with self.subTest(op=op):
485 asm = (
486 "; test_unsupported_clamp\n"
487 "\tv_mov_b32 v1, 1\n\tv_mov_b32 v2, 2\n\tv_mov_b32 v3, 3\n"
488 f"\t{op} v0, v1, v2, v3 clamp\n"
489 "\texp mrt0 v0, v0, v0, v0 done vm\n\ts_endpgm\n"
490 )
491 with self.assertRaises(rdna2spirv.Unsupported):
492 translate_asm(asm)
493
494 def test_non_vgpr_opsel_dst_rejected(self):
495 for op in ALL_OPS:
496 with self.subTest(op=op):
497 asm = (
498 "; test_unsupported_dst\n"
499 "\tv_mov_b32 v1, 1\n\tv_mov_b32 v2, 2\n\tv_mov_b32 v3, 3\n"
500 f"\t{op} s0, v1, v2, v3 op_sel:[0,0,0,1]\n"
501 "\texp mrt0 v1, v1, v1, v1 done vm\n\ts_endpgm\n"
502 )
503 with self.assertRaises(rdna2spirv.Unsupported):
504 translate_asm(asm)
505
506
507class RandomSweepTests(unittest.TestCase):
508 """Seeded random sweep over all eight opcodes, halves, and destination halves."""
509
510 def test_seeded_sweep(self):
511 rng = random.Random(0x1633)
512 int_pool = [0, 1, 0x7FFE, 0x7FFF, 0x8000, 0x8001, 0xFFFE, 0xFFFF]
513 for op in INT_OPS:
514 for _ in range(18):
515 w1, w2, w3 = (
516 ((rng.choice(int_pool) if rng.random() < 0.4 else rng.randrange(0x10000)) << 16)
517 | (rng.choice(int_pool) if rng.random() < 0.4 else rng.randrange(0x10000))
518 for _ in range(3)
519 )
520 sel = tuple(rng.randrange(2) for _ in range(3))
521 dst_hi = rng.randrange(2)
522 mods = f"op_sel:[{sel[0]},{sel[1]},{sel[2]},{dst_hi}]"
523 with self.subTest(op=op, w=(hex(w1), hex(w2), hex(w3)), mods=mods):
524 self.assertEqual(run_insn(op, (w1, w2, w3), tail_mods=mods), ref_word(op, w1, w2, w3, sel, dst_hi))
525
526 for op in FLOAT_OPS:
527 for _ in range(18):
528 w1, w2, w3 = ((rng.choice(F16_VALS) << 16) | rng.choice(F16_VALS) for _ in range(3))
529 sel = tuple(rng.randrange(2) for _ in range(3))
530 dst_hi = rng.randrange(2)
531 mods = f"op_sel:[{sel[0]},{sel[1]},{sel[2]},{dst_hi}]"
532 with self.subTest(op=op, w=(hex(w1), hex(w2), hex(w3)), mods=mods):
533 self.assertEqual(run_insn(op, (w1, w2, w3), tail_mods=mods), ref_word(op, w1, w2, w3, sel, dst_hi))
534
535
536if __name__ == "__main__":
537 unittest.main()
diff --git a/tests/semantic/test_alu_sincos.py b/tests/semantic/test_alu_sincos.py
new file mode 100644
index 000000000..78d864bd3
--- /dev/null
+++ b/tests/semantic/test_alu_sincos.py
@@ -0,0 +1,183 @@
1"""Semantic interpreter tests for RDNA2 v_sin_f32 / v_cos_f32 / v_sin_f16 / v_cos_f16 (SHADER-88).
2
3The operand is an angle in TURNS (valid over +-256 turns). Multiplying by 2*pi before reducing rounds the fractional
4turn away in binary32 (up to ~1e-4 rad near +-255 turns), so the translator reduces in turns first. Each case
5translates a synthetic pixel shader with tools/rdna2spirv.py, runs it in tests/semantic/spirv_mini_interp.py and
6compares the exported value with math.sin / math.cos(2*pi*x) computed in double (a reference, not a model of the
7translator). Tolerances are absolute and explicit: 1e-6 for f32 (a few ulp of a value near 1), 1e-3 for f16 (one
8f16 ulp near 1 is ~4.9e-4 and the result is rounded to f16).
9"""
10import math
11import os
12import struct
13import sys
14import tempfile
15import unittest
16import warnings
17
18HERE = os.path.dirname(os.path.abspath(__file__))
19ROOT = os.path.dirname(os.path.dirname(HERE))
20TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools")
21
22sys.dont_write_bytecode = True
23sys.path.insert(0, TOOLS_DIR)
24sys.path.insert(0, HERE)
25
26import rdna2spirv # noqa: E402
27import spirv_mini_interp as si # noqa: E402
28
29STUB_DXBC = b"DXBC" + bytes(24) + struct.pack("<I", 0) + bytes(4)
30OLD = 0xAAAA5555
31TOL32 = 1e-6
32TOL16 = 1e-3
33INPUTS = [0.25, 0.5, 1.0, 100.3, 254.25, 254.51, 255.9, 0.1, 0.0, -0.0, -0.25, -100.3, -254.51, -255.5]
34
35_TMP_DIR = None
36_SRC_PATH = None
37
38
39def f2u(x):
40 return struct.unpack("<I", struct.pack("<f", x))[0]
41
42
43def u2f(u):
44 return struct.unpack("<f", struct.pack("<I", u & 0xFFFFFFFF))[0]
45
46
47def h2f(h):
48 return struct.unpack("<e", struct.pack("<H", h & 0xFFFF))[0]
49
50
51def f2h(x):
52 return struct.unpack("<H", struct.pack("<e", x))[0]
53
54
55def ref(op, x):
56 return math.sin(2 * math.pi * x) if "sin" in op else math.cos(2 * math.pi * x)
57
58
59def setUpModule():
60 global _TMP_DIR, _SRC_PATH
61 _TMP_DIR = tempfile.TemporaryDirectory()
62 disasm_dir = os.path.join(_TMP_DIR.name, "disasm")
63 os.mkdir(disasm_dir)
64 _SRC_PATH = os.path.join(disasm_dir, "ps_sincos.s")
65 with open(os.path.join(_TMP_DIR.name, "ps_sincos.dxbc"), "wb") as f:
66 f.write(STUB_DXBC)
67
68
69def tearDownModule():
70 global _TMP_DIR
71 if _TMP_DIR is not None:
72 _TMP_DIR.cleanup()
73 _TMP_DIR = None
74
75
76def run(line, v1, old=0):
77 if _TMP_DIR is None:
78 setUpModule()
79 lines = [f"v_mov_b32 v1, {v1:#x}", f"v_mov_b32 v0, {old:#x}", line]
80 asm = "; test_sincos\n" + "".join(f"\t{ln}\n" for ln in lines) + "\texp mrt0 v0, v0, v0, v0 done vm\n\ts_endpgm\n"
81 with open(_SRC_PATH, "w", encoding="utf-8") as f:
82 f.write(asm)
83 with warnings.catch_warnings():
84 warnings.simplefilter("ignore", ResourceWarning)
85 spv = rdna2spirv.translate(_SRC_PATH)
86 return si.run_fragment(spv)["%out_mrt0"][0]
87
88
89class SinCosF32Tests(unittest.TestCase):
90 def test_values_against_double_reference(self):
91 for op in ("v_sin_f32", "v_cos_f32"):
92 for x in INPUTS:
93 x32 = u2f(f2u(x)) # the binary32 operand the shader sees
94 with self.subTest(op=op, x=x):
95 got = u2f(run(f"{op}_e32 v0, v1", f2u(x)))
96 self.assertLessEqual(abs(got - ref(op, x32)), TOL32)
97
98 def test_exact_quarter_turns(self):
99 self.assertLessEqual(abs(u2f(run("v_sin_f32_e32 v0, v1", f2u(0.25))) - 1.0), TOL32)
100 self.assertLessEqual(abs(u2f(run("v_cos_f32_e32 v0, v1", f2u(0.5))) + 1.0), TOL32)
101 self.assertLessEqual(abs(u2f(run("v_sin_f32_e32 v0, v1", f2u(254.25))) - 1.0), TOL32)
102 self.assertLessEqual(abs(u2f(run("v_cos_f32_e32 v0, v1", f2u(-254.5))) + 1.0), TOL32)
103
104 def test_worst_case_of_the_issue(self):
105 # x = 254.51: x * 2*pi first was off by 1.05e-4; reducing in turns is within 1e-6.
106 x32 = u2f(f2u(254.51))
107 got = u2f(run("v_sin_f32_e32 v0, v1", f2u(254.51)))
108 self.assertLessEqual(abs(got - math.sin(2 * math.pi * x32)), TOL32)
109
110 def test_signed_zero_and_special_values(self):
111 self.assertEqual(run("v_sin_f32_e32 v0, v1", 0x00000000), 0x00000000)
112 self.assertEqual(run("v_sin_f32_e32 v0, v1", 0x80000000), 0x80000000) # sin(-0) = -0
113 self.assertEqual(u2f(run("v_cos_f32_e32 v0, v1", 0x80000000)), 1.0)
114 for bits in (0x7F800000, 0xFF800000, 0x7FC00000):
115 for op in ("v_sin_f32", "v_cos_f32"):
116 with self.subTest(op=op, x=hex(bits)):
117 self.assertTrue(math.isnan(u2f(run(f"{op}_e32 v0, v1", bits))))
118
119 def test_modifiers(self):
120 got = u2f(run("v_sin_f32_e64 v0, -v1", f2u(100.3))) # neg: sin(-x)
121 self.assertLessEqual(abs(got - math.sin(-2 * math.pi * u2f(f2u(100.3)))), TOL32)
122 got = u2f(run("v_cos_f32_e64 v0, |v1|", f2u(-254.51))) # abs
123 self.assertLessEqual(abs(got - math.cos(2 * math.pi * u2f(f2u(254.51)))), TOL32)
124 got = u2f(run("v_sin_f32_e64 v0, v1 clamp", f2u(-0.25))) # clamp: sin = -1 -> 0
125 self.assertEqual(got, 0.0)
126 got = u2f(run("v_sin_f32_e64 v0, v1 mul:2", f2u(100.3))) # omod
127 self.assertLessEqual(abs(got - 2 * math.sin(2 * math.pi * u2f(f2u(100.3)))), 2 * TOL32)
128
129 def test_whole_turns_give_plus_zero_for_either_sign(self):
130 """Measured on an RX 6800 (gfx1030, #616): v_sin_f32 of a whole number of turns, negative or positive, is
131 +0 (only sin(-0) is -0) and v_cos_f32 of it is 1."""
132 for x in (-1.0, -2.0, -100.0, 1.0, 2.0, 100.0):
133 with self.subTest(x=x):
134 self.assertEqual(run("v_sin_f32_e32 v0, v1", f2u(x)), 0x00000000)
135 self.assertEqual(run("v_cos_f32_e32 v0, v1", f2u(x)), f2u(1.0))
136
137 def test_tiny_arguments_keep_their_sign_and_size(self):
138 """A reducer built on floor() would turn x = -2**-26 into 1.0 - 2**-26 = 1.0 in binary32 and return +0;
139 x - RoundEven(x) keeps the small centred argument. The result is below TOL32 either way, so the check is on
140 the sign and on a much tighter absolute tolerance (suggested by bobcatchris on #616)."""
141 for x in (-2.0 ** -26, 2.0 ** -26, -2.0 ** -20, 2.0 ** -20):
142 with self.subTest(x=x):
143 got = u2f(run("v_sin_f32_e32 v0, v1", f2u(x)))
144 self.assertEqual(math.copysign(1.0, got), math.copysign(1.0, x))
145 self.assertNotEqual(got, 0.0)
146 self.assertLessEqual(abs(got - math.sin(2 * math.pi * x)), 2e-9)
147 self.assertLessEqual(abs(u2f(run("v_cos_f32_e32 v0, v1", f2u(x))) - 1.0), 1e-6)
148
149
150class SinCosF16Tests(unittest.TestCase):
151 def test_values_keep_the_high_half(self):
152 for op in ("v_sin_f16", "v_cos_f16"):
153 for x in (0.25, 0.5, 100.25, 254.5, -254.25, 0.3):
154 h = f2h(x)
155 with self.subTest(op=op, x=x):
156 got = run(f"{op}_e32 v0, v1", 0x12340000 | h, OLD)
157 self.assertEqual(got & 0xFFFF0000, OLD & 0xFFFF0000)
158 self.assertLessEqual(abs(h2f(got) - ref(op, h2f(h))), TOL16)
159
160 def test_negative_zero_keeps_its_sign(self):
161 """f16 -0.0 is 0x8000: sin(-0) stays -0 (the sign bit survives the turns reduction) and cos(-0) is 1;
162 the high half of the destination is kept in both."""
163 got = run("v_sin_f16_e32 v0, v1", 0x12340000 | 0x8000, OLD)
164 self.assertEqual(got, (OLD & 0xFFFF0000) | 0x8000)
165 got = run("v_cos_f16_e32 v0, v1", 0x12340000 | 0x8000, OLD)
166 self.assertEqual(got & 0xFFFF0000, OLD & 0xFFFF0000)
167 self.assertEqual(h2f(got), 1.0)
168
169 def test_large_angle_near_the_256_turn_edge(self):
170 """Where x * 2*pi first would lose the fractional turn: 254.25 and 255.0 are exact in f16, and the
171 reference is computed in double."""
172 for op, x in (("v_sin_f16", 254.25), ("v_sin_f16", -254.25), ("v_cos_f16", 254.5), ("v_cos_f16", 255.0),
173 ("v_sin_f16", 255.5), ("v_cos_f16", -255.5)):
174 h = f2h(x)
175 self.assertEqual(h2f(h), x) # the input is exactly representable
176 with self.subTest(op=op, x=x):
177 got = run(f"{op}_e32 v0, v1", 0x12340000 | h, OLD)
178 self.assertEqual(got & 0xFFFF0000, OLD & 0xFFFF0000)
179 self.assertLessEqual(abs(h2f(got) - ref(op, x)), TOL16)
180
181
182if __name__ == "__main__":
183 unittest.main()
diff --git a/tests/semantic/test_alu_swaprel.py b/tests/semantic/test_alu_swaprel.py
new file mode 100644
index 000000000..cf89d4c27
--- /dev/null
+++ b/tests/semantic/test_alu_swaprel.py
@@ -0,0 +1,92 @@
1"""Value tests for v_swaprel_b32 (GFX10 VOP1 opcode 104), run through spirv_mini_interp.
2
3 tmp = VGPR[D + M0[25:16]]; VGPR[D + M0[25:16]] = VGPR[S0 + M0[9:0]]; VGPR[S0 + M0[9:0]] = tmp
4
5The same two M0 fields as v_movrelsd_2_b32; the other M0 bits are ignored. Each case loads a distinct sentinel into
6v1..v30 (0x40000000 + n, normal floats, so the export round trip can't change them), sets M0, runs one v_swaprel_b32
7and exports four registers through exp mrt0. Expected words come from a plain-Python register-file model.
8Standard library only; no GPU, no game files.
9"""
10import os
11import struct
12import sys
13import tempfile
14import unittest
15import warnings
16
17HERE = os.path.dirname(os.path.abspath(__file__))
18ROOT = os.path.dirname(os.path.dirname(HERE))
19sys.dont_write_bytecode = True
20sys.path.insert(0, os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools"))
21sys.path.insert(0, HERE)
22
23import rdna2spirv # noqa: E402
24import spirv_mini_interp as si # noqa: E402
25
26STUB_DXBC = b"DXBC" + bytes(24) + struct.pack("<I", 0) + bytes(4)
27
28
29def sentinel(n):
30 return 0x40000000 + n
31
32
33def model(d, s0, m0):
34 regs = {n: sentinel(n) for n in range(1, 31)}
35 a, b = d + ((m0 >> 16) & 0x3FF), s0 + (m0 & 0x3FF)
36 regs[a], regs[b] = regs[b], regs[a]
37 return regs
38
39
40def run(d, s0, m0, export, extra=()):
41 with tempfile.TemporaryDirectory() as tmp:
42 os.mkdir(os.path.join(tmp, "disasm"))
43 with open(os.path.join(tmp, "ps_swaprel.dxbc"), "wb") as f:
44 f.write(STUB_DXBC)
45 lines = [f"v_mov_b32 v{n}, {sentinel(n):#x}" for n in range(1, 31)] + [f"s_mov_b32 m0, {m0:#x}", *extra,
46 f"v_swaprel_b32 v{d}, v{s0}", f"exp mrt0 {', '.join(f'v{r}' for r in export)} done vm", "s_endpgm"]
47 src = os.path.join(tmp, "disasm", "ps_swaprel.s")
48 with open(src, "w", encoding="utf-8") as f:
49 f.write("; ps_swaprel\n" + "".join(f"\t{ln}\n" for ln in lines))
50 with warnings.catch_warnings():
51 warnings.simplefilter("ignore", ResourceWarning)
52 spv = rdna2spirv.translate(src)
53 return list(si.run_fragment(spv)["%out_mrt0"])
54
55
56class SwaprelTests(unittest.TestCase):
57 def check(self, d, s0, m0):
58 regs = model(d, s0, m0)
59 a, b = d + ((m0 >> 16) & 0x3FF), s0 + (m0 & 0x3FF)
60 export = [a, b, a + 1, b - 1 if b > 1 else b + 1]
61 self.assertEqual(run(d, s0, m0, export), [regs[r] for r in export])
62
63 def test_fields(self):
64 for d, s0, m0 in ((1, 2, 0), (3, 10, 0x0005_0002), (20, 1, 0x0002_0007), (5, 5, 0x0001_0000)):
65 with self.subTest(d=d, s0=s0, m0=hex(m0)):
66 self.check(d, s0, m0)
67
68 def test_other_m0_bits_are_ignored(self):
69 # bits 15:10 and 31:26 set: same result as M0 = (3 << 16) | 4
70 self.check(2, 6, 0xFC03_FC04)
71
72 def test_both_sides_name_one_register(self):
73 # D + M0[25:16] == S0 + M0[9:0]: the register is swapped with itself and keeps its value
74 self.assertEqual(run(4, 6, 0x0003_0001, [7, 6, 8, 1]), [sentinel(7), sentinel(6), sentinel(8), sentinel(1)])
75
76 def test_model(self):
77 regs = model(1, 2, 0x0002_0005) # D slot 1 + 2 = 3, S0 slot 2 + 5 = 7
78 self.assertEqual((regs[3], regs[7], regs[4]), (sentinel(7), sentinel(3), sentinel(4)))
79
80 def test_non_vgpr_operand_rejected(self):
81 with tempfile.TemporaryDirectory() as tmp:
82 os.mkdir(os.path.join(tmp, "disasm"))
83 with open(os.path.join(tmp, "ps_swaprel.dxbc"), "wb") as f:
84 f.write(STUB_DXBC)
85 src = os.path.join(tmp, "disasm", "ps_swaprel.s")
86 with open(src, "w", encoding="utf-8") as f:
87 f.write("; ps_swaprel\n\tv_swaprel_b32 v1, s2\n\texp mrt0 v1, v1, v1, v1 done vm\n\ts_endpgm\n")
88 with self.assertRaises(rdna2spirv.Unsupported):
89 rdna2spirv.translate(src)
90
91if __name__ == "__main__":
92 unittest.main()
diff --git a/tests/semantic/test_buffer_oob_select.py b/tests/semantic/test_buffer_oob_select.py
index 50170c924..a936452b4 100644
--- a/tests/semantic/test_buffer_oob_select.py
+++ b/tests/semantic/test_buffer_oob_select.py
@@ -222,6 +222,59 @@ class OobSelect(unittest.TestCase):
222 want = {BASE + addr + 4 * k: 0x11111111 * (k + 1) for k in range(4)} if ok else {} 222 want = {BASE + addr + 4 * k: 0x11111111 * (k + 1) for k in range(4)} if ok else {}
223 self.assertEqual(dict(memory), want, ("store", mode, stride, nr, idx, off, runtime)) 223 self.assertEqual(dict(memory), want, ("store", mode, stride, nr, idx, off, runtime))
224 224
225 def test_loads_literal_v_sharp_from_s_mov_b64(self):
226 # s_mov_b64 s[6:7], imm folds word3 (OOB_SELECT mode) without run-time extraction.
227 for mode in range(4):
228 with self.subTest(mode=mode):
229 w3 = 0x01000FAC | (mode << 28)
230 val64 = (w3 << 32) | 0x10
231 lines = [f"s_mov_b64 s[4:5], {BASE:#x}", f"s_mov_b64 s[6:7], {val64:#x}",
232 "buffer_load_dword v2, off, s[4:7], 0", "s_waitcnt vmcnt(0)",
233 "buffer_store_dword v2, off, s[0:3], 0"]
234 spv = self.translate(lines)
235 self.assertEqual(len(MODE_EXTRACT.findall(spv)), 1, f"mode {mode} did not fold from s_mov_b64")
225 236
237 def test_loads_literal_v_sharp_from_s_movk_i32(self):
238 # s_movk_i32 s7, imm sets word3 for modes where word3 fits in 16 bits sign-extended.
239 lines = [f"s_mov_b32 s4, {BASE:#x}", "s_mov_b32 s5, 0", "s_mov_b32 s6, 16",
240 "s_movk_i32 s7, 0x3000",
241 "buffer_load_dword v2, off, s[4:7], 0", "s_waitcnt vmcnt(0)",
242 "buffer_store_dword v2, off, s[0:3], 0"]
243 spv = self.translate(lines)
244 self.assertEqual(len(MODE_EXTRACT.findall(spv)), 1, "s_movk_i32 did not fold into literal V#")
245
246 def test_loads_literal_v_sharp_from_sgpr_copy(self):
247 # Copy propagation: s_mov_b32 from a constant SGPR preserves sgpr_imm.
248 w3 = 0x31000FAC
249 lines = [f"s_mov_b32 s8, {w3:#x}", "s_mov_b32 s7, s8",
250 f"s_mov_b32 s4, {BASE:#x}", "s_mov_b32 s5, 0", "s_mov_b32 s6, 16",
251 "buffer_load_dword v2, off, s[4:7], 0", "s_waitcnt vmcnt(0)",
252 "buffer_store_dword v2, off, s[0:3], 0"]
253 spv = self.translate(lines)
254 self.assertEqual(len(MODE_EXTRACT.findall(spv)), 1, "s_mov_b32 copy did not fold into literal V#")
255
256 def test_loads_literal_v_sharp_from_s_mov_b64_copy(self):
257 # Copy propagation: s_mov_b64 64-bit pair copy preserves sgpr_imm.
258 w3 = 0x31000FAC
259 val64 = (w3 << 32) | 16
260 lines = [f"s_mov_b64 s[8:9], {val64:#x}", "s_mov_b64 s[6:7], s[8:9]",
261 f"s_mov_b32 s4, {BASE:#x}", "s_mov_b32 s5, 0",
262 "buffer_load_dword v2, off, s[4:7], 0", "s_waitcnt vmcnt(0)",
263 "buffer_store_dword v2, off, s[0:3], 0"]
264 spv = self.translate(lines)
265 self.assertEqual(len(MODE_EXTRACT.findall(spv)), 1, "s_mov_b64 pair copy did not fold into literal V#")
266
267 def test_loads_literal_v_sharp_from_s_mov_b64_overlapping_copy(self):
268 # Overlapping 64-bit copy s_mov_b64 s[6:7], s[5:6] where d == s + 1:
269 # Both source registers must be evaluated before writing destination,
270 # so s7 gets the old s6 literal rather than the newly written s6 (s5).
271 w3 = 0x31000FAC
272 lines = [f"s_mov_b32 s4, {BASE:#x}", "s_mov_b32 s5, 16",
273 f"s_mov_b32 s6, {w3:#x}",
274 "s_mov_b64 s[6:7], s[5:6]",
275 "buffer_load_dword v2, off, s[4:7], 0", "s_waitcnt vmcnt(0)",
276 "buffer_store_dword v2, off, s[0:3], 0"]
277 spv = self.translate(lines)
278 self.assertEqual(len(MODE_EXTRACT.findall(spv)), 1, "s_mov_b64 overlapping copy did not fold into literal V#")
226if __name__ == "__main__": 279if __name__ == "__main__":
227 unittest.main() 280 unittest.main()
diff --git a/tests/semantic/test_f16_interp_fallback.py b/tests/semantic/test_f16_interp_fallback.py
index 5565252ea..3eb9c8b5d 100644
--- a/tests/semantic/test_f16_interp_fallback.py
+++ b/tests/semantic/test_f16_interp_fallback.py
@@ -3,8 +3,9 @@
3By default a location any *_f16 interp reads is a PerVertexKHR vec4[3] of the producer's raw words, decoded and 3By default a location any *_f16 interp reads is a PerVertexKHR vec4[3] of the producer's raw words, decoded and
4weighted in the PS (test_interp_f16_high.py). MoltenVK can't compile that decoration to MSL ("PerVertexKHR decoration 4weighted in the PS (test_interp_f16_high.py). MoltenVK can't compile that decoration to MSL ("PerVertexKHR decoration
5is not supported in MSL"), so with the flag the producer (VS `exp paramN`, mesh params) also exports each channel's two 5is not supported in MSL"), so with the flag the producer (VS `exp paramN`, mesh params) also exports each channel's two
6f16 halves decoded to f32, low halves at location 29 - 2N and high halves at 30 - 2N, and the PS reads them as ordinary 6f16 halves decoded to f32, low halves at location 28 - 2N and high halves at 29 - 2N, and the PS reads them as ordinary
7smooth inputs. Interpolating the decoded halves is the same P0 + i(P1 - P0) + j(P2 - P0). Here: 7smooth inputs (the top is 29: MoltenVK's maxVertexOutputComponents, 124, counts gl_Position; SHADER-291).
8Interpolating the decoded halves is the same P0 + i(P1 - P0) + j(P2 - P0). Here:
8* the PS has no PerVertexKHR, no barycentric builtin, and reads 1.75 / 9.0 from the decoded-half inputs (the 9* the PS has no PerVertexKHR, no barycentric builtin, and reads 1.75 / 9.0 from the decoded-half inputs (the
9 per-vertex values of test_interp_f16_high.py, interpolated as Vulkan would), the f32 control and the flat raw read 10 per-vertex values of test_interp_f16_high.py, interpolated as Vulkan would), the f32 control and the flat raw read
10 unchanged; 11 unchanged;
@@ -15,6 +16,7 @@ smooth inputs. Interpolating the decoded halves is the same P0 + i(P1 - P0) + j(
15The GPU check is runtime/test/shaders/ps_interp_f16_high drawn with vs_f16_pack, which run_gpu_tests.py translates 16The GPU check is runtime/test/shaders/ps_interp_f16_high drawn with vs_f16_pack, which run_gpu_tests.py translates
16with the flag where tools/vk_subgroup_info.py reports per_vertex_inputs false (MoltenVK). 17with the flag where tools/vk_subgroup_info.py reports per_vertex_inputs false (MoltenVK).
17""" 18"""
19import re
18import struct 20import struct
19import unittest 21import unittest
20 22
@@ -82,11 +84,11 @@ class FallbackPixelShader(unittest.TestCase):
82 self.assertNotIn("fragmentShaderBarycentric", self.meta["features"]) 84 self.assertNotIn("fragmentShaderBarycentric", self.meta["features"])
83 85
84 def test_decoded_half_inputs(self): 86 def test_decoded_half_inputs(self):
85 self.assertIn("OpDecorate %in_f16h0_0 Location 29", self.spv) 87 self.assertIn("OpDecorate %in_f16h0_0 Location 28", self.spv)
86 self.assertIn("OpDecorate %in_f16h0_1 Location 30", self.spv) 88 self.assertIn("OpDecorate %in_f16h0_1 Location 29", self.spv)
87 self.assertNotIn("%in_f16h0_0 Flat", self.spv) 89 self.assertNotIn("%in_f16h0_0 Flat", self.spv)
88 self.assertEqual(self.meta["f16_halves"], {"0": [29, 30]}) 90 self.assertEqual(self.meta["f16_halves"], {"0": [28, 29]})
89 self.assertEqual(self.meta["inputs"], [0, 1, 29, 30]) 91 self.assertEqual(self.meta["inputs"], [0, 1, 28, 29])
90 92
91 def test_values(self): 93 def test_values(self):
92 words = support.mrt0_words(self.spv, inputs=self.inputs()) 94 words = support.mrt0_words(self.spv, inputs=self.inputs())
@@ -102,9 +104,9 @@ class FallbackPixelShader(unittest.TestCase):
102 self.assertEqual([f"{w & 0xFFFF:#06x}" for w in words[:2]], ["0x3f00", "0x3f00"]) 104 self.assertEqual([f"{w & 0xFFFF:#06x}" for w in words[:2]], ["0x3f00", "0x3f00"])
103 105
104 def test_location_clash_is_rejected(self): 106 def test_location_clash_is_rejected(self):
105 """attr29 read as f32 sits where attr0's low halves go: refuse instead of reading the wrong data.""" 107 """attr28 read as f32 sits where attr0's low halves go: refuse instead of reading the wrong data."""
106 clash = ["v_interp_p1ll_f16 v2, v0, attr0.x", "v_interp_p2_f16 v2, v1, attr0.x, v2", 108 clash = ["v_interp_p1ll_f16 v2, v0, attr0.x", "v_interp_p2_f16 v2, v1, attr0.x, v2",
107 "v_interp_p1_f32_e32 v3, v0, attr29.x", "v_interp_p2_f32_e32 v3, v1, attr29.x", 109 "v_interp_p1_f32_e32 v3, v0, attr28.x", "v_interp_p2_f32_e32 v3, v1, attr28.x",
108 "exp mrt0 v2, v3, v3, v3 done vm", "s_endpgm"] 110 "exp mrt0 v2, v3, v3, v3 done vm", "s_endpgm"]
109 with self.assertRaises(rdna2spirv.Unsupported): 111 with self.assertRaises(rdna2spirv.Unsupported):
110 translate("ps_f16_clash", clash) 112 translate("ps_f16_clash", clash)
@@ -119,10 +121,10 @@ class FallbackPixelShader(unittest.TestCase):
119class FallbackVertexShader(unittest.TestCase): 121class FallbackVertexShader(unittest.TestCase):
120 def test_exports_decoded_halves(self): 122 def test_exports_decoded_halves(self):
121 spv, meta = translate("vs_f16_fallback", VS.splitlines()) 123 spv, meta = translate("vs_f16_fallback", VS.splitlines())
122 for n, lo, hi in ((0, 29, 30), (1, 27, 28)): 124 for n, lo, hi in ((0, 28, 29), (1, 26, 27)):
123 self.assertIn(f"OpDecorate %out_f16h{n}_0 Location {lo}", spv) 125 self.assertIn(f"OpDecorate %out_f16h{n}_0 Location {lo}", spv)
124 self.assertIn(f"OpDecorate %out_f16h{n}_1 Location {hi}", spv) 126 self.assertIn(f"OpDecorate %out_f16h{n}_1 Location {hi}", spv)
125 self.assertEqual(meta["f16_halves"], {"0": [29, 30], "1": [27, 28]}) 127 self.assertEqual(meta["f16_halves"], {"0": [28, 29], "1": [26, 27]})
126 for vid in range(3): 128 for vid in range(3):
127 out = run_fragment(spv, inputs={"%vertex_index": vid, "%instance_index": 0}) 129 out = run_fragment(spv, inputs={"%vertex_index": vid, "%instance_index": 0})
128 u, v = float((vid << 1) & 2), float(vid & 2) 130 u, v = float((vid << 1) & 2), float(vid & 2)
@@ -137,13 +139,31 @@ class FallbackVertexShader(unittest.TestCase):
137 self.assertEqual(list(out["%out_param1"])[:2], [support_bits(u), support_bits(v)]) 139 self.assertEqual(list(out["%out_param1"])[:2], [support_bits(u), support_bits(v)])
138 140
139 def test_halves_never_overlap_the_shaders_params(self): 141 def test_halves_never_overlap_the_shaders_params(self):
140 """param29 occupies location 29, so param0's halves (29, 30) are left out; nothing else moves.""" 142 """param28 occupies location 28, so param0's halves (28, 29) are left out; nothing else moves."""
141 spv, meta = translate("vs_f16_far", ["v_mov_b32_e32 v1, 1.0", "exp pos0 v1, v1, v1, v1 done", 143 spv, meta = translate("vs_f16_far", ["v_mov_b32_e32 v1, 1.0", "exp pos0 v1, v1, v1, v1 done",
142 "exp param0 v1, v1, v1, v1", "exp param29 v1, v1, v1, v1", 144 "exp param0 v1, v1, v1, v1", "exp param28 v1, v1, v1, v1",
143 "s_endpgm"]) 145 "s_endpgm"])
144 self.assertNotIn("%out_f16h0", spv) 146 self.assertNotIn("%out_f16h0", spv)
145 self.assertNotIn("f16_halves", meta) 147 self.assertNotIn("f16_halves", meta)
146 self.assertIn("OpDecorate %out_param29 Location 29", spv) 148 self.assertIn("OpDecorate %out_param28 Location 28", spv)
149
150 def test_halves_fit_just_above_the_shaders_params(self):
151 """param27 ends at location 27, so param0's halves still fit at 28 and 29."""
152 spv, meta = translate("vs_f16_near", ["v_mov_b32_e32 v1, 1.0", "exp pos0 v1, v1, v1, v1 done",
153 "exp param0 v1, v1, v1, v1", "exp param27 v1, v1, v1, v1",
154 "s_endpgm"])
155 self.assertEqual(meta["f16_halves"], {"0": [28, 29]})
156 self.assertIn("OpDecorate %out_param27 Location 27", spv)
157
158 def test_top_half_fits_moltenvk_output_budget(self):
159 """SHADER-291: MoltenVK reports maxVertexOutputComponents = 124, and Metal and the validation layer count
160 gl_Position's 4 in it (VUID-RuntimeSpirv-Location-06272), so the highest location a VS writes must be 29."""
161 top = rdna2spirv.f16_half_location(0, 1)
162 self.assertEqual(top, 29)
163 self.assertLessEqual((top + 1) * 4 + 4, 124)
164 spv, _ = translate("vs_f16_fallback", VS.splitlines())
165 locations = [int(m) for m in re.findall(r"OpDecorate %out\S+ Location (\d+)", spv)]
166 self.assertEqual(max(locations), top)
147 167
148 def test_off_by_default(self): 168 def test_off_by_default(self):
149 spv, meta = translate("vs_f16_fallback", VS.splitlines(), fallback=False) 169 spv, meta = translate("vs_f16_fallback", VS.splitlines(), fallback=False)
diff --git a/tests/semantic/test_interp_merge_check.py b/tests/semantic/test_interp_merge_check.py
new file mode 100644
index 000000000..382955f5f
--- /dev/null
+++ b/tests/semantic/test_interp_merge_check.py
@@ -0,0 +1,78 @@
1"""spirv_mini_interp and spirv_wave_interp reject a module that breaks spirv-val's merge rule.
2
3OpSelectionMerge must directly precede OpBranchConditional / OpSwitch, and OpLoopMerge directly precede OpBranch /
4OpBranchConditional (SPIR-V 2.16.2). Both interpreters used to skip merges, so #1633's first version, with an
5`OpLoad %active` between the merge and its branch, passed every semantic test while spirv-val rejected every module
6it produced (found by @mokkymiah, confirmed by @Impre-visible). Each case takes a translated module, which the
7interpreters run, and moves one instruction to sit between a merge and its branch. Standard library only.
8"""
9import os
10import re
11import sys
12import unittest
13
14HERE = os.path.dirname(os.path.abspath(__file__))
15sys.dont_write_bytecode = True
16sys.path.insert(0, HERE)
17
18from test_salu64_bitwise_data import translate_ps # noqa: E402 (also puts tools/ on sys.path)
19import spirv_mini_interp as si # noqa: E402
20import spirv_wave_interp as wi # noqa: E402
21
22LINES = ["v_mbcnt_lo_u32_b32 v4, -1, 0", "v_cmpx_gt_u32_e32 5, v4", "v_mov_b32 v0, 1.0",
23 "exp mrt0 v0, v0, v0, v0 done vm", "s_endpgm"]
24
25
26def spv():
27 text = translate_ps(LINES)
28 assert text.count("OpSelectionMerge") >= 1
29 return text
30
31
32def break_merge(text):
33 """Put the instruction just before the first OpSelectionMerge between it and its branch."""
34 lines = text.splitlines()
35 k = next(i for i, ln in enumerate(lines) if ln.strip().startswith("OpSelectionMerge"))
36 assert re.match(r"\s*%\S+ = Op", lines[k - 1]), lines[k - 1]
37 lines[k - 1], lines[k] = lines[k], lines[k - 1]
38 return "\n".join(lines) + "\n"
39
40
41def drop_branch(text):
42 """Remove the branch after the first OpSelectionMerge, so the merge is followed by something else."""
43 lines = text.splitlines()
44 k = next(i for i, ln in enumerate(lines) if ln.strip().startswith("OpSelectionMerge"))
45 return "\n".join(lines[:k + 1] + lines[k + 2:]) + "\n"
46
47
48class MergeRule(unittest.TestCase):
49 def test_translated_module_runs(self):
50 text = spv()
51 self.assertEqual(si.run_fragment(text)["%out_mrt0"][0], 0x3F800000)
52 self.assertEqual(len(wi.run_wave(text, wave=32)["outputs"]), 32)
53
54 def test_instruction_between_merge_and_branch(self):
55 bad = break_merge(spv())
56 with self.assertRaisesRegex(si.InvalidModule, "OpSelectionMerge"):
57 si.run_fragment(bad)
58 with self.assertRaisesRegex(wi.InvalidModule, "OpSelectionMerge"):
59 wi.run_wave(bad, wave=32)
60
61 def test_merge_without_its_branch(self):
62 bad = drop_branch(spv())
63 with self.assertRaises(si.InvalidModule):
64 si.run_fragment(bad)
65 with self.assertRaises(wi.InvalidModule):
66 wi.run_wave(bad, wave=32)
67
68 def test_loop_merge_rule(self):
69 ok = [(None, "OpLoopMerge", [], "OpLoopMerge %m %c None"), (None, "OpBranch", [], "OpBranch %h")]
70 si.check_structure(ok)
71 with self.assertRaisesRegex(si.InvalidModule, "OpLoopMerge"):
72 si.check_structure([ok[0], (None, "OpIAdd", [], "%x = OpIAdd %uint %a %b"), ok[1]])
73 with self.assertRaisesRegex(si.InvalidModule, "end of the function"):
74 si.check_structure([ok[0]])
75
76
77if __name__ == "__main__":
78 unittest.main()
diff --git a/tests/semantic/test_interp_p1lv_f16.py b/tests/semantic/test_interp_p1lv_f16.py
new file mode 100644
index 000000000..0ddf9bd74
--- /dev/null
+++ b/tests/semantic/test_interp_p1lv_f16.py
@@ -0,0 +1,470 @@
1"""Semantic and translation tests for v_interp_p1lv_f16, f16 --bary-fallback, and stage/attr guards.
2
3Covers the remaining 16-bit interpolation behaviour in tools/rdna2spirv.py not exercised by
4test_interp_f16.py (clamp), test_interp_f16_high.py (p1ll low/high), or test_f16_interp_fallback.py:
5- v_interp_p1lv_f16: PerVertexKHR low/high half decoding, standalone f32 intermediate, paired v_interp_p2_f16
6 f16 narrowing and VOP3 clamp, nearest-even tie rounding, SV_Position ISG1 layout coexistence,
7 --f16-interp-fallback (F16_HALVES) execution and location-clash rejection, and SPIR-V negative controls.
8- --bary-fallback (BARY_FALLBACK) with v_interp_p1ll_f16, v_interp_p1lv_f16, and v_interp_p2_f16: omits
9 PerVertexKHR / BaryCoordKHR, reads ordinary smooth vec4 inputs (where `high` cannot be distinguished),
10 places %bary at the lowest free location when raw v0/v1 reads are also present, and yields to
11 --f16-interp-fallback when both flags are enabled.
12- I-source guards (interp_pair_src) for v_interp_p1lv_f16 and v_interp_p1ll_f16, plus Unsupported("<op> form")
13 rejection on non-PS stages (vs_, cs_) and missing `attr` operands for all three *_f16 opcodes.
14"""
15import os
16import re
17import struct
18import sys
19import unittest
20
21HERE = os.path.dirname(os.path.abspath(__file__))
22ROOT = os.path.dirname(os.path.dirname(HERE))
23TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools")
24
25sys.dont_write_bytecode = True
26if TOOLS_DIR not in sys.path:
27 sys.path.insert(0, TOOLS_DIR)
28if HERE not in sys.path:
29 sys.path.insert(0, HERE)
30
31import rdna2spirv # noqa: E402
32import support # noqa: E402
33
34BARY = (0.25, 0.25, 0.5) # vertex 0, 1, 2 weights (AMD i = 0.25, j = 0.5)
35LO = (0.5, 1.5, 2.5) # exact interpolated value: 1.75 (0x3f00)
36HI = (-4.0, 8.0, 16.0) # exact interpolated value: 9.0 (0x4880)
37
38
39def pack_f16(lo, hi):
40 """Pack two floats as (low_f16 | high_f16 << 16) in a 32-bit word."""
41 return struct.unpack("<I", struct.pack("<ee", lo, hi))[0]
42
43
44def f16_bits(val):
45 return struct.unpack("<H", struct.pack("<e", float(val)))[0]
46
47
48def f32_bits(val):
49 return struct.unpack("<I", struct.pack("<f", float(val)))[0]
50
51
52def lerp(values, bary=BARY):
53 return sum(b * v for b, v in zip(bary, values))
54
55
56def isg1_dxbc(elements):
57 """Synthetic DXBC container with one ISG1 chunk: elements = (register, mask, rw_mask, sysv, ctype)."""
58 payload = bytearray(struct.pack("<II", len(elements), 8))
59 for reg, mask, rw_mask, sysv, ctype in elements:
60 elem = bytearray(32)
61 struct.pack_into("<6I", elem, 0, 0, 0, 0, sysv, ctype, reg)
62 elem[24], elem[25] = mask, rw_mask
63 payload += elem
64 part = b"ISG1" + struct.pack("<I", len(payload)) + bytes(payload)
65 part += bytes((-len(part)) % 4)
66 header = b"DXBC" + bytes(16) + struct.pack("<III", 1, 0, 1)
67 return header + struct.pack("<I", len(header) + 8) + bytes(4) + part
68
69
70def cs_fssm(rsrc2, group):
71 """Minimal compute FSSM header carrying COMPUTE_PGM_RSRC2 and local thread-group dimensions."""
72 header = bytearray(0x148)
73 struct.pack_into("<4I", header, 0x138, rsrc2, *group)
74 return bytes(header)
75
76
77# Default compute FSSM (4 user SGPRs, 64x1x1 threads) and PS ISG1 (attr0.xyzw + attr1.x, float32).
78CS_FSSM = cs_fssm(0x8088, (64, 1, 1))
79PS_ATTR01_DXBC = isg1_dxbc([(0, 0xF, 0xF, 0, 3), (1, 0x1, 0x1, 0, 3)])
80PS_POS_ATTR0_DXBC = isg1_dxbc([(0, 0xF, 0x3, 1, 3), (1, 0xF, 0xF, 0, 3)])
81
82
83def translate_with_flags(name, lines, *, dxbc=support.STUB_DXBC, fssm=None,
84 bary_fallback=False, f16_halves=False):
85 """Translate `lines` with explicit BARY_FALLBACK / F16_HALVES flags and return (spvasm, meta)."""
86 old_bf, old_fh = rdna2spirv.BARY_FALLBACK, rdna2spirv.F16_HALVES
87 rdna2spirv.BARY_FALLBACK = bary_fallback
88 rdna2spirv.F16_HALVES = f16_halves
89 try:
90 spv = support.translate_lines(name, lines, dxbc=dxbc, fssm=fssm)
91 meta = rdna2spirv.shader_meta(rdna2spirv.translate.last_gen, spv)
92 finally:
93 rdna2spirv.BARY_FALLBACK = old_bf
94 rdna2spirv.F16_HALVES = old_fh
95 return spv, meta
96
97
98# Primary v_interp_p1lv_f16 PS exercising low half, high half, clamp, standalone f32 intermediate,
99# and f32/flat controls on attr0 (PerVertexKHR) and attr1 (smooth f32).
100P1LV_SHADER = [
101 "v_mov_b32_e32 v10, 0",
102 "v_interp_p1lv_f16 v2, v0, attr0.x, v10",
103 "v_interp_p2_f16 v2, v1, attr0.x, v2",
104 "v_interp_p1lv_f16 v3, v0, attr0.x, v10 high",
105 "v_interp_p2_f16 v3, v1, attr0.x, v3 high",
106 "v_interp_p1lv_f16 v4, v0, attr0.y, v10",
107 "v_interp_p2_f16 v4, v1, attr0.y, v4 clamp",
108 "v_interp_p1lv_f16 v5, v0, attr0.y, v10 high",
109 "v_interp_p2_f16 v5, v1, attr0.y, v5 high clamp",
110 "v_interp_p1lv_f16 v6, v0, attr0.z, v10", # standalone f32 intermediate
111 "v_interp_p1_f32_e32 v7, v0, attr1.x",
112 "v_interp_p2_f32_e32 v7, v1, attr1.x",
113 "v_interp_mov_f32_e32 v8, p0, attr0.w",
114 "exp mrt0 v2, v3, v4, v5",
115 "s_nop 0",
116 "exp mrt1 v6, v7, v8, v8 done vm",
117 "s_endpgm",
118]
119
120P1LV_CLAMP_PAIR = [
121 "v_mov_b32_e32 v10, 0",
122 "v_interp_p1lv_f16 v2, v0, attr0.x, v10",
123 "v_interp_p2_f16 v2, v1, attr0.x, v2 clamp",
124 "v_interp_p1lv_f16 v3, v0, attr0.x, v10 high",
125 "v_interp_p2_f16 v3, v1, attr0.x, v3 high clamp",
126 "v_interp_p1lv_f16 v4, v0, attr0.y, v10",
127 "v_interp_p2_f16 v4, v1, attr0.y, v4",
128 "v_interp_p1lv_f16 v5, v0, attr0.z, v10",
129 "exp mrt0 v2, v3, v4, v5 done vm",
130 "s_endpgm",
131]
132
133
134class InterpP1lvF16DefaultTests(unittest.TestCase):
135 """Default PerVertexKHR translation and execution for v_interp_p1lv_f16."""
136
137 def _default_attrs(self):
138 # attr0.x: (lo=1.75, hi=9.0); attr0.y: (lo=-0.25 -> clamp 0.0, hi=1.75 -> clamp 1.0);
139 # attr0.z: lo=(1.0, 3.0, 5.0) -> 3.5 as f32 intermediate; attr0.w: raw flat words.
140 y_lo = (-1.0, -1.0, 0.5) # 0.25*(-1.0) + 0.25*(-1.0) + 0.5*0.5 = -0.25 -> clamped to 0.0
141 y_hi = (0.5, 1.5, 2.5) # 1.75 -> clamped to 1.0
142 z_lo = (1.0, 3.0, 5.0) # 3.5
143 w_raw = (0x1234, 0x5678, 0x9ABC)
144 attr0 = [(pack_f16(lo, hi), pack_f16(yl, yh), pack_f16(zl, 0.0), wr)
145 for lo, hi, yl, yh, zl, wr in zip(LO, HI, y_lo, y_hi, z_lo, w_raw)]
146 attr1 = [(f32_bits(x), 0, 0, 0) for x in (-2.0, 2.0, 4.0)] # 0.25*(-2)+0.25*2+0.5*4 = 2.0
147 return {0: attr0, 1: attr1}
148
149 def test_p1lv_low_high_clamp_and_intermediate_end_to_end(self):
150 spv, meta = translate_with_flags("ps_p1lv", P1LV_SHADER, dxbc=PS_ATTR01_DXBC)
151
152 self.assertIn("OpCapability FragmentBarycentricKHR", spv)
153 self.assertIn('OpExtension "SPV_KHR_fragment_shader_barycentric"', spv)
154 self.assertIn("OpDecorate %in_attr0 PerVertexKHR", spv)
155 self.assertIn("OpDecorate %bary BuiltIn BaryCoordKHR", spv)
156 self.assertIn("OpDecorate %in_attr1 Location 1", spv)
157 self.assertNotIn("OpDecorate %in_attr1 PerVertexKHR", spv)
158 self.assertNotIn("OpDecorate %in_attr1 Flat", spv)
159 self.assertIn("UnpackHalf2x16", spv)
160 self.assertEqual(meta["features"], ["fragmentShaderBarycentric"])
161 self.assertEqual(meta["inputs"], [0, 1])
162
163 attrs = self._default_attrs()
164 out = support.run_fragment(spv, inputs=support.varyings(spv, attrs, BARY))
165 mrt0, mrt1 = out["%out_mrt0"], out["%out_mrt1"]
166 self.assertEqual([w & 0xFFFF for w in mrt0], [0x3F00, 0x4880, 0x0000, 0x3C00])
167 # Standalone v_interp_p1lv_f16 exports the f32 intermediate (3.5), not f16 bits.
168 self.assertEqual(f"{mrt1[0]:#010x}", f"{f32_bits(3.5):#010x}")
169 self.assertEqual(f"{mrt1[1]:#010x}", f"{f32_bits(2.0):#010x}")
170 self.assertEqual(mrt1[2], 0x1234)
171
172 def test_p1lv_clamp_vs_unclamped_and_in_range(self):
173 # attr0.x: lo=1.5 (clamp->1.0), hi=-0.25 (clamp->+0.0); attr0.y: lo=0.5 (in-range); attr0.z: lo=3.5 (p1lv)
174 attrs = {0: [(pack_f16(1.5, -0.25), pack_f16(0.5, 0.0), pack_f16(3.5, 0.0), 0)] * 3}
175 spv_clamp, _ = translate_with_flags("ps_p1lv_clamp", P1LV_CLAMP_PAIR, dxbc=PS_ATTR01_DXBC)
176 self.assertIn("FClamp", spv_clamp)
177 words_clamp = support.mrt0_words(spv_clamp, inputs=support.varyings(spv_clamp, attrs, BARY))
178 self.assertEqual([w & 0xFFFF for w in words_clamp[:3]], [0x3C00, 0x0000, 0x3800])
179 self.assertEqual(words_clamp[3], f32_bits(3.5))
180
181 no_clamp_lines = [ln.replace(" clamp", "") for ln in P1LV_CLAMP_PAIR]
182 spv_raw, _ = translate_with_flags("ps_p1lv_noclamp", no_clamp_lines, dxbc=PS_ATTR01_DXBC)
183 self.assertNotIn("FClamp", spv_raw)
184 words_raw = support.mrt0_words(spv_raw, inputs=support.varyings(spv_raw, attrs, BARY))
185 self.assertEqual([w & 0xFFFF for w in words_raw[:3]], [f16_bits(1.5), f16_bits(-0.25), 0x3800])
186
187 def test_p1lv_nearest_even_rounding_and_subnormal_f16(self):
188 # Midpoint ties:
189 # 1.0 (0x3c00) and 1.0 + 2^-10 (0x3c01) averaged at (0.5, 0.5, 0.0) -> 1.0 + 2^-11 -> 0x3c00 (even)
190 # 1.0 + 2^-10 (0x3c01) and 1.0 + 2^-9 (0x3c02) averaged -> 1.0 + 3*2^-11 -> 0x3c02 (even)
191 # Subnormals 0x0002 and 0x0004 averaged -> 0x0003 (subnormal preserved by f16_bits)
192 lines = [
193 "v_mov_b32_e32 v10, 0",
194 "v_interp_p1lv_f16 v2, v0, attr0.x, v10",
195 "v_interp_p2_f16 v2, v1, attr0.x, v2",
196 "v_interp_p1lv_f16 v3, v0, attr0.x, v10 high",
197 "v_interp_p2_f16 v3, v1, attr0.x, v3 high",
198 "v_interp_p1lv_f16 v4, v0, attr0.y, v10",
199 "v_interp_p2_f16 v4, v1, attr0.y, v4",
200 "exp mrt0 v2, v3, v4, v4 done vm",
201 "s_endpgm",
202 ]
203 h0 = 0x3C00
204 h1 = 0x3C01
205 h2 = 0x3C02
206 attr0 = [
207 ((h0 & 0xFFFF) | ((h1 & 0xFFFF) << 16), 0x0002, 0, 0),
208 ((h1 & 0xFFFF) | ((h2 & 0xFFFF) << 16), 0x0004, 0, 0),
209 ((h0 & 0xFFFF) | ((h1 & 0xFFFF) << 16), 0x0002, 0, 0),
210 ]
211 spv, _ = translate_with_flags("ps_p1lv_ties", lines, dxbc=PS_ATTR01_DXBC)
212 words = support.mrt0_words(spv, inputs=support.varyings(spv, {0: attr0}, (0.5, 0.5, 0.0)))
213 self.assertEqual([w & 0xFFFF for w in words[:3]], [0x3C00, 0x3C02, 0x0003])
214
215 def test_p1lv_with_sv_position_in_isg1(self):
216 # SV_Position at ISG1 reg 0 occupies v2..v5; v_interp_p1lv_f16 reads v0 and vsrc2=v10 without conflict.
217 lines = [
218 "v_mov_b32_e32 v10, 0",
219 "v_interp_p1lv_f16 v6, v0, attr0.x, v10 high",
220 "v_interp_p2_f16 v6, v1, attr0.x, v6 high",
221 "v_add_f32_e32 v7, v2, v3",
222 "exp mrt0 v6, v7, v6, v7 done vm",
223 "s_endpgm",
224 ]
225 spv, meta = translate_with_flags("ps_p1lv_pos", lines, dxbc=PS_POS_ATTR0_DXBC)
226 self.assertEqual(meta["ps_system_inputs"], ["0", "1"])
227 attr0 = [(pack_f16(0.5, hi), 0, 0, 0) for hi in HI]
228 inputs = support.varyings(spv, {0: attr0}, BARY)
229 inputs["%frag_coord"] = (1.25, 2.5, 0.0, 1.0)
230 words = support.mrt0_words(spv, inputs=inputs)
231 self.assertEqual(words[0] & 0xFFFF, 0x4880)
232 self.assertEqual(words[1], f32_bits(3.75))
233
234 def test_negative_controls_p1lv(self):
235 attrs = {0: [(pack_f16(1.5, -0.25), pack_f16(0.5, 0.0), pack_f16(3.5, 0.0), 0)] * 3}
236 spv, _ = translate_with_flags("ps_p1lv_neg", P1LV_CLAMP_PAIR, dxbc=PS_ATTR01_DXBC)
237 inputs = support.varyings(spv, attrs, BARY)
238 baseline = support.mrt0_words(spv, inputs=inputs)
239 self.assertEqual([w & 0xFFFF for w in baseline[:3]], [0x3C00, 0x0000, 0x3800])
240
241 # Sabotage 1: force high-half extract (component 1) to low half (component 0).
242 bad_half = re.sub(r"OpCompositeExtract %float (%\S+) 1", r"OpCompositeExtract %float \1 0", spv)
243 self.assertNotEqual(bad_half, spv)
244 self.assertNotEqual(support.mrt0_words(bad_half, inputs=inputs), baseline)
245
246 # Sabotage 2: drop FClamp by replacing FClamp %v %f0 %f1 with FMax %v %f0.
247 bad_clamp = re.sub(r"OpExtInst %float %glsl FClamp (%\S+) %f0 %f1", r"OpExtInst %float %glsl FMax \1 %f0", spv)
248 self.assertNotEqual(bad_clamp, spv)
249 self.assertNotEqual(support.mrt0_words(bad_clamp, inputs=inputs), baseline)
250
251
252class InterpP1lvF16HalvesFallbackTests(unittest.TestCase):
253 """--f16-interp-fallback (F16_HALVES) behaviour with v_interp_p1lv_f16."""
254
255 def test_p1lv_f16_halves_translation_and_execution(self):
256 spv, meta = translate_with_flags("ps_p1lv_fh", P1LV_CLAMP_PAIR,
257 dxbc=PS_ATTR01_DXBC, f16_halves=True)
258 self.assertNotIn("PerVertexKHR", spv)
259 self.assertNotIn("BaryCoordKHR", spv)
260 self.assertNotIn("FragmentBarycentricKHR", spv)
261 self.assertNotIn("fragmentShaderBarycentric", meta["features"])
262 self.assertIn("OpDecorate %in_f16h0_0 Location 28", spv)
263 self.assertIn("OpDecorate %in_f16h0_1 Location 29", spv)
264 self.assertNotIn("OpDecorate %in_f16h0_0 Flat", spv)
265 self.assertEqual(meta["f16_halves"], {"0": [28, 29]})
266 self.assertEqual(meta["inputs"], [28, 29])
267
268 inputs = {
269 "%in_f16h0_0": (lerp(LO), 0.5, 3.5, 0.0), # attr0 low: 1.75 (clamped->1.0), 0.5, 3.5 (p1lv f32)
270 "%in_f16h0_1": (lerp(HI), 0.0, 0.0, 0.0), # attr0 high: 9.0 (clamped->1.0)
271 }
272 words = support.mrt0_words(spv, inputs=inputs)
273 self.assertEqual([w & 0xFFFF for w in words[:3]], [0x3C00, 0x3C00, 0x3800])
274 self.assertEqual(words[3], f32_bits(3.5))
275
276 def test_p1lv_f16_halves_location_clash_rejected(self):
277 clash = [
278 "v_mov_b32_e32 v10, 0",
279 "v_interp_p1lv_f16 v2, v0, attr0.x, v10",
280 "v_interp_p2_f16 v2, v1, attr0.x, v2",
281 "v_interp_p1_f32_e32 v3, v0, attr29.x",
282 "v_interp_p2_f32_e32 v3, v1, attr29.x",
283 "exp mrt0 v2, v3, v3, v3 done vm",
284 "s_endpgm",
285 ]
286 with self.assertRaises(rdna2spirv.Unsupported) as cm:
287 translate_with_flags("ps_p1lv_fh_clash", clash, f16_halves=True)
288 self.assertIn("decoded-half location", str(cm.exception))
289
290
291class InterpF16BaryFallbackTests(unittest.TestCase):
292 """--bary-fallback (BARY_FALLBACK) translation and execution for *_f16 ops."""
293
294 def test_bary_fallback_for_p1ll_p1lv_p2_uses_smooth_inputs_without_per_vertex(self):
295 lines = [
296 "v_mov_b32_e32 v10, 0",
297 "v_interp_p1ll_f16 v2, v0, attr0.x",
298 "v_interp_p2_f16 v2, v1, attr0.x, v2",
299 "v_interp_p1lv_f16 v3, v0, attr0.y, v10 high",
300 "v_interp_p2_f16 v3, v1, attr0.y, v3 high clamp",
301 "v_interp_p1lv_f16 v4, v0, attr0.z, v10", # standalone f32 intermediate
302 "exp mrt0 v2, v3, v4, v2 done vm",
303 "s_endpgm",
304 ]
305 spv, meta = translate_with_flags("ps_f16_bf", lines, dxbc=PS_ATTR01_DXBC, bary_fallback=True)
306
307 self.assertNotIn("PerVertexKHR", spv)
308 self.assertNotIn("BaryCoordKHR", spv)
309 self.assertNotIn("FragmentBarycentricKHR", spv)
310 self.assertNotIn("SPV_KHR_fragment_shader_barycentric", spv)
311 self.assertNotIn("%bary", spv)
312 self.assertIn("OpDecorate %in_attr0 Location 0", spv)
313 self.assertNotIn("OpDecorate %in_attr0 Flat", spv)
314 self.assertEqual(meta["features"], [])
315 self.assertEqual(meta["inputs"], [0])
316 self.assertNotIn("bary_fallback_input", meta)
317 self.assertNotIn("f16_halves", meta)
318
319 # Under --bary-fallback there are no per-vertex inputs, so high reads the same smooth f32 channel.
320 attrs = {0: [(f32_bits(x), f32_bits(y), f32_bits(z), 0)
321 for x, y, z in zip((0.5, 1.5, 2.5), (-1.0, -1.0, 0.5), (1.0, 3.0, 5.0))]}
322 words = support.mrt0_words(spv, inputs=support.varyings(spv, attrs, BARY))
323 self.assertEqual(words[0] & 0xFFFF, 0x3F00) # 1.75
324 self.assertEqual(words[1] & 0xFFFF, 0x0000) # -0.25 clamped to +0.0
325 self.assertEqual(words[2], f32_bits(3.5)) # standalone p1lv f32 intermediate
326
327 # Confirm `high` and non-`high` read identically under --bary-fallback.
328 lines_same = [
329 "v_mov_b32_e32 v10, 0",
330 "v_interp_p1ll_f16 v2, v0, attr0.x",
331 "v_interp_p2_f16 v2, v1, attr0.x, v2",
332 "v_interp_p1lv_f16 v3, v0, attr0.x, v10 high",
333 "v_interp_p2_f16 v3, v1, attr0.x, v3 high",
334 "exp mrt0 v2, v3, v2, v3 done vm",
335 "s_endpgm",
336 ]
337 spv_same, _ = translate_with_flags("ps_f16_bf_same", lines_same, dxbc=PS_ATTR01_DXBC, bary_fallback=True)
338 words_same = support.mrt0_words(spv_same, inputs={"%in_attr0": (1.75, 0.0, 0.0, 0.0)})
339 self.assertEqual([w & 0xFFFF for w in words_same[:2]], [0x3F00, 0x3F00])
340
341 def test_bary_fallback_with_raw_bary_read_and_sparse_attr(self):
342 for attr_idx, want_bary_loc in ((0, 1), (30, 0)):
343 with self.subTest(attr=attr_idx):
344 lines = [
345 "v_mov_b32_e32 v10, 0",
346 f"v_interp_p1lv_f16 v2, v0, attr{attr_idx}.x, v10",
347 f"v_interp_p2_f16 v2, v1, attr{attr_idx}.x, v2",
348 "v_mov_b32_e32 v4, v0",
349 "v_mov_b32_e32 v5, v1",
350 "exp mrt0 v2, v4, v5, v2 done vm",
351 "s_endpgm",
352 ]
353 spv, meta = translate_with_flags(f"ps_f16_bf_raw_{attr_idx}", lines, bary_fallback=True)
354 self.assertNotIn("PerVertexKHR", spv)
355 self.assertNotIn("BaryCoordKHR", spv)
356 self.assertNotIn("FragmentBarycentricKHR", spv)
357 self.assertIn(f"OpDecorate %in_attr{attr_idx} Location {attr_idx}", spv)
358 self.assertIn(f"OpDecorate %bary Location {want_bary_loc}", spv)
359 self.assertIsNone(re.search(r"OpDecorate %bary (Flat|NoPerspective)", spv))
360 self.assertEqual(meta["bary_fallback_input"], {"location": want_bary_loc})
361 self.assertEqual(meta["ps_system_inputs"], ["bary_i", "bary_j"])
362
363 words = support.mrt0_words(spv, inputs={
364 f"%in_attr{attr_idx}": (1.75, 0.0, 0.0, 0.0),
365 "%bary": BARY,
366 })
367 self.assertEqual(words[0] & 0xFFFF, 0x3F00)
368 self.assertEqual(words[1], f32_bits(BARY[1]))
369 self.assertEqual(words[2], f32_bits(BARY[2]))
370
371 def test_f16_halves_takes_precedence_over_bary_fallback(self):
372 spv, meta = translate_with_flags("ps_both_flags", P1LV_CLAMP_PAIR,
373 dxbc=PS_ATTR01_DXBC, bary_fallback=True, f16_halves=True)
374 self.assertNotIn("PerVertexKHR", spv)
375 self.assertIn("OpDecorate %in_f16h0_0 Location 28", spv)
376 self.assertIn("OpDecorate %in_f16h0_1 Location 29", spv)
377 self.assertEqual(meta["f16_halves"], {"0": [28, 29]})
378
379
380class InterpF16GuardsAndRejectionsTests(unittest.TestCase):
381 """interp_pair_src guards and Unsupported('<op> form') stage/attr rejections."""
382
383 def test_p1lv_and_p1ll_i_source_guards(self):
384 bad_cases = [
385 ("v_interp_p1lv_f16 I source v4", [
386 "v_mov_b32_e32 v10, 0",
387 "v_interp_p1lv_f16 v2, v4, attr0.x, v10",
388 "v_interp_p2_f16 v2, v1, attr0.x, v2",
389 "exp mrt0 v2, v2, v2, v2 done vm",
390 "s_endpgm",
391 ]),
392 ("v_interp_p1lv_f16 I source v1", [
393 "v_mov_b32_e32 v10, 0",
394 "v_interp_p1lv_f16 v2, v1, attr0.x, v10",
395 "v_interp_p2_f16 v2, v1, attr0.x, v2",
396 "exp mrt0 v2, v2, v2, v2 done vm",
397 "s_endpgm",
398 ]),
399 ("v_interp_p1ll_f16 I source v1", [
400 "v_interp_p1ll_f16 v2, v1, attr0.x",
401 "v_interp_p2_f16 v2, v1, attr0.x, v2",
402 "exp mrt0 v2, v2, v2, v2 done vm",
403 "s_endpgm",
404 ]),
405 # An I source holding a zeroed v0 ("v_mov v0, 0; v_mov v6, v0") is a computed I of 0, which the translator
406 # models since #1545 (computed I/J barycentrics) instead of rejecting; it is no longer a bad case here.
407 ("v_interp_p2_f16 J source v0", [
408 "v_mov_b32_e32 v10, 0",
409 "v_interp_p1lv_f16 v2, v0, attr0.x, v10",
410 "v_interp_p2_f16 v2, v0, attr0.x, v2",
411 "exp mrt0 v2, v2, v2, v2 done vm",
412 "s_endpgm",
413 ]),
414 ]
415 for msg, lines in bad_cases:
416 with self.subTest(msg=msg):
417 with self.assertRaises(rdna2spirv.Unsupported) as cm:
418 translate_with_flags("ps_guard_bad", lines, dxbc=PS_ATTR01_DXBC)
419 self.assertIn(msg, str(cm.exception))
420
421 def test_p1lv_accepts_saved_copy_of_v0_even_if_v0_later_zeroed(self):
422 lines = [
423 "v_mov_b32_e32 v6, v0",
424 "v_mov_b32_e32 v7, v1",
425 "v_mov_b32_e32 v0, 0",
426 "v_mov_b32_e32 v1, 0",
427 "v_mov_b32_e32 v10, 0",
428 "v_interp_p1lv_f16 v2, v6, attr0.x, v10 high",
429 "v_interp_p2_f16 v2, v7, attr0.x, v2 high",
430 "exp mrt0 v2, v2, v2, v2 done vm",
431 "s_endpgm",
432 ]
433 spv, _ = translate_with_flags("ps_p1lv_copy", lines, dxbc=PS_ATTR01_DXBC)
434 attrs = {0: [(pack_f16(lo, hi), 0, 0, 0) for lo, hi in zip(LO, HI)]}
435 words = support.mrt0_words(spv, inputs=support.varyings(spv, attrs, BARY))
436 self.assertEqual(words[0] & 0xFFFF, 0x4880)
437
438 def test_non_ps_stages_rejected_for_all_f16_interp_ops(self):
439 ops = [
440 ("v_interp_p1ll_f16", "v_interp_p1ll_f16 v2, v0, attr0.x"),
441 ("v_interp_p1lv_f16", "v_interp_p1lv_f16 v2, v0, attr0.x, v3"),
442 ("v_interp_p2_f16", "v_interp_p2_f16 v2, v1, attr0.x, v2"),
443 ]
444 for op, insn in ops:
445 with self.subTest(stage="vs", op=op):
446 with self.assertRaises(rdna2spirv.Unsupported) as cm:
447 translate_with_flags(f"vs_{op}", [insn, "exp pos0 v2, v2, v2, v2 done", "s_endpgm"])
448 self.assertIn(f"{op} form", str(cm.exception))
449 with self.subTest(stage="cs", op=op):
450 with self.assertRaises(rdna2spirv.Unsupported) as cm:
451 translate_with_flags(f"cs_{op}", [insn, "s_endpgm"], fssm=CS_FSSM)
452 self.assertIn(f"{op} form", str(cm.exception))
453
454 def test_missing_attr_operand_rejected_for_all_f16_interp_ops(self):
455 ops = [
456 ("v_interp_p1ll_f16", "v_interp_p1ll_f16 v2, v0, v3"),
457 ("v_interp_p1lv_f16", "v_interp_p1lv_f16 v2, v0, v3, v4"),
458 ("v_interp_p2_f16", "v_interp_p2_f16 v2, v1, v3, v2"),
459 ]
460 for op, insn in ops:
461 with self.subTest(op=op):
462 with self.assertRaises(rdna2spirv.Unsupported) as cm:
463 translate_with_flags(f"ps_noattr_{op}",
464 [insn, "exp mrt0 v2, v2, v2, v2 done vm", "s_endpgm"],
465 dxbc=PS_ATTR01_DXBC)
466 self.assertIn(f"{op} form", str(cm.exception))
467
468
469if __name__ == "__main__":
470 unittest.main()
diff --git a/tests/semantic/test_lds_bitwise_b64.py b/tests/semantic/test_lds_bitwise_b64.py
new file mode 100644
index 000000000..5b9f0bddf
--- /dev/null
+++ b/tests/semantic/test_lds_bitwise_b64.py
@@ -0,0 +1,83 @@
1"""Value tests for RDNA2 ds_and_b64, ds_or_b64, ds_xor_b64 and their _rtn_ forms, run through spirv_mini_interp.
2
3RDNA2 ISA, "Data Share Instructions": M = M op DATA on the 64-bit element at ADDR = vaddr + offset (the dwords at ADDR
4and ADDR + 4, low first); the _rtn_ forms return the old 64 bits in vdst[0:1]. The translator does one 32-bit atomic
5per dword, which leaves the same memory because a bitwise op works on each bit alone. Each case is a compute shader
6run as one invocation: it seeds both dwords with ds_write_b64, runs the op, reads the element back with ds_read_b64
7and stores (vdst lo, vdst hi, M lo, M hi) to a buffer. Standard library only; no GPU, no LLVM, no game files.
8"""
9import os
10import random
11import sys
12import unittest
13
14HERE = os.path.dirname(os.path.abspath(__file__))
15sys.dont_write_bytecode = True
16sys.path.insert(0, HERE)
17
18from test_lds_atomics_values import run_listing # noqa: E402 (also puts tools/ on sys.path)
19import rdna2spirv # noqa: E402
20
21M32 = 0xFFFFFFFF
22OPS = {"and": lambda m, d: m & d, "or": lambda m, d: m | d, "xor": lambda m, d: m ^ d}
23VALUES = [0, (1 << 64) - 1, 0x00000000_FFFFFFFF, 0xFFFFFFFF_00000000, 0x12345678_9ABCDEF0, 0x80000000_00000001]
24
25
26def run_b64(line: str, init: int, data: int, addr: int = 0x40, offset: int = 0):
27 body = [f"v_mov_b32_e32 v1, {addr:#x}", f"v_mov_b32_e32 v2, {init & M32:#x}", f"v_mov_b32_e32 v3, {init >> 32:#x}",
28 f"ds_write_b64 v1, v[2:3] offset:{offset}", "s_waitcnt lgkmcnt(0)",
29 f"v_mov_b32_e32 v4, {data & M32:#x}", f"v_mov_b32_e32 v5, {data >> 32:#x}",
30 "v_mov_b32_e32 v6, 0xdead", "v_mov_b32_e32 v7, 0xbeef",
31 line + (f" offset:{offset}" if offset else ""), "s_waitcnt lgkmcnt(0)",
32 f"ds_read_b64 v[8:9], v1 offset:{offset}", "s_waitcnt lgkmcnt(0)"]
33 for k, r in enumerate((6, 7, 8, 9)):
34 body += [f"v_mov_b32_e32 v31, {4 * k}", f"buffer_store_dword v{r}, v31, s[0:3], 0 offen"]
35 mem = run_listing(body)
36 return tuple(mem.get(4 * k) for k in range(4))
37
38
39def split(v: int):
40 return v & M32, v >> 32
41
42
43class LdsBitwiseB64(unittest.TestCase):
44 def test_returning_forms(self):
45 for kind, fn in OPS.items():
46 for m in VALUES:
47 for d in VALUES[::2]:
48 with self.subTest(op=kind, m=hex(m), d=hex(d)):
49 got = run_b64(f"ds_{kind}_rtn_b64 v[6:7], v1, v[4:5]", m, d)
50 self.assertEqual(got, split(m) + split(fn(m, d)))
51
52 def test_non_returning_forms_leave_vdst_alone(self):
53 for kind, fn in OPS.items():
54 for m, d in ((0x12345678_9ABCDEF0, 0x0F0F0F0F_F0F0F0F0), (0, (1 << 64) - 1)):
55 with self.subTest(op=kind, m=hex(m), d=hex(d)):
56 self.assertEqual(run_b64(f"ds_{kind}_b64 v1, v[4:5]", m, d), (0xDEAD, 0xBEEF) + split(fn(m, d)))
57
58 def test_offset(self):
59 m, d = 0x11111111_22222222, 0x0000FFFF_FFFF0000
60 self.assertEqual(run_b64("ds_xor_rtn_b64 v[6:7], v1, v[4:5]", m, d, addr=0x20, offset=0x18),
61 split(m) + split(m ^ d))
62
63 def test_vdst_aliasing_data(self):
64 # vdst v[4:5] is also the data pair: the data is read before the old value is written back.
65 m, d = 0xF0F0F0F0_0F0F0F0F, 0xFF00FF00_00FF00FF
66 got = run_b64("ds_or_rtn_b64 v[4:5], v1, v[4:5]", m, d)
67 self.assertEqual(got[2:], split(m | d))
68
69 def test_seeded(self):
70 rng = random.Random(0xB64)
71 for _ in range(15):
72 kind, m, d = rng.choice(list(OPS)), rng.getrandbits(64), rng.getrandbits(64)
73 with self.subTest(op=kind, m=hex(m), d=hex(d)):
74 self.assertEqual(run_b64(f"ds_{kind}_rtn_b64 v[6:7], v1, v[4:5]", m, d),
75 split(m) + split(OPS[kind](m, d)))
76
77 def test_bad_operands_rejected(self):
78 with self.assertRaises(rdna2spirv.Unsupported):
79 run_listing(["v_mov_b32_e32 v1, 0", "ds_and_b64 v1, v4"])
80
81
82if __name__ == "__main__":
83 unittest.main()
diff --git a/tests/semantic/test_pack_b32_f16_mods.py b/tests/semantic/test_pack_b32_f16_mods.py
new file mode 100644
index 000000000..c949eb32f
--- /dev/null
+++ b/tests/semantic/test_pack_b32_f16_mods.py
@@ -0,0 +1,136 @@
1"""Semantic tests for the neg/abs source modifiers on v_pack_b32_f16 (SHADER-260, abs is the follow-up to #1570).
2
3v_pack_b32_f16 packs the low 16 bits of src0 and of src1 into one dword (op_sel picks a source's high half
4instead). On RDNA2 the VOP3 NEG and ABS fields act on the selected 16-bit half as plain bit moves, before the
5half is packed: ABS clears bit 15 and NEG flips it, ABS first. NEG was measured on a Radeon 680M (gfx1036, RDNA2
6iGPU, AMD Windows driver 32.0.21044.64) with 192 hand-written raw kernels in wave32 and wave64 (#1548
7SHADER-260): ``-v0`` turned 0x7c01 into 0xfe01 with IEEE mode 1 and into 0xfc01 with IEEE mode 0, in either half
8and with op_sel, so the sign move does not depend on the mode. ABS is the ISA's sign clear of the same field pair
9and has no hardware run of this instruction yet. The translator used to reject any such operand as Unsupported.
10
11Not modelled here: IEEE mode 1 quieting a signalling NaN half (0x7c01 -> 0x7e01). Which mode the game's shaders
12run in is SHADER-190; the NaN cases below are the plain bit moves of mode 0.
13
14The whole 16-bit half is moved, so an sNaN payload survives; the interpreter runs the integer SPIR-V
15(OpBitwiseAnd/OpBitwiseXor), which is exact.
16"""
17import os
18import struct
19import sys
20import tempfile
21import unittest
22import warnings
23
24HERE = os.path.dirname(os.path.abspath(__file__))
25ROOT = os.path.dirname(os.path.dirname(HERE))
26TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools")
27
28sys.dont_write_bytecode = True
29sys.path.insert(0, TOOLS_DIR)
30sys.path.insert(0, HERE)
31
32import rdna2spirv # noqa: E402
33import spirv_mini_interp as si # noqa: E402
34
35STUB_DXBC = b"DXBC" + bytes(24) + struct.pack("<I", 0) + bytes(4)
36SIGN = 0x8000
37MANT = 0x7FFF
38
39# Operand words. Each holds a different value in each half so that op_sel and the modifier can be told apart.
40# Low halves: 1.5, -0.25, an sNaN. High halves: -3.0, 1.5, another sNaN, +0/-0.
41W1 = 0xB400_3E00
42W2 = 0x3E00_B400
43W3 = 0x3E00_7C01
44W4 = 0x0000_8000
45W5 = 0xC400_3E00
46
47_TMP = None
48
49
50def run(lines, export=None):
51 """Run the listing through the translator and the interpreter, return the mrt0 words."""
52 global _TMP
53 if _TMP is None:
54 _TMP = tempfile.TemporaryDirectory()
55 os.mkdir(os.path.join(_TMP.name, "disasm"))
56 with open(os.path.join(_TMP.name, "ps_packmods.dxbc"), "wb") as f:
57 f.write(STUB_DXBC)
58 path = os.path.join(_TMP.name, "disasm", "ps_packmods.s")
59 exp = export or ("v0",) * 4
60 with open(path, "w", encoding="utf-8") as f:
61 f.write("; ps_packmods\n" + "".join(f"\t{ln}\n" for ln in lines) +
62 "\texp mrt0 " + ", ".join(exp) + " done vm\n\ts_endpgm\n")
63 with warnings.catch_warnings():
64 warnings.simplefilter("ignore", ResourceWarning)
65 spv = rdna2spirv.translate(path)
66 return si.run_fragment(spv)["%out_mrt0"][:len(exp)]
67
68
69def tearDownModule():
70 global _TMP
71 if _TMP is not None:
72 _TMP.cleanup()
73 _TMP = None
74
75
76def half(word, hi, neg, abs_):
77 """One source half as the hardware hands it to the packer: op_sel picks the half, then ABS, then NEG."""
78 bits = word >> (16 if hi else 0) & 0xFFFF
79 if abs_:
80 bits &= MANT
81 if neg:
82 bits ^= SIGN
83 return bits
84
85
86def operand(base, neg, abs_, hi):
87 text = f"{'-' if neg else ''}{'|' if abs_ else ''}{base}{'|' if abs_ else ''}"
88 return text, f"[{1 if hi else 0}]"
89
90
91# (src0 word, src1 word, src0 neg/abs/hi, src1 neg/abs/hi)
92CASES = [
93 (W1, W2, (0, 0, 0), (0, 0, 0)), # plain pack (control)
94 (W2, W1, (1, 0, 0), (0, 0, 0)), # src0 neg flips the low half's sign
95 (W3, W4, (0, 1, 0), (0, 0, 0)), # src0 abs on an sNaN half keeps the payload
96 (W4, W4, (1, 1, 0), (0, 0, 0)), # neg(abs(-0.0)) -> -0.0
97 (W3, W5, (1, 1, 1), (1, 1, 1)), # high halves of both, both modifiers: sNaN negated, -3.0 abs
98 (W2, W1, (0, 1, 1), (0, 0, 0)), # op_sel high with abs (the high half of W2 is 1.5)
99 (W1, W3, (1, 0, 0), (1, 0, 1)), # neg on both, src1 op_sel high: -1.5 | -sNaN
100]
101
102
103class PackModsTests(unittest.TestCase):
104 def test_neg_abs_are_bit_moves_on_the_selected_half(self):
105 for w1, w2, (n0, ab0, hi0), (n1, ab1, hi1) in CASES:
106 with self.subTest(w1=f"{w1:08x}", w2=f"{w2:08x}", mods=(n0, ab0, hi0, n1, ab1, hi1)):
107 s0, o0 = operand("v1", n0, ab0, hi0)
108 s1, o1 = operand("v2", n1, ab1, hi1)
109 mods = f" op_sel:[{o0[1]},{o1[1]},0]" if (hi0 or hi1) else ""
110 lines = [f"v_mov_b32 v1, {w1:#x}", f"v_mov_b32 v2, {w2:#x}",
111 f"v_pack_b32_f16 v0, {s0}, {s1}{mods}"]
112 want = half(w1, hi0, n0, ab0) | half(w2, hi1, n1, ab1) << 16
113 self.assertEqual(run(lines)[0], want)
114
115 def test_negative_inline_constant_keeps_its_sign(self):
116 # -1.0 as an inline constant arrives with the sign in the value, not as a NEG modifier.
117 self.assertEqual(run(["v_pack_b32_f16 v0, -1.0, v1"])[0], 0xBC00)
118
119 def test_abs_inline_constant(self):
120 self.assertEqual(run(["v_pack_b32_f16 v0, 1.0, |v1|"])[0], 0x3C00)
121
122 def test_snan_payload_is_kept(self):
123 # 0x7c01 is an sNaN half: the packer moves the whole 16 bits, it does not round a float.
124 self.assertEqual(run(["v_mov_b32 v1, 0x7c01", "v_pack_b32_f16 v0, v1, v2"])[0], 0x00007C01)
125
126 def test_gpu_fixture_words(self):
127 # The words in runtime/test/shaders/ps_f16_pack_mods.asm are what a GPU must give.
128 words = run(["v_mov_b32 v0, 0x42003400", "v_mov_b32 v1, 0x34004400",
129 "v_pack_b32_f16 v2, -v0, |v1|", "v_pack_b32_f16 v3, v0, -v1",
130 "v_pack_b32_f16 v4, -|v0|, v1 op_sel:[1,0,0]",
131 "v_pack_b32_f16 v5, -v0, -|v1| op_sel:[0,1,0]"], export=("v2", "v3", "v4", "v5"))
132 self.assertEqual(list(words), [0x4400B400, 0xC4003400, 0x4400C200, 0xB400B400])
133
134
135if __name__ == "__main__":
136 unittest.main()
diff --git a/tests/semantic/test_salu_cmov_b64.py b/tests/semantic/test_salu_cmov_b64.py
new file mode 100644
index 000000000..934df9cc3
--- /dev/null
+++ b/tests/semantic/test_salu_cmov_b64.py
@@ -0,0 +1,247 @@
1"""Semantic tests for RDNA2 s_cmov_b64 on 64-bit scalar *data* pairs.
2
3Rule: D[63:0] = SCC ? S0[63:0] : D[63:0]; SCC is read, not written (RDNA2 ISA SOP1,
4LLVM AMDGPU SOPInstructions.td `S_CMOV_B64 : SOP1_64` under `Uses = [SCC]`).
5
6Only plain data is supported. A lane-mask register holds one lane's bit in this
7translator, so selecting it as 64-bit data would silently read back a per-lane
8bool instead of the wave's mask (issue #210). Those operands stay rejected.
9
10Every program here is hand-written; the translator and mini interpreter from
11this repository do the work. No LLVM, SPIR-V tools, GPU or game files are used.
12
13Run directly:
14 python -I tests/semantic/test_salu_cmov_b64.py -v
15"""
16import os
17import re
18import sys
19import tempfile
20import unittest
21import warnings
22
23HERE = os.path.dirname(os.path.abspath(__file__))
24if HERE not in sys.path:
25 sys.path.insert(0, HERE)
26
27from support import STUB_DXBC, mrt0_words, rdna2spirv # noqa: E402
28
29MASK32 = 0xFFFFFFFF
30MASK64 = 0xFFFFFFFFFFFFFFFF
31
32_TMP_DIR = None
33_PS_PATH = None
34
35
36def setUpModule():
37 global _TMP_DIR, _PS_PATH
38 _TMP_DIR = tempfile.TemporaryDirectory()
39 dis = os.path.join(_TMP_DIR.name, "disasm")
40 os.mkdir(dis)
41 _PS_PATH = os.path.join(dis, "ps_cmov64.s")
42 with open(os.path.join(_TMP_DIR.name, "ps_cmov64.dxbc"), "wb") as f:
43 f.write(STUB_DXBC)
44
45
46def tearDownModule():
47 global _TMP_DIR
48 if _TMP_DIR is not None:
49 _TMP_DIR.cleanup()
50 _TMP_DIR = None
51
52
53def translate_ps(lines):
54 if _TMP_DIR is None:
55 setUpModule()
56 asm = "; ps_cmov64\n" + "".join(f"\t{ln}\n" for ln in lines)
57 with open(_PS_PATH, "w", encoding="utf-8", newline="") as f:
58 f.write(asm)
59 with warnings.catch_warnings():
60 warnings.simplefilter("ignore", ResourceWarning)
61 return rdna2spirv.translate(_PS_PATH)
62
63
64def run_ps(lines):
65 spv = translate_ps(lines + ["exp mrt0 v0, v1, v2, v3 done vm", "s_endpgm"])
66 return mrt0_words(spv)
67
68
69def scc_line(scc):
70 return "s_cmp_eq_u32 1, 1" if scc else "s_cmp_eq_u32 0, 1"
71
72
73def load_pair_lines(reg, val64):
74 return [f"s_mov_b32 s{reg}, {val64 & MASK32:#x}",
75 f"s_mov_b32 s{reg + 1}, {(val64 >> 32) & MASK32:#x}"]
76
77
78def export_pair_lines(reg):
79 return [f"v_mov_b32 v0, s{reg}", f"v_mov_b32 v1, s{reg + 1}"]
80
81
82def ref_cmov64(old, src, scc):
83 return (src if scc else old) & MASK64
84
85
86class DataPairTests(unittest.TestCase):
87 def test_plain_data_pair_is_accepted(self):
88 # The explicit non-mask case: both dwords come from plain immediate moves,
89 # not from EXEC, VCC or a compare. D is an ordinary SGPR data pair.
90 old = 0xDEADBEEF_11223344
91 src = 0x55667788_90ABCDEF
92 for scc in (0, 1):
93 with self.subTest(scc=scc):
94 want = ref_cmov64(old, src, scc)
95 words = run_ps(
96 load_pair_lines(2, old)
97 + load_pair_lines(4, src)
98 + [scc_line(scc), "s_cmov_b64 s[2:3], s[4:5]",
99 "s_cselect_b32 s10, 1, 0"]
100 + export_pair_lines(2)
101 + ["v_mov_b32 v2, s10", "v_mov_b32 v3, 0"]
102 )
103 self.assertEqual(words, [want & MASK32, want >> 32, scc, 0])
104
105 def test_edge_values(self):
106 pairs = [
107 (0, 0xFFFFFFFF_FFFFFFFF),
108 (0x00000001_00000000, 0x80000000_7FFFFFFF),
109 (0x7FFFFFFF_FFFFFFFF, 0x80000000_00000000),
110 (0x00000002_80000001, 0x00000002_80000002),
111 ]
112 for old, src in pairs:
113 for scc in (0, 1):
114 with self.subTest(old=hex(old), src=hex(src), scc=scc):
115 want = ref_cmov64(old, src, scc)
116 words = run_ps(
117 load_pair_lines(2, old)
118 + load_pair_lines(4, src)
119 + [scc_line(scc), "s_cmov_b64 s[2:3], s[4:5]"]
120 + export_pair_lines(2)
121 + ["v_mov_b32 v2, 0", "v_mov_b32 v3, 0"]
122 )
123 self.assertEqual(words, [want & MASK32, want >> 32, 0, 0])
124
125 def test_immediate_and_null_sources(self):
126 old = 0x55667788_11223344
127 # shader_ir leaves a literal wider than 32 bits as a raw operand, which
128 # src64_data does not accept (the same holds for s_mov_b64); use the
129 # immediate forms the parser actually delivers.
130 for src_asm, src in (("0x12345678", 0x12345678), ("42", 42),
131 ("0", 0), ("-1", MASK64), ("-2", MASK64 - 1), ("null", 0)):
132 for scc in (0, 1):
133 with self.subTest(src=src_asm, scc=scc):
134 want = ref_cmov64(old, src, scc)
135 words = run_ps(
136 load_pair_lines(2, old)
137 + [scc_line(scc), f"s_cmov_b64 s[2:3], {src_asm}"]
138 + export_pair_lines(2)
139 + ["v_mov_b32 v2, 0", "v_mov_b32 v3, 0"]
140 )
141 self.assertEqual(words, [want & MASK32, want >> 32, 0, 0])
142
143 def test_destination_aliasing(self):
144 a64 = 0x55667788_11223344
145 b64 = 0xDDEEFF00_99AABBCC
146 # s[3:4] = (s4 << 32) | s3, with s4 = low(a64), s3 = low(b64).
147 overlap_val = ((a64 & MASK32) << 32) | (b64 & MASK32)
148 for source, src_val in (("s[4:5]", a64), ("s[3:4]", overlap_val)):
149 for scc in (0, 1):
150 with self.subTest(source=source, scc=scc):
151 want = ref_cmov64(a64, src_val, scc)
152 lines = load_pair_lines(3, b64) + load_pair_lines(4, a64)
153 lines += [scc_line(scc), f"s_cmov_b64 s[4:5], {source}"]
154 lines += export_pair_lines(4) + ["v_mov_b32 v2, 0", "v_mov_b32 v3, 0"]
155 words = run_ps(lines)
156 self.assertEqual(words, [want & MASK32, want >> 32, 0, 0])
157
158 def test_constant_pairs_are_not_mistaken_for_masks(self):
159 # 0 / -1 are EITHER in tools/lane_masks.py (the same bits as data), so
160 # they must not be mistaken for lane masks here.
161 for src_asm, src in (("-1", MASK64), ("0", 0)):
162 for scc in (0, 1):
163 with self.subTest(src=src_asm, scc=scc):
164 want = ref_cmov64(0x11223344_55667788, src, scc)
165 words = run_ps(
166 load_pair_lines(2, 0x11223344_55667788)
167 + [f"s_mov_b64 s[4:5], {src_asm}", scc_line(scc),
168 "s_cmov_b64 s[2:3], s[4:5]"]
169 + export_pair_lines(2)
170 + ["v_mov_b32 v2, 0", "v_mov_b32 v3, 0"]
171 )
172 self.assertEqual(words, [want & MASK32, want >> 32, 0, 0])
173
174 def test_scc_is_not_written(self):
175 old, src = 0x11111111_22222222, 0x33333333_44444444
176 for scc in (0, 1):
177 with self.subTest(scc=scc):
178 want = ref_cmov64(old, src, scc)
179 words = run_ps(
180 load_pair_lines(2, old)
181 + load_pair_lines(4, src)
182 + [scc_line(scc), "s_cmov_b64 s[2:3], s[4:5]",
183 "s_addc_u32 s10, 10, 20"]
184 + export_pair_lines(2)
185 + ["v_mov_b32 v2, s10", "v_mov_b32 v3, 0"]
186 )
187 self.assertEqual(words, [want & MASK32, want >> 32, 30 + scc, 0])
188
189
190class RejectionTests(unittest.TestCase):
191 MASK_SOURCE = "s_cmov_b64 lane-mask source"
192 MASK_DEST = "s_cmov_b64 lane-mask destination"
193 DEST = "s_cmov_b64 destination"
194
195 def test_lane_mask_source_rejected_with_message(self):
196 cmp = "v_cmp_ne_u32_e64 s[20:21], 0, v0"
197 cases = [
198 ([cmp, "s_mov_b64 s[22:23], s[20:21]"], "s[22:23]"),
199 (["s_mov_b64 s[22:23], exec"], "s[22:23]"),
200 ([], "exec"),
201 # A zero-extended 32-bit mask: one dword is a mask, the other is
202 # an EITHER constant. holds_lane_mask() alone misses this pair.
203 ([cmp, "s_mov_b32 s2, s20", "s_mov_b32 s3, 0"], "s[2:3]"),
204 ([cmp, "s_mov_b32 s2, 0", "s_mov_b32 s3, s20"], "s[2:3]"),
205 ]
206 for prologue, src in cases:
207 with self.subTest(src=src, prologue=prologue[-1] if prologue else "none"):
208 lines = prologue + [scc_line(1), f"s_cmov_b64 s[2:3], {src}",
209 "exp mrt0 v0, v0, v0, v0 done vm", "s_endpgm"]
210 with self.assertRaisesRegex(rdna2spirv.Unsupported, re.escape(self.MASK_SOURCE)):
211 translate_ps(lines)
212
213 def test_mask_destination_rejected_with_message(self):
214 cmp = "v_cmp_ne_u32_e64 s[20:21], 0, v0"
215 cases = [
216 [cmp, "s_cmov_b64 s[20:21], s[4:5]"],
217 [cmp, "s_mov_b32 s2, s20", "s_mov_b32 s3, 0", "s_cmov_b64 s[2:3], s[4:5]"],
218 ]
219 for lines in cases:
220 with self.subTest(lines=lines[-1]):
221 full = lines + ["exp mrt0 v0, v0, v0, v0 done vm", "s_endpgm"]
222 with self.assertRaisesRegex(rdna2spirv.Unsupported, re.escape(self.MASK_DEST)):
223 translate_ps(full)
224
225 def test_ever_mask_pair_rejected_after_overwrite(self):
226 # A register that held a mask earlier, then plain data, is refused: at a
227 # CFG join lane_masks.py can drop the register (mask on one path, data on
228 # another), so "not a mask now" does not prove it is data on every path.
229 lines = ["v_cmp_ne_u32_e64 s[20:21], 0, v0",
230 "s_mov_b64 s[20:21], 0", "s_mov_b64 s[2:3], 0",
231 "s_cmov_b64 s[2:3], s[20:21]",
232 "exp mrt0 v0, v0, v0, v0 done vm", "s_endpgm"]
233 with self.assertRaisesRegex(rdna2spirv.Unsupported, re.escape(self.MASK_SOURCE)):
234 translate_ps(lines)
235
236 def test_invalid_destinations_rejected_with_message(self):
237 for line in ("s_cmov_b64 exec, s[4:5]", "s_cmov_b64 vcc, s[4:5]",
238 "s_cmov_b64 m0, s[4:5]", "s_cmov_b64 s4, s[4:5]",
239 "s_cmov_b64 null, s[4:5]"):
240 with self.subTest(line=line):
241 full = [line, "exp mrt0 v0, v0, v0, v0 done vm", "s_endpgm"]
242 with self.assertRaisesRegex(rdna2spirv.Unsupported, re.escape(self.DEST)):
243 translate_ps(full)
244
245
246if __name__ == "__main__":
247 unittest.main()
diff --git a/tests/semantic/test_salu_movrels_lane_mask.py b/tests/semantic/test_salu_movrels_lane_mask.py
new file mode 100644
index 000000000..15a791609
--- /dev/null
+++ b/tests/semantic/test_salu_movrels_lane_mask.py
@@ -0,0 +1,117 @@
1"""s_movrels_b32 / s_movrels_b64 reading an SGPR that holds a lane mask (#1548, SHADER-284).
2
3A lane-mask SGPR (a saved EXEC, a v_cmp result) holds only this lane's bit in the translation, so a plain dynamic
4load copied that bit as data: with EXEC saved as 5, `s_movrels_b32 s12, s10` then `s_bcnt1_i32_b32 s13, s12` gave
532 where the ISA gives 2. The translator now collects the whole wave's mask word for every mask SGPR and uses it
6when the index lands there. Each case runs every lane of a synthetic compute shader in
7spirv_mini_interp.run_workgroup (wave32 and native wave64) and stores D and the bit count per lane. Standard
8library only; no GPU, no game files.
9"""
10import gc
11import os
12import struct
13import sys
14import tempfile
15import unittest
16import warnings
17
18HERE = os.path.dirname(os.path.abspath(__file__))
19ROOT = os.path.dirname(os.path.dirname(HERE))
20TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools")
21
22sys.dont_write_bytecode = True
23if HERE not in sys.path:
24 sys.path.insert(0, HERE)
25if TOOLS_DIR not in sys.path:
26 sys.path.insert(0, TOOLS_DIR)
27
28import rdna2spirv # noqa: E402
29import spirv_mini_interp as si # noqa: E402
30
31STUB_DXBC = b"DXBC" + bytes(24) + struct.pack("<I", 0) + bytes(4)
32VSHARP = [0, 0, 0xFFFFFFFF, 0x31016FAC] # OOB_SELECT 3 (raw)
33
34
35def run_cs(name, body, wave_size):
36 """Translate `body` as a compute shader (s[0:3] = output V#) and run all lanes; return the memory."""
37 prev = rdna2spirv.WAVE64_EMULATE
38 try:
39 rdna2spirv.WAVE64_EMULATE = False
40 with tempfile.TemporaryDirectory() as tmp:
41 os.mkdir(os.path.join(tmp, "disasm"))
42 os.mkdir(os.path.join(tmp, "fssm"))
43 path = os.path.join(tmp, "disasm", name + ".s")
44 with open(path, "w", encoding="utf-8") as f:
45 f.write(f"; {name}\n" + "".join(f"\t{ln}\n" for ln in body) + "\ts_endpgm\n")
46 with open(os.path.join(tmp, name + ".dxbc"), "wb") as f:
47 f.write(STUB_DXBC)
48 with open(os.path.join(tmp, "fssm", name + ".fssm"), "wb") as f:
49 f.write(bytes(0x138) + struct.pack("<4I", 0x8088, wave_size, 1, 1))
50 with warnings.catch_warnings():
51 warnings.simplefilter("ignore", ResourceWarning)
52 spv = rdna2spirv.translate(path)
53 gc.collect()
54 finally:
55 rdna2spirv.WAVE64_EMULATE = prev
56 return si.run_workgroup(spv, wave_size, wave_size,
57 inputs_for=lambda i: {"%wg_id": (0, 0, 0), "%local_id": (i, 0, 0), "%sg_lane": i},
58 push_constants=VSHARP + [0] * 28, memory={})
59
60
61def store(regs):
62 """Store the four SGPRs `regs` for each lane at lane * 16 (v0 = lane)."""
63 return (["s_mov_b32 exec_lo, -1", "v_lshlrev_b32 v20, 4, v0"] +
64 [f"v_mov_b32 v{21 + k}, s{s}" for k, s in enumerate(regs)] +
65 ["buffer_store_dwordx4 v[21:24], v20, s[0:3], 0 offen"])
66
67
68def lanes(mem, wave_size, count):
69 return [tuple(mem.get(lane * 16 + 4 * k, 0) for k in range(count)) for lane in range(wave_size)]
70
71
72class MovrelsLaneMaskWave32(unittest.TestCase):
73 def test_finding_reproducer(self):
74 # The listing from the finding: EXEC = lanes 0 and 2, saved in s10, read back through s_movrels.
75 body = ["s_mov_b32 exec_lo, 5", "s_mov_b32 s10, exec_lo", "s_mov_b32 exec_lo, -1", "s_mov_b32 m0, 0",
76 "s_movrels_b32 s12, s10", "s_bcnt1_i32_b32 s13, s12",
77 "s_mov_b32 s14, s10", "s_bcnt1_i32_b32 s15, s14"] # the control: a plain copy
78 got = lanes(run_cs("cs_movrels_mask_w32", body + store([12, 13, 14, 15]), 32), 32, 4)
79 for lane, (d, bits, ctl_d, ctl_bits) in enumerate(got):
80 with self.subTest(lane=lane):
81 self.assertEqual((d, bits), (5, 2))
82 self.assertEqual(ctl_bits, 2)
83 self.assertEqual(ctl_d, 0xFFFFFFFF if lane in (0, 2) else 0) # a copy stays a mask
84
85 def test_index_from_m0_hits_mask_and_data_neighbours(self):
86 # s10 data, s11 a v_cmp mask (lanes 1, 4, 9), s12 data; M0 picks each in turn from a base of s9.
87 body = ["s_mov_b32 exec_lo, -1", "s_mov_b32 s10, 0x1234", "s_mov_b32 s12, 0xabcd",
88 "v_cmp_eq_u32_e64 s11, v0, 1", "v_cmp_eq_u32_e64 s16, v0, 4", "s_or_b32 s11, s11, s16",
89 "v_cmp_eq_u32_e64 s16, v0, 9", "s_or_b32 s11, s11, s16", "s_mov_b32 s9, 0"]
90 reads = []
91 for k, m in enumerate((1, 2, 3)):
92 reads += [f"s_mov_b32 s17, {m}", "s_mov_b32 m0, s17", f"s_movrels_b32 s{20 + k}, s9"]
93 reads += ["s_bcnt1_i32_b32 s23, s21"]
94 got = lanes(run_cs("cs_movrels_mix_w32", body + reads + store([20, 21, 22, 23]), 32), 32, 4)
95 want_mask = (1 << 1) | (1 << 4) | (1 << 9)
96 for lane, row in enumerate(got):
97 with self.subTest(lane=lane):
98 self.assertEqual(row, (0x1234, want_mask, 0xABCD, 3))
99
100
101class MovrelsLaneMaskWave64(unittest.TestCase):
102 def test_b64_pair_of_saved_exec(self):
103 # EXEC = lanes 0, 2 and 40, saved in s[10:11]; the b64 read gives both halves as data.
104 body = ["s_mov_b64 exec, -1", "v_cmp_eq_u32_e64 s[4:5], v0, 0", "v_cmp_eq_u32_e64 s[6:7], v0, 2",
105 "s_or_b64 s[4:5], s[4:5], s[6:7]", "v_cmp_eq_u32_e64 s[6:7], v0, 40",
106 "s_or_b64 s[4:5], s[4:5], s[6:7]", "s_mov_b64 exec, s[4:5]", "s_mov_b64 s[10:11], exec",
107 "s_mov_b64 exec, -1", "s_mov_b32 m0, 0", "s_movrels_b64 s[12:13], s[10:11]",
108 "s_bcnt1_i32_b64 s14, s[12:13]", "s_mov_b32 m0, 1", "s_movrels_b32 s15, s10"]
109 got = lanes(run_cs("cs_movrels_mask_w64", body + ["s_mov_b64 exec, -1"] + store([12, 13, 14, 15]), 64),
110 64, 4)
111 for lane, row in enumerate(got):
112 with self.subTest(lane=lane):
113 self.assertEqual(row, (5, 1 << 8, 3, 1 << 8)) # M0 = 1 from s10 lands on s11, the high half
114
115
116if __name__ == "__main__":
117 unittest.main()
diff --git a/tests/semantic/test_scalar_alu_and_smem_folding.py b/tests/semantic/test_scalar_alu_and_smem_folding.py
new file mode 100644
index 000000000..bb34022e5
--- /dev/null
+++ b/tests/semantic/test_scalar_alu_and_smem_folding.py
@@ -0,0 +1,193 @@
1from __future__ import annotations
2
3"""Regression and semantic tests for scalar ALU and s_buffer_load constant folding in the translator.
4
5Verifies that:
6- Constant scalar ALU operations (s_and_b32, s_or_b32, s_xor_b32, s_not_b32, s_lshl_b32, s_lshr_b32, s_mul_i32)
7 fold at translate time without emitting runtime SPIR-V instructions.
8- s_buffer_load with known descriptor limits folds limit calculations at translate time, eliminating
9 OpBitFieldUExtract, OpIMul, OpIEqual, and OpSelect.
10- In-bounds s_buffer_load dwords emit direct straight-line OpLoad without OpSelectionMerge, OpBranchConditional, or OpPhi.
11- Out-of-bounds s_buffer_load dwords emit constant zero without memory load or branch.
12- Constant SGPR offsets in scalar loads fold directly into the 64-bit address calculation.
13"""
14import os
15import struct
16import sys
17import tempfile
18import unittest
19import warnings
20
21HERE = os.path.dirname(os.path.abspath(__file__))
22ROOT = os.path.dirname(os.path.dirname(HERE))
23TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools")
24
25sys.dont_write_bytecode = True
26if TOOLS_DIR not in sys.path:
27 sys.path.insert(0, TOOLS_DIR)
28if HERE not in sys.path:
29 sys.path.insert(0, HERE)
30
31import rdna2spirv # noqa: E402
32from shader_ir import parse_line # noqa: E402
33import spirv_mini_interp as si # noqa: E402
34
35STUB_DXBC = b"DXBC" + bytes(24) + struct.pack("<I", 0) + bytes(4)
36
37
38class ScalarAluAndSmemFoldingTests(unittest.TestCase):
39 def translate_lines(self, lines: list[str]) -> str:
40 body = "\n".join("\t" + line for line in lines)
41 asm = f"; scalar_fold_test\n{body}\n\texp mrt0 v0, v0, v0, v0 done vm\n\ts_endpgm\n"
42 with tempfile.TemporaryDirectory() as tmp:
43 d_dir = os.path.join(tmp, "disasm")
44 os.mkdir(d_dir)
45 s_path = os.path.join(d_dir, "ps_scalar.s")
46 with open(s_path, "w", encoding="utf-8") as f:
47 f.write(asm)
48 with open(os.path.join(tmp, "ps_scalar.dxbc"), "wb") as f:
49 f.write(STUB_DXBC)
50 with warnings.catch_warnings():
51 warnings.simplefilter("ignore", ResourceWarning)
52 return rdna2spirv.translate(s_path)
53
54 def test_s_and_b32_and_s_or_b32_constant_folding(self):
55 # Bitwise s_and_b32 / s_or_b32 fold constants without runtime bitwise instructions
56 lines = [
57 "s_and_b32 s4, 0xFF00, 0x0FF0",
58 "v_mov_b32 v0, s4",
59 ]
60 spv = self.translate_lines(lines)
61 self.assertNotIn("OpBitwiseAnd %uint", spv)
62 res = si.run_fragment(spv)["%out_mrt0"][0]
63 self.assertEqual(res, 0x0F00)
64
65 lines_or = [
66 "s_or_b32 s4, 0xF0, 0x0F",
67 "v_mov_b32 v0, s4",
68 ]
69 spv_or = self.translate_lines(lines_or)
70 self.assertNotIn("OpBitwiseOr %uint", spv_or)
71 res_or = si.run_fragment(spv_or)["%out_mrt0"][0]
72 self.assertEqual(res_or, 0xFF)
73
74 def test_s_xor_b32_and_s_not_b32_constant_folding(self):
75 # Bitwise s_xor_b32 and s_not_b32 fold constants
76 lines_xor = [
77 "s_xor_b32 s4, 0xAAAA5555, 0x5555AAAA",
78 "v_mov_b32 v0, s4",
79 ]
80 spv_xor = self.translate_lines(lines_xor)
81 self.assertNotIn("OpBitwiseXor %uint", spv_xor)
82 res_xor = si.run_fragment(spv_xor)["%out_mrt0"][0]
83 self.assertEqual(res_xor, 0xFFFFFFFF)
84
85 lines_not = [
86 "s_not_b32 s4, 0",
87 "v_mov_b32 v0, s4",
88 ]
89 spv_not = self.translate_lines(lines_not)
90 self.assertNotIn("OpNot %uint", spv_not)
91 res_not = si.run_fragment(spv_not)["%out_mrt0"][0]
92 self.assertEqual(res_not, 0xFFFFFFFF)
93
94 def test_s_lshl_b32_s_lshr_b32_s_mul_i32_folding(self):
95 # Shifts and multiply fold constants
96 lines_shl = [
97 "s_lshl_b32 s4, 3, 4", # 3 << 4 = 48
98 "v_mov_b32 v0, s4",
99 ]
100 spv_shl = self.translate_lines(lines_shl)
101 self.assertNotIn("OpShiftLeftLogical %uint", spv_shl)
102 res_shl = si.run_fragment(spv_shl)["%out_mrt0"][0]
103 self.assertEqual(res_shl, 48)
104
105 lines_mul = [
106 "s_mul_i32 s4, 6, 7",
107 "v_mov_b32 v0, s4",
108 ]
109 spv_mul = self.translate_lines(lines_mul)
110 self.assertNotIn("OpIMul %uint", spv_mul)
111 res_mul = si.run_fragment(spv_mul)["%out_mrt0"][0]
112 self.assertEqual(res_mul, 42)
113
114 lines_shr = [
115 "s_lshr_b32 s4, 96, 3", # 96 >> 3 = 12
116 "v_mov_b32 v0, s4",
117 ]
118 spv_shr = self.translate_lines(lines_shr)
119 self.assertNotIn("OpShiftRightLogical %uint", spv_shr)
120 res_shr = si.run_fragment(spv_shr)["%out_mrt0"][0]
121 self.assertEqual(res_shr, 12)
122
123 def test_s_buffer_load_in_bounds_eliminates_branch_diamond(self):
124 # When V# limits and offset are constants with offset in bounds:
125 # eliminates limit setup and conditional branch diamond.
126 g = rdna2spirv.Gen("ps")
127 # Load literal V# into s[4:7]:
128 # s4: base lo, s5: base hi (0) + stride 4 in bits 16..29 (0x00040000)
129 # s6: num_records = 256 (limit = 256 * 4 = 1024 bytes)
130 # s7: word3
131 g.sgpr_imm[4] = 0x1000
132 g.sgpr_imm[5] = 0x00040000
133 g.sgpr_imm[6] = 256
134 g.sgpr_imm[7] = 0x31000FAC
135
136 ins = parse_line("s_buffer_load_dword s0, s[4:7], 0x10")
137 g.scalar_load(ins["op"], ins["args"], ins["mods"])
138 text = "\n".join(g.body)
139
140 # No dynamic limit calculation instructions
141 self.assertNotIn("OpBitFieldUExtract %uint", text)
142 self.assertNotIn("OpIMul %ulong", text)
143 self.assertNotIn("OpSelect %ulong", text)
144
145 # In bounds (0x10 + 4 = 20 <= 1024): no branch or phi
146 self.assertNotIn("OpBranchConditional", text)
147 self.assertNotIn("OpSelectionMerge", text)
148 self.assertNotIn("OpPhi", text)
149
150 # Emits direct aligned load
151 self.assertIn("OpAccessChain %_ptr_PSB_uint", text)
152 self.assertIn("OpLoad %uint", text)
153
154 def test_s_buffer_load_out_of_bounds_emits_constant_zero(self):
155 # When V# limits and offset are constants with offset out of bounds:
156 # emits constant 0 without memory load or branches.
157 g = rdna2spirv.Gen("ps")
158 g.sgpr_imm[4] = 0x1000
159 g.sgpr_imm[5] = 0x00040000
160 g.sgpr_imm[6] = 16 # limit = 16 * 4 = 64 bytes
161 g.sgpr_imm[7] = 0x31000FAC
162
163 ins = parse_line("s_buffer_load_dword s0, s[4:7], 0x80") # offset 128 > limit 64
164 g.scalar_load(ins["op"], ins["args"], ins["mods"])
165 text = "\n".join(g.body)
166
167 # No branch or PSB memory load emitted for out of bounds
168 self.assertNotIn("OpBranchConditional", text)
169 self.assertNotIn("OpSelectionMerge", text)
170 self.assertNotIn("OpPhi", text)
171 self.assertNotIn("OpAccessChain %_ptr_PSB_uint", text)
172 self.assertNotIn("Aligned 4", text)
173
174 # Directly stores %c0 to sgpr 0
175 self.assertTrue(any(ln.strip().startswith("OpStore %t") and ln.strip().endswith(g.cu(0)) for ln in g.body))
176
177 def test_s_buffer_load_sgpr_offset_folded_from_sgpr_imm(self):
178 # When offset is passed via SGPR holding a known literal:
179 # folded into constant offset without runtime OpBitwiseAnd / OpUConvert on the offset register.
180 g = rdna2spirv.Gen("ps")
181 g.sgpr_imm[2] = 0x20 # s2 = 32
182 ins = parse_line("s_load_dword s0, s[4:5], s2")
183 g.scalar_load(ins["op"], ins["args"], ins["mods"])
184 text = "\n".join(g.body)
185
186 # The offset is folded into constant ulong %cl20
187 self.assertIn("%cl20", text)
188 # Only base lo is masked with %cfffffffc; offset s2 is not dynamically masked
189 self.assertEqual(text.count("%cfffffffc"), 1)
190
191
192if __name__ == "__main__":
193 unittest.main()
diff --git a/tests/semantic/test_scalar_noop_waitcnt.py b/tests/semantic/test_scalar_noop_waitcnt.py
new file mode 100644
index 000000000..67b805220
--- /dev/null
+++ b/tests/semantic/test_scalar_noop_waitcnt.py
@@ -0,0 +1,636 @@
1"""Semantic and translation tests for RDNA2 scalar no-op, hint, waitcnt, and mode instructions.
2
3Covers the 11 named scalar instructions and their syntax variants in tools/shader_ir.py and tools/rdna2spirv.py:
4 * In rdna2spirv.NOOPS (emits no SPIR-V instructions, preserves VGPRs, SGPRs, VCC, SCC, and EXEC):
5 s_clause, s_delay_alu (RDNA3 hint kept in NOOPS), s_inst_prefetch, s_setprio, s_sleep,
6 s_waitcnt_depctr, s_waitcnt_expcnt, s_waitcnt_lgkmcnt, s_waitcnt_vmcnt,
7 plus the sibling wait/no-op forms s_waitcnt, s_waitcnt_vscnt, s_nop, and v_nop.
8 * Refused mode mnemonics in rdna2spirv._insn:
9 s_denorm_mode and s_round_mode raise Unsupported ("MODE is modelled through s_setreg only");
10 valid MODE.FP_ROUND[3:2] writes go through s_setreg_imm32_b32 hwreg(HW_REG_MODE, 2, 2), 0|3,
11 which updates %mode_r16 only and leaves VGPRs, SGPRs, VCC, SCC, and EXEC intact, while
12 non-MODE s_setreg* writes emit nothing and other MODE writes stay Unsupported.
13
14Standard library only (runs with python -I); hand-written RDNA2 listings, no GPU or game data.
15"""
16from __future__ import annotations
17
18import gc
19import os
20import struct
21import sys
22import tempfile
23import unittest
24import warnings
25
26HERE = os.path.dirname(os.path.abspath(__file__))
27ROOT = os.path.dirname(os.path.dirname(HERE))
28TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools")
29
30sys.dont_write_bytecode = True
31for _p in (HERE, TOOLS_DIR):
32 if _p not in sys.path:
33 sys.path.insert(0, _p)
34
35import rdna2spirv # noqa: E402
36import shader_ir # noqa: E402
37import spirv_mini_interp as si # noqa: E402
38
39M32 = 0xFFFFFFFF
40STUB_DXBC = b"DXBC" + bytes(24) + struct.pack("<I", 0) + bytes(4)
41# Raw buffer V# (OOB_SELECT 3, stride 0): any dword offset is in bounds in spirv_mini_interp.
42VSHARP = [0, 0, 0xFFFFFFFF, 0x31016FAC]
43
44# Handled scalar no-op/hint/waitcnt instructions and explicit syntax variants accepted by shader_ir.py.
45SCALAR_NOOP_VARIANTS = [
46 "s_clause 0x1",
47 "s_clause 0",
48 "s_clause 15",
49 "s_delay_alu 0",
50 "s_delay_alu instid0(VALU_DEP_1) | instskip(NEXT) | instid1(SALU_CYCLE_1)",
51 "s_delay_alu instid0(VALU_DEP_2)",
52 "s_inst_prefetch 0x0",
53 "s_inst_prefetch 0x1",
54 "s_inst_prefetch -1",
55 "s_setprio 0x0",
56 "s_setprio 0x2",
57 "s_setprio 3",
58 "s_sleep 0x0",
59 "s_sleep 0x1",
60 "s_sleep 7",
61 "s_waitcnt_depctr 0xffe3",
62 "s_waitcnt_depctr 0x0",
63 "s_waitcnt_depctr depctr_vm_vsrc(0) depctr_va_sdst(0)",
64 "s_waitcnt_depctr depctr_hold_cnt(0) depctr_sa_sdst(0) depctr_va_vdst(0)",
65 "s_waitcnt_expcnt null, 0x0",
66 "s_waitcnt_expcnt null, 0x7",
67 "s_waitcnt_expcnt 0x0",
68 "s_waitcnt_lgkmcnt null, 0x0",
69 "s_waitcnt_lgkmcnt null, 0x3f",
70 "s_waitcnt_lgkmcnt 0x0",
71 "s_waitcnt_vmcnt null, 0x0",
72 "s_waitcnt_vmcnt null, 0x3f",
73 "s_waitcnt_vmcnt 0x0",
74 # Sibling wait/no-op and non-MODE setreg forms handled alongside them in NOOPS / mode_write.
75 "s_waitcnt vmcnt(0)",
76 "s_waitcnt expcnt(0)",
77 "s_waitcnt lgkmcnt(0)",
78 "s_waitcnt vmcnt(1) lgkmcnt(2)",
79 "s_waitcnt vmcnt(0) expcnt(0) lgkmcnt(0)",
80 "s_waitcnt 0",
81 "s_waitcnt_vscnt null, 0x0",
82 "s_waitcnt_vscnt vscnt(0)",
83 "s_nop 0",
84 "s_nop 0x7",
85 "v_nop",
86 "v_nop_e32",
87 "v_nop_e64",
88 "s_setreg_imm32_b32 hwreg(HW_REG_FLAT_SCR_LO, 0, 32), 0",
89 "s_setreg_b32 hwreg(HW_REG_IB_STS), s2",
90]
91
92# Representative instruction per handled mnemonic from the 9-op scalar NOOPS group + s_waitcnt / s_nop.
93REPRESENTATIVE_NOOPS = [
94 "s_clause 0x1",
95 "s_delay_alu instid0(VALU_DEP_1) | instskip(NEXT) | instid1(SALU_CYCLE_1)",
96 "s_inst_prefetch 0x0",
97 "s_setprio 0x2",
98 "s_sleep 0x1",
99 "s_waitcnt_depctr 0xffe3",
100 "s_waitcnt_expcnt null, 0x0",
101 "s_waitcnt_lgkmcnt null, 0x0",
102 "s_waitcnt_vmcnt null, 0x0",
103 "s_waitcnt vmcnt(0) expcnt(0) lgkmcnt(0)",
104 "s_waitcnt_vscnt null, 0x0",
105 "s_nop 0",
106]
107
108REFUSED_MODE_VARIANTS = [
109 "s_denorm_mode 0x3",
110 "s_denorm_mode 0",
111 "s_round_mode 0x3",
112 "s_round_mode 0",
113]
114
115MODELLED_MODE_VARIANTS = [
116 ("s_setreg_imm32_b32 hwreg(HW_REG_MODE, 2, 2), 0", "%c0"),
117 ("s_setreg_imm32_b32 hwreg(HW_REG_MODE, 2, 2), 3", "%c3"),
118]
119
120_TMP_DIR: tempfile.TemporaryDirectory | None = None
121
122
123def setUpModule() -> None:
124 global _TMP_DIR
125 _TMP_DIR = tempfile.TemporaryDirectory()
126 os.mkdir(os.path.join(_TMP_DIR.name, "disasm"))
127 os.mkdir(os.path.join(_TMP_DIR.name, "fssm"))
128
129
130def tearDownModule() -> None:
131 global _TMP_DIR
132 if _TMP_DIR is not None:
133 gc.collect()
134 _TMP_DIR.cleanup()
135 _TMP_DIR = None
136
137
138def _ensure_dir() -> str:
139 if _TMP_DIR is None:
140 setUpModule()
141 assert _TMP_DIR is not None
142 return _TMP_DIR.name
143
144
145def make_fssm(threads: int, user_sgprs: int = 4) -> bytes:
146 """Synthetic compute FSSM header: user_sgprs USER_SGPRs, TGID_X_EN=0, TIDIG_COMP_CNT=0, size=(threads,1,1)."""
147 blob = bytearray(0x148)
148 rsrc2 = (user_sgprs & 31) << 1
149 struct.pack_into("<4I", blob, 0x138, rsrc2, threads, 1, 1)
150 return bytes(blob)
151
152
153def translate_ps(name: str, lines: list[str]) -> str:
154 root = _ensure_dir()
155 src = os.path.join(root, "disasm", name + ".s")
156 with open(src, "w", encoding="utf-8", newline="\n") as f:
157 f.write(f"; {name}\n" + "".join(f"\t{ln}\n" for ln in lines))
158 with open(os.path.join(root, name + ".dxbc"), "wb") as f:
159 f.write(STUB_DXBC)
160 with warnings.catch_warnings():
161 warnings.simplefilter("ignore", ResourceWarning)
162 return rdna2spirv.translate(src)
163
164
165def translate_cs(name: str, lines: list[str], threads: int) -> str:
166 root = _ensure_dir()
167 src = os.path.join(root, "disasm", name + ".s")
168 with open(src, "w", encoding="utf-8", newline="\n") as f:
169 f.write(f"; {name}\n" + "".join(f"\t{ln}\n" for ln in lines))
170 with open(os.path.join(root, name + ".dxbc"), "wb") as f:
171 f.write(STUB_DXBC)
172 with open(os.path.join(root, "fssm", name + ".fssm"), "wb") as f:
173 f.write(make_fssm(threads))
174 with warnings.catch_warnings():
175 warnings.simplefilter("ignore", ResourceWarning)
176 return rdna2spirv.translate(src)
177
178
179def ps_program(middle: list[str], *, scc_one: bool = True, vcc_one: bool = True,
180 exec_lo: int = 0xAAAA5555, add_k: int = 0x10) -> list[str]:
181 """Synthetic PS testing VGPRs, SGPRs, SCC, VCC, and EXEC across interleaved arithmetic and `middle`."""
182 s_rhs = 5 if scc_one else 0
183 s_lhs = 0xFFFFFFFF if scc_one else 0x12340000
184 cmp_val = (0x11112222 + add_k) & M32 if vcc_one else 0x00000000
185 return [
186 "v_mov_b32 v0, 0x11112222",
187 "v_mov_b32 v1, 0x33334444",
188 "v_mov_b32 v2, 0x55556666",
189 "v_mov_b32 v3, 0x77778888",
190 f"s_mov_b32 s2, {s_lhs:#x}",
191 f"s_mov_b32 s3, {s_rhs:#x}",
192 "s_add_u32 s4, s2, s3", # SCC = 1 iff s_lhs + s_rhs overflows 32 bits
193 f"v_add_nc_u32 v0, v0, {add_k:#x}",
194 f"v_cmp_eq_u32 vcc_lo, v0, {cmp_val:#x}", # VCC = 1 iff vcc_one
195 f"s_mov_b32 exec_lo, {exec_lo:#x}",
196 *middle,
197 "s_cselect_b32 s5, 0x10000001, 0x20000002", # reads SCC
198 "s_add_u32 s6, s4, s5", # reads SGPR s4 and selected s5
199 "v_cndmask_b32 v1, 0x99990000, v1, vcc_lo", # reads VCC (and VGPR v1 when VCC=1)
200 "v_add_nc_u32 v2, v2, s6", # reads EXEC, VGPR v2, SGPR s6
201 "exp mrt0 v0, v1, v2, v3 done vm",
202 "s_endpgm",
203 ]
204
205
206def expected_ps_mrt0(*, scc_one: bool = True, vcc_one: bool = True,
207 exec_lo: int = 0xAAAA5555, add_k: int = 0x10) -> tuple[int, int, int, int]:
208 """Plain-Python reference for ps_program()."""
209 active = bool(exec_lo & 1)
210 s_lhs = 0xFFFFFFFF if scc_one else 0x12340000
211 s_rhs = 5 if scc_one else 0
212 s4 = (s_lhs + s_rhs) & M32
213 scc = (s_lhs + s_rhs) > M32
214 v0 = ((0x11112222 + add_k) & M32) # executed while EXEC=1 initially
215 vcc = vcc_one # evaluated while EXEC=1 initially
216 s5 = 0x10000001 if scc else 0x20000002
217 s6 = (s4 + s5) & M32
218 v1 = (0x33334444 if vcc else 0x99990000) if active else 0x33334444
219 v2 = ((0x55556666 + s6) & M32) if active else 0x55556666
220 v3 = 0x77778888
221 if not active:
222 return (0, 0, 0, 0)
223 return (v0, v1, v2, v3)
224
225
226def cs_program(middle: list[str], *, wave64: bool, scc_one: bool = True,
227 exec_lo: int = 0xA5A55A5A, exec_hi: int = 0x3C3C6969) -> list[str]:
228 """Synthetic wave32/wave64 CS checking VGPRs, SGPRs, SCC, VCC, and EXEC across all lanes."""
229 s_lhs = 0xFFFFFFFF if scc_one else 0x10203040
230 s_rhs = 3 if scc_one else 1
231 if wave64:
232 lane_setup = [
233 "s_mov_b64 exec, -1",
234 "v_mbcnt_lo_u32_b32 v0, -1, 0",
235 "v_mbcnt_hi_u32_b32 v0, -1, v0",
236 ]
237 vcc_cmp = "v_cmp_eq_u32 vcc, v4, 0"
238 set_exec = [f"s_mov_b32 exec_lo, {exec_lo:#x}", f"s_mov_b32 exec_hi, {exec_hi:#x}"]
239 reset_exec = "s_mov_b64 exec, -1"
240 vcc_cnd = "v_cndmask_b32 v2, 0x99990000, v2, vcc"
241 else:
242 lane_setup = [] # v0 is seeded directly from LocalInvocationId.x
243 vcc_cmp = "v_cmp_eq_u32 vcc_lo, v4, 0"
244 set_exec = [f"s_mov_b32 exec_lo, {exec_lo:#x}"]
245 reset_exec = "s_mov_b32 exec_lo, -1"
246 vcc_cnd = "v_cndmask_b32 v2, 0x99990000, v2, vcc_lo"
247
248 return [
249 *lane_setup,
250 "v_mov_b32 v1, v0",
251 "v_add_nc_u32 v1, v1, 10",
252 "v_mov_b32 v2, 0x77770000",
253 "v_add_nc_u32 v2, v2, v0",
254 "v_mov_b32 v3, 0x1000",
255 "v_and_b32 v4, v0, 1",
256 vcc_cmp, # even lanes: VCC = 1; odd lanes: VCC = 0
257 "s_mov_b32 s8, 0x01020304",
258 "s_mov_b32 s9, 0x55667788",
259 f"s_mov_b32 s10, {s_lhs:#x}",
260 f"s_add_u32 s11, s10, {s_rhs:#x}", # SCC = 1 iff scc_one
261 *set_exec,
262 *middle,
263 "v_add_nc_u32 v1, v1, 0x100", # updates v1 only in lanes where EXEC=1
264 "s_cselect_b32 s12, 0x10000, 0x20000", # reads SCC
265 reset_exec,
266 vcc_cnd, # reads VCC across all lanes (even keeps v2, odd gets 0x99990000)
267 "v_add_nc_u32 v3, v3, s8", # reads SGPR s8
268 "v_add_nc_u32 v3, v3, s12", # reads s12 (SCC outcome)
269 "v_add_nc_u32 v3, v3, s11", # reads s11 (s_add_u32 sum)
270 "v_mov_b32 v4, s9", # reads SGPR s9
271 "v_lshlrev_b32 v5, 4, v0", # byte offset = 16 * lane
272 "buffer_store_dwordx4 v[1:4], v5, s[0:3], 0 offen",
273 "s_endpgm",
274 ]
275
276
277def expected_cs_words(lanes: int, *, scc_one: bool = True,
278 exec_lo: int = 0xA5A55A5A, exec_hi: int = 0x3C3C6969) -> list[tuple[int, int, int, int]]:
279 """Plain-Python reference for cs_program()."""
280 s_lhs = 0xFFFFFFFF if scc_one else 0x10203040
281 s_rhs = 3 if scc_one else 1
282 s11 = (s_lhs + s_rhs) & M32
283 s12 = 0x10000 if ((s_lhs + s_rhs) > M32) else 0x20000
284 exec_mask = (exec_hi << 32) | exec_lo
285 out = []
286 for lane in range(lanes):
287 active = bool((exec_mask >> lane) & 1)
288 w0 = (lane + 10 + (0x100 if active else 0)) & M32
289 w1 = (0x77770000 + lane) if (lane % 2 == 0) else 0x99990000
290 w2 = (0x1000 + 0x01020304 + s12 + s11) & M32
291 w3 = 0x55667788
292 out.append((w0, w1, w2, w3))
293 return out
294
295
296def run_cs(spv: str, lanes: int) -> list[tuple[int, int, int, int]]:
297 mem = si.run_workgroup(
298 spv, lanes, lanes,
299 inputs_for=lambda i: {"%wg_id": (0, 0, 0), "%local_id": (i, 0, 0), "%sg_lane": i},
300 push_constants=VSHARP + [0] * 28,
301 memory={},
302 )
303 return [tuple(mem[16 * lane + 4 * c] for c in range(4)) for lane in range(lanes)]
304
305
306class ScalarNoopWaitcntParsingTests(unittest.TestCase):
307 """Exact syntax and operand parsing in tools/shader_ir.py for all 11 scalar ops and variants."""
308
309 def test_parse_all_scalar_noop_waitcnt_and_mode_forms(self):
310 cases = [
311 ("s_clause 0x1", "s_clause", [{"k": "imm", "v": 1}]),
312 ("s_delay_alu 0", "s_delay_alu", [{"k": "imm", "v": 0}]),
313 (
314 "s_delay_alu instid0(VALU_DEP_1) | instskip(NEXT) | instid1(SALU_CYCLE_1)",
315 "s_delay_alu",
316 [{"k": "special", "t": "instid0(VALU_DEP_1) | instskip(NEXT) | instid1(SALU_CYCLE_1)"}],
317 ),
318 ("s_denorm_mode 0x3", "s_denorm_mode", [{"k": "imm", "v": 3}]),
319 ("s_inst_prefetch 0x0", "s_inst_prefetch", [{"k": "imm", "v": 0}]),
320 ("s_inst_prefetch -1", "s_inst_prefetch", [{"k": "imm", "v": -1}]),
321 ("s_round_mode 0x3", "s_round_mode", [{"k": "imm", "v": 3}]),
322 ("s_setprio 0x2", "s_setprio", [{"k": "imm", "v": 2}]),
323 ("s_sleep 0x1", "s_sleep", [{"k": "imm", "v": 1}]),
324 ("s_waitcnt_depctr 0xffe3", "s_waitcnt_depctr", [{"k": "imm", "v": 0xFFE3}]),
325 (
326 "s_waitcnt_depctr depctr_vm_vsrc(0) depctr_va_sdst(0)",
327 "s_waitcnt_depctr",
328 [{"k": "special", "t": "depctr_vm_vsrc(0)"}, {"k": "special", "t": "depctr_va_sdst(0)"}],
329 ),
330 (
331 "s_waitcnt_expcnt null, 0x0",
332 "s_waitcnt_expcnt",
333 [{"k": "special", "t": "null", "neg": False, "abs": False}, {"k": "imm", "v": 0}],
334 ),
335 (
336 "s_waitcnt_lgkmcnt null, 0x3f",
337 "s_waitcnt_lgkmcnt",
338 [{"k": "special", "t": "null", "neg": False, "abs": False}, {"k": "imm", "v": 0x3F}],
339 ),
340 (
341 "s_waitcnt_vmcnt null, 0x0",
342 "s_waitcnt_vmcnt",
343 [{"k": "special", "t": "null", "neg": False, "abs": False}, {"k": "imm", "v": 0}],
344 ),
345 (
346 "s_waitcnt_vscnt null, 0x0",
347 "s_waitcnt_vscnt",
348 [{"k": "special", "t": "null", "neg": False, "abs": False}, {"k": "imm", "v": 0}],
349 ),
350 ("s_waitcnt vmcnt(0)", "s_waitcnt", [{"k": "special", "t": "vmcnt(0)"}]),
351 ("s_waitcnt expcnt(0)", "s_waitcnt", [{"k": "special", "t": "expcnt(0)"}]),
352 ("s_waitcnt lgkmcnt(0)", "s_waitcnt", [{"k": "special", "t": "lgkmcnt(0)"}]),
353 (
354 "s_waitcnt vmcnt(1) lgkmcnt(2)",
355 "s_waitcnt",
356 [{"k": "special", "t": "vmcnt(1)"}, {"k": "special", "t": "lgkmcnt(2)"}],
357 ),
358 (
359 "s_waitcnt vmcnt(0) expcnt(0) lgkmcnt(0)",
360 "s_waitcnt",
361 [{"k": "special", "t": "vmcnt(0) expcnt(0) lgkmcnt(0)"}],
362 ),
363 ("s_waitcnt 0", "s_waitcnt", [{"k": "imm", "v": 0}]),
364 (
365 "s_setreg_imm32_b32 hwreg(HW_REG_MODE, 2, 2), 3",
366 "s_setreg_imm32_b32",
367 [{"k": "special", "t": "hwreg(HW_REG_MODE, 2, 2)"}, {"k": "imm", "v": 3}],
368 ),
369 ("s_nop 0", "s_nop", [{"k": "imm", "v": 0}]),
370 ("v_nop", "v_nop", []),
371 ]
372 for text, want_op, want_args in cases:
373 with self.subTest(line=text):
374 parsed = shader_ir.parse_line("\t" + text)
375 self.assertIsNotNone(parsed)
376 self.assertEqual(parsed["op"], want_op)
377 self.assertEqual(parsed["args"], want_args)
378 self.assertEqual(parsed["mods"], [])
379 self.assertTrue(all(arg["k"] != "raw" for arg in parsed["args"]))
380
381
382class PixelShaderNoopWaitcntTests(unittest.TestCase):
383 """PS translation and spirv_mini_interp execution across all handled NOOPS and waitcnt variants."""
384
385 def test_variants_emit_no_extra_spirv_and_preserve_state_active_scc1_vcc1(self):
386 baseline = translate_ps("ps_noop_base_11", ps_program([], scc_one=True, vcc_one=True))
387 want = expected_ps_mrt0(scc_one=True, vcc_one=True)
388 self.assertEqual(want, (0x11112232, 0x33334444, 0x6555666B, 0x77778888))
389 self.assertEqual(tuple(si.run_fragment(baseline, inputs={"%sg_lane": 0})["%out_mrt0"]), want)
390 self.assertNotIn("OpControlBarrier", baseline)
391 self.assertNotIn("OpMemoryBarrier", baseline)
392
393 for variant in SCALAR_NOOP_VARIANTS:
394 with self.subTest(insn=variant):
395 spv = translate_ps("ps_noop_var", ps_program([variant], scc_one=True, vcc_one=True))
396 self.assertEqual(spv, baseline, f"{variant} emitted unexpected SPIR-V operations")
397 self.assertEqual(tuple(si.run_fragment(spv, inputs={"%sg_lane": 0})["%out_mrt0"]), want)
398
399 def test_variants_preserve_scc0_and_vcc0(self):
400 baseline = translate_ps("ps_noop_base_00", ps_program([], scc_one=False, vcc_one=False))
401 want = expected_ps_mrt0(scc_one=False, vcc_one=False)
402 self.assertEqual(want, (0x11112232, 0x99990000, 0x87896668, 0x77778888))
403 self.assertEqual(tuple(si.run_fragment(baseline, inputs={"%sg_lane": 0})["%out_mrt0"]), want)
404
405 for variant in SCALAR_NOOP_VARIANTS:
406 with self.subTest(insn=variant):
407 spv = translate_ps("ps_noop_var00", ps_program([variant], scc_one=False, vcc_one=False))
408 self.assertEqual(spv, baseline)
409 self.assertEqual(tuple(si.run_fragment(spv, inputs={"%sg_lane": 0})["%out_mrt0"]), want)
410
411 def test_interleaved_across_every_arithmetic_step(self):
412 base_lines = ps_program([], scc_one=True, vcc_one=True)
413 baseline = translate_ps("ps_interleave_base", base_lines)
414 want = expected_ps_mrt0(scc_one=True, vcc_one=True)
415 interleaved = [
416 "v_mov_b32 v0, 0x11112222",
417 "v_mov_b32 v1, 0x33334444",
418 "v_mov_b32 v2, 0x55556666",
419 "v_mov_b32 v3, 0x77778888",
420 "s_clause 0x1",
421 "s_mov_b32 s2, 0xffffffff",
422 "s_mov_b32 s3, 5",
423 "s_delay_alu instid0(VALU_DEP_1) | instskip(NEXT) | instid1(SALU_CYCLE_1)",
424 "s_add_u32 s4, s2, s3",
425 "s_inst_prefetch 0x0",
426 "s_setprio 0x2",
427 "v_add_nc_u32 v0, v0, 0x10",
428 "s_sleep 0x1",
429 "v_cmp_eq_u32 vcc_lo, v0, 0x11112232",
430 "s_waitcnt_depctr depctr_vm_vsrc(0) depctr_va_sdst(0)",
431 "s_mov_b32 exec_lo, 0xaaaa5555",
432 "s_waitcnt_expcnt null, 0x0",
433 "s_waitcnt_lgkmcnt null, 0x0",
434 "s_waitcnt_vmcnt null, 0x0",
435 "s_waitcnt vmcnt(0) expcnt(0) lgkmcnt(0)",
436 "s_waitcnt_vscnt null, 0x0",
437 "s_nop 0",
438 "v_nop",
439 "s_cselect_b32 s5, 0x10000001, 0x20000002",
440 "s_add_u32 s6, s4, s5",
441 "v_cndmask_b32 v1, 0x99990000, v1, vcc_lo",
442 "v_add_nc_u32 v2, v2, s6",
443 "exp mrt0 v0, v1, v2, v3 done vm",
444 "s_endpgm",
445 ]
446 spv = translate_ps("ps_interleave", interleaved)
447 self.assertEqual(spv, baseline)
448 self.assertEqual(tuple(si.run_fragment(spv, inputs={"%sg_lane": 0})["%out_mrt0"]), want)
449
450 def test_inactive_exec_stays_zero_for_vgpr_writes_and_exports(self):
451 # Part 1: EXEC=0 around all handled no-ops blocks VGPR writes, then restoring EXEC exports intact values.
452 base_vgpr = [
453 "v_mov_b32 v0, 0x10000001",
454 "v_mov_b32 v1, 0x20000002",
455 "v_mov_b32 v2, 0x30000003",
456 "v_mov_b32 v3, 0x40000004",
457 "s_mov_b32 exec_lo, 0",
458 "v_add_nc_u32 v2, v2, 0x1234",
459 "v_mov_b32 v3, 0xdeadbeef",
460 "s_mov_b32 exec_lo, -1",
461 "exp mrt0 v0, v1, v2, v3 done vm",
462 "s_endpgm",
463 ]
464 with_noops = base_vgpr[:5] + REPRESENTATIVE_NOOPS + base_vgpr[5:]
465 spv_base = translate_ps("ps_exec0_vgpr_base", base_vgpr)
466 spv_noops = translate_ps("ps_exec0_vgpr_noops", with_noops)
467 self.assertEqual(spv_noops, spv_base)
468 self.assertEqual(tuple(si.run_fragment(spv_noops, inputs={"%sg_lane": 0})["%out_mrt0"]),
469 (0x10000001, 0x20000002, 0x30000003, 0x40000004))
470
471 # Part 2: EXEC=0 across all handled no-ops keeps the lane inactive through end of shader (OpKill -> {}).
472 base_exp = [
473 "v_mov_b32 v0, 0x10000001",
474 "v_mov_b32 v1, 0x20000002",
475 "v_mov_b32 v2, 0x30000003",
476 "v_mov_b32 v3, 0x40000004",
477 "exp mrt0 v0, v1, v2, v3 vm",
478 "s_mov_b32 exec_lo, 0xaaaa5554",
479 "v_mov_b32 v0, 0xbad00000",
480 "exp mrt0 v0, v0, v0, v0 done vm",
481 "s_endpgm",
482 ]
483 spv_exp_base = translate_ps("ps_exec0_exp_base", base_exp)
484 spv_exp_noops = translate_ps("ps_exec0_exp_noops", base_exp[:6] + REPRESENTATIVE_NOOPS + base_exp[6:])
485 self.assertEqual(spv_exp_noops, spv_exp_base)
486 self.assertEqual(si.run_fragment(spv_exp_noops, inputs={"%sg_lane": 0}), {})
487
488
489class ComputeShaderNoopWaitcntTests(unittest.TestCase):
490 """FSSM compute shader translation and multi-lane execution (wave32 & wave64)."""
491
492 def test_wave32_each_and_all_preserve_registers_vcc_scc_and_exec(self):
493 for scc_one in (True, False):
494 baseline = translate_cs("cs_w32_base", cs_program([], wave64=False, scc_one=scc_one), threads=32)
495 want = expected_cs_words(32, scc_one=scc_one)
496 self.assertEqual(run_cs(baseline, 32), want)
497 self.assertNotIn("OpControlBarrier", baseline)
498 self.assertNotIn("OpMemoryBarrier", baseline)
499
500 for variant in SCALAR_NOOP_VARIANTS:
501 with self.subTest(scc_one=scc_one, insn=variant):
502 spv = translate_cs("cs_w32_var", cs_program([variant], wave64=False, scc_one=scc_one), threads=32)
503 self.assertEqual(spv, baseline)
504 self.assertEqual(run_cs(spv, 32), want)
505
506 spv_all = translate_cs("cs_w32_all", cs_program(REPRESENTATIVE_NOOPS, wave64=False, scc_one=scc_one),
507 threads=32)
508 self.assertEqual(spv_all, baseline)
509 self.assertEqual(run_cs(spv_all, 32), want)
510
511 def test_wave64_preserves_state_across_all_64_lanes(self):
512 for scc_one in (True, False):
513 baseline = translate_cs("cs_w64_base", cs_program([], wave64=True, scc_one=scc_one), threads=64)
514 want = expected_cs_words(64, scc_one=scc_one)
515 self.assertEqual(run_cs(baseline, 64), want)
516 self.assertNotIn("OpControlBarrier", baseline)
517 self.assertNotIn("OpMemoryBarrier", baseline)
518
519 with self.subTest(scc_one=scc_one):
520 spv_all = translate_cs("cs_w64_all", cs_program(REPRESENTATIVE_NOOPS, wave64=True, scc_one=scc_one),
521 threads=64)
522 self.assertEqual(spv_all, baseline)
523 self.assertEqual(run_cs(spv_all, 64), want)
524
525
526class ModeInstructionsTests(unittest.TestCase):
527 """Tests for s_denorm_mode, s_round_mode, and s_setreg* hardware MODE writes."""
528
529 def test_s_denorm_mode_and_s_round_mode_stay_unsupported(self):
530 for insn in REFUSED_MODE_VARIANTS:
531 op = insn.split()[0]
532 with self.subTest(stage="ps", insn=insn):
533 with self.assertRaises(rdna2spirv.Unsupported) as ctx:
534 translate_ps("ps_refused_mode", ps_program([insn]))
535 self.assertIn(op, str(ctx.exception))
536 self.assertIn("s_setreg", str(ctx.exception))
537
538 with self.subTest(stage="cs", insn=insn):
539 with self.assertRaises(rdna2spirv.Unsupported) as ctx:
540 translate_cs("cs_refused_mode", cs_program([insn], wave64=False), threads=32)
541 self.assertIn(op, str(ctx.exception))
542 self.assertIn("s_setreg", str(ctx.exception))
543
544 def test_s_setreg_mode_fp_round_emits_only_mode_r16_and_preserves_state(self):
545 ps_base = translate_ps("ps_mode_base", ps_program([]))
546 want_ps = expected_ps_mrt0()
547 cs_base = translate_cs("cs_mode_base", cs_program([], wave64=False), threads=32)
548 want_cs = expected_cs_words(32)
549
550 for insn, mode_const in MODELLED_MODE_VARIANTS:
551 with self.subTest(stage="ps", insn=insn):
552 spv = translate_ps("ps_mode_setreg", ps_program([insn]))
553 self.assertIn("%mode_r16 = OpVariable %_ptr_Function_uint Function %c0", spv)
554 self.assertIn(f"OpStore %mode_r16 {mode_const}", spv)
555 self.assertNotIn("OpControlBarrier", spv)
556 # Removing the two mode lines recovers the exact baseline SPIR-V (modulo unused %c3 if added).
557 self.assertEqual(spv.count("OpStore %mode_r16"), 1)
558 self.assertEqual(tuple(si.run_fragment(spv, inputs={"%sg_lane": 0})["%out_mrt0"]), want_ps)
559 self.assertEqual(tuple(si.run_fragment(ps_base, inputs={"%sg_lane": 0})["%out_mrt0"]), want_ps)
560
561 with self.subTest(stage="cs", insn=insn):
562 spv = translate_cs("cs_mode_setreg", cs_program([insn], wave64=False), threads=32)
563 self.assertIn("%mode_r16 = OpVariable %_ptr_Function_uint Function %c0", spv)
564 self.assertIn(f"OpStore %mode_r16 {mode_const}", spv)
565 self.assertEqual(run_cs(spv, 32), want_cs)
566 self.assertEqual(run_cs(cs_base, 32), want_cs)
567
568 def test_unmodelled_s_setreg_mode_forms_raise_unsupported(self):
569 bad_mode_writes = [
570 "s_setreg_imm32_b32 hwreg(HW_REG_MODE, 0, 2), 3",
571 "s_setreg_imm32_b32 hwreg(HW_REG_MODE, 4, 4), 15",
572 "s_setreg_imm32_b32 hwreg(HW_REG_MODE), 0",
573 "s_setreg_imm32_b32 hwreg(HW_REG_MODE, 2, 2), 1",
574 "s_setreg_imm32_b32 hwreg(HW_REG_MODE, 2, 2), 2",
575 "s_setreg_b32 hwreg(HW_REG_MODE, 2, 2), s2",
576 ]
577 for insn in bad_mode_writes:
578 with self.subTest(insn=insn):
579 with self.assertRaises(rdna2spirv.Unsupported):
580 translate_ps("ps_bad_mode", ps_program([insn]))
581
582
583class NegativeControlTests(unittest.TestCase):
584 """Negative controls: sabotaging arithmetic or using unknown mnemonics must be detected."""
585
586 def test_sabotaging_arithmetic_around_noop_waitcnt_changes_output(self):
587 good_spv = translate_ps("ps_neg_good", ps_program(["s_waitcnt_vmcnt null, 0x0", "s_clause 0x1"]))
588 good_out = si.run_fragment(good_spv, inputs={"%sg_lane": 0})
589 self.assertEqual(tuple(good_out["%out_mrt0"]), expected_ps_mrt0(scc_one=True, vcc_one=True))
590
591 # Assembly-level sabotage around the waitcnt/clause instructions:
592 sabotaged_cases = [
593 ("SCC flipped 1->0", ps_program(["s_waitcnt_vmcnt null, 0x0", "s_clause 0x1"], scc_one=False)),
594 ("VCC flipped 1->0", ps_program(["s_waitcnt_vmcnt null, 0x0", "s_clause 0x1"], vcc_one=False)),
595 ("v_add_nc_u32 addend changed", ps_program(["s_waitcnt_vmcnt null, 0x0", "s_clause 0x1"], add_k=0x20)),
596 ("EXEC bit 0 cleared", ps_program(["s_waitcnt_vmcnt null, 0x0", "s_clause 0x1"], exec_lo=0xAAAA5554)),
597 ]
598 for label, bad_lines in sabotaged_cases:
599 with self.subTest(sabotage=label):
600 bad_spv = translate_ps("ps_neg_bad", bad_lines)
601 bad_out = si.run_fragment(bad_spv, inputs={"%sg_lane": 0})
602 self.assertNotEqual(bad_out, good_out)
603
604 # SPIR-V-level sabotage on the translated output around the no-op/waitcnt block:
605 for old, new, label in (
606 ("OpIAdd %uint", "OpISub %uint", "v_add_nc_u32/s_add_u32 turned into OpISub"),
607 ("OpIEqual %bool", "OpINotEqual %bool", "v_cmp_eq_u32 inverted"),
608 ):
609 with self.subTest(spirv_sabotage=label):
610 self.assertIn(old, good_spv)
611 mutated = good_spv.replace(old, new)
612 self.assertNotEqual(si.run_fragment(mutated, inputs={"%sg_lane": 0}), good_out)
613
614 # CS multi-lane negative control:
615 cs_good = translate_cs("cs_neg_good", cs_program(["s_sleep 0x1", "s_waitcnt_depctr 0xffe3"], wave64=False),
616 threads=32)
617 cs_good_words = run_cs(cs_good, 32)
618 cs_bad = translate_cs("cs_neg_bad", cs_program(["s_sleep 0x1", "s_waitcnt_depctr 0xffe3"],
619 wave64=False, scc_one=False), threads=32)
620 self.assertNotEqual(run_cs(cs_bad, 32), cs_good_words)
621
622 def test_unknown_waitcnt_and_noop_mnemonics_fail_with_unsupported(self):
623 for bogus in ("s_bogus_waitcnt 0x0", "s_bogus_waitcnt", "s_bogus_noop 0"):
624 with self.subTest(stage="ps", insn=bogus):
625 with self.assertRaises(rdna2spirv.Unsupported) as ctx:
626 translate_ps("ps_bogus", ps_program([bogus]))
627 self.assertIn(bogus.split()[0], str(ctx.exception))
628
629 with self.subTest(stage="cs", insn=bogus):
630 with self.assertRaises(rdna2spirv.Unsupported) as ctx:
631 translate_cs("cs_bogus", cs_program([bogus], wave64=False), threads=32)
632 self.assertIn(bogus.split()[0], str(ctx.exception))
633
634
635if __name__ == "__main__":
636 unittest.main()
diff --git a/tests/semantic/test_valu_cvt_pk_u8_f32.py b/tests/semantic/test_valu_cvt_pk_u8_f32.py
new file mode 100644
index 000000000..d0f42b1f1
--- /dev/null
+++ b/tests/semantic/test_valu_cvt_pk_u8_f32.py
@@ -0,0 +1,757 @@
1"""Semantic value tests for RDNA2 v_cvt_pk_u8_f32 (VOP3).
2
3AMD RDNA2 ISA semantics for `v_cvt_pk_u8_f32 vD, src0, src1, src2`:
4 - Converts binary32 `src0` to an 8-bit unsigned integer using IEEE-754 round-to-nearest-even (`RoundEven`),
5 clamped to [0, 255] (negative values and -inf -> 0; values >= 255.0 and +inf -> 255; NaN -> 0).
6 - Inserts that byte into byte lane `src1[1:0]` (`src1 & 3`, i.e. bits [7:0], [15:8], [23:16], or [31:24])
7 of `src2`, leaving the other 3 bytes of `src2` untouched in `vD`.
8
9Executed end-to-end through tools/rdna2spirv.py and tests/semantic/spirv_mini_interp.py (single-lane pixel
10shaders via run_fragment and multi-lane compute shaders via run_workgroup), and checked against hand-worked
11constants and an independent pure-Python binary32 Fraction/RTE reference oracle. Standard library only;
12hand-written RDNA2 disassembly listings only.
13
14Finding on NaN inputs (open item also listed in docs/design.md, "Multiply-add and output modifiers" row):
15 tools/rdna2spirv.py lowers `v_cvt_pk_u8_f32` via `OpExtInst %float %glsl FClamp {x} %f0 %f_255` without an
16 `OpIsNan` guard before `RoundEven` + `OpConvertFToU`. In SPIR-V / GLSL.std.450, `FClamp` with a NaN operand
17 is undefined, so tests/semantic/spirv_mini_interp.py raises `UnsupportedConstruct` for `qNaN`, `-qNaN`, and
18 `sNaN`. Accordingly, `OracleTests` verifies the RDNA2 ISA `NaN -> 0` rule, and `NaNHandlingTests` asserts
19 both the translated SPIR-V structure (`FClamp`, `RoundEven`, `OpConvertFToU`) and that `spirv_mini_interp.py`
20 rejects NaN inputs with `UnsupportedConstruct` rather than returning a fabricated value.
21"""
22import gc
23import os
24import random
25import re
26import struct
27import sys
28import tempfile
29import unittest
30import warnings
31from fractions import Fraction
32
33HERE = os.path.dirname(os.path.abspath(__file__))
34ROOT = os.path.dirname(os.path.dirname(HERE))
35TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools")
36
37sys.dont_write_bytecode = True
38if TOOLS_DIR not in sys.path:
39 sys.path.insert(0, TOOLS_DIR)
40if HERE not in sys.path:
41 sys.path.insert(0, HERE)
42
43import rdna2spirv # noqa: E402
44import spirv_mini_interp as si # noqa: E402
45
46MASK32 = 0xFFFFFFFF
47OLD = 0xDEADBEEF
48CANARY = 0xCAFEBABE
49HEAP_FILL = 0xEEEEEEEE
50STUB_DXBC = b"DXBC" + bytes(24) + struct.pack("<I", 0) + bytes(4)
51VSHARP = [0, 0, 0xFFFFFFFF, 0x31016FAC]
52
53# Representative binary32 bit encodings.
54F32_POS_ZERO = 0x00000000
55F32_NEG_ZERO = 0x80000000
56F32_POS_SUB_MIN = 0x00000001
57F32_POS_SUB_MID = 0x00400000
58F32_POS_SUB_MAX = 0x007FFFFF
59F32_NEG_SUB_MIN = 0x80000001
60F32_NEG_SUB_MAX = 0x807FFFFF
61F32_POS_NORM_MIN = 0x00800000
62F32_NEG_NORM_MIN = 0x80800000
63F32_FLT_MAX = 0x7F7FFFFF
64F32_NEG_FLT_MAX = 0xFF7FFFFF
65F32_POS_INF = 0x7F800000
66F32_NEG_INF = 0xFF800000
67F32_QNAN = 0x7FC00000
68F32_NEG_QNAN = 0xFFC00000
69F32_QNAN_PAYLOAD = 0x7FC12345
70F32_SNAN = 0x7F800001
71F32_NEG_SNAN = 0xFF800001
72
73
74def f32_bits(x: float) -> int:
75 try:
76 return struct.unpack("<I", struct.pack("<f", x))[0]
77 except OverflowError:
78 return F32_POS_INF if x > 0 else F32_NEG_INF
79
80
81def bits_f32(bits: int) -> float:
82 return struct.unpack("<f", struct.pack("<I", bits & MASK32))[0]
83
84
85def is_f32_nan_bits(bits: int) -> bool:
86 return (bits & 0x7F800000) == 0x7F800000 and (bits & 0x007FFFFF) != 0
87
88
89# -----------------------------------------------------------------------------
90# Independent IEEE-754 Binary32 Fraction/RTE Reference Oracle
91# -----------------------------------------------------------------------------
92
93def f32_bits_to_fraction(bits: int) -> Fraction:
94 """Exact rational value of a finite IEEE-754 binary32 bit encoding."""
95 bits &= MASK32
96 sign = -1 if (bits >> 31) else 1
97 exp = (bits >> 23) & 0xFF
98 man = bits & 0x7FFFFF
99 if exp == 0xFF:
100 raise ValueError(f"non-finite binary32 {bits:#010x}")
101 if exp == 0:
102 return sign * Fraction(man, 1 << 23) * (Fraction(2) ** -126)
103 return sign * Fraction((1 << 23) | man, 1 << 23) * (Fraction(2) ** (exp - 127))
104
105
106def rne_nonneg_fraction(q: Fraction) -> int:
107 """Round a non-negative rational to the nearest integer, ties to even."""
108 n = q.numerator // q.denominator
109 rem = q - n
110 half = Fraction(1, 2)
111 if rem > half or (rem == half and (n & 1)):
112 n += 1
113 return n
114
115
116def ref_cvt_pk_u8_byte(x_bits: int) -> int:
117 """RDNA2 flt32_to_uint8: binary32 bits -> IEEE-754 RTE clamped [0, 255] (NaN -> 0)."""
118 bits = x_bits & MASK32
119 if is_f32_nan_bits(bits):
120 return 0
121 if (bits >> 31) or (bits & 0x7FFFFFFF) == 0:
122 return 0
123 if bits == F32_POS_INF:
124 return 255
125 q = f32_bits_to_fraction(bits)
126 if q >= 255:
127 return 255
128 return min(255, rne_nonneg_fraction(q))
129
130
131def ref_cvt_pk_u8_f32(x_bits: int, slot: int, base: int) -> int:
132 """RDNA2 V_CVT_PK_U8_F32: insert ref_cvt_pk_u8_byte(x_bits) at byte (slot & 3) of base."""
133 u = ref_cvt_pk_u8_byte(x_bits)
134 sh = 8 * (slot & 3)
135 return ((base & MASK32) & ~(0xFF << sh)) | (u << sh)
136
137
138# Hand-worked reference expectations: (label, x_bits, slot, base, expected_dword).
139HAND_WORKED = (
140 ("slot0_old", f32_bits(18.0), 0, OLD, 0xDEADBE12),
141 ("slot1_old", f32_bits(52.0), 1, OLD, 0xDEAD34EF),
142 ("slot2_old", f32_bits(86.0), 2, OLD, 0xDE56BEEF),
143 ("slot3_old", f32_bits(120.0), 3, OLD, 0x78ADBEEF),
144 ("slot4_wraps_0", f32_bits(0xAB), 4, OLD, 0xDEADBEAB),
145 ("slot5_wraps_1", f32_bits(0xCD), 5, OLD, 0xDEADCDEF),
146 ("slot7_wraps_3", f32_bits(0x42), 7, OLD, 0x42ADBEEF),
147 ("slot_neg1_wraps_3", f32_bits(0x99), -1, OLD, 0x99ADBEEF),
148 ("tie_0_5_even", f32_bits(0.5), 0, OLD, 0xDEADBE00),
149 ("tie_1_5_even", f32_bits(1.5), 1, OLD, 0xDEAD02EF),
150 ("tie_2_5_even", f32_bits(2.5), 2, OLD, 0xDE02BEEF),
151 ("tie_253_5_even", f32_bits(253.5), 0, OLD, 0xDEADBEFE),
152 ("tie_254_5_even", f32_bits(254.5), 1, OLD, 0xDEADFEEF),
153 ("clamp_255_49", f32_bits(255.49), 2, OLD, 0xDEFFBEEF),
154 ("clamp_255_5", f32_bits(255.5), 3, OLD, 0xFFADBEEF),
155 ("neg_0_001", f32_bits(-0.001), 0, OLD, 0xDEADBE00),
156 ("neg_1000", f32_bits(-1000.0), 1, OLD, 0xDEAD00EF),
157 ("neg_inf", F32_NEG_INF, 2, OLD, 0xDE00BEEF),
158 ("pos_inf", F32_POS_INF, 3, OLD, 0xFFADBEEF),
159 ("subnormal_pos", F32_POS_SUB_MIN, 0, OLD, 0xDEADBE00),
160 ("subnormal_neg", F32_NEG_SUB_MAX, 1, OLD, 0xDEAD00EF),
161 ("qnan", F32_QNAN, 0, OLD, 0xDEADBE00),
162 ("neg_qnan", F32_NEG_QNAN, 2, OLD, 0xDE00BEEF),
163 ("snan", F32_SNAN, 3, OLD, 0x00ADBEEF),
164)
165
166
167# -----------------------------------------------------------------------------
168# Translation & Execution Helpers
169# -----------------------------------------------------------------------------
170
171_TMP_DIR = None
172_PS_PATH = None
173_CS_PATH = None
174_CS_FSSM = None
175
176
177def _make_fssm(rsrc2: int, group: tuple[int, int, int]) -> bytes:
178 header = bytearray(0x148)
179 struct.pack_into("<4I", header, 0x138, rsrc2, *group)
180 return bytes(header)
181
182
183def setUpModule():
184 global _TMP_DIR, _PS_PATH, _CS_PATH, _CS_FSSM
185 _TMP_DIR = tempfile.TemporaryDirectory()
186 disasm_dir = os.path.join(_TMP_DIR.name, "disasm")
187 fssm_dir = os.path.join(_TMP_DIR.name, "fssm")
188 os.mkdir(disasm_dir)
189 os.mkdir(fssm_dir)
190 _PS_PATH = os.path.join(disasm_dir, "ps_valu_cvt_pk_u8_f32.s")
191 _CS_PATH = os.path.join(disasm_dir, "cs_valu_cvt_pk_u8_f32.s")
192 _CS_FSSM = os.path.join(fssm_dir, "cs_valu_cvt_pk_u8_f32.fssm")
193 with open(os.path.join(_TMP_DIR.name, "ps_valu_cvt_pk_u8_f32.dxbc"), "wb") as f:
194 f.write(STUB_DXBC)
195
196
197def tearDownModule():
198 global _TMP_DIR, _PS_PATH, _CS_PATH, _CS_FSSM
199 if _TMP_DIR is not None:
200 gc.collect()
201 _TMP_DIR.cleanup()
202 _TMP_DIR = None
203 _PS_PATH = None
204 _CS_PATH = None
205 _CS_FSSM = None
206
207
208def translate_ps(lines: list[str]) -> str:
209 if _TMP_DIR is None:
210 setUpModule()
211 asm = "; test_valu_cvt_pk_u8_f32\n" + "".join(f"\t{ln}\n" for ln in lines) + "\ts_endpgm\n"
212 with open(_PS_PATH, "w", encoding="utf-8", newline="") as f:
213 f.write(asm)
214 with warnings.catch_warnings():
215 warnings.simplefilter("ignore", ResourceWarning)
216 spv = rdna2spirv.translate(_PS_PATH)
217 gc.collect()
218 return spv
219
220
221def run_ps_mrt0(lines: list[str], regs: tuple[str, str, str, str] = ("v0", "v0", "v0", "v0")) -> tuple[int, ...]:
222 spv = translate_ps(list(lines) + [f"exp mrt0 {', '.join(regs)} done vm"])
223 out = si.run_fragment(spv)
224 if list(out) != ["%out_mrt0"]:
225 raise AssertionError(f"expected %out_mrt0 only; got {sorted(out)}")
226 return tuple(out["%out_mrt0"])
227
228
229def run_cs(lines: list[str], group_size: int, subgroup_size: int, memory: dict[int, int]) -> dict[int, int]:
230 if _TMP_DIR is None:
231 setUpModule()
232 # rsrc2 = 0x0088: USER_SGPR = 4 (s[0:3] V#), TGID_X_EN = 1 (s4), TIDIG_COMP_CNT = 0 (v0 = local_id.x).
233 with open(_CS_FSSM, "wb") as f:
234 f.write(_make_fssm(0x0088, (group_size, 1, 1)))
235 asm = "; test_cs_valu_cvt_pk_u8_f32\n" + "".join(f"\t{ln}\n" for ln in lines) + "\ts_endpgm\n"
236 with open(_CS_PATH, "w", encoding="utf-8", newline="") as f:
237 f.write(asm)
238 with warnings.catch_warnings():
239 warnings.simplefilter("ignore", ResourceWarning)
240 spv = rdna2spirv.translate(_CS_PATH)
241 gc.collect()
242 return si.run_workgroup(
243 spv, group_size, subgroup_size,
244 inputs_for=lambda i: {"%wg_id": (0, 0, 0), "%local_id": (i, 0, 0)},
245 push_constants=VSHARP + [0] * 28,
246 memory=memory,
247 )
248
249
250class _Heap(dict):
251 def get(self, key, default=None):
252 return super().get(key, HEAP_FILL)
253
254
255# -----------------------------------------------------------------------------
256# 1. Reference Oracle Self-Tests
257# -----------------------------------------------------------------------------
258
259class OracleTests(unittest.TestCase):
260 def test_hand_worked_constants_match_oracle(self):
261 for label, x_bits, slot, base, want in HAND_WORKED:
262 with self.subTest(case=label):
263 self.assertEqual(ref_cvt_pk_u8_f32(x_bits, slot, base), want)
264
265 def test_oracle_agrees_with_python_float_round_for_finite_values(self):
266 for k in range(256):
267 for delta in (-0.25, 0.0, 0.25, 0.5):
268 x = k + delta
269 xb = f32_bits(x)
270 expected_u = min(255, max(0, round(bits_f32(xb))))
271 self.assertEqual(ref_cvt_pk_u8_byte(xb), expected_u, f"x={x}")
272 # Verify 1-ULP neighbors around .5 ties.
273 for tie in (0.5, 1.5, 2.5, 127.5, 128.5, 253.5, 254.5):
274 tb = f32_bits(tie)
275 for b in (tb - 1, tb, tb + 1):
276 expected_u = min(255, max(0, round(bits_f32(b))))
277 self.assertEqual(ref_cvt_pk_u8_byte(b), expected_u, f"b={b:#010x}")
278
279
280# -----------------------------------------------------------------------------
281# 2. Byte Slots (0..3), Slot Masking (slot & 3), and Untouched Bytes
282# -----------------------------------------------------------------------------
283
284class ByteSlotAndMaskingTests(unittest.TestCase):
285 def test_all_four_slots_preserve_other_three_bytes_of_base(self):
286 # Distinct byte values including 0x00 and 0xFF (slot 3 gives 0xFFADBEEF / 0x00ADBEEF).
287 byte_vals = (0.0, 1.0, 18.0, 127.0, 128.0, 254.0, 255.0)
288 for suffix in ("", "_e64"):
289 for slot in range(4):
290 for start in range(0, len(byte_vals), 4):
291 chunk = byte_vals[start:start + 4]
292 lines, expected = [f"v_mov_b32 v3, {OLD:#x}"], []
293 for lane, val in enumerate(chunk):
294 xb = f32_bits(val)
295 dst = f"v{10 + lane}"
296 lines += [
297 f"v_mov_b32 {dst}, {CANARY:#x}",
298 f"v_mov_b32 v1, {xb:#x}",
299 f"v_mov_b32 v2, {slot}",
300 f"v_cvt_pk_u8_f32{suffix} {dst}, v1, v2, v3",
301 ]
302 expected.append(ref_cvt_pk_u8_f32(xb, slot, OLD))
303 while len(expected) < 4:
304 lines.append(f"v_mov_b32 v{10 + len(expected)}, 0")
305 expected.append(0)
306 with self.subTest(suffix=suffix or "bare", slot=slot, batch=start // 4):
307 got = run_ps_mrt0(lines, ("v10", "v11", "v12", "v13"))
308 self.assertEqual(got, tuple(expected))
309
310 def test_slot_and_3_masking_across_vgpr_sgpr_and_inline_operands(self):
311 slots = [0, 1, 2, 3, 4, 5, 6, 7, 8, -1, 0xFFFFFFFF, 0xFFFFFFFC, 0x80000001, 0x1234567A]
312 payloads = [17.0, 65.0, 145.0, 243.0]
313
314 for op_kind in ("vgpr", "sgpr", "inline"):
315 for start in range(0, len(slots), 4):
316 chunk = slots[start:start + 4]
317 lines, expected = [f"v_mov_b32 v3, {OLD:#x}"], []
318 for idx, slot in enumerate(chunk):
319 x = payloads[(start + idx) % len(payloads)]
320 xb = f32_bits(x)
321 dst = f"v{10 + idx}"
322 lines.append(f"v_mov_b32 {dst}, {CANARY:#x}")
323 lines.append(f"v_mov_b32 v1, {xb:#x}")
324 if op_kind == "vgpr":
325 lines.append(f"v_mov_b32 v2, {slot & MASK32:#x}")
326 slot_arg = "v2"
327 elif op_kind == "sgpr":
328 lines.append(f"s_mov_b32 s4, {slot & MASK32:#x}")
329 slot_arg = "s4"
330 else:
331 slot_arg = str(slot) if -16 <= slot <= 64 else f"{slot & MASK32:#x}"
332 lines.append(f"v_cvt_pk_u8_f32_e64 {dst}, v1, {slot_arg}, v3")
333 expected.append(ref_cvt_pk_u8_f32(xb, slot, OLD))
334 while len(expected) < 4:
335 lines.append(f"v_mov_b32 v{10 + len(expected)}, 0")
336 expected.append(0)
337 with self.subTest(op_kind=op_kind, chunk=chunk):
338 got = run_ps_mrt0(lines, ("v10", "v11", "v12", "v13"))
339 self.assertEqual(got, tuple(expected))
340
341 def test_base_from_sgpr_inline_and_sequential_four_byte_pack(self):
342 # src2 from SGPR, inline 0, and inline -1.
343 got_bases = run_ps_mrt0([
344 f"v_mov_b32 v1, {f32_bits(0x4A):#x}",
345 f"s_mov_b32 s5, {OLD:#x}",
346 "v_cvt_pk_u8_f32 v10, v1, 2, s5", # 0xDE4ABEEF
347 "v_cvt_pk_u8_f32 v11, v1, 1, 0", # 0x00004A00
348 "v_cvt_pk_u8_f32 v12, v1, 3, -1", # 0x4AFFFFFF
349 "v_cvt_pk_u8_f32 v13, v1, 0, -1", # 0xFFFFFF4A
350 ], ("v10", "v11", "v12", "v13"))
351 self.assertEqual(got_bases, (
352 ref_cvt_pk_u8_f32(f32_bits(0x4A), 2, OLD),
353 ref_cvt_pk_u8_f32(f32_bits(0x4A), 1, 0),
354 ref_cvt_pk_u8_f32(f32_bits(0x4A), 3, MASK32),
355 ref_cvt_pk_u8_f32(f32_bits(0x4A), 0, MASK32),
356 ))
357
358 # Pack 4 floats sequentially into bytes 0, 1, 2, 3 of v0 starting from OLD.
359 got_packed = run_ps_mrt0([
360 f"v_mov_b32 v0, {OLD:#x}",
361 f"v_mov_b32 v1, {f32_bits(0x11):#x}",
362 f"v_mov_b32 v2, {f32_bits(0x22):#x}",
363 f"v_mov_b32 v3, {f32_bits(0x33):#x}",
364 f"v_mov_b32 v4, {f32_bits(0x44):#x}",
365 "v_cvt_pk_u8_f32 v0, v1, 0, v0",
366 "v_cvt_pk_u8_f32 v0, v2, 1, v0",
367 "v_cvt_pk_u8_f32 v0, v3, 2, v0",
368 "v_cvt_pk_u8_f32 v0, v4, 3, v0",
369 ])[0]
370 self.assertEqual(got_packed, 0x44332211)
371
372
373# -----------------------------------------------------------------------------
374# 3. Clamping, Special Float Inputs, and .5 Round-to-Nearest-Even Ties
375# -----------------------------------------------------------------------------
376
377class ClampingAndSpecialInputsTests(unittest.TestCase):
378 def test_negative_overflow_and_subnormal_clamping(self):
379 cases = [
380 # Negatives -> 0
381 ("pos_zero", F32_POS_ZERO),
382 ("neg_zero", F32_NEG_ZERO),
383 ("neg_tiny", f32_bits(-1e-30)),
384 ("neg_0_001", f32_bits(-0.001)),
385 ("neg_half", f32_bits(-0.5)),
386 ("neg_one", f32_bits(-1.0)),
387 ("neg_127_5", f32_bits(-127.5)),
388 ("neg_1000", f32_bits(-1000.0)),
389 ("neg_flt_max", F32_NEG_FLT_MAX),
390 ("neg_inf", F32_NEG_INF),
391 # Overflow -> 255
392 ("255_0", f32_bits(255.0)),
393 ("255_001", f32_bits(255.001)),
394 ("255_49", f32_bits(255.49)),
395 ("255_5", f32_bits(255.5)),
396 ("256_0", f32_bits(256.0)),
397 ("512_0", f32_bits(512.0)),
398 ("1e10", f32_bits(1e10)),
399 ("flt_max", F32_FLT_MAX),
400 ("pos_inf", F32_POS_INF),
401 # Tiny subnormals & near-zero normals -> 0
402 ("pos_sub_min", F32_POS_SUB_MIN),
403 ("pos_sub_mid", F32_POS_SUB_MID),
404 ("pos_sub_max", F32_POS_SUB_MAX),
405 ("neg_sub_min", F32_NEG_SUB_MIN),
406 ("neg_sub_max", F32_NEG_SUB_MAX),
407 ("pos_norm_min", F32_POS_NORM_MIN),
408 ("neg_norm_min", F32_NEG_NORM_MIN),
409 # ULP boundaries around 0.5, 1.5, 254.5, 255.0
410 ("0_5_minus_ulp", f32_bits(0.5) - 1),
411 ("0_5_plus_ulp", f32_bits(0.5) + 1),
412 ("1_5_minus_ulp", f32_bits(1.5) - 1),
413 ("1_5_plus_ulp", f32_bits(1.5) + 1),
414 ("254_5_minus_ulp", f32_bits(254.5) - 1),
415 ("254_5_plus_ulp", f32_bits(254.5) + 1),
416 ("255_0_minus_ulp", f32_bits(255.0) - 1),
417 ("255_0_plus_ulp", f32_bits(255.0) + 1),
418 ]
419 for start in range(0, len(cases), 4):
420 chunk = cases[start:start + 4]
421 lines, expected = [f"v_mov_b32 v3, {OLD:#x}"], []
422 for idx, (_, xb) in enumerate(chunk):
423 slot = (start + idx) & 3
424 dst = f"v{10 + idx}"
425 lines += [
426 f"v_mov_b32 v1, {xb:#x}",
427 f"v_cvt_pk_u8_f32 {dst}, v1, {slot}, v3",
428 ]
429 expected.append(ref_cvt_pk_u8_f32(xb, slot, OLD))
430 while len(expected) < 4:
431 lines.append(f"v_mov_b32 v{10 + len(expected)}, 0")
432 expected.append(0)
433 with self.subTest(cases=[lbl for lbl, _ in chunk]):
434 got = run_ps_mrt0(lines, ("v10", "v11", "v12", "v13"))
435 self.assertEqual(got, tuple(expected))
436
437 def test_seeded_finite_sweep(self):
438 rng = random.Random(0xC08E)
439 samples = [(f32_bits(rng.uniform(-20.0, 280.0)), rng.randrange(0, 8)) for _ in range(64)]
440 for start in range(0, len(samples), 4):
441 chunk = samples[start:start + 4]
442 lines, expected = [f"v_mov_b32 v3, {OLD:#x}"], []
443 for idx, (xb, slot) in enumerate(chunk):
444 dst = f"v{10 + idx}"
445 lines += [
446 f"v_mov_b32 v1, {xb:#x}",
447 f"v_cvt_pk_u8_f32 {dst}, v1, {slot}, v3",
448 ]
449 expected.append(ref_cvt_pk_u8_f32(xb, slot, OLD))
450 with self.subTest(batch=start // 4):
451 self.assertEqual(run_ps_mrt0(lines, ("v10", "v11", "v12", "v13")), tuple(expected))
452
453
454class RoundToNearestEvenTieTests(unittest.TestCase):
455 def test_all_half_ties_from_0_5_to_255_5_and_255_49(self):
456 ties = [k + 0.5 for k in range(256)] + [255.49]
457 for start in range(0, len(ties), 4):
458 chunk = ties[start:start + 4]
459 lines, expected = [f"v_mov_b32 v3, {OLD:#x}"], []
460 for idx, x in enumerate(chunk):
461 xb = f32_bits(x)
462 slot = (start + idx) & 3
463 dst = f"v{10 + idx}"
464 lines += [
465 f"v_mov_b32 v1, {xb:#x}",
466 f"v_cvt_pk_u8_f32 {dst}, v1, {slot}, v3",
467 ]
468 expected.append(ref_cvt_pk_u8_f32(xb, slot, OLD))
469 while len(expected) < 4:
470 lines.append(f"v_mov_b32 v{10 + len(expected)}, 0")
471 expected.append(0)
472 with self.subTest(ties=chunk):
473 got = run_ps_mrt0(lines, ("v10", "v11", "v12", "v13"))
474 self.assertEqual(got, tuple(expected))
475
476 def test_all_exact_integers_0_to_255(self):
477 for start in range(0, 256, 4):
478 chunk = range(start, start + 4)
479 lines, expected = [f"v_mov_b32 v3, {OLD:#x}"], []
480 for idx, k in enumerate(chunk):
481 xb = f32_bits(float(k))
482 dst = f"v{10 + idx}"
483 lines += [
484 f"v_mov_b32 v1, {xb:#x}",
485 f"v_cvt_pk_u8_f32 {dst}, v1, {idx}, v3",
486 ]
487 expected.append(ref_cvt_pk_u8_f32(xb, idx, OLD))
488 with self.subTest(start=start):
489 self.assertEqual(run_ps_mrt0(lines, ("v10", "v11", "v12", "v13")), tuple(expected))
490
491
492# -----------------------------------------------------------------------------
493# 4. VOP3 Modifiers, SGPR/Inline Float Sources, Destination Aliasing, EXEC
494# -----------------------------------------------------------------------------
495
496class SourceModifiersAndOperandsTests(unittest.TestCase):
497 def test_vop3_source_modifiers(self):
498 cases = [
499 (f32_bits(-42.5), "-v1", 0, 42), # -(-42.5) = 42.5 -> 42 (even)
500 (f32_bits(-43.5), "-v1", 1, 44), # -(-43.5) = 43.5 -> 44 (even)
501 (f32_bits(42.5), "-v1", 2, 0), # -(42.5) = -42.5 -> 0
502 (F32_NEG_INF, "-v1", 3, 255), # -(-inf) = +inf -> 255
503 (F32_POS_INF, "-v1", 0, 0), # -(+inf) = -inf -> 0
504 (f32_bits(-13.5), "|v1|", 1, 14), # |-13.5| = 13.5 -> 14 (even)
505 (f32_bits(-14.5), "|v1|", 2, 14), # |-14.5| = 14.5 -> 14 (even)
506 (f32_bits(-300.0), "|v1|", 3, 255), # |-300.0| = 300.0 -> 255
507 (F32_NEG_INF, "|v1|", 0, 255), # |-inf| = +inf -> 255
508 (f32_bits(10.0), "-|v1|", 1, 0), # -|10.0| = -10.0 -> 0
509 (f32_bits(-10.0), "-|v1|", 2, 0), # -|-10.0| = -10.0 -> 0
510 (F32_NEG_INF, "-|v1|", 3, 0), # -|-inf| = -inf -> 0
511 (f32_bits(-1.5), "neg(v1)", 0, 2), # neg(-1.5) = 1.5 -> 2
512 (f32_bits(-2.5), "abs(v1)", 1, 2), # abs(-2.5) = 2.5 -> 2
513 (f32_bits(-7.5), "-|s4|", 2, 0),
514 (f32_bits(-7.5), "|s4|", 3, 8),
515 ]
516 for start in range(0, len(cases), 4):
517 chunk = cases[start:start + 4]
518 lines, expected = [f"v_mov_b32 v3, {OLD:#x}"], []
519 for idx, (xb, expr, slot, want_byte) in enumerate(chunk):
520 dst = f"v{10 + idx}"
521 reg = "s4" if "s4" in expr else "v1"
522 lines += [
523 f"{'s_mov_b32' if reg == 's4' else 'v_mov_b32'} {reg}, {xb:#x}",
524 f"v_cvt_pk_u8_f32_e64 {dst}, {expr}, {slot}, v3",
525 ]
526 sh = 8 * (slot & 3)
527 expected.append((OLD & ~(0xFF << sh)) | (want_byte << sh))
528 while len(expected) < 4:
529 lines.append(f"v_mov_b32 v{10 + len(expected)}, 0")
530 expected.append(0)
531 with self.subTest(cases=[(e, s) for _, e, s, _ in chunk]):
532 got = run_ps_mrt0(lines, ("v10", "v11", "v12", "v13"))
533 self.assertEqual(got, tuple(expected))
534
535 def test_inline_constant_and_sgpr_float_sources(self):
536 inline_cases = [
537 ("0.5", 0, 0),
538 ("1.0", 1, 1),
539 ("2.0", 2, 2),
540 ("4.0", 3, 4),
541 ("-1.0", 0, 0),
542 ("-0.5", 1, 0),
543 ("-2.0", 2, 0),
544 ("-4.0", 3, 0),
545 ("0.0", 0, 0),
546 ("0", 1, 0),
547 ]
548 for start in range(0, len(inline_cases), 4):
549 chunk = inline_cases[start:start + 4]
550 lines, expected = [f"v_mov_b32 v3, {OLD:#x}"], []
551 for idx, (lit, slot, want_byte) in enumerate(chunk):
552 dst = f"v{10 + idx}"
553 lines.append(f"v_cvt_pk_u8_f32 {dst}, {lit}, {slot}, v3")
554 sh = 8 * (slot & 3)
555 expected.append((OLD & ~(0xFF << sh)) | (want_byte << sh))
556 while len(expected) < 4:
557 lines.append(f"v_mov_b32 v{10 + len(expected)}, 0")
558 expected.append(0)
559 with self.subTest(inlines=[c[0] for c in chunk]):
560 got = run_ps_mrt0(lines, ("v10", "v11", "v12", "v13"))
561 self.assertEqual(got, tuple(expected))
562
563 # SGPR float sources across edge values.
564 sgpr_cases = [
565 (f32_bits(0.5), 0),
566 (f32_bits(1.0), 1),
567 (f32_bits(2.0), 2),
568 (f32_bits(4.0), 3),
569 (f32_bits(-1.0), 0),
570 (f32_bits(127.5), 1),
571 (f32_bits(254.5), 2),
572 (F32_POS_INF, 3),
573 ]
574 for start in range(0, len(sgpr_cases), 4):
575 chunk = sgpr_cases[start:start + 4]
576 lines, expected = [f"v_mov_b32 v3, {OLD:#x}"], []
577 for idx, (xb, slot) in enumerate(chunk):
578 dst = f"v{10 + idx}"
579 lines += [
580 f"s_mov_b32 s4, {xb:#x}",
581 f"v_cvt_pk_u8_f32_e64 {dst}, s4, {slot}, v3",
582 ]
583 expected.append(ref_cvt_pk_u8_f32(xb, slot, OLD))
584 with self.subTest(batch=start // 4):
585 got = run_ps_mrt0(lines, ("v10", "v11", "v12", "v13"))
586 self.assertEqual(got, tuple(expected))
587
588 def test_destination_aliasing(self):
589 # 1. dst == src2: v_cvt_pk_u8_f32 v0, v1, 2, v0
590 # 2. dst == src0: v_cvt_pk_u8_f32 v0, v0, 1, v3
591 # 3. dst == src1: v_cvt_pk_u8_f32 v0, v1, v0, v3
592 # 4. dst == src0 == src2: v_cvt_pk_u8_f32 v0, v0, 1, v0 (v0 holds 12.5 = 0x41480000 -> byte 12 at slot 1)
593 got = run_ps_mrt0([
594 f"v_mov_b32 v3, {OLD:#x}",
595 f"v_mov_b32 v1, {f32_bits(86.0):#x}",
596 f"v_mov_b32 v10, {OLD:#x}",
597 "v_cvt_pk_u8_f32 v10, v1, 2, v10",
598 f"v_mov_b32 v11, {f32_bits(35.5):#x}",
599 "v_cvt_pk_u8_f32 v11, v11, 1, v3",
600 "v_mov_b32 v12, 7",
601 "v_cvt_pk_u8_f32 v12, v1, v12, v3",
602 f"v_mov_b32 v13, {f32_bits(12.5):#x}",
603 "v_cvt_pk_u8_f32 v13, v13, 1, v13",
604 ], ("v10", "v11", "v12", "v13"))
605 self.assertEqual(got, (
606 ref_cvt_pk_u8_f32(f32_bits(86.0), 2, OLD),
607 ref_cvt_pk_u8_f32(f32_bits(35.5), 1, OLD),
608 ref_cvt_pk_u8_f32(f32_bits(86.0), 7, OLD),
609 ref_cvt_pk_u8_f32(f32_bits(12.5), 1, f32_bits(12.5)),
610 ))
611
612 # 5. All four operands alias v0: 0x41480003 is 12.500003 -> byte 13 (0x0D) at slot (0x41480003 & 3 == 3).
613 all_alias_in = 0x41480003
614 got_all = run_ps_mrt0([
615 f"v_mov_b32 v0, {all_alias_in:#x}",
616 "v_cvt_pk_u8_f32 v0, v0, v0, v0",
617 ])[0]
618 self.assertEqual(got_all, ref_cvt_pk_u8_f32(all_alias_in, all_alias_in, all_alias_in))
619 self.assertEqual(got_all, 0x0D480003)
620
621
622class ExecMaskingTests(unittest.TestCase):
623 def test_single_lane_exec_mask_preserves_destination(self):
624 # Inactive lane leaves v0 untouched; disabled instruction before re-enabling EXEC is skipped.
625 got = run_ps_mrt0([
626 f"v_mov_b32 v1, {f32_bits(77.0):#x}",
627 f"v_mov_b32 v3, {CANARY:#x}",
628 f"v_mov_b32 v10, {OLD:#x}",
629 f"v_mov_b32 v11, {OLD:#x}",
630 "s_mov_b32 exec_lo, 0",
631 "v_cvt_pk_u8_f32 v10, v1, 1, v3",
632 "v_cvt_pk_u8_f32 v11, v1, 0, v3",
633 "s_mov_b32 exec_lo, -1",
634 "v_cvt_pk_u8_f32 v11, v1, 2, v3",
635 ], ("v10", "v11", "v10", "v11"))
636 self.assertEqual(got[:2], (OLD, ref_cvt_pk_u8_f32(f32_bits(77.0), 2, CANARY)))
637
638 def test_multilane_compute_exec_masking(self):
639 # 16 lanes in lockstep: odd lanes are masked off via v_cmpx_eq_u32 before v_cvt_pk_u8_f32,
640 # so active even lanes write the converted byte into OLD while inactive odd lanes keep OLD.
641 lane_floats = [f32_bits(float(i * 15) + 0.5) for i in range(16)]
642 mem = _Heap({0x100 + 4 * i: w for i, w in enumerate(lane_floats)})
643 run_cs([
644 "v_lshlrev_b32_e32 v5, 2, v0",
645 "v_add_nc_u32_e32 v6, 0x100, v5",
646 "buffer_load_dword v1, v6, s[0:3], 0 offen",
647 f"v_mov_b32_e32 v2, {OLD:#x}",
648 f"v_mov_b32_e32 v3, {OLD:#x}",
649 "v_and_b32_e32 v4, 1, v0",
650 "v_cmpx_eq_u32_e32 0, v4", # keep even lanes active
651 "v_cvt_pk_u8_f32_e64 v2, v1, v0, v3",
652 "s_mov_b32 exec_lo, -1",
653 "buffer_store_dword v2, v5, s[0:3], 0 offen",
654 ], group_size=16, subgroup_size=32, memory=mem)
655
656 got = [mem.get(4 * i) for i in range(16)]
657 want = [
658 ref_cvt_pk_u8_f32(lane_floats[i], i, OLD) if (i & 1) == 0 else OLD
659 for i in range(16)
660 ]
661 self.assertEqual(got, want)
662
663
664# -----------------------------------------------------------------------------
665# 5. NaN Inputs (Documented Open Gap in Translator SPIR-V Lowering)
666# -----------------------------------------------------------------------------
667
668class NaNHandlingTests(unittest.TestCase):
669 """v_cvt_pk_u8_f32 emits FClamp without an OpIsNan guard (docs/design.md line 287).
670
671 In spirv_mini_interp.py, FClamp on NaN raises UnsupportedConstruct because GLSL.std.450 leaves it undefined.
672 """
673
674 def test_nan_translation_and_interpreter_rejection(self):
675 nan_cases = [
676 ("qnan", F32_QNAN, "v1"),
677 ("neg_qnan", F32_NEG_QNAN, "v1"),
678 ("qnan_payload", F32_QNAN_PAYLOAD, "v1"),
679 ("snan", F32_SNAN, "v1"),
680 ("neg_snan", F32_NEG_SNAN, "v1"),
681 ("qnan_abs", F32_NEG_QNAN, "|v1|"),
682 ("qnan_neg", F32_QNAN, "-v1"),
683 ]
684 for label, xb, expr in nan_cases:
685 with self.subTest(case=label):
686 spv = translate_ps([
687 f"v_mov_b32 v1, {xb:#x}",
688 f"v_mov_b32 v3, {OLD:#x}",
689 f"v_cvt_pk_u8_f32_e64 v0, {expr}, 0, v3",
690 "exp mrt0 v0, v0, v0, v0 done vm",
691 ])
692 self.assertIn("glsl FClamp", spv)
693 self.assertIn("glsl RoundEven", spv)
694 self.assertIn("OpConvertFToU", spv)
695 with self.assertRaisesRegex(si.UnsupportedConstruct, r"FClamp.*undefined"):
696 si.run_fragment(spv)
697
698
699# -----------------------------------------------------------------------------
700# 6. Negative Controls (SPIR-V Sabotage Detection)
701# -----------------------------------------------------------------------------
702
703class NegativeControlsTests(unittest.TestCase):
704 def test_sabotage_round_even_to_trunc(self):
705 # 1.5 -> RoundEven gives 2, whereas Trunc gives 1.
706 good = translate_ps([
707 f"v_mov_b32 v1, {f32_bits(1.5):#x}",
708 f"v_mov_b32 v3, {OLD:#x}",
709 "v_cvt_pk_u8_f32 v0, v1, 1, v3",
710 "exp mrt0 v0, v0, v0, v0 done vm",
711 ])
712 want = ref_cvt_pk_u8_f32(f32_bits(1.5), 1, OLD)
713 self.assertEqual(si.run_fragment(good)["%out_mrt0"][0], want)
714
715 bad, n = re.subn(r"\bRoundEven\b", "Trunc", good)
716 self.assertEqual(n, 1)
717 got_bad = si.run_fragment(bad)["%out_mrt0"][0]
718 self.assertNotEqual(got_bad, want)
719 self.assertEqual(got_bad, 0xDEAD01EF)
720
721 def test_sabotage_missing_slot_shift(self):
722 # Removing the * 8 shift (OpIMul %uint %slot3 %c8 -> %c0) writes slot 0 instead of slot 2.
723 good = translate_ps([
724 f"v_mov_b32 v1, {f32_bits(0x42):#x}",
725 f"v_mov_b32 v3, {OLD:#x}",
726 "v_cvt_pk_u8_f32 v0, v1, 2, v3",
727 "exp mrt0 v0, v0, v0, v0 done vm",
728 ])
729 want = ref_cvt_pk_u8_f32(f32_bits(0x42), 2, OLD)
730 self.assertEqual(si.run_fragment(good)["%out_mrt0"][0], want)
731
732 bad, n = re.subn(r"OpIMul %uint (%\w+) %c8\b", r"OpIMul %uint \1 %c0", good)
733 self.assertEqual(n, 1)
734 got_bad = si.run_fragment(bad)["%out_mrt0"][0]
735 self.assertNotEqual(got_bad, want)
736 self.assertEqual(got_bad, ref_cvt_pk_u8_f32(f32_bits(0x42), 0, OLD))
737
738 def test_sabotage_missing_slot_mask(self):
739 # Widening slot & 3 to slot & 7 breaks slot 5 (shift = 40 >= 32 -> undefined in SPIR-V).
740 good = translate_ps([
741 f"v_mov_b32 v1, {f32_bits(0x42):#x}",
742 f"v_mov_b32 v2, 5",
743 f"v_mov_b32 v3, {OLD:#x}",
744 "v_cvt_pk_u8_f32 v0, v1, v2, v3",
745 "exp mrt0 v0, v0, v0, v0 done vm",
746 ])
747 want = ref_cvt_pk_u8_f32(f32_bits(0x42), 5, OLD)
748 self.assertEqual(si.run_fragment(good)["%out_mrt0"][0], want)
749
750 bad, n = re.subn(r"OpBitwiseAnd %uint (%\w+) %c3\b", r"OpBitwiseAnd %uint \1 %c7", good)
751 self.assertEqual(n, 1)
752 with self.assertRaises(si.UnsupportedConstruct):
753 si.run_fragment(bad)
754
755
756if __name__ == "__main__":
757 unittest.main()
diff --git a/tests/semantic/test_valu_f32_class_rndne.py b/tests/semantic/test_valu_f32_class_rndne.py
index d57dd546f..618a2a94d 100644
--- a/tests/semantic/test_valu_f32_class_rndne.py
+++ b/tests/semantic/test_valu_f32_class_rndne.py
@@ -17,15 +17,15 @@ run_fragment and multi-lane compute run_workgroup), and checked against hand-com
17plain-Python RDNA2 ISA reference functions. Standard library only; hand-written RDNA2 listings only. 17plain-Python RDNA2 ISA reference functions. Standard library only; hand-written RDNA2 listings only.
18 18
19Findings & exclusions (no shared files modified): 19Findings & exclusions (no shared files modified):
20 1. v_rcp_iflag_f32 CANNOT execute in tests/semantic/spirv_mini_interp.py: 20 1. v_rcp_iflag_f32 lowers to `OpFDiv %float %f1 {x}` followed by the VOP3 output modifiers (`clamp`, `mul:2`,
21 tools/rdna2spirv.py (lines 3693-3697) lowers v_rcp_iflag_f32 to `OpFDiv %float %f1 {x}`, and 21 `mul:4`, `div:2`) through `clamp_mods`, as `v_rcp_f32` does. When this file was written the translator dropped
22 tests/semantic/spirv_mini_interp.py does not implement `OpFDiv` (it raises `UnsupportedConstruct: OpFDiv`). 22 those modifiers and spirv_mini_interp.py had no `OpFDiv`; both have changed since (FUZZ-3, ed6da6b6), so
23 In addition, tools/rdna2spirv.py line 3697 emits `self.dst(a[0], self.tou(r))` without calling 23 RcpIflagF32OracleAndTranslationTests now executes it on exact inputs (powers of two, so the 1-ULP hardware
24 `self.clamp_mods(r, mods)` (unlike `v_rcp_f32` at line 3737 and `v_rndne_f32` at line 2178), so VOP3 output 24 approximation and the interpreter's exact division agree) with each output modifier. A zero operand stays
25 modifiers (`clamp`, `mul:2`, `mul:4`, `div:2`) on `v_rcp_iflag_f32_e64` are silently dropped by the translator. 25 out: `OpFDiv` by zero is undefined in SPIR-V and the interpreter refuses it (docs/design.md, "Denormal flush
26 Accordingly, `v_rcp_iflag_f32` is excluded from `spirv_mini_interp.py` value-execution assertions; its 26 and special results", Not modelled yet). gfx1036 hardware agrees with the translator on 2,570 of 3,000 fuzzed
27 independent RDNA2 ISA reference oracle and hand-worked constants are checked in OracleTests, and its 27 programs with clamp/omod and differs on none (`tools/f32_fuzz.py --oracle translator,hw --ops
28 SPIR-V translation (`OpFDiv %float %f1 ...`) is checked structurally in RcpIflagF32OracleAndTranslationTests. 28 v_rcp_iflag_f32`, seeds 1 to 3; the rest are division by zero or cases the model does not judge).
29 2. NaN caveats in SPIR-V / spirv_mini_interp.py: 29 2. NaN caveats in SPIR-V / spirv_mini_interp.py:
30 - For `v_rndne_f32` on NaN (`qNaN` / `sNaN`), SPIR-V / GLSL.std.450 `RoundEven` leaves NaN payload/quieting 30 - For `v_rndne_f32` on NaN (`qNaN` / `sNaN`), SPIR-V / GLSL.std.450 `RoundEven` leaves NaN payload/quieting
31 unspecified (spirv_mini_interp.py returns the input NaN unchanged; hardware quiets `sNaN`). Tests assert 31 unspecified (spirv_mini_interp.py returns the input NaN unchanged; hardware quiets `sNaN`). Tests assert
@@ -729,16 +729,47 @@ class RndneF32Tests(unittest.TestCase):
729 729
730 730
731# ----------------------------------------------------------------------------- 731# -----------------------------------------------------------------------------
732# 4. v_rcp_iflag_f32 (Excluded from spirv_mini_interp execution; documented finding) 732# 4. v_rcp_iflag_f32
733# ----------------------------------------------------------------------------- 733# -----------------------------------------------------------------------------
734 734
735class RcpIflagF32OracleAndTranslationTests(unittest.TestCase): 735class RcpIflagF32OracleAndTranslationTests(unittest.TestCase):
736 """Documents and checks translation for v_rcp_iflag_f32 without executing OpFDiv in spirv_mini_interp.py. 736 """Checks the translation of v_rcp_iflag_f32 and executes it with source and output modifiers.
737 737
738 See module docstring: spirv_mini_interp.py raises UnsupportedConstruct("OpFDiv"), and tools/rdna2spirv.py 738 See module docstring, finding 1: exact (power-of-two) inputs only, and no zero operand.
739 omits clamp_mods on v_rcp_iflag_f32.
740 """ 739 """
741 740
741 def test_executes_with_output_modifiers(self):
742 got = run_ps_mrt0([
743 "v_mov_b32 v1, 0x40000000", # +2.0
744 "v_rcp_iflag_f32_e64 v10, v1 mul:2", # 0.5 * 2 = 1.0
745 "v_rcp_iflag_f32_e64 v11, v1 mul:4", # 0.5 * 4 = 2.0
746 "v_rcp_iflag_f32_e64 v12, v1 div:2", # 0.5 / 2 = 0.25
747 "v_rcp_iflag_f32_e64 v13, -v1 clamp", # clamp(-0.5, 0, 1) = +0.0
748 ], ("v10", "v11", "v12", "v13"))
749 self.assertEqual(got, (f32_bits(1.0), f32_bits(2.0), f32_bits(0.25), f32_bits(0.0)))
750
751 got2 = run_ps_mrt0([
752 "v_mov_b32 v1, 0x3e800000", # +0.25
753 "v_rcp_iflag_f32_e64 v10, v1 clamp", # clamp(4.0, 0, 1) = 1.0
754 "v_rcp_iflag_f32_e64 v11, -|v1|", # -4.0
755 "v_rcp_iflag_f32_e64 v12, v1 div:2 clamp", # clamp(2.0, 0, 1) = 1.0
756 "v_rcp_iflag_f32_e32 v13, v1", # 4.0, no modifiers
757 ], ("v10", "v11", "v12", "v13"))
758 self.assertEqual(got2, (f32_bits(1.0), f32_bits(-4.0), f32_bits(1.0), f32_bits(4.0)))
759 for x_bits, want in ((0x40000000, 0x3F000000), (0x3E800000, 0x40800000), (0xC0000000, 0xBF000000)):
760 with self.subTest(x=f"{x_bits:#010x}"):
761 self.assertEqual(ref_rcp_iflag_f32(x_bits), want)
762
763 def test_dropping_output_modifiers_is_detected(self):
764 # Negative control: if the translator stopped applying the modifier, mul:2 would read back 0.5, not 1.0.
765 good = translate_ps(["v_mov_b32 v1, 0x40000000", "v_rcp_iflag_f32_e64 v0, v1 mul:2",
766 "exp mrt0 v0, v0, v0, v0 done vm"])
767 self.assertEqual(si.run_fragment(good)["%out_mrt0"][0], f32_bits(1.0))
768 bad, n = re.subn(r"^(\s*%\w+) = OpFMul %float (%\w+) %\w+$", r"\1 = OpFMul %float \2 %f1", good,
769 count=1, flags=re.M)
770 self.assertEqual(n, 1)
771 self.assertNotEqual(si.run_fragment(bad)["%out_mrt0"][0], f32_bits(1.0))
772
742 def test_translates_to_op_fdiv_with_no_contraction(self): 773 def test_translates_to_op_fdiv_with_no_contraction(self):
743 for line in ( 774 for line in (
744 "v_rcp_iflag_f32_e32 v0, v1", 775 "v_rcp_iflag_f32_e32 v0, v1",
diff --git a/tests/semantic/test_valu_fma_mix.py b/tests/semantic/test_valu_fma_mix.py
index 1d0730fe3..6c2a39cc6 100644
--- a/tests/semantic/test_valu_fma_mix.py
+++ b/tests/semantic/test_valu_fma_mix.py
@@ -212,6 +212,25 @@ class FmaMixF16Tests(unittest.TestCase):
212 got = run("v_fma_mixhi_f16 v0, v0, v1, v2 op_sel:[0,0,0] op_sel_hi:[1,0,1]", f2u(2.0), pack_h(0.5, 9.0), 0, old=old) 212 got = run("v_fma_mixhi_f16 v0, v0, v1, v2 op_sel:[0,0,0] op_sel_hi:[1,0,1]", f2u(2.0), pack_h(0.5, 9.0), 0, old=old)
213 self.assertEqual(got, pack_h(1.5, 3.5)) 213 self.assertEqual(got, pack_h(1.5, 3.5))
214 214
215 def test_single_rounding_discriminating_cases(self):
216 # Discriminating test cases A through G from tools/fma_mix_probe.py where
217 # hardware single rounding gives 1 ulp difference from double rounding.
218 # Case A: 1 * 2^-40 + (1 + 2^-11) -> single: 0x3c01, double: 0x3c00
219 got_a = run("v_fma_mixlo_f16 v0, v1, v2, v3", 0x3F800000, 0x2B800000, 0x3F801000, old=OLD)
220 self.assertEqual(got_a, (OLD & 0xFFFF0000) | 0x3C01)
221
222 # Case B: 1 * -2^-40 + (1 + 3 * 2^-11) -> single: 0x3c01, double: 0x3c02
223 got_b = run("v_fma_mixhi_f16 v0, v1, v2, v3", 0x3F800000, 0xAB800000, 0x3F803000, old=OLD)
224 self.assertEqual(got_b, (0x3C01 << 16) | (OLD & 0xFFFF))
225
226 # Case C: -1 * 2^-40 - (1 + 2^-11) -> single: 0xbc01, double: 0xbc00
227 got_c = run("v_fma_mixlo_f16 v0, v1, v2, v3", 0xBF800000, 0x2B800000, 0xBF801000, old=OLD)
228 self.assertEqual(got_c, (OLD & 0xFFFF0000) | 0xBC01)
229
230 # Case G (f16 operands): (1 + 2^-7) * (2^-11 - 2^-18) + (1 + 2^-10) -> single: 0x3c01, double: 0x3c02
231 got_g = run("v_fma_mixlo_f16 v0, v1, v2, v3 op_sel_hi:[1,1,1]", 0x3C08, 0x0FF0, 0x3C01, old=OLD)
232 self.assertEqual(got_g, (OLD & 0xFFFF0000) | 0x3C01)
233
215 234
216class NegativeControls(unittest.TestCase): 235class NegativeControls(unittest.TestCase):
217 """Sabotaging the translated SPIR-V must change the observed output.""" 236 """Sabotaging the translated SPIR-V must change the observed output."""
@@ -226,5 +245,52 @@ class NegativeControls(unittest.TestCase):
226 self.assertNotEqual(si.run_fragment(bad)["%out_mrt0"][0], good) 245 self.assertNotEqual(si.run_fragment(bad)["%out_mrt0"][0], good)
227 246
228 247
248class FmaMixF32DenormalOperandTests(unittest.TestCase):
249 """SHADER-298: an f32 operand of v_fma_mix* that is denormal reads as a zero of its sign (the game's MODE has
250 denorm_mode_32 = 0), measured on gfx1036 by @Sanonymous01 for 0x00000001, 0x807fffff and the integer inline
251 constants 1 and 64. The result is not flushed here (not measured), so 0 * y + denormal keeps the denormal only
252 when the denormal is not an operand, which cannot happen; the checks below use operands only."""
253
254 BIG = f2u(1.0e30)
255 ZERO = 0x00000000
256 NEG_ZERO = 0x80000000
257
258 def test_denormal_multiplicand_reads_as_zero(self):
259 # 1.4e-45 * 1e30 = 1.4e-15 if the denormal is kept; 0 if it is flushed.
260 for d in (0x00000001, 0x007FFFFF):
261 with self.subTest(denormal=hex(d), slot="src0"):
262 self.assertEqual(run("v_fma_mix_f32 v0, v1, v2, v3", d, self.BIG, self.ZERO), 0x00000000)
263 with self.subTest(denormal=hex(d), slot="src1"):
264 self.assertEqual(run("v_fma_mix_f32 v0, v1, v2, v3", self.BIG, d, self.ZERO), 0x00000000)
265
266 def test_negative_denormal_reads_as_negative_zero(self):
267 # (-0) * 1e30 + (-0) = -0; a kept denormal would give -1.1e-8-ish tiny non-zero.
268 for d in (0x80000001, 0x807FFFFF):
269 with self.subTest(denormal=hex(d)):
270 self.assertEqual(run("v_fma_mix_f32 v0, v1, v2, v3", d, self.BIG, self.NEG_ZERO), 0x80000000)
271
272 def test_denormal_addend_reads_as_zero(self):
273 # 0 * y + denormal: the denormal addend is flushed, so the result is +0 (kept it would be the denormal).
274 self.assertEqual(run("v_fma_mix_f32 v0, v1, v2, v3", self.ZERO, self.BIG, 0x00000001), 0x00000000)
275
276 def test_integer_inline_constants_are_denormal_f32_operands(self):
277 # `1` and `64` in an f32 operand slot are the words 0x00000001 and 0x00000040: denormal, flushed to +0.
278 for const in ("1", "64"):
279 with self.subTest(const=const):
280 self.assertEqual(run(f"v_fma_mix_f32 v0, {const}, v2, v3", self.ZERO, self.BIG, self.ZERO), 0x00000000)
281
282 def test_normal_operands_are_untouched(self):
283 a, b, c = f2u(2.5), f2u(-1.25), f2u(0.75)
284 self.assertEqual(run("v_fma_mix_f32 v0, v1, v2, v3", a, b, c), f2u(ref_fma(a, b, c, (0, 0, 0), (0, 0, 0))))
285 smallest_normal = 0x00800000 # 2**-126 is the first value that is not flushed
286 got = run("v_fma_mix_f32 v0, v1, v2, v3", smallest_normal, f2u(1.0), self.ZERO)
287 self.assertEqual(got, smallest_normal)
288
289 def test_the_flush_reaches_the_f16_result(self):
290 # 1.4e-45 * 3e37 = 4.2e-8 rounds to the f16 subnormal 0x0001 if the denormal is kept, and is 0 flushed.
291 got = run("v_fma_mixlo_f16 v0, v1, v2, v3", 0x00000001, f2u(3.0e37), self.ZERO, old=0xAAAA0000)
292 self.assertEqual(got, 0xAAAA0000)
293
294
229if __name__ == "__main__": 295if __name__ == "__main__":
230 unittest.main() 296 unittest.main()
diff --git a/tests/semantic/test_valu_fract_f16.py b/tests/semantic/test_valu_fract_f16.py
new file mode 100644
index 000000000..aabad97c6
--- /dev/null
+++ b/tests/semantic/test_valu_fract_f16.py
@@ -0,0 +1,703 @@
1"""End-to-end semantic value tests for RDNA2 v_fract_f16 (S0.f16 - floor(S0.f16)).
2
3Covers v_fract_f16 executed end-to-end through tools/rdna2spirv.py and
4tests/semantic/spirv_mini_interp.py against an independent Fraction-based
5IEEE-754 binary16 `x - floor(x)` oracle:
6 - Positive & negative finite non-integers, including tiny negatives and
7 negative subnormals (-0.0001, -1e-5, -2**-12, -2**-24) whose exact
8 x - floor(x) rounds to 1.0 in binary16 and maps to 0x3bff (the largest
9 binary16 strictly below 1.0), plus the adjacent 0x3bfe / 0x3bff edge.
10 - Exact integers (0.0, 1.0, -1.0, 65504.0, -65504.0 -> +0.0) and -0.0 -> +0.0.
11 - +-inf and qNaN/sNaN behavior (GLSL.std.450 Fract returns NaN; fract_below_one
12 uses OpFOrdEqual + OpSelect so NaN survives into f16_bits -> qNaN).
13 - _e32, _e64, and bare mnemonics, keeping the untouched 16-bit half of dst.
14 - Runtime memory inputs via s_buffer_load_dwordx4 alongside immediate inputs.
15 - All 4 op_sel:[src,dst] combinations ([0,0], [1,0], [0,1], [1,1]).
16 - VOP3 source modifiers (-v1, |v1|, -|v1|) and output modifiers
17 (clamp, mul:2, mul:4, div:2, mul:2 clamp, mul:4 clamp).
18 - Inline f16 constants (0.5, -0.5, 1.0, -1.0), SGPR sources, destination
19 aliasing (v0, v0), single-lane and multi-lane EXEC masking, and SPIR-V
20 sabotage negative controls (Fract -> Trunc / Floor).
21
22Note: Under VOP3 `clamp`, GLSL.std.450 FClamp on NaN is undefined in SPIR-V
23and spirv_mini_interp.py raises UnsupportedConstruct (documented in
24docs/design.md), so `clamp` value tests use finite inputs. Standard library
25only; hand-written RDNA2 disassembly listings only; zero game data.
26"""
27from fractions import Fraction
28import gc
29import itertools
30import math
31import os
32import re
33import struct
34import sys
35import tempfile
36import unittest
37import warnings
38
39HERE = os.path.dirname(os.path.abspath(__file__))
40ROOT = os.path.dirname(os.path.dirname(HERE))
41TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools")
42
43sys.dont_write_bytecode = True
44if TOOLS_DIR not in sys.path:
45 sys.path.insert(0, TOOLS_DIR)
46if HERE not in sys.path:
47 sys.path.insert(0, HERE)
48
49import rdna2spirv # noqa: E402
50import spirv_mini_interp as si # noqa: E402
51
52STUB_DXBC = b"DXBC" + bytes(24) + struct.pack("<I", 0) + bytes(4)
53OLD = 0xBEEF1234
54PUSH_ADDR = [0x1000, 0, 32, 0] + [0] * 28
55VSHARP_CS = [0, 0, 0xFFFFFFFF, 0x31016FAC]
56HEAP_FILL = 0xEEEEEEEE
57
58# Representative binary16 encodings (cross-checked in OracleTests).
59H_POS_ZERO = 0x0000 # +0.0
60H_NEG_ZERO = 0x8000 # -0.0
61H_SUB_MIN = 0x0001 # +2^-24 (~5.96e-8)
62H_NEG_SUB_MIN = 0x8001 # -2^-24
63H_SUB_1E5 = 0x00A8 # +1e-5 rounded to f16 subnormal (~1.001e-5)
64H_NEG_SUB_1E5 = 0x80A8 # -1e-5 rounded to f16 subnormal (~-1.001e-5)
65H_SUB_MAX = 0x03FF # +1023 * 2^-24 (largest +subnormal)
66H_NEG_SUB_MAX = 0x83FF # -1023 * 2^-24 (largest-magnitude -subnormal)
67H_NORM_MIN = 0x0400 # +2^-14 (smallest +normal)
68H_NEG_NORM_MIN = 0x8400 # -2^-14
69H_1E4 = 0x068E # +0.0001 rounded to f16 (~1.000166e-4)
70H_NEG_1E4 = 0x868E # -0.0001 rounded to f16 (~-1.000166e-4)
71H_2PM13 = 0x0800 # +2^-13
72H_NEG_2PM13 = 0x8800 # -2^-13
73H_NEG_2PM12_M = 0x8BFF # -(2^-12 - 2^-23): just above -2^-12
74H_NEG_2PM12 = 0x8C00 # -2^-12: exact tie between 0x3bff and 0x3c00
75H_NEG_2PM12_P = 0x8C01 # -(2^-12 + 2^-22): strictly closer to 0x3bff
76H_NEG_3P2M13 = 0x8E00 # -3 * 2^-13: strictly closer to 0x3bff
77H_NEG_2PM11 = 0x9000 # -2^-11: 1 - 2^-11 = 0x3bff exact
78H_NEG_3P2M12 = 0x9200 # -3 * 2^-12: exact tie between 0x3bfe (even) and 0x3bff (odd) -> 0x3bfe
79H_NEG_2PM10 = 0x9400 # -2^-10: 1 - 2^-10 = 0x3bfe exact
80H_0P125 = 0x3000 # 0.125
81H_0P25 = 0x3400 # 0.25
82H_NEG_0P25 = 0xB400 # -0.25
83H_0P375 = 0x3600 # 0.375
84H_0P5 = 0x3800 # 0.5
85H_NEG_0P5 = 0xB800 # -0.5
86H_0P75 = 0x3A00 # 0.75
87H_NEG_0P75 = 0xBA00 # -0.75
88H_NEAR_ONE = 0x3BFF # 1 - 2^-11 (largest f16 < 1.0)
89H_1P0 = 0x3C00 # 1.0
90H_NEG_1P0 = 0xBC00 # -1.0
91H_1P25 = 0x3D00 # 1.25
92H_NEG_1P25 = 0xBD00 # -1.25
93H_1P5 = 0x3E00 # 1.5
94H_NEG_1P5 = 0xBE00 # -1.5
95H_1P75 = 0x3F00 # 1.75
96H_NEG_1P75 = 0xBF00 # -1.75
97H_2P0 = 0x4000 # 2.0
98H_NEG_2P0 = 0xC000 # -2.0
99H_2P5 = 0x4100 # 2.5
100H_NEG_2P5 = 0xC100 # -2.5
101H_3P0 = 0x4200 # 3.0
102H_NEG_3P0 = 0xC200 # -3.0
103H_3P75 = 0x4380 # 3.75
104H_NEG_3P75 = 0xC380 # -3.75
105H_1023P5 = 0x63FF # 1023.5
106H_NEG_1023P5 = 0xE3FF # -1023.5
107H_1024 = 0x6400 # 1024.0
108H_NEG_1024 = 0xE400 # -1024.0
109H_MAX = 0x7BFF # 65504.0
110H_NEG_MAX = 0xFBFF # -65504.0
111H_POS_INF = 0x7C00 # +inf
112H_NEG_INF = 0xFC00 # -inf
113H_QNAN = 0x7E01 # +qNaN
114H_NEG_QNAN = 0xFE01 # -qNaN
115H_SNAN = 0x7C01 # +sNaN
116H_NEG_SNAN = 0xFC01 # -sNaN
117
118
119# -----------------------------------------------------------------------------
120# Independent Fraction-Based IEEE-754 Binary16 Oracle
121# -----------------------------------------------------------------------------
122
123def h16_is_finite(h: int) -> bool:
124 return ((h >> 10) & 0x1F) != 0x1F
125
126
127def h16_is_nan(h: int) -> bool:
128 return (h & 0x7FFF) > 0x7C00
129
130
131def h16_is_inf(h: int) -> bool:
132 return (h & 0x7FFF) == 0x7C00
133
134
135def h16_to_fraction(h: int) -> Fraction:
136 """Decode finite IEEE-754 binary16 bit pattern ``h`` into an exact Fraction."""
137 h &= 0xFFFF
138 exp = (h >> 10) & 0x1F
139 if exp == 0x1F:
140 raise ValueError(f"non-finite binary16 {h:#06x}")
141 sign = -1 if (h >> 15) else 1
142 mant = h & 0x3FF
143 if exp == 0:
144 return Fraction(0) if mant == 0 else Fraction(sign * mant, 1 << 24)
145 return Fraction(sign * ((1 << 10) | mant)) * (Fraction(2) ** (exp - 25))
146
147
148def fraction_to_h16(q: Fraction) -> int:
149 """Round an exact Fraction to IEEE-754 binary16 (nearest, ties to even)."""
150 if q == 0:
151 return H_POS_ZERO
152 sgn = 0x8000 if q < 0 else 0
153 a = abs(q)
154 e = max(a.numerator.bit_length() - a.denominator.bit_length(), -14)
155 if e > -14 and Fraction(2) ** e > a:
156 e -= 1
157 m = a / (Fraction(2) ** (e - 10))
158 n = m.numerator // m.denominator
159 rem = m - n
160 if rem > Fraction(1, 2) or (rem == Fraction(1, 2) and (n & 1)):
161 n += 1
162 if e == -14 and n < 1024:
163 return sgn | n
164 if n >= 2048:
165 n >>= 1
166 e += 1
167 if e > 15:
168 return sgn | H_POS_INF
169 return sgn | ((e + 15) << 10) | (n - 1024)
170
171
172def exact_fract_fraction(h: int) -> Fraction | None:
173 """Exact ``x - floor(x)`` as a Fraction in [0, 1), or None for +-inf / NaN."""
174 if not h16_is_finite(h):
175 return None
176 q = h16_to_fraction(h)
177 return q - math.floor(q)
178
179
180def oracle_fract_f16(
181 h: int,
182 *,
183 abs_: bool = False,
184 neg: bool = False,
185 mul: int = 1,
186 div: int = 1,
187 clamp: bool = False,
188) -> int | None:
189 """Independent binary16 reference for v_fract_f16, returning 16-bit int or None for NaN.
190
191 Models RDNA2 source modifiers (abs before neg), exact ``x - floor(x)``,
192 the hardware/translator 0x3c00 -> 0x3bff clamp when no output multiplier is
193 present, and VOP3 output scaling (mul/div) + [0, 1] clamp before narrowing.
194 """
195 h &= 0xFFFF
196 if abs_:
197 h &= 0x7FFF
198 if neg:
199 h ^= 0x8000
200 r = exact_fract_fraction(h)
201 if r is None:
202 return None
203 if mul == 1 and div == 1:
204 res = fraction_to_h16(r)
205 return H_NEAR_ONE if res == H_1P0 else res
206 scaled = r * Fraction(mul, div)
207 if clamp:
208 scaled = min(max(scaled, Fraction(0)), Fraction(1))
209 return fraction_to_h16(scaled)
210
211
212def merge_half(old: int, half: int, dst_hi: int) -> int:
213 h = half & 0xFFFF
214 return ((h << 16) | (old & 0xFFFF)) if dst_hi else ((old & 0xFFFF0000) | h)
215
216
217# -----------------------------------------------------------------------------
218# Translation & Execution Helpers
219# -----------------------------------------------------------------------------
220
221_TMP_DIR = None
222_PS_PATH = None
223_CS_PATH = None
224_CS_FSSM = None
225
226
227def _make_fssm(rsrc2: int, group: tuple[int, int, int]) -> bytes:
228 header = bytearray(0x148)
229 struct.pack_into("<4I", header, 0x138, rsrc2, *group)
230 return bytes(header)
231
232
233def setUpModule():
234 global _TMP_DIR, _PS_PATH, _CS_PATH, _CS_FSSM
235 _TMP_DIR = tempfile.TemporaryDirectory()
236 disasm_dir = os.path.join(_TMP_DIR.name, "disasm")
237 fssm_dir = os.path.join(_TMP_DIR.name, "fssm")
238 os.mkdir(disasm_dir)
239 os.mkdir(fssm_dir)
240 _PS_PATH = os.path.join(disasm_dir, "ps_fract_f16.s")
241 _CS_PATH = os.path.join(disasm_dir, "cs_fract_f16.s")
242 _CS_FSSM = os.path.join(fssm_dir, "cs_fract_f16.fssm")
243 with open(os.path.join(_TMP_DIR.name, "ps_fract_f16.dxbc"), "wb") as f:
244 f.write(STUB_DXBC)
245
246
247def tearDownModule():
248 global _TMP_DIR, _PS_PATH, _CS_PATH, _CS_FSSM
249 if _TMP_DIR is not None:
250 gc.collect()
251 _TMP_DIR.cleanup()
252 _TMP_DIR = None
253 _PS_PATH = None
254 _CS_PATH = None
255 _CS_FSSM = None
256
257
258def translate_ps(lines: list[str]) -> str:
259 if _TMP_DIR is None:
260 setUpModule()
261 asm = (
262 "; test_valu_fract_f16\n"
263 + "".join(f"\t{ln}\n" for ln in lines)
264 + "\texp mrt0 v0, v0, v0, v0 done vm\n\ts_endpgm\n"
265 )
266 with open(_PS_PATH, "w", encoding="utf-8", newline="\n") as f:
267 f.write(asm)
268 with warnings.catch_warnings():
269 warnings.simplefilter("ignore", ResourceWarning)
270 spv = rdna2spirv.translate(_PS_PATH)
271 gc.collect()
272 return spv
273
274
275def run_ps(lines: list[str], *, push_constants=None, memory=None) -> int:
276 out = si.run_fragment(translate_ps(lines), push_constants=push_constants, memory=memory)
277 return out["%out_mrt0"][0]
278
279
280def run_op(line: str, v1: int = 0, *, old: int = OLD, s4: int = 0) -> int:
281 return run_ps([
282 f"s_mov_b32 s4, {s4:#x}",
283 f"v_mov_b32 v1, {v1:#x}",
284 f"v_mov_b32 v0, {old:#x}",
285 line,
286 ])
287
288
289def run_cs(lines: list[str], group_size: int, memory: dict[int, int]) -> None:
290 if _TMP_DIR is None:
291 setUpModule()
292 # rsrc2 = 0x0088: USER_SGPR = 4 (s[0:3] V#), TGID_X_EN = 1 (s4), TIDIG_COMP_CNT = 0 (v0 = local_id.x).
293 with open(_CS_FSSM, "wb") as f:
294 f.write(_make_fssm(0x0088, (group_size, 1, 1)))
295 asm = "; test_cs_valu_fract_f16\n" + "".join(f"\t{ln}\n" for ln in lines) + "\ts_endpgm\n"
296 with open(_CS_PATH, "w", encoding="utf-8", newline="\n") as f:
297 f.write(asm)
298 with warnings.catch_warnings():
299 warnings.simplefilter("ignore", ResourceWarning)
300 spv = rdna2spirv.translate(_CS_PATH)
301 gc.collect()
302 si.run_workgroup(
303 spv,
304 group_size,
305 32,
306 inputs_for=lambda i: {"%wg_id": (0, 0, 0), "%local_id": (i, 0, 0)},
307 push_constants=VSHARP_CS + [0] * 28,
308 memory=memory,
309 )
310
311
312class _Heap(dict):
313 def get(self, key, default=None):
314 return super().get(key, HEAP_FILL)
315
316
317# -----------------------------------------------------------------------------
318# Oracle Self-Tests
319# -----------------------------------------------------------------------------
320
321class OracleTests(unittest.TestCase):
322 """Cross-checks the independent Fraction binary16 oracle against IEEE-754 encodings."""
323
324 def test_exhaustive_binary16_decode_and_roundtrip(self):
325 for h in range(0x10000):
326 if not h16_is_finite(h):
327 self.assertIsNone(exact_fract_fraction(h))
328 self.assertIsNone(oracle_fract_f16(h))
329 continue
330 q = h16_to_fraction(h)
331 expected_float = struct.unpack("<e", struct.pack("<H", h))[0]
332 self.assertEqual(q, Fraction(expected_float))
333 want = H_POS_ZERO if h == H_NEG_ZERO else h
334 self.assertEqual(fraction_to_h16(q), want)
335
336 def test_hand_worked_fract_f16_rows(self):
337 rows = [
338 (H_POS_ZERO, H_POS_ZERO),
339 (H_NEG_ZERO, H_POS_ZERO),
340 (H_0P25, H_0P25),
341 (H_1P25, H_0P25),
342 (H_3P75, H_0P75),
343 (H_NEG_0P25, H_0P75),
344 (H_NEG_1P25, H_0P75),
345 (H_NEG_0P5, H_0P5),
346 (H_NEG_0P75, H_0P25),
347 (H_1P0, H_POS_ZERO),
348 (H_NEG_1P0, H_POS_ZERO),
349 (H_MAX, H_POS_ZERO),
350 (H_NEG_MAX, H_POS_ZERO),
351 (H_NEG_2PM10, 0x3BFE),
352 (H_NEG_3P2M12, 0x3BFE),
353 (H_NEG_2PM11, H_NEAR_ONE),
354 (H_NEG_3P2M13, H_NEAR_ONE),
355 (H_NEG_2PM12_P, H_NEAR_ONE),
356 (H_NEG_2PM12, H_NEAR_ONE),
357 (H_NEG_2PM12_M, H_NEAR_ONE),
358 (H_NEG_2PM13, H_NEAR_ONE),
359 (H_NEG_1E4, H_NEAR_ONE),
360 (H_NEG_SUB_1E5, H_NEAR_ONE),
361 (H_NEG_SUB_MAX, H_NEAR_ONE),
362 (H_NEG_SUB_MIN, H_NEAR_ONE),
363 (H_SUB_MIN, H_SUB_MIN),
364 (H_SUB_1E5, H_SUB_1E5),
365 (H_1E4, H_1E4),
366 ]
367 for h, want in rows:
368 with self.subTest(h=hex(h)):
369 self.assertEqual(oracle_fract_f16(h), want)
370 # Verify decimal conversions match our binary16 constants.
371 self.assertEqual(struct.unpack("<H", struct.pack("<e", -0.0001))[0], H_NEG_1E4)
372 self.assertEqual(struct.unpack("<H", struct.pack("<e", -1e-5))[0], H_NEG_SUB_1E5)
373 self.assertEqual(struct.unpack("<H", struct.pack("<e", 3.75))[0], H_3P75)
374
375
376# -----------------------------------------------------------------------------
377# End-to-End Execution Tests
378# -----------------------------------------------------------------------------
379
380class FractF16ExecutionTests(unittest.TestCase):
381 def test_finite_values_across_e32_e64_and_bare(self):
382 samples = [
383 H_POS_ZERO, H_NEG_ZERO,
384 H_SUB_MIN, H_NEG_SUB_MIN, H_SUB_1E5, H_NEG_SUB_1E5,
385 H_SUB_MAX, H_NEG_SUB_MAX, H_NORM_MIN, H_NEG_NORM_MIN,
386 H_1E4, H_NEG_1E4, H_2PM13, H_NEG_2PM13,
387 H_NEG_2PM12_M, H_NEG_2PM12, H_NEG_2PM12_P, H_NEG_3P2M13,
388 H_NEG_2PM11, H_NEG_3P2M12, H_NEG_2PM10,
389 H_0P125, H_0P25, H_NEG_0P25, H_0P5, H_NEG_0P5, H_0P75, H_NEG_0P75,
390 H_NEAR_ONE,
391 H_1P0, H_NEG_1P0, H_1P25, H_NEG_1P25, H_1P5, H_NEG_1P5, H_1P75, H_NEG_1P75,
392 H_2P0, H_NEG_2P0, H_2P5, H_NEG_2P5, H_3P0, H_NEG_3P0, H_3P75, H_NEG_3P75,
393 H_1023P5, H_NEG_1023P5, H_1024, H_NEG_1024, H_MAX, H_NEG_MAX,
394 ]
395 for suffix in ("_e32", "_e64", ""):
396 for h in samples:
397 v1 = 0x55550000 | h
398 want = merge_half(OLD, oracle_fract_f16(h), 0)
399 with self.subTest(form="v_fract_f16" + suffix, h=hex(h)):
400 self.assertEqual(run_op(f"v_fract_f16{suffix} v0, v1", v1), want)
401
402 def test_tiny_negatives_and_subnormals_near_one_boundary(self):
403 # Crosses the exact binary16 rounding transition: -2^-10 and -3*2^-12 give 0x3bfe;
404 # -2^-11 .. -2^-24 (including -0.0001 and -1e-5) give 0x3bff (never 0x3c00 = 1.0).
405 cases = [
406 (H_NEG_2PM10, 0x3BFE),
407 (H_NEG_3P2M12, 0x3BFE),
408 (H_NEG_2PM11, H_NEAR_ONE),
409 (H_NEG_3P2M13, H_NEAR_ONE),
410 (H_NEG_2PM12_P, H_NEAR_ONE),
411 (H_NEG_2PM12, H_NEAR_ONE),
412 (H_NEG_2PM12_M, H_NEAR_ONE),
413 (H_NEG_2PM13, H_NEAR_ONE),
414 (H_NEG_1E4, H_NEAR_ONE),
415 (H_NEG_SUB_1E5, H_NEAR_ONE),
416 (H_NEG_SUB_MAX, H_NEAR_ONE),
417 (H_NEG_SUB_MIN, H_NEAR_ONE),
418 ]
419 for h, want in cases:
420 with self.subTest(h=hex(h)):
421 self.assertEqual(oracle_fract_f16(h), want)
422 self.assertEqual(run_op("v_fract_f16_e32 v0, v1", 0xCAFE0000 | h), merge_half(OLD, want, 0))
423 self.assertEqual(run_op("v_fract_f16_e64 v0, v1 op_sel:[0,1]", 0xCAFE0000 | h),
424 merge_half(OLD, want, 1))
425
426 def test_exact_integers_and_signed_zero_give_positive_zero(self):
427 # GLSL.std.450 Fract(-0.0) in spirv_mini_interp returns +0.0 (copysign == +1), matching hardware.
428 self.assertEqual(si._fract(-0.0), 0.0)
429 self.assertEqual(math.copysign(1.0, si._fract(-0.0)), 1.0)
430 for h in (H_POS_ZERO, H_NEG_ZERO, H_1P0, H_NEG_1P0, H_2P0, H_NEG_2P0,
431 H_3P0, H_NEG_3P0, H_1024, H_NEG_1024, H_MAX, H_NEG_MAX):
432 with self.subTest(h=hex(h)):
433 got = run_op("v_fract_f16_e32 v0, v1", 0xABCD0000 | h)
434 self.assertEqual(got, merge_half(OLD, H_POS_ZERO, 0))
435 self.assertNotEqual(got & 0xFFFF, H_NEG_ZERO)
436 got_hi = run_op("v_fract_f16_e64 v0, v1 op_sel:[1,1]", (h << 16) | 0x1111)
437 self.assertEqual(got_hi, merge_half(OLD, H_POS_ZERO, 1))
438
439 def test_runtime_memory_inputs_via_s_buffer_load(self):
440 # Loaded at runtime through s_buffer_load_dwordx4 so constant folding cannot bypass Fract.
441 lanes_lo = [H_NEG_1E4, H_NEG_SUB_1E5, H_NEG_ZERO, H_3P75]
442 lanes_hi = [H_NEG_MAX, H_NEG_0P25, H_1P25, H_POS_INF]
443 packed = [(hi << 16) | lo for lo, hi in zip(lanes_lo, lanes_hi)]
444 mem = {0x1000 + 4 * i: w for i, w in enumerate(packed)}
445 for idx, (lo, hi) in enumerate(zip(lanes_lo, lanes_hi)):
446 reg = f"v{idx + 1}"
447 lines_head = [
448 "s_buffer_load_dwordx4 s[4:7], s[0:3], 0",
449 "s_waitcnt lgkmcnt(0)",
450 "v_mov_b32_e32 v1, s4",
451 "v_mov_b32_e32 v2, s5",
452 "v_mov_b32_e32 v3, s6",
453 "v_mov_b32_e32 v4, s7",
454 f"v_mov_b32_e32 v0, {OLD:#x}",
455 ]
456 got_lo = run_ps(lines_head + [f"v_fract_f16_e32 v0, {reg}"], push_constants=PUSH_ADDR, memory=mem)
457 self.assertEqual(got_lo, merge_half(OLD, oracle_fract_f16(lo), 0))
458 got_hi = run_ps(lines_head + [f"v_fract_f16_e64 v0, {reg} op_sel:[1,1]"],
459 push_constants=PUSH_ADDR, memory=mem)
460 want_hi = oracle_fract_f16(hi)
461 if want_hi is None:
462 self.assertEqual(got_hi & 0xFFFF, OLD & 0xFFFF)
463 self.assertTrue(h16_is_nan(got_hi >> 16), hex(got_hi))
464 else:
465 self.assertEqual(got_hi, merge_half(OLD, want_hi, 1))
466
467 def test_inf_and_nan_produce_nan_and_preserve_untouched_half(self):
468 # Verify spirv_mini_interp Fract on +-inf/NaN and translator's OpFOrdEqual guard.
469 self.assertTrue(math.isnan(si._fract(float("inf"))))
470 self.assertTrue(math.isnan(si._fract(float("-inf"))))
471 self.assertTrue(math.isnan(si._fract(float("nan"))))
472
473 for h in (H_POS_INF, H_NEG_INF, H_QNAN, H_NEG_QNAN, H_SNAN, H_NEG_SNAN):
474 for suffix in ("_e32", "_e64", ""):
475 with self.subTest(h=hex(h), form=suffix or "bare"):
476 got = run_op(f"v_fract_f16{suffix} v0, v1", 0xCAFE0000 | h)
477 self.assertEqual(got & 0xFFFF0000, OLD & 0xFFFF0000)
478 self.assertTrue(h16_is_nan(got & 0xFFFF), f"expected NaN in low half, got {got:#010x}")
479 for src_hi, dst_hi in itertools.product((0, 1), repeat=2):
480 v1 = ((h << 16) | H_0P25) if src_hi else ((H_0P25 << 16) | h)
481 with self.subTest(h=hex(h), src_hi=src_hi, dst_hi=dst_hi):
482 got = run_op(f"v_fract_f16_e64 v0, v1 op_sel:[{src_hi},{dst_hi}]", v1)
483 if dst_hi:
484 self.assertEqual(got & 0xFFFF, OLD & 0xFFFF)
485 self.assertTrue(h16_is_nan(got >> 16), hex(got))
486 else:
487 self.assertEqual(got & 0xFFFF0000, OLD & 0xFFFF0000)
488 self.assertTrue(h16_is_nan(got & 0xFFFF), hex(got))
489
490 def test_op_sel_all_four_combinations(self):
491 pairs = [
492 (H_NEG_1P25, H_0P25), # hi: 0.75, lo: 0.25
493 (H_NEG_SUB_1E5, H_3P75), # hi: 0x3bff, lo: 0.75
494 ]
495 for hi, lo in pairs:
496 v1 = (hi << 16) | lo
497 for src_hi, dst_hi in itertools.product((0, 1), repeat=2):
498 h_in = hi if src_hi else lo
499 line = f"v_fract_f16_e64 v0, v1 op_sel:[{src_hi},{dst_hi}]"
500 with self.subTest(line=line, v1=hex(v1)):
501 self.assertEqual(run_op(line, v1), merge_half(OLD, oracle_fract_f16(h_in), dst_hi))
502
503 def test_vop3_source_modifiers(self):
504 cases = [
505 ("v_fract_f16_e64 v0, -v1 op_sel:[0,0]", (H_NEG_1P25 << 16) | H_0P25, H_0P25, False, True, 0),
506 ("v_fract_f16_e64 v0, -v1 op_sel:[1,1]", (H_NEG_0P25 << 16) | H_1P25, H_NEG_0P25, False, True, 1),
507 ("v_fract_f16_e64 v0, -v1 op_sel:[0,0]", (H_0P25 << 16) | H_2PM13, H_2PM13, False, True, 0),
508 ("v_fract_f16_e64 v0, -v1 op_sel:[0,0]", H_POS_ZERO, H_POS_ZERO, False, True, 0),
509 ("v_fract_f16_e64 v0, -v1 op_sel:[0,0]", H_1P0, H_1P0, False, True, 0),
510 ("v_fract_f16_e64 v0, |v1| op_sel:[1,1]", (H_NEG_1P25 << 16) | H_0P25, H_NEG_1P25, True, False, 1),
511 ("v_fract_f16_e64 v0, |v1| op_sel:[1,0]", (H_NEG_2PM13 << 16) | H_0P5, H_NEG_2PM13, True, False, 0),
512 ("v_fract_f16_e64 v0, -|v1| op_sel:[1,0]", (H_NEG_1P25 << 16) | H_0P25, H_NEG_1P25, True, True, 0),
513 ("v_fract_f16_e64 v0, -|v1| op_sel:[0,1]", (H_0P5 << 16) | H_3P75, H_3P75, True, True, 1),
514 ("v_fract_f16_e64 v0, -|v1| op_sel:[0,0]", H_2PM13, H_2PM13, True, True, 0),
515 ]
516 for line, v1, h_in, abs_, neg, dst_hi in cases:
517 with self.subTest(line=line, v1=hex(v1)):
518 want = oracle_fract_f16(h_in, abs_=abs_, neg=neg)
519 self.assertEqual(run_op(line, v1), merge_half(OLD, want, dst_hi))
520
521 # Source modifiers on inf/NaN preserve NaN output and keep untouched half.
522 for mod in ("-v1", "|v1|", "-|v1|"):
523 for h in (H_POS_INF, H_NEG_INF, H_QNAN):
524 with self.subTest(mod=mod, h=hex(h)):
525 got = run_op(f"v_fract_f16_e64 v0, {mod}", (H_0P25 << 16) | h)
526 self.assertEqual(got & 0xFFFF0000, OLD & 0xFFFF0000)
527 self.assertTrue(h16_is_nan(got & 0xFFFF), hex(got))
528
529 def test_vop3_output_modifiers(self):
530 # (asm_suffix, input_h, dst_hi, kwargs_for_oracle)
531 cases = [
532 # clamp without omod keeps [0, 1) and preserves 0x3c00 -> 0x3bff
533 ("clamp", H_0P75, 0, dict(clamp=True)),
534 ("clamp", H_NEG_0P25, 0, dict(clamp=True)),
535 ("clamp", H_NEG_2PM13, 0, dict(clamp=True)),
536 ("clamp", H_NEG_ZERO, 0, dict(clamp=True)),
537 # mul:2 / mul:4 / div:2 (true 1.0 stays 0x3c00 when omod is active)
538 ("mul:2", H_0P5, 0, dict(mul=2)),
539 ("mul:2", H_0P75, 0, dict(mul=2)),
540 ("mul:2", H_NEG_0P25, 0, dict(mul=2)),
541 ("mul:2", H_NEG_2PM13, 0, dict(mul=2)),
542 ("mul:4", H_0P25, 0, dict(mul=4)),
543 ("mul:4", H_0P5, 0, dict(mul=4)),
544 ("mul:4", H_NEG_1P25, 0, dict(mul=4)),
545 ("div:2", H_0P5, 0, dict(div=2)),
546 ("div:2", H_NEG_1P25, 0, dict(div=2)),
547 ("div:2", H_0P25, 0, dict(div=2)),
548 ("div:2", H_NEG_2PM13, 0, dict(div=2)),
549 # combined omod + clamp
550 ("mul:2 clamp", H_0P25, 0, dict(mul=2, clamp=True)),
551 ("mul:2 clamp", H_0P5, 0, dict(mul=2, clamp=True)),
552 ("mul:2 clamp", H_0P75, 0, dict(mul=2, clamp=True)),
553 ("mul:2 clamp", H_NEG_0P25, 0, dict(mul=2, clamp=True)),
554 ("mul:4 clamp", H_0P5, 0, dict(mul=4, clamp=True)),
555 ("op_sel:[1,1] mul:2 clamp", H_NEG_1P25, 1, dict(mul=2, clamp=True)),
556 ("op_sel:[1,1] mul:4 clamp", H_0P125, 1, dict(mul=4, clamp=True)),
557 ]
558 for suffix, h_in, dst_hi, kw in cases:
559 v1 = ((h_in << 16) | H_0P25) if "op_sel:[1,1]" in suffix else ((H_3P75 << 16) | h_in)
560 line = f"v_fract_f16_e64 v0, v1 {suffix}"
561 want = oracle_fract_f16(h_in, **kw)
562 with self.subTest(line=line, h_in=hex(h_in)):
563 self.assertEqual(run_op(line, v1), merge_half(OLD, want, dst_hi))
564
565 # Verify explicit exact values for the critical omod transitions.
566 self.assertEqual(run_op("v_fract_f16_e64 v0, v1 mul:2", H_0P5), merge_half(OLD, H_1P0, 0))
567 self.assertEqual(run_op("v_fract_f16_e64 v0, v1 mul:2 clamp", H_0P75), merge_half(OLD, H_1P0, 0))
568 self.assertEqual(run_op("v_fract_f16_e64 v0, v1 mul:4", H_0P5), merge_half(OLD, H_2P0, 0))
569 self.assertEqual(run_op("v_fract_f16_e64 v0, v1 div:2", H_0P5), merge_half(OLD, H_0P25, 0))
570
571 def test_inline_f16_constants(self):
572 for lit, h in (("0.5", H_0P5), ("-0.5", H_NEG_0P5), ("1.0", H_1P0), ("-1.0", H_NEG_1P0)):
573 want = oracle_fract_f16(h)
574 for form in ("_e32", "_e64", ""):
575 with self.subTest(lit=lit, form=form or "bare"):
576 self.assertEqual(run_op(f"v_fract_f16{form} v0, {lit}"), merge_half(OLD, want, 0))
577 # op_sel:[0,1] writes the inline constant's fract into high half; low half preserved.
578 self.assertEqual(run_op(f"v_fract_f16_e64 v0, {lit} op_sel:[0,1]"), merge_half(OLD, want, 1))
579 # Inline float constants place +0.0 in the high half (docs/design.md / src_h).
580 self.assertEqual(run_op(f"v_fract_f16_e64 v0, {lit} op_sel:[1,0]"), merge_half(OLD, H_POS_ZERO, 0))
581
582 self.assertEqual(run_op("v_fract_f16_e64 v0, -0.5 mul:2"), merge_half(OLD, H_1P0, 0))
583 self.assertEqual(run_op("v_fract_f16_e64 v0, -0.5 div:2"), merge_half(OLD, H_0P25, 0))
584
585 def test_sgpr_sources_and_destination_aliasing(self):
586 s4 = (H_NEG_1P25 << 16) | H_0P25
587 self.assertEqual(run_op("v_fract_f16_e32 v0, s4", s4=s4), merge_half(OLD, H_0P25, 0))
588 self.assertEqual(run_op("v_fract_f16_e64 v0, s4 op_sel:[0,0]", s4=s4), merge_half(OLD, H_0P25, 0))
589 self.assertEqual(run_op("v_fract_f16_e64 v0, s4 op_sel:[1,0]", s4=s4), merge_half(OLD, H_0P75, 0))
590 self.assertEqual(run_op("v_fract_f16_e64 v0, s4 op_sel:[0,1]", s4=s4), merge_half(OLD, H_0P25, 1))
591 self.assertEqual(run_op("v_fract_f16_e64 v0, s4 op_sel:[1,1]", s4=s4), merge_half(OLD, H_0P75, 1))
592 self.assertEqual(run_op("v_fract_f16_e64 v0, -s4 op_sel:[1,0]", s4=s4), merge_half(OLD, H_0P25, 0))
593 self.assertEqual(run_op("v_fract_f16_e64 v0, |s4| op_sel:[1,1]", s4=s4), merge_half(OLD, H_0P25, 1))
594
595 # Destination aliasing: dst == src (v0, v0) keeps the untouched half of v0.
596 v0_init = (H_3P75 << 16) | H_NEG_0P25
597 self.assertEqual(
598 run_ps([f"v_mov_b32 v0, {v0_init:#x}", "v_fract_f16_e32 v0, v0"]),
599 (H_3P75 << 16) | H_0P75,
600 )
601 self.assertEqual(
602 run_ps([f"v_mov_b32 v0, {v0_init:#x}", "v_fract_f16 v0, v0"]),
603 (H_3P75 << 16) | H_0P75,
604 )
605 for src_hi, dst_hi in itertools.product((0, 1), repeat=2):
606 h_in = H_3P75 if src_hi else H_NEG_0P25
607 want_h = oracle_fract_f16(h_in)
608 with self.subTest(alias_op_sel=(src_hi, dst_hi)):
609 self.assertEqual(
610 run_ps([
611 f"v_mov_b32 v0, {v0_init:#x}",
612 f"v_fract_f16_e64 v0, v0 op_sel:[{src_hi},{dst_hi}]",
613 ]),
614 merge_half(v0_init, want_h, dst_hi),
615 )
616
617 def test_exec_masking_single_lane_and_workgroup(self):
618 # Single-lane pixel shader: inactive lane preserves pre-existing v0; re-enabling executes.
619 self.assertEqual(run_ps([
620 f"v_mov_b32 v1, {H_1P5:#x}",
621 f"v_mov_b32 v0, {OLD:#x}",
622 "s_mov_b32 exec_lo, 0",
623 "v_fract_f16_e32 v0, v1",
624 "v_fract_f16_e64 v0, v1 op_sel:[0,1]",
625 "s_mov_b32 exec_lo, 1",
626 ]), OLD)
627
628 self.assertEqual(run_ps([
629 f"v_mov_b32 v1, {(H_NEG_1P25 << 16) | H_2P5:#x}",
630 f"v_mov_b32 v0, {OLD:#x}",
631 "s_mov_b32 exec_lo, 0",
632 "v_fract_f16_e64 v0, v1 op_sel:[0,0]",
633 "v_fract_f16_e64 v0, v1 op_sel:[1,1]",
634 "s_mov_b32 exec_lo, 1",
635 "v_fract_f16_e64 v0, v1 op_sel:[1,0]",
636 ]), merge_half(OLD, H_0P75, 0))
637
638 # Multi-lane 8-thread compute shader: even lanes active, odd lanes masked off keep OLD.
639 lane_inputs = [
640 (H_NEG_1P25 << 16) | H_0P25,
641 (H_3P75 << 16) | H_NEG_0P25,
642 (H_NEG_SUB_1E5 << 16) | H_1P25,
643 (H_2P5 << 16) | H_NEG_1E4,
644 (H_NEG_ZERO << 16) | H_NEG_0P5,
645 (H_1P5 << 16) | H_NEG_MAX,
646 (H_NEG_MAX << 16) | H_NEG_2PM12,
647 (H_0P75 << 16) | H_3P75,
648 ]
649 lane_olds = [0xAA00BB00 + 0x00110001 * i for i in range(8)]
650 for dst_hi, op_line in (
651 (0, "v_fract_f16_e32 v2, v1"),
652 (1, "v_fract_f16_e64 v2, v1 op_sel:[1,1]"),
653 ):
654 mem = _Heap(
655 {0x100 + 4 * i: w for i, w in enumerate(lane_inputs)}
656 | {0x200 + 4 * i: w for i, w in enumerate(lane_olds)}
657 )
658 run_cs([
659 "v_lshlrev_b32_e32 v5, 2, v0",
660 "v_add_nc_u32_e32 v6, 0x100, v5",
661 "v_add_nc_u32_e32 v7, 0x200, v5",
662 "buffer_load_dword v1, v6, s[0:3], 0 offen",
663 "buffer_load_dword v2, v7, s[0:3], 0 offen",
664 "v_and_b32_e32 v3, 1, v0",
665 "v_cmp_eq_u32_e32 vcc_lo, 0, v3",
666 "s_and_saveexec_b32 s6, vcc_lo",
667 op_line,
668 "s_mov_b32 exec_lo, s6",
669 "buffer_store_dword v2, v5, s[0:3], 0 offen",
670 ], group_size=8, memory=mem)
671
672 got = [mem.get(4 * i) for i in range(8)]
673 want = []
674 for lane, (inp, old_w) in enumerate(zip(lane_inputs, lane_olds)):
675 if lane & 1:
676 want.append(old_w)
677 else:
678 h_in = (inp >> 16) if dst_hi else (inp & 0xFFFF)
679 want.append(merge_half(old_w, oracle_fract_f16(h_in), dst_hi))
680 with self.subTest(op_line=op_line):
681 self.assertEqual(got, want)
682
683 def test_negative_control_sabotaged_spirv(self):
684 # Input -1.25: true fract = 0.75 (0x3a00); Trunc gives -1.0 (0xbc00); Floor gives -2.0 (0xc000).
685 spv = translate_ps([
686 f"v_mov_b32 v1, {H_NEG_1P25:#x}",
687 f"v_mov_b32 v0, {OLD:#x}",
688 "v_fract_f16_e32 v0, v1",
689 ])
690 expected = merge_half(OLD, H_0P75, 0)
691 self.assertEqual(si.run_fragment(spv)["%out_mrt0"][0], expected)
692
693 for replacement, sabotaged_half in (("Trunc", H_NEG_1P0), ("Floor", H_NEG_2P0)):
694 sabotaged, n = re.subn(r"\bFract\b", replacement, spv, count=1)
695 self.assertEqual(n, 1)
696 got = si.run_fragment(sabotaged)["%out_mrt0"][0]
697 with self.subTest(replacement=replacement):
698 self.assertNotEqual(got, expected)
699 self.assertEqual(got, merge_half(OLD, sabotaged_half, 0))
700
701
702if __name__ == "__main__":
703 unittest.main()
diff --git a/tests/semantic/test_valu_permlane16.py b/tests/semantic/test_valu_permlane16.py
new file mode 100644
index 000000000..3256b9d8d
--- /dev/null
+++ b/tests/semantic/test_valu_permlane16.py
@@ -0,0 +1,814 @@
1"""Semantic value and translation tests for RDNA2 cross-lane permutes:
2 v_permlane16_b32 D = vS[(l & ~15) | sel[l & 15]]
3 v_permlanex16_b32 D = vS[((l & ~15) ^ 16) | sel[l & 15]]
4
5where the 4-bit lane selector nibbles `sel[0..7]` come from `src1` (bits `[4*k+3 : 4*k]`) and
6`sel[8..15]` come from `src2` (bits `[4*(k-8)+3 : 4*(k-8)]`), applied independently inside each
732-lane row (`[0..15]` and `[16..31]`, and in wave64 `[32..47]` and `[48..63]`). Only lanes active
8in `EXEC` write `vD`; inactive destination lanes preserve their prior `vD`.
9
10Executed end-to-end through `tools/rdna2spirv.py` and `tests/semantic/spirv_mini_interp.py`
11(`run_workgroup`) across 32 lanes (wave32) and 64 lanes (wave64 on both one 64-wide subgroup and
12two 32-wide subgroups), as well as partial waves (20 and 40 lanes), and checked against
13hand-computed constants and an independent plain-Python RDNA2 ISA reference model. Standard library
14only; zero game data; hand-written RDNA2 disassembly listings only.
15
16Documented findings (observed in `tools/rdna2spirv.py`; no shared files modified):
17 1. `op_sel:[fi, bound_ctrl]` and inactive source lanes (`tools/rdna2spirv.py` lines 4608-4632):
18 In RDNA2 ISA (measured on RDNA2 gfx1036 and RDNA3.5 gfx1150; see `docs/shader_validation.md`
19 and `tools/crosslane_fuzz.py`), when a source lane is inactive in `EXEC` (`EXEC[src] == 0`):
20 - `fi=1` (`op_sel:[1,0]`, `op_sel:[1,1]`): reads the inactive source lane's pre-existing `vS`.
21 - `fi=0, bound_ctrl=0` (`op_sel:[0,0]` or omitted): keeps the destination lane's prior `vD`.
22 - `fi=0, bound_ctrl=1` (`op_sel:[0,1]`): writes `0` to the destination lane.
23 `tools/rdna2spirv.py` lines 4608-4632 do not inspect `mods` (`op_sel:[fi, bound_ctrl]`) and emit
24 `self.g_shuffle(r, v, src)` unconditionally without checking the source lane's `%active` bit.
25 Therefore:
26 - When all accessed source lanes are active in `EXEC`, all four `op_sel` modes (`[0,0]`,
27 `[1,0]`, `[0,1]`, `[1,1]`) and omitted `op_sel` match the RDNA2 ISA.
28 - When a source lane is inactive in `EXEC` and `fi=1` (`op_sel:[1,0]`, `op_sel:[1,1]`), the
29 translation matches the RDNA2 ISA (reading the inactive source lane's pre-existing `vS`).
30 - When a source lane is inactive in `EXEC` and `fi=0` (`op_sel:[0,0]`/omitted,
31 `op_sel:[0,1]`), the translator currently reads `vS[src]` instead of keeping `vD` or
32 writing `0`. Those inactive-source `fi=0` cases are tested in the plain-Python ISA
33 reference tests (`OracleTests`) and excluded from passing end-to-end assertions rather
34 than relaxing expected values; structural SPIR-V translation is verified in
35 `EmulationAndFindingTests`.
36 2. `--wave64-emulate` (`tools/rdna2spirv.py` lines 2671-2810, 2890-2895, 4608-4632):
37 With `WAVE64_EMULATE = True`, wave64 compute/mesh shaders lower `g_shuffle` and `sub_lane`
38 through `%x_buf` Workgroup-memory exchanges, `OpControlBarrier`, and a round loop (`OpLoopMerge`
39 with a backward branch). `tests/semantic/spirv_mini_interp.py` rejects `Workgroup` barriers and
40 non-forward branches (`UnsupportedConstruct`), so `--wave64-emulate` is covered by translation
41 and structural SPIR-V invariants here (and rejected cleanly by `run_workgroup`).
42 3. Wave64 native on two 32-wide subgroups (`subgroup_size = 32`):
43 Because `v_permlane16_b32` and `v_permlanex16_b32` never cross the 32-lane row boundary
44 (`0..31` vs `32..63`), both instructions stay exact across all 64 lanes even on two 32-wide
45 subgroups without `--wave64-emulate`.
46"""
47import gc
48import os
49import re
50import struct
51import sys
52import tempfile
53import unittest
54import warnings
55
56HERE = os.path.dirname(os.path.abspath(__file__))
57ROOT = os.path.dirname(os.path.dirname(HERE))
58TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools")
59
60sys.dont_write_bytecode = True
61if TOOLS_DIR not in sys.path:
62 sys.path.insert(0, TOOLS_DIR)
63if HERE not in sys.path:
64 sys.path.insert(0, HERE)
65
66import rdna2spirv # noqa: E402
67import spirv_mini_interp as si # noqa: E402
68
69MASK32 = 0xFFFFFFFF
70ALL32 = 0xFFFFFFFF
71ALL64 = 0xFFFFFFFFFFFFFFFF
72OLD_SENTINEL = 0xCAFE0000
73HEAP_FILL = 0xEEEEEEEE
74# V# in s[0:3]: base 0, stride 0, num_records 0x10000 bytes (OOB_SELECT = 3).
75VSHARP = [0, 0, 0x10000, 0x31016FAC]
76INPUT_BASE = 0x8000
77
78ID_S1 = 0x76543210
79ID_S2 = 0xFEDCBA98
80REV8_S1 = 0x01234567
81REV8_S2 = 0x89ABCDEF
82REV16_S1 = 0x89ABCDEF
83REV16_S2 = 0x01234567
84PAIR_SWAP_S1 = 0x10325476
85PAIR_SWAP_S2 = 0x98BADCFE
86ASYM_S1 = 0x3A0F5C91
87ASYM_S2 = 0xE27B48D6
88
89
90def ref_permlane(x16: bool, src_vals: list[int], dst_old: list[int], s1: int, s2: int,
91 exec_mask: int, fi: int = 0, bound_ctrl: int = 0) -> list[int]:
92 """Independent RDNA2 ISA reference model for v_permlane16_b32 / v_permlanex16_b32."""
93 lanes = len(src_vals)
94 assert len(dst_old) == lanes and lanes in (32, 64)
95 out = []
96 for lane in range(lanes):
97 if not ((exec_mask >> lane) & 1):
98 out.append(dst_old[lane] & MASK32)
99 continue
100 within = lane & 15
101 sel_word = s2 if within >= 8 else s1
102 nib = (sel_word >> (4 * (lane & 7))) & 0xF
103 half = lane & ~15
104 row = (half ^ 16) if x16 else half
105 src_lane = row | nib
106 if ((exec_mask >> src_lane) & 1) or fi:
107 out.append(src_vals[src_lane] & MASK32)
108 elif bound_ctrl:
109 out.append(0)
110 else:
111 out.append(dst_old[lane] & MASK32)
112 return out
113
114
115class _Heap(dict):
116 def get(self, key, default=None):
117 return super().get(key, HEAP_FILL)
118
119
120_TMP_DIR = None
121_DISASM_DIR = None
122_FSSM_DIR = None
123
124
125def _make_fssm(threads: int, rsrc2: int = 0x8088) -> bytes:
126 header = bytearray(0x148)
127 struct.pack_into("<4I", header, 0x138, rsrc2, threads, 1, 1)
128 return bytes(header)
129
130
131def setUpModule():
132 global _TMP_DIR, _DISASM_DIR, _FSSM_DIR
133 _TMP_DIR = tempfile.TemporaryDirectory()
134 _DISASM_DIR = os.path.join(_TMP_DIR.name, "disasm")
135 _FSSM_DIR = os.path.join(_TMP_DIR.name, "fssm")
136 os.mkdir(_DISASM_DIR)
137 os.mkdir(_FSSM_DIR)
138
139
140def tearDownModule():
141 global _TMP_DIR, _DISASM_DIR, _FSSM_DIR
142 if _TMP_DIR is not None:
143 gc.collect()
144 _TMP_DIR.cleanup()
145 _TMP_DIR = None
146 _DISASM_DIR = None
147 _FSSM_DIR = None
148
149
150def translate_cs(name: str, lines: list[str], threads: int, emulate: bool = False) -> tuple[str, object]:
151 assert name.startswith("cs_"), f"compute shader name must start with cs_: {name!r}"
152 if _TMP_DIR is None:
153 setUpModule()
154 with open(os.path.join(_FSSM_DIR, name + ".fssm"), "wb") as f:
155 f.write(_make_fssm(threads))
156 src_path = os.path.join(_DISASM_DIR, name + ".s")
157 asm = f"; {name}\n" + "".join(f"\t{ln}\n" for ln in lines) + "\ts_endpgm\n"
158 with open(src_path, "w", encoding="utf-8", newline="") as f:
159 f.write(asm)
160 old_emu = rdna2spirv.WAVE64_EMULATE
161 rdna2spirv.WAVE64_EMULATE = emulate
162 try:
163 with warnings.catch_warnings():
164 warnings.simplefilter("ignore", ResourceWarning)
165 spv = rdna2spirv.translate(src_path)
166 gen = rdna2spirv.translate.last_gen
167 gc.collect()
168 finally:
169 rdna2spirv.WAVE64_EMULATE = old_emu
170 return spv, gen
171
172
173def run_cs(name: str, lines: list[str], threads: int, subgroup_size: int,
174 init_inputs: list[int] | None = None, out_slots: int = 1) -> list[int]:
175 """Translate and run a compute shader; return `threads * out_slots` 32-bit output words."""
176 spv, _ = translate_cs(name, lines, threads, emulate=False)
177 mem = _Heap()
178 if init_inputs is not None:
179 for i, val in enumerate(init_inputs):
180 mem[INPUT_BASE + 4 * i] = val & MASK32
181 si.run_workgroup(
182 spv, threads, subgroup_size,
183 inputs_for=lambda i: {"%wg_id": (0, 0, 0), "%local_id": (i, 0, 0), "%sg_lane": i % subgroup_size},
184 push_constants=VSHARP + [0] * 28,
185 memory=mem,
186 )
187 out_bytes = 4 * threads * out_slots
188 stray = sorted(a for a in mem if a < INPUT_BASE and (a % 4 != 0 or a >= out_bytes))
189 if stray:
190 raise AssertionError(f"{name}: unexpected stores outside out[0..{threads * out_slots - 1}]: {stray}")
191 return [mem.get(4 * k) for k in range(threads * out_slots)]
192
193
194def exec_mask_lines(mask: int, wave: int) -> list[str]:
195 lines = [f"s_mov_b32 exec_lo, {mask & MASK32:#x}"]
196 if wave == 64:
197 lines.append(f"s_mov_b32 exec_hi, {(mask >> 32) & MASK32:#x}")
198 return lines
199
200
201def restore_exec_lines(wave: int) -> list[str]:
202 return ["s_mov_b64 exec, -1"] if wave == 64 else ["s_mov_b32 exec_lo, -1"]
203
204
205def store_slots_lines(regs: list[str], threads: int) -> list[str]:
206 """Emit buffer_store_dword for each VGPR in `regs` at `4 * (slot * threads + v0)`."""
207 lines = ["v_lshlrev_b32_e32 v21, 2, v0"]
208 for slot, reg in enumerate(regs):
209 if slot == 0:
210 lines.append(f"buffer_store_dword {reg}, v21, s[0:3], 0 offen")
211 else:
212 lines.append(f"buffer_store_dword {reg}, v21, s[0:3], 0 offen offset:{4 * slot * threads}")
213 return lines
214
215
216class OracleTests(unittest.TestCase):
217 """Cross-check hand-worked constants and ISA semantics against ref_permlane."""
218
219 def test_hand_worked_identity_and_half_swap(self):
220 vals32 = [100 + l for l in range(32)]
221 old32 = [OLD_SENTINEL | l for l in range(32)]
222 # v_permlane16_b32 identity leaves all 32 lanes unchanged.
223 self.assertEqual(ref_permlane(False, vals32, old32, ID_S1, ID_S2, ALL32), vals32)
224 # v_permlanex16_b32 swaps [0..15] and [16..31].
225 self.assertEqual(
226 ref_permlane(True, vals32, old32, ID_S1, ID_S2, ALL32),
227 [100 + (l ^ 16) for l in range(32)],
228 )
229
230 # Wave64 swaps within each 32-lane row: [0..15]<->[16..31] and [32..47]<->[48..63].
231 vals64 = [500 + l for l in range(64)]
232 old64 = [OLD_SENTINEL | l for l in range(64)]
233 got64 = ref_permlane(True, vals64, old64, ID_S1, ID_S2, ALL64)
234 self.assertEqual((got64[0], got64[15], got64[16], got64[31]), (516, 531, 500, 515))
235 self.assertEqual((got64[32], got64[47], got64[48], got64[63]), (548, 563, 532, 547))
236
237 def test_hand_worked_nibble_patterns_and_exec_opsel_rules(self):
238 vals32 = [1000 + l for l in range(32)]
239 old32 = [OLD_SENTINEL | l for l in range(32)]
240
241 # Broadcast 0 from s1 (lanes 0..7) and 15 from s2 (lanes 8..15).
242 got_bcast = ref_permlane(False, vals32, old32, 0x00000000, 0xFFFFFFFF, ALL32)
243 self.assertEqual(got_bcast[0:8], [1000] * 8)
244 self.assertEqual(got_bcast[8:16], [1015] * 8)
245 self.assertEqual(got_bcast[16:24], [1016] * 8)
246 self.assertEqual(got_bcast[24:32], [1031] * 8)
247
248 # Full 16-lane reversal: s1=0x89abcdef (lanes 0..7 -> 15..8), s2=0x01234567 (lanes 8..15 -> 7..0).
249 got_rev16 = ref_permlane(False, vals32, old32, REV16_S1, REV16_S2, ALL32)
250 self.assertEqual(got_rev16[0:16], [1000 + (15 - l) for l in range(16)])
251 self.assertEqual(got_rev16[16:32], [1016 + (15 - l) for l in range(16)])
252
253 # Sub-half 8-lane reversal: s1=0x01234567 (0..7 -> 7..0), s2=0x89abcdef (8..15 -> 15..8).
254 got_rev8 = ref_permlane(True, vals32, old32, REV8_S1, REV8_S2, ALL32)
255 self.assertEqual(got_rev8[0:8], [1016 + (7 - l) for l in range(8)])
256 self.assertEqual(got_rev8[8:16], [1016 + (15 - l) for l in range(8)])
257
258 # op_sel:[fi, bound_ctrl] when lane 0 is INACTIVE in EXEC (0xFFFFFFFE):
259 # lanes 1..15 broadcast local lane 0 (inactive in half 0!), lanes 16..31 broadcast local lane 16 (active!).
260 exec_no_0 = ALL32 ^ 1
261 # fi=0, bound_ctrl=0 -> lanes 1..15 keep old32, lane 0 keeps old32[0], lanes 16..31 read 1016.
262 r00 = ref_permlane(False, vals32, old32, 0, 0, exec_no_0, fi=0, bound_ctrl=0)
263 self.assertEqual(r00[0], old32[0])
264 self.assertEqual(r00[1:16], old32[1:16])
265 self.assertEqual(r00[16:32], [1016] * 16)
266
267 # fi=0, bound_ctrl=1 -> lanes 1..15 write 0, lane 0 keeps old32[0], lanes 16..31 read 1016.
268 r01 = ref_permlane(False, vals32, old32, 0, 0, exec_no_0, fi=0, bound_ctrl=1)
269 self.assertEqual(r01[0], old32[0])
270 self.assertEqual(r01[1:16], [0] * 15)
271 self.assertEqual(r01[16:32], [1016] * 16)
272
273 # fi=1, bound_ctrl=0 or 1 -> lanes 1..15 read inactive lane 0's vals32[0], lane 0 keeps old32[0].
274 for bc in (0, 1):
275 r1x = ref_permlane(False, vals32, old32, 0, 0, exec_no_0, fi=1, bound_ctrl=bc)
276 self.assertEqual(r1x[0], old32[0])
277 self.assertEqual(r1x[1:16], [1000] * 15)
278 self.assertEqual(r1x[16:32], [1016] * 16)
279
280
281class Wave32ExecutionTests(unittest.TestCase):
282 """End-to-end 32-lane execution for v_permlane16_b32 and v_permlanex16_b32."""
283
284 def _run_batch(self, specs: list[tuple[bool, int, int, str, str]], init_vals: list[int],
285 old_vals: list[int], exec_mask: int = ALL32) -> list[list[int]]:
286 """Run a list of (x16, s1, s2, src_form, extra_mods) batched into one shader."""
287 lines = [
288 "v_lshlrev_b32_e32 v20, 2, v0",
289 f"v_add_nc_u32_e32 v20, {INPUT_BASE:#x}, v20",
290 "buffer_load_dword v1, v20, s[0:3], 0 offen",
291 ]
292 regs = []
293 for idx, _ in enumerate(specs):
294 dst = f"v{2 + idx}"
295 regs.append(dst)
296 lines.append(f"v_or_b32_e32 {dst}, {OLD_SENTINEL:#x}, v0")
297 lines.extend(exec_mask_lines(exec_mask, 32))
298 for idx, (x16, s1, s2, src_expr, extra) in enumerate(specs):
299 dst = f"v{2 + idx}"
300 op = "v_permlanex16_b32" if x16 else "v_permlane16_b32"
301 if src_expr == "sgpr":
302 lines += [f"s_mov_b32 s4, {s1:#x}", f"s_mov_b32 s5, {s2:#x}",
303 f"{op} {dst}, v1, s4, s5{extra}"]
304 elif src_expr == "lit_sgpr":
305 lines += [f"s_mov_b32 s5, {s2:#x}", f"{op} {dst}, v1, {s1:#x}, s5{extra}"]
306 elif src_expr == "sgpr_lit":
307 lines += [f"s_mov_b32 s4, {s1:#x}", f"{op} {dst}, v1, s4, {s2:#x}{extra}"]
308 elif src_expr == "inline":
309 lines.append(f"{op} {dst}, v1, {s1}, {s2}{extra}")
310 elif src_expr == "same_sgpr":
311 assert s1 == s2
312 lines += [f"s_mov_b32 s4, {s1:#x}", f"{op} {dst}, v1, s4, s4{extra}"]
313 elif src_expr == "e64_sgpr":
314 lines += [f"s_mov_b32 s4, {s1:#x}", f"s_mov_b32 s5, {s2:#x}",
315 f"{op}_e64 {dst}, v1, s4, s5{extra}"]
316 else:
317 raise ValueError(src_expr)
318 lines.extend(restore_exec_lines(32))
319 lines.extend(store_slots_lines(regs, 32))
320 flat = run_cs("cs_w32_permlane_batch", lines, 32, 32, init_inputs=init_vals, out_slots=len(specs))
321 return [flat[slot * 32:(slot + 1) * 32] for slot in range(len(specs))]
322
323 def test_half_isolation_vs_cross_half_swap_and_nibble_selectors(self):
324 init_vals = [(0x10000000 + l * 0x010101) & MASK32 for l in range(32)]
325 old_vals = [OLD_SENTINEL | l for l in range(32)]
326 specs = [
327 # Identity (SGPR+SGPR, literal+SGPR, SGPR+literal, _e64)
328 (False, ID_S1, ID_S2, "sgpr", ""),
329 (True, ID_S1, ID_S2, "sgpr", ""),
330 (False, ID_S1, ID_S2, "lit_sgpr", ""),
331 (True, ID_S1, ID_S2, "sgpr_lit", ""),
332 (True, ID_S1, ID_S2, "e64_sgpr", ""),
333 # Broadcasts with inline constants (0, -1, 15, -16) and same-SGPR
334 (False, 0, 0, "inline", ""),
335 (True, 0, 0, "inline", ""),
336 (False, -1, -1, "inline", ""),
337 (True, 0, -1, "inline", ""),
338 (False, -16, 15, "inline", ""), # -16 = 0xfffffff0, 15 = 0x0000000f
339 (True, 0x55555555, 0x55555555, "same_sgpr", ""),
340 # 8-lane reversal vs full 16-lane reversal
341 (False, REV8_S1, REV8_S2, "sgpr", ""),
342 (True, REV8_S1, REV8_S2, "sgpr", ""),
343 (False, REV16_S1, REV16_S2, "sgpr", ""),
344 (True, REV16_S1, REV16_S2, "sgpr", ""),
345 # Pairwise swap & asymmetric non-bijective permutation
346 (False, PAIR_SWAP_S1, PAIR_SWAP_S2, "sgpr", ""),
347 (True, ASYM_S1, ASYM_S2, "sgpr", ""),
348 ]
349 results = self._run_batch(specs, init_vals, old_vals)
350 for idx, (x16, s1, s2, form, _) in enumerate(specs):
351 s1_u = s1 & MASK32
352 s2_u = s2 & MASK32
353 want = ref_permlane(x16, init_vals, old_vals, s1_u, s2_u, ALL32)
354 with self.subTest(idx=idx, x16=x16, form=form, s1=hex(s1_u), s2=hex(s2_u)):
355 self.assertEqual(results[idx], want)
356
357 # Spot-check half-staying vs half-swapping explicitly:
358 self.assertEqual(results[0], init_vals)
359 self.assertEqual(results[1], init_vals[16:32] + init_vals[0:16])
360
361 def test_all_16_nibble_broadcasts_for_both_ops(self):
362 init_vals = [0x9000 + l * 17 for l in range(32)]
363 old_vals = [OLD_SENTINEL | l for l in range(32)]
364 specs = []
365 for nib in range(16):
366 sel = 0x11111111 * nib
367 specs.append((False, sel, sel, "same_sgpr", ""))
368 specs.append((True, sel, sel, "same_sgpr", ""))
369 # Batch 16 specs at a time to stay well within VGPR file (v2..v17).
370 for base in (0, 16):
371 chunk = specs[base:base + 16]
372 results = self._run_batch(chunk, init_vals, old_vals)
373 for idx, (x16, s1, s2, _, _) in enumerate(chunk):
374 want = ref_permlane(x16, init_vals, old_vals, s1, s2, ALL32)
375 with self.subTest(x16=x16, nib=s1 & 0xF):
376 self.assertEqual(results[idx], want)
377
378 def test_butterfly_32lane_sum_reduction(self):
379 # Real compiler idiom: xor 1, 2, 4, 8 via v_permlane16_b32 then xor 16 via v_permlanex16_b32.
380 init_vals = [3 * l + 5 for l in range(32)]
381 expected_sum = sum(init_vals)
382 got = run_cs("cs_w32_permlane_butterfly", [
383 "v_lshlrev_b32_e32 v20, 2, v0",
384 f"v_add_nc_u32_e32 v20, {INPUT_BASE:#x}, v20",
385 "buffer_load_dword v1, v20, s[0:3], 0 offen",
386 # xor 1: s1=0x67452301, s2=0xefcdab89
387 "s_mov_b32 s5, 0xefcdab89",
388 "v_permlane16_b32 v2, v1, 0x67452301, s5",
389 "v_add_nc_u32_e32 v1, v1, v2",
390 # xor 2: s1=0x54761032, s2=0xdcfe98ba
391 "s_mov_b32 s5, 0xdcfe98ba",
392 "v_permlane16_b32 v2, v1, 0x54761032, s5",
393 "v_add_nc_u32_e32 v1, v1, v2",
394 # xor 4: s1=0x32107654, s2=0xba98fedc
395 "s_mov_b32 s5, 0xba98fedc",
396 "v_permlane16_b32 v2, v1, 0x32107654, s5",
397 "v_add_nc_u32_e32 v1, v1, v2",
398 # xor 8: s1=0xfedcba98, s2=0x76543210
399 "s_mov_b32 s5, 0x76543210",
400 "v_permlane16_b32 v2, v1, 0xfedcba98, s5",
401 "v_add_nc_u32_e32 v1, v1, v2",
402 # xor 16: identity nibbles via v_permlanex16_b32
403 "s_mov_b32 s4, 0x76543210",
404 "s_mov_b32 s5, 0xfedcba98",
405 "v_permlanex16_b32 v2, v1, s4, s5",
406 "v_add_nc_u32_e32 v1, v1, v2",
407 "v_lshlrev_b32_e32 v21, 2, v0",
408 "buffer_store_dword v1, v21, s[0:3], 0 offen",
409 ], 32, 32, init_inputs=init_vals)
410 self.assertEqual(got, [expected_sum] * 32)
411
412 def test_exec_destination_masking_and_all_op_sel_with_active_sources(self):
413 # Active lanes in each 16-lane half are {0, 2, 4, 6, 8, 9, 10, 11};
414 # selectors ONLY read from active lanes {0, 2, 4, 6, 8, 9, 10, 11}, so all 4 op_sel modes match ISA.
415 exec_mask = 0x0F550F55
416 s1_sel = 0x64206420 # nibbles in {0, 2, 4, 6} (all active)
417 s2_sel = 0xBA98BA98 # nibbles in {8, 9, 10, 11} (all active)
418 init_vals = [0x100 + l for l in range(32)]
419 old_vals = [OLD_SENTINEL | l for l in range(32)]
420 specs = []
421 for x16 in (False, True):
422 for mods in ("", " op_sel:[0,0]", " op_sel:[1,0]", " op_sel:[0,1]", " op_sel:[1,1]"):
423 specs.append((x16, s1_sel, s2_sel, "sgpr", mods))
424 results = self._run_batch(specs, init_vals, old_vals, exec_mask=exec_mask)
425 for idx, (x16, s1, s2, _, mods) in enumerate(specs):
426 want = ref_permlane(x16, init_vals, old_vals, s1, s2, exec_mask)
427 with self.subTest(x16=x16, mods=mods or "default"):
428 self.assertEqual(results[idx], want)
429
430 def test_op_sel_fi1_reads_inactive_source_lanes(self):
431 # Lanes 0, 16 are OFF in EXEC; active lanes modify v1 to 9999 AFTER pre-filling v1,
432 # then v_permlane16_b32 / v_permlanex16_b32 with op_sel:[1,0] and op_sel:[1,1] broadcast
433 # local lane 0 (inactive lane 0 / inactive lane 16!). Active lanes must see the inactive
434 # lanes' pre-existing values (2000 and 2016), while inactive lanes 0 and 16 keep OLD.
435 exec_mask = ALL32 ^ ((1 << 0) | (1 << 16))
436 init_vals = [2000 + l for l in range(32)]
437 old_vals = [OLD_SENTINEL | l for l in range(32)]
438 updated_vals = [init_vals[l] if not ((exec_mask >> l) & 1) else 9999 for l in range(32)]
439
440 lines = [
441 "v_lshlrev_b32_e32 v20, 2, v0",
442 f"v_add_nc_u32_e32 v20, {INPUT_BASE:#x}, v20",
443 "buffer_load_dword v1, v20, s[0:3], 0 offen",
444 f"v_or_b32_e32 v2, {OLD_SENTINEL:#x}, v0",
445 f"v_or_b32_e32 v3, {OLD_SENTINEL:#x}, v0",
446 f"v_or_b32_e32 v4, {OLD_SENTINEL:#x}, v0",
447 f"v_or_b32_e32 v5, {OLD_SENTINEL:#x}, v0",
448 *exec_mask_lines(exec_mask, 32),
449 "v_mov_b32_e32 v1, 9999", # inactive lanes 0 & 16 keep 2000 & 2016
450 "v_permlane16_b32 v2, v1, 0, 0 op_sel:[1,0]",
451 "v_permlane16_b32 v3, v1, 0, 0 op_sel:[1,1]",
452 "v_permlanex16_b32 v4, v1, 0, 0 op_sel:[1,0]",
453 "v_permlanex16_b32 v5, v1, 0, 0 op_sel:[1,1]",
454 *restore_exec_lines(32),
455 *store_slots_lines(["v2", "v3", "v4", "v5"], 32),
456 ]
457 flat = run_cs("cs_w32_permlane_fi1", lines, 32, 32, init_inputs=init_vals, out_slots=4)
458 for slot, x16 in enumerate((False, False, True, True)):
459 got = flat[slot * 32:(slot + 1) * 32]
460 want = ref_permlane(x16, updated_vals, old_vals, 0, 0, exec_mask, fi=1, bound_ctrl=slot & 1)
461 self.assertEqual(got, want)
462 self.assertEqual(flat[0], OLD_SENTINEL | 0)
463 self.assertEqual(flat[1], 2000)
464 self.assertEqual(flat[16], OLD_SENTINEL | 16)
465 self.assertEqual(flat[17], 2016)
466 # Slot 2 (permlanex16 op_sel:[1,0]): active lanes 1..15 read inactive lane 16 (2016).
467 self.assertEqual(flat[2 * 32 + 1], 2016)
468 self.assertEqual(flat[2 * 32 + 17], 2000)
469
470 def test_destination_aliasing_v1_and_v0(self):
471 init_vals = [300 + l for l in range(32)]
472 # 1. Alias v1, v1 (with EXEC mask & fi=1 reading inactive lane 0 before overwrite)
473 exec_mask = ALL32 ^ (1 << 0)
474 got_v1 = run_cs("cs_w32_permlane_alias_v1", [
475 "v_lshlrev_b32_e32 v20, 2, v0",
476 f"v_add_nc_u32_e32 v20, {INPUT_BASE:#x}, v20",
477 "buffer_load_dword v1, v20, s[0:3], 0 offen",
478 "v_mov_b32_e32 v2, v1",
479 *exec_mask_lines(exec_mask, 32),
480 "s_mov_b32 s4, 0x00000000",
481 "s_mov_b32 s5, 0x00000000",
482 "v_permlane16_b32 v1, v1, s4, s5 op_sel:[1,0]",
483 "v_permlanex16_b32 v2, v2, 0x76543210, 0xfedcba98 op_sel:[1,0]",
484 *restore_exec_lines(32),
485 *store_slots_lines(["v1", "v2"], 32),
486 ], 32, 32, init_inputs=init_vals, out_slots=2)
487 self.assertEqual(got_v1[:32], ref_permlane(False, init_vals, init_vals, 0, 0, exec_mask, fi=1))
488 self.assertEqual(got_v1[32:], ref_permlane(True, init_vals, init_vals, ID_S1, ID_S2, exec_mask, fi=1))
489
490 # 2. Alias v0, v0 directly (save output byte offset 4 * v0 in v21 first)
491 got_v0_16 = run_cs("cs_w32_permlane16_alias_v0", [
492 "v_lshlrev_b32_e32 v21, 2, v0",
493 f"s_mov_b32 s4, {REV16_S1:#x}",
494 f"s_mov_b32 s5, {REV16_S2:#x}",
495 "v_permlane16_b32 v0, v0, s4, s5",
496 "buffer_store_dword v0, v21, s[0:3], 0 offen",
497 ], 32, 32)
498 self.assertEqual(got_v0_16, ref_permlane(False, list(range(32)), list(range(32)), REV16_S1, REV16_S2, ALL32))
499
500 got_v0_x16 = run_cs("cs_w32_permlanex16_alias_v0", [
501 "v_lshlrev_b32_e32 v21, 2, v0",
502 f"s_mov_b32 s4, {REV16_S1:#x}",
503 f"s_mov_b32 s5, {REV16_S2:#x}",
504 "v_permlanex16_b32 v0, v0, s4, s5",
505 "buffer_store_dword v0, v21, s[0:3], 0 offen",
506 ], 32, 32)
507 self.assertEqual(got_v0_x16, ref_permlane(True, list(range(32)), list(range(32)), REV16_S1, REV16_S2, ALL32))
508
509 def test_partial_wave_20_lanes_avoids_missing_lanes(self):
510 # 20 threads on a 32-wide subgroup: lanes 20..31 do not exist.
511 # 1. All 20 existing lanes active (0xFFFFF): selectors in {0..3} read existing active lanes 0..3 / 16..19.
512 exec_20 = 0xFFFFF
513 got_all20 = run_cs("cs_w32_partial20_all", [
514 "v_add_nc_u32_e32 v1, 700, v0",
515 f"v_or_b32_e32 v2, {OLD_SENTINEL:#x}, v0",
516 f"v_or_b32_e32 v3, {OLD_SENTINEL:#x}, v0",
517 *exec_mask_lines(exec_20, 32),
518 "v_permlane16_b32 v2, v1, 0x32103210, 0x01230123",
519 "v_permlanex16_b32 v3, v1, 0x32103210, 0x01230123",
520 *restore_exec_lines(32),
521 *store_slots_lines(["v2", "v3"], 20),
522 ], 20, 32, out_slots=2)
523 vals_padded = [700 + l for l in range(20)] + [0] * 12
524 old_padded = [OLD_SENTINEL | l for l in range(20)] + [0] * 12
525 self.assertEqual(got_all20[:20], ref_permlane(False, vals_padded, old_padded, 0x32103210, 0x01230123, exec_20)[:20])
526 self.assertEqual(got_all20[20:40], ref_permlane(True, vals_padded, old_padded, 0x32103210, 0x01230123, exec_20)[:20])
527
528 # 2. EXEC = 0xFFFF (lanes 16..19 inactive): permlane16 reads [0..15] and preserves OLD on 16..19;
529 # permlanex16 op_sel:[1,0] (fi=1) reads inactive lanes 16..19 while inactive lanes 16..19 discard UNDEF
530 # shuffles from missing lanes 20..31 and keep OLD.
531 exec_16 = 0xFFFF
532 got_masked = run_cs("cs_w32_partial20_masked", [
533 "v_add_nc_u32_e32 v1, 700, v0",
534 f"v_or_b32_e32 v2, {OLD_SENTINEL:#x}, v0",
535 f"v_or_b32_e32 v3, {OLD_SENTINEL:#x}, v0",
536 *exec_mask_lines(exec_16, 32),
537 "v_permlane16_b32 v2, v1, 0x01234567, 0x89abcdef",
538 "v_permlanex16_b32 v3, v1, 0x32103210, 0x01230123 op_sel:[1,0]",
539 *restore_exec_lines(32),
540 *store_slots_lines(["v2", "v3"], 20),
541 ], 20, 32, out_slots=2)
542 self.assertEqual(got_masked[:20], ref_permlane(False, vals_padded, old_padded, REV8_S1, REV8_S2, exec_16)[:20])
543 self.assertEqual(got_masked[20:40], ref_permlane(True, vals_padded, old_padded, 0x32103210, 0x01230123, exec_16, fi=1)[:20])
544
545
546class Wave64ExecutionTests(unittest.TestCase):
547 """End-to-end 64-lane execution across one 64-wide subgroup AND two 32-wide subgroups."""
548
549 def test_wave64_halves_selectors_exec_and_fi1_on_subgroup_64_and_32(self):
550 init_vals = [0x4000 + l * 31 for l in range(64)]
551 old_vals = [OLD_SENTINEL | l for l in range(64)]
552 # Asymmetric 64-bit EXEC: active lanes in each 16-lane quarter are {0, 2, 4, 6, 8, 9, 10, 11}.
553 exec_active_only = 0x0F550F550F550F55
554 # Inactive source lane 0 and lane 32 (one in each 32-lane row) for fi=1 test.
555 exec_no_0_32 = ALL64 ^ ((1 << 0) | (1 << 32))
556 updated_fi1 = [init_vals[l] if not ((exec_no_0_32 >> l) & 1) else (8800 + l) for l in range(64)]
557
558 lines = [
559 "s_mov_b64 exec, -1",
560 "v_lshlrev_b32_e32 v20, 2, v0",
561 f"v_add_nc_u32_e32 v20, {INPUT_BASE:#x}, v20",
562 "buffer_load_dword v1, v20, s[0:3], 0 offen",
563 "v_mov_b32_e32 v10, v1",
564 # Slot 0: v_permlane16_b32 identity (stays in [0..15], [16..31], [32..47], [48..63])
565 f"s_mov_b32 s4, {ID_S1:#x}",
566 f"s_mov_b32 s5, {ID_S2:#x}",
567 "v_permlane16_b32 v2, v1, s4, s5",
568 # Slot 1: v_permlanex16_b32 identity (swaps [0..15]<->[16..31] and [32..47]<->[48..63])
569 "v_permlanex16_b32 v3, v1, s4, s5",
570 # Slot 2: v_permlane16_b32 asymmetric non-bijective selectors
571 f"s_mov_b32 s6, {ASYM_S1:#x}",
572 f"s_mov_b32 s7, {ASYM_S2:#x}",
573 "v_permlane16_b32 v4, v1, s6, s7",
574 # Slot 3: v_permlanex16_b32_e64 full 16-lane reversal
575 f"s_mov_b32 s8, {REV16_S2:#x}",
576 f"v_permlanex16_b32_e64 v5, v1, {REV16_S1:#x}, s8",
577 # Slot 4: 64-bit EXEC destination masking with active sources (v6 pre-loaded with OLD)
578 f"v_or_b32_e32 v6, {OLD_SENTINEL:#x}, v0",
579 "s_mov_b32 s9, 0xba98ba98",
580 *exec_mask_lines(exec_active_only, 64),
581 "v_permlanex16_b32 v6, v1, 0x64206420, s9",
582 *restore_exec_lines(64),
583 # Slot 5: fi=1 reading inactive source lane 0 (in low 32) and lane 32 (in high 32)
584 f"v_or_b32_e32 v7, {OLD_SENTINEL:#x}, v0",
585 *exec_mask_lines(exec_no_0_32, 64),
586 "v_add_nc_u32_e32 v10, 8800, v0",
587 "v_permlane16_b32 v7, v10, 0, 0 op_sel:[1,0]",
588 # Slot 6: fi=1 permlanex16 reading inactive lane 32 from lanes 48..63 & lane 0 from 16..31
589 *restore_exec_lines(64),
590 f"v_or_b32_e32 v8, {OLD_SENTINEL:#x}, v0",
591 *exec_mask_lines(exec_no_0_32, 64),
592 "v_permlanex16_b32 v8, v10, 0, 0 op_sel:[1,1]",
593 *restore_exec_lines(64),
594 *store_slots_lines(["v2", "v3", "v4", "v5", "v6", "v7", "v8"], 64),
595 ]
596
597 expected_slots = [
598 ref_permlane(False, init_vals, old_vals, ID_S1, ID_S2, ALL64),
599 ref_permlane(True, init_vals, old_vals, ID_S1, ID_S2, ALL64),
600 ref_permlane(False, init_vals, old_vals, ASYM_S1, ASYM_S2, ALL64),
601 ref_permlane(True, init_vals, old_vals, REV16_S1, REV16_S2, ALL64),
602 ref_permlane(True, init_vals, old_vals, 0x64206420, 0xBA98BA98, exec_active_only),
603 ref_permlane(False, updated_fi1, old_vals, 0, 0, exec_no_0_32, fi=1, bound_ctrl=0),
604 ref_permlane(True, updated_fi1, old_vals, 0, 0, exec_no_0_32, fi=1, bound_ctrl=1),
605 ]
606
607 for subgroup_size in (64, 32):
608 with self.subTest(subgroup_size=subgroup_size):
609 flat = run_cs(f"cs_w64_permlane_sg{subgroup_size}", lines, 64, subgroup_size,
610 init_inputs=init_vals, out_slots=7)
611 for slot, want in enumerate(expected_slots):
612 got = flat[slot * 64:(slot + 1) * 64]
613 self.assertEqual(got, want, f"subgroup={subgroup_size}, slot={slot}")
614
615 def test_wave64_destination_aliasing_v0_and_v1(self):
616 for subgroup_size in (64, 32):
617 with self.subTest(subgroup_size=subgroup_size):
618 got = run_cs(f"cs_w64_permlane_alias_sg{subgroup_size}", [
619 "s_mov_b64 exec, -1",
620 "v_lshlrev_b32_e32 v21, 2, v0",
621 "v_add_nc_u32_e32 v1, 500, v0",
622 f"s_mov_b32 s4, {PAIR_SWAP_S1:#x}",
623 f"s_mov_b32 s5, {PAIR_SWAP_S2:#x}",
624 "v_permlane16_b32 v1, v1, s4, s5",
625 "v_permlanex16_b32 v0, v0, s4, s5",
626 "buffer_store_dword v1, v21, s[0:3], 0 offen",
627 f"buffer_store_dword v0, v21, s[0:3], 0 offen offset:{4 * 64}",
628 ], 64, subgroup_size, out_slots=2)
629 self.assertEqual(
630 got[:64],
631 ref_permlane(False, [500 + l for l in range(64)], [0] * 64, PAIR_SWAP_S1, PAIR_SWAP_S2, ALL64),
632 )
633 self.assertEqual(
634 got[64:],
635 ref_permlane(True, list(range(64)), list(range(64)), PAIR_SWAP_S1, PAIR_SWAP_S2, ALL64),
636 )
637
638 def test_wave64_partial_wave_40_lanes(self):
639 # 40 threads in a 64-wide subgroup: lanes 32..39 exist in quarter [32..47]; lanes 40..63 do not.
640 # Active lanes 0..31 run v_permlanex16_b32 across [0..15] <-> [16..31], and lanes 32..39 run
641 # v_permlane16_b32 within [32..39]; inactive lanes 32..39 on permlanex16 discard UNDEF from [48..63].
642 exec_low32 = 0x00000000FFFFFFFF
643 got = run_cs("cs_w64_partial40_permlane", [
644 "s_mov_b64 exec, -1",
645 "v_add_nc_u32_e32 v1, 200, v0",
646 f"v_or_b32_e32 v2, {OLD_SENTINEL:#x}, v0",
647 f"v_or_b32_e32 v3, {OLD_SENTINEL:#x}, v0",
648 "v_permlane16_b32 v2, v1, 0x32107654, 0x32107654",
649 *exec_mask_lines(exec_low32, 64),
650 "v_permlanex16_b32 v3, v1, 0x01234567, 0x89abcdef",
651 *restore_exec_lines(64),
652 *store_slots_lines(["v2", "v3"], 40),
653 ], 40, 64, out_slots=2)
654 vals64 = [200 + l for l in range(40)] + [0] * 24
655 old64 = [OLD_SENTINEL | l for l in range(40)] + [0] * 24
656 self.assertEqual(got[:40], ref_permlane(False, vals64, old64, 0x32107654, 0x32107654, ALL64)[:40])
657 self.assertEqual(got[40:], ref_permlane(True, vals64, old64, REV8_S1, REV8_S2, exec_low32)[:40])
658
659
660class EmulationAndFindingTests(unittest.TestCase):
661 """Translation / structural SPIR-V checks for --wave64-emulate and documented op_sel finding."""
662
663 def test_wave64_emulate_lowers_permlane_through_x_buf_without_subgroup_ops(self):
664 base = [
665 "s_mov_b64 exec, -1",
666 "v_add_nc_u32_e32 v1, 100, v0",
667 f"s_mov_b32 s4, {ID_S1:#x}",
668 f"s_mov_b32 s5, {ID_S2:#x}",
669 ]
670 tail = [
671 "v_lshlrev_b32_e32 v21, 2, v0",
672 "buffer_store_dword v2, v21, s[0:3], 0 offen",
673 ]
674 spv_16, gen_16 = translate_cs("cs_w64_emu_perm16", base + ["v_permlane16_b32 v2, v1, s4, s5"] + tail,
675 64, emulate=True)
676 spv_x16, gen_x16 = translate_cs("cs_w64_emu_permx16", base + ["v_permlanex16_b32 v2, v1, s4, s5"] + tail,
677 64, emulate=True)
678 for spv, gen in ((spv_16, gen_16), (spv_x16, gen_x16)):
679 self.assertTrue(gen.wave64 and gen.emulate)
680 self.assertNotIn("OpGroupNonUniform", spv)
681 self.assertNotIn("%sg_lane", spv)
682 self.assertIn("%x_buf = OpVariable", spv)
683 self.assertGreaterEqual(spv.count("OpControlBarrier"), 2)
684 # Nibble extraction (width = 4) and 16-lane half mask (0xFFFFFFF0)
685 self.assertRegex(spv, r"OpBitFieldUExtract %uint %\w+ %\w+ %c4\b")
686 self.assertIn("OpBitwiseAnd %uint %", spv)
687 self.assertIn("%cfffffff0", spv)
688 # spirv_mini_interp.py deliberately rejects the emulated Workgroup/loop scheduler.
689 with self.assertRaises(si.UnsupportedConstruct):
690 si.run_workgroup(
691 spv, 64, 32,
692 inputs_for=lambda i: {"%wg_id": (0, 0, 0), "%local_id": (i, 0, 0), "%sg_lane": i % 32},
693 push_constants=VSHARP + [0] * 28, memory={},
694 )
695
696 # v_permlanex16_b32 XORs the masked half base with 16 (%c10); v_permlane16_b32 does not.
697 xor16_pat = r"OpBitwiseAnd %uint %\w+ %cfffffff0\n\s*%\w+ = OpBitwiseXor %uint %\w+ %c10\b"
698 self.assertIsNone(re.search(xor16_pat, spv_16))
699 self.assertIsNotNone(re.search(xor16_pat, spv_x16))
700
701 # Wave32 shaders are unaffected by WAVE64_EMULATE=True.
702 w32_lines = ["v_permlanex16_b32 v2, v0, 0x76543210, 0xfedcba98",
703 "v_lshlrev_b32_e32 v21, 2, v0", "buffer_store_dword v2, v21, s[0:3], 0 offen"]
704 spv_w32_plain, _ = translate_cs("cs_w32_emu_nop", w32_lines, 32, emulate=False)
705 spv_w32_emu, gen_w32_emu = translate_cs("cs_w32_emu_nop", w32_lines, 32, emulate=True)
706 self.assertFalse(gen_w32_emu.wave64 or gen_w32_emu.emulate)
707 self.assertEqual(spv_w32_plain, spv_w32_emu)
708
709 def test_op_sel_fi0_translates_cleanly_while_inactive_src_handling_is_excluded(self):
710 # Documented finding (tools/rdna2spirv.py lines 4608-4632): op_sel:[0,0] and op_sel:[0,1]
711 # are accepted by shader_ir/rdna2spirv without raising Unsupported, and lower to
712 # OpGroupNonUniformShuffle without inspecting mods or source %active; inactive-source fi=0
713 # value assertions stay excluded from Wave32ExecutionTests / Wave64ExecutionTests.
714 for op in ("v_permlane16_b32", "v_permlanex16_b32"):
715 for opsel in ("op_sel:[0,0]", "op_sel:[0,1]"):
716 with self.subTest(op=op, opsel=opsel):
717 spv, gen = translate_cs("cs_w32_opsel_fi0", [
718 "v_mov_b32_e32 v1, v0",
719 "s_mov_b32 exec_lo, 0xfffffffe",
720 f"{op} v2, v1, 0, 0 {opsel}",
721 "s_mov_b32 exec_lo, -1",
722 "v_lshlrev_b32_e32 v21, 2, v0",
723 "buffer_store_dword v2, v21, s[0:3], 0 offen",
724 ], 32)
725 self.assertFalse(gen.wave64)
726 self.assertIn("OpGroupNonUniformShuffle %uint %c3", spv)
727 self.assertRegex(spv, r"OpBitFieldUExtract %uint %\w+ %\w+ %c4\b")
728
729
730class NegativeControls(unittest.TestCase):
731 """Sabotage the translated SPIR-V like a translator regression; multi-lane execution must detect it."""
732
733 def _run(self, spv: str, threads: int, subgroup_size: int) -> list[int]:
734 mem = _Heap()
735 si.run_workgroup(
736 spv, threads, subgroup_size,
737 inputs_for=lambda i: {"%wg_id": (0, 0, 0), "%local_id": (i, 0, 0), "%sg_lane": i % subgroup_size},
738 push_constants=VSHARP + [0] * 28,
739 memory=mem,
740 )
741 return [mem.get(4 * k) for k in range(threads)]
742
743 def test_sabotage_permlanex16_xor16_dropped(self):
744 spv, _ = translate_cs("cs_w64_neg_x16", [
745 "s_mov_b64 exec, -1",
746 "v_add_nc_u32_e32 v1, 100, v0",
747 f"v_permlanex16_b32 v2, v1, {ID_S1:#x}, {ID_S2:#x}",
748 "v_lshlrev_b32_e32 v21, 2, v0",
749 "buffer_store_dword v2, v21, s[0:3], 0 offen",
750 ], 64)
751 want = ref_permlane(True, [100 + l for l in range(64)], [0] * 64, ID_S1, ID_S2, ALL64)
752 self.assertEqual(self._run(spv, 64, 64), want)
753
754 bad, n = re.subn(r"(%\w+) = OpBitwiseXor %uint (%\w+) %c10\b", r"\1 = OpCopyObject %uint \2", spv)
755 self.assertEqual(n, 1)
756 got_bad = self._run(bad, 64, 64)
757 self.assertNotEqual(got_bad, want)
758 self.assertEqual(got_bad, [100 + l for l in range(64)]) # collapsed to permlane16
759
760 def test_sabotage_half_base_dropped_or_shuffle_removed(self):
761 spv, _ = translate_cs("cs_w32_neg_perm16", [
762 "v_add_nc_u32_e32 v1, 200, v0",
763 f"v_or_b32_e32 v2, {OLD_SENTINEL:#x}, v0",
764 f"s_mov_b32 exec_lo, {0x0F550F55:#x}",
765 "s_mov_b32 s4, 0x64206420",
766 "s_mov_b32 s5, 0xba98ba98",
767 "v_permlane16_b32 v2, v1, s4, s5",
768 "s_mov_b32 exec_lo, -1",
769 "v_lshlrev_b32_e32 v21, 2, v0",
770 "buffer_store_dword v2, v21, s[0:3], 0 offen",
771 ], 32)
772 want = ref_permlane(False, [200 + l for l in range(32)], [OLD_SENTINEL | l for l in range(32)],
773 0x64206420, 0xBA98BA98, 0x0F550F55)
774 self.assertEqual(self._run(spv, 32, 32), want)
775
776 # 1. Dropping the 0xFFFFFFF0 half-base mask sends lanes 16..31 into [0..15].
777 bad_half, n1 = re.subn(r"OpBitwiseAnd %uint (%\w+) %cfffffff0\b", r"OpBitwiseAnd %uint \1 %c0", spv)
778 self.assertEqual(n1, 1)
779 self.assertNotEqual(self._run(bad_half, 32, 32), want)
780
781 # 2. Swapping the hi8 OpSelect arms swaps s1 (lanes 0..7) and s2 (lanes 8..15).
782 bad_sel, n2 = re.subn(
783 r"(%\w+ = OpUGreaterThanEqual %bool %\w+ %c8\n(?:.*\n){0,5}?\s*%\w+ = OpSelect %uint %\w+ )(%\w+) (%\w+)",
784 r"\1\3 \2",
785 spv,
786 )
787 self.assertEqual(n2, 1)
788 self.assertNotEqual(self._run(bad_sel, 32, 32), want)
789
790 # 3. Replacing OpGroupNonUniformShuffle with OpCopyObject turns permute into own-lane copy.
791 bad_shuf, n3 = re.subn(
792 r"(%\w+) = OpGroupNonUniformShuffle %uint %c3 (%\w+) %\w+",
793 r"\1 = OpCopyObject %uint \2",
794 spv,
795 )
796 self.assertEqual(n3, 1)
797 self.assertNotEqual(self._run(bad_shuf, 32, 32), want)
798
799 # 4. Dropping the destination EXEC OpSelect overwrites inactive destination lanes.
800 bad_exec, n4 = re.subn(
801 r"(%\w+ = OpGroupNonUniformShuffle %uint %c3 %\w+ %\w+\n(?:.*\n){0,4}?\s*"
802 r"%\w+ = OpLoad %bool %active\n\s*"
803 r"(%\w+) = OpSelect %uint %\w+ (%\w+)) %\w+",
804 r"\1 \3",
805 spv,
806 )
807 self.assertEqual(n4, 1)
808 got_bad_exec = self._run(bad_exec, 32, 32)
809 self.assertNotEqual(got_bad_exec, want)
810 self.assertNotEqual(got_bad_exec[1], OLD_SENTINEL | 1)
811
812
813if __name__ == "__main__":
814 unittest.main()
diff --git a/tests/semantic/test_valu_rcp_fdiv.py b/tests/semantic/test_valu_rcp_fdiv.py
new file mode 100644
index 000000000..e7f649ae0
--- /dev/null
+++ b/tests/semantic/test_valu_rcp_fdiv.py
@@ -0,0 +1,824 @@
1"""Semantic value tests for OpFDiv in spirv_mini_interp and RDNA2 reciprocal VALU ops:
2 - OpFDiv (scalar %float and vector %v2float) directly in tests/semantic/spirv_mini_interp.py
3 - v_rcp_f32: D.f32 = 1.0 / S0.f32
4 - v_rcp_iflag_f32: D.f32 = 1.0 / S0.f32 (no FP flags)
5 - v_rcp_f16: D.f16 = 1.0 / S0.f16 (preserves the untouched 16-bit half of D)
6
7Per the SPIR-V specification and tests/semantic/README.md, OpFDiv by zero (+-0.0) is undefined and raises
8spirv_mini_interp.UnsupportedConstruct("OpFDiv by zero (undefined in SPIR-V)"). Accordingly, finite non-zero,
9subnormal, +-inf, and NaN operands are value-checked against independent Fraction-based binary32/binary16
10oracles, while +-0.0 divisors/inputs are verified to raise UnsupportedConstruct.
11
12NaN payloads are not pinned because values passing through Python floats lose exact NaN payload bits; NaN
13results are asserted as binary32/binary16 NaNs. Standard library only; hand-written RDNA2 listings only.
14"""
15from fractions import Fraction
16import gc
17import itertools
18import math
19import os
20import re
21import struct
22import sys
23import tempfile
24import unittest
25import warnings
26
27HERE = os.path.dirname(os.path.abspath(__file__))
28ROOT = os.path.dirname(os.path.dirname(HERE))
29TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools")
30
31sys.dont_write_bytecode = True
32if TOOLS_DIR not in sys.path:
33 sys.path.insert(0, TOOLS_DIR)
34if HERE not in sys.path:
35 sys.path.insert(0, HERE)
36
37import rdna2spirv # noqa: E402
38import spirv_mini_interp as si # noqa: E402
39
40MASK32 = 0xFFFFFFFF
41STUB_DXBC = b"DXBC" + bytes(24) + struct.pack("<I", 0) + bytes(4)
42VSHARP = [0, 0, 0xFFFFFFFF, 0x31016FAC]
43OLD = 0xBEEF1234
44
45# Representative binary16 encodings.
46H_POS_ZERO = 0x0000
47H_NEG_ZERO = 0x8000
48H_SUB_MIN = 0x0001 # 2^-24
49H_NEG_SUB_MIN = 0x8001 # -2^-24
50H_SUB_2M16 = 0x0100 # 2^-16 (1/x = 65536 >= 65520 -> +inf)
51H_SUB_2M15 = 0x0200 # 2^-15 (1/x = 32768 = 0x7800)
52H_SUB_MAX = 0x03FF # 1023 * 2^-24
53H_NORM_MIN = 0x0400 # 2^-14 (1/x = 16384 = 0x7400)
54H_0P25 = 0x3400 # 0.25
55H_NEG_0P25 = 0xB400 # -0.25
56H_0P5 = 0x3800 # 0.5
57H_NEG_0P5 = 0xB800 # -0.5
58H_0P75 = 0x3A00 # 0.75
59H_1P0 = 0x3C00 # 1.0
60H_NEG_1P0 = 0xBC00 # -1.0
61H_NEG_1P25 = 0xBD00 # -1.25
62H_1P5 = 0x3E00 # 1.5
63H_2P0 = 0x4000 # 2.0
64H_NEG_2P0 = 0xC000 # -2.0
65H_3P0 = 0x4200 # 3.0
66H_NEG_3P0 = 0xC200 # -3.0
67H_4P0 = 0x4400 # 4.0
68H_NEG_4P0 = 0xC400 # -4.0
69H_8P0 = 0x4800 # 8.0
70H_16P0 = 0x4C00 # 16.0
71H_1024 = 0x6400 # 1024.0
72H_MAX = 0x7BFF # 65504.0
73H_NEG_MAX = 0xFBFF # -65504.0
74H_POS_INF = 0x7C00 # +inf
75H_NEG_INF = 0xFC00 # -inf
76H_QNAN = 0x7E01 # +qNaN
77H_NEG_QNAN = 0xFE01 # -qNaN
78H_SNAN = 0x7C01 # +sNaN
79
80
81def f32_bits(x: float) -> int:
82 try:
83 return struct.unpack("<I", struct.pack("<f", x))[0]
84 except OverflowError:
85 return 0x7F800000 if x > 0 else 0xFF800000
86
87
88def is_f32_nan_bits(bits: int) -> bool:
89 return (bits & 0x7F800000) == 0x7F800000 and (bits & 0x007FFFFF) != 0
90
91
92def is_f16_nan(half: int) -> bool:
93 return (half & 0x7FFF) > 0x7C00
94
95
96def merge_half(old: int, half: int, dst_hi: int) -> int:
97 h = half & 0xFFFF
98 return ((h << 16) | (old & 0xFFFF)) if dst_hi else ((old & 0xFFFF0000) | h)
99
100
101# -----------------------------------------------------------------------------
102# Independent Exact-Rational Binary32 / Binary16 Reference Oracles
103# -----------------------------------------------------------------------------
104
105def _rne_int(q: Fraction) -> int:
106 n = q.numerator // q.denominator
107 rem = q - n
108 if rem > Fraction(1, 2) or (rem == Fraction(1, 2) and (n & 1)):
109 n += 1
110 return n
111
112
113def f32_to_fraction(bits: int) -> Fraction:
114 bits &= MASK32
115 sign = -1 if (bits >> 31) else 1
116 exp = (bits >> 23) & 0xFF
117 man = bits & 0x7FFFFF
118 if exp == 0xFF:
119 raise ValueError(f"non-finite f32 bits {bits:#010x}")
120 if exp == 0:
121 return sign * Fraction(man, 1 << 23) * Fraction(2) ** -126
122 return sign * Fraction((1 << 23) | man, 1 << 23) * Fraction(2) ** (exp - 127)
123
124
125def round_fraction_to_f32(val: Fraction, neg_zero: bool = False) -> int:
126 if val == 0:
127 return 0x80000000 if neg_zero else 0x00000000
128 sign = 0x80000000 if val < 0 else 0
129 a = abs(val)
130 e = a.numerator.bit_length() - a.denominator.bit_length()
131 if Fraction(2) ** e > a:
132 e -= 1
133 if e < -126:
134 n = _rne_int(a / Fraction(2) ** -149)
135 if n == 0:
136 return sign
137 if n < (1 << 23):
138 return sign | n
139 return sign | (1 << 23)
140 n = _rne_int(a / Fraction(2) ** (e - 23))
141 if n == (1 << 24):
142 n >>= 1
143 e += 1
144 if e > 127:
145 return sign | 0x7F800000
146 return sign | ((e + 127) << 23) | (n & 0x7FFFFF)
147
148
149def f16_to_fraction(half: int) -> Fraction:
150 half &= 0xFFFF
151 sign = -1 if (half >> 15) else 1
152 exp = (half >> 10) & 0x1F
153 man = half & 0x3FF
154 if exp == 0x1F:
155 raise ValueError(f"non-finite f16 bits {half:#06x}")
156 if exp == 0:
157 return sign * Fraction(man, 1 << 10) * Fraction(2) ** -14
158 return sign * Fraction((1 << 10) | man, 1 << 10) * Fraction(2) ** (exp - 15)
159
160
161def round_fraction_to_f16(val: Fraction, neg_zero: bool = False) -> int:
162 if val == 0:
163 return 0x8000 if neg_zero else 0x0000
164 sign = 0x8000 if val < 0 else 0
165 a = abs(val)
166 e = a.numerator.bit_length() - a.denominator.bit_length()
167 if Fraction(2) ** e > a:
168 e -= 1
169 if e < -14:
170 n = _rne_int(a / Fraction(2) ** -24)
171 return sign | n
172 n = _rne_int(a / Fraction(2) ** (e - 10))
173 if n == (1 << 11):
174 n >>= 1
175 e += 1
176 if e > 15:
177 return sign | 0x7C00
178 return sign | ((e + 15) << 10) | (n & 0x3FF)
179
180
181def ref_rcp_f32(x_bits: int, *, scale: Fraction = Fraction(1), clamp: bool = False) -> int:
182 """Reference oracle for non-zero f32 reciprocal (with optional output scale/clamp)."""
183 bits = x_bits & MASK32
184 sign = bits & 0x80000000
185 absu = bits & 0x7FFFFFFF
186 if absu == 0:
187 raise ValueError("division by zero is undefined in SPIR-V")
188 if absu > 0x7F800000:
189 if clamp:
190 raise ValueError("clamp of NaN is undefined in GLSL.std.450")
191 return 0x7FC00000
192 if absu == 0x7F800000:
193 # 1 / (+-inf) = +-0.0; omod preserves sign of zero, clamp orders -0 below +0 -> +0.
194 return 0 if clamp else sign
195 # Match OpFDiv(1, x) rounded to binary32 before clamp_mods (scale, then FClamp [0, 1]).
196 r_bits = round_fraction_to_f32(Fraction(1) / f32_to_fraction(bits))
197 if (r_bits & 0x7FFFFFFF) == 0x7F800000:
198 r_sign = r_bits & 0x80000000
199 if clamp:
200 return 0 if r_sign else 0x3F800000
201 return r_bits
202 val = f32_to_fraction(r_bits) * scale
203 if clamp:
204 if val <= 0:
205 return 0x00000000
206 if val >= 1:
207 return 0x3F800000
208 return round_fraction_to_f32(val)
209
210
211def ref_rcp_f16(h_bits: int, *, scale: Fraction = Fraction(1), clamp: bool = False) -> int:
212 """Reference oracle for non-zero f16 reciprocal (f32 OpFDiv + clamp_mods + f16_bits)."""
213 h = h_bits & 0xFFFF
214 sign = (h & 0x8000) << 16
215 absh = h & 0x7FFF
216 if absh == 0:
217 raise ValueError("division by zero is undefined in SPIR-V")
218 if absh > 0x7C00:
219 if clamp:
220 raise ValueError("clamp of NaN is undefined in GLSL.std.450")
221 return (h & 0x8000) | 0x7E00
222 if absh == 0x7C00:
223 return 0 if clamp else (h & 0x8000)
224 # Widening f16 -> f32 is exact, then f32 OpFDiv + omod/clamp, then f16 nearest-even narrowing.
225 r_bits = round_fraction_to_f32(Fraction(1) / f16_to_fraction(h))
226 r_sign = r_bits & 0x80000000
227 if (r_bits & 0x7FFFFFFF) == 0x7F800000:
228 if clamp:
229 return 0 if r_sign else 0x3C00
230 return (r_sign >> 16) | 0x7C00
231 val = f32_to_fraction(r_bits) * scale
232 if clamp:
233 if val <= 0:
234 return 0x0000
235 if val >= 1:
236 return 0x3C00
237 r_f32 = round_fraction_to_f32(val, neg_zero=bool(sign))
238 return round_fraction_to_f16(f32_to_fraction(r_f32), neg_zero=bool(r_f32 & 0x80000000))
239
240
241RCP_F32_HAND_WORKED = (
242 ("pos_one", 0x3F800000, 0x3F800000),
243 ("neg_one", 0xBF800000, 0xBF800000),
244 ("pos_two", 0x40000000, 0x3F000000),
245 ("neg_two", 0xC0000000, 0xBF000000),
246 ("pos_four", 0x40800000, 0x3E800000),
247 ("neg_quarter", 0xBE800000, 0xC0800000),
248 ("pos_2p20", 0x49800000, 0x35800000),
249 ("neg_2pm20", 0xB5800000, 0xC9800000),
250 ("pos_1p5", 0x3FC00000, 0x3F2AAAAB),
251 ("neg_3p0", 0xC0400000, 0xBEAAAAAB),
252 ("pos_0p3", 0x3E99999A, 0x40555555),
253 ("subnorm_2m128_to_inf", 0x00200000, 0x7F800000),
254 ("neg_subnorm_min_to_ninf", 0x80000001, 0xFF800000),
255 ("2p127_to_subnorm", 0x7F000000, 0x00400000),
256 ("pos_inf", 0x7F800000, 0x00000000),
257 ("neg_inf", 0xFF800000, 0x80000000),
258)
259
260RCP_F16_HAND_WORKED = (
261 ("pos_one", H_1P0, H_1P0),
262 ("neg_one", H_NEG_1P0, H_NEG_1P0),
263 ("pos_two", H_2P0, H_0P5),
264 ("neg_two", H_NEG_2P0, H_NEG_0P5),
265 ("pos_four", H_4P0, H_0P25),
266 ("neg_quarter", H_NEG_0P25, H_NEG_4P0),
267 ("pos_1p5", H_1P5, 0x3955),
268 ("pos_3p0", H_3P0, 0x3555),
269 ("neg_3p0", H_NEG_3P0, 0xB555),
270 ("sub_min_overflow", H_SUB_MIN, H_POS_INF),
271 ("neg_sub_min_overflow", H_NEG_SUB_MIN, H_NEG_INF),
272 ("sub_2m16_overflow", H_SUB_2M16, H_POS_INF),
273 ("sub_2m15", H_SUB_2M15, 0x7800),
274 ("sub_max", H_SUB_MAX, 0x7401),
275 ("norm_min", H_NORM_MIN, 0x7400),
276 ("f16_max", H_MAX, 0x0100),
277 ("neg_f16_max", H_NEG_MAX, 0x8100),
278 ("pos_inf", H_POS_INF, H_POS_ZERO),
279 ("neg_inf", H_NEG_INF, H_NEG_ZERO),
280)
281
282
283# -----------------------------------------------------------------------------
284# Translation & Execution Helpers
285# -----------------------------------------------------------------------------
286
287_TMP_DIR = None
288_PS_PATH = None
289_CS_PATH = None
290_CS_FSSM = None
291
292
293def _make_fssm(rsrc2: int, group: tuple[int, int, int]) -> bytes:
294 header = bytearray(0x148)
295 struct.pack_into("<4I", header, 0x138, rsrc2, *group)
296 return bytes(header)
297
298
299def setUpModule():
300 global _TMP_DIR, _PS_PATH, _CS_PATH, _CS_FSSM
301 _TMP_DIR = tempfile.TemporaryDirectory()
302 disasm_dir = os.path.join(_TMP_DIR.name, "disasm")
303 fssm_dir = os.path.join(_TMP_DIR.name, "fssm")
304 os.mkdir(disasm_dir)
305 os.mkdir(fssm_dir)
306 _PS_PATH = os.path.join(disasm_dir, "ps_valu_rcp_fdiv.s")
307 _CS_PATH = os.path.join(disasm_dir, "cs_valu_rcp_fdiv.s")
308 _CS_FSSM = os.path.join(fssm_dir, "cs_valu_rcp_fdiv.fssm")
309 with open(os.path.join(_TMP_DIR.name, "ps_valu_rcp_fdiv.dxbc"), "wb") as f:
310 f.write(STUB_DXBC)
311
312
313def tearDownModule():
314 global _TMP_DIR, _PS_PATH, _CS_PATH, _CS_FSSM
315 if _TMP_DIR is not None:
316 gc.collect()
317 _TMP_DIR.cleanup()
318 _TMP_DIR = None
319 _PS_PATH = None
320 _CS_PATH = None
321 _CS_FSSM = None
322
323
324def translate_ps(lines: list[str]) -> str:
325 if _TMP_DIR is None:
326 setUpModule()
327 asm = (
328 "; test_valu_rcp_fdiv\n"
329 + "".join(f"\t{ln}\n" for ln in lines)
330 + "\texp mrt0 v0, v0, v0, v0 done vm\n"
331 + "\ts_endpgm\n"
332 )
333 with open(_PS_PATH, "w", encoding="utf-8", newline="") as f:
334 f.write(asm)
335 with warnings.catch_warnings():
336 warnings.simplefilter("ignore", ResourceWarning)
337 spv = rdna2spirv.translate(_PS_PATH)
338 gc.collect()
339 return spv
340
341
342def run_ps_v0(lines: list[str]) -> int:
343 return si.run_fragment(translate_ps(lines))["%out_mrt0"][0]
344
345
346def run_op(line: str, v1: int, old: int = OLD, s4: int = 0) -> int:
347 return run_ps_v0([
348 f"s_mov_b32 s4, {s4:#x}",
349 f"v_mov_b32 v1, {v1:#x}",
350 f"v_mov_b32 v0, {old:#x}",
351 line,
352 ])
353
354
355def run_cs(lines: list[str], group_size: int, subgroup_size: int, memory: dict[int, int]) -> dict[int, int]:
356 if _TMP_DIR is None:
357 setUpModule()
358 with open(_CS_FSSM, "wb") as f:
359 f.write(_make_fssm(0x0088, (group_size, 1, 1)))
360 asm = "; test_cs_valu_rcp_fdiv\n" + "".join(f"\t{ln}\n" for ln in lines) + "\ts_endpgm\n"
361 with open(_CS_PATH, "w", encoding="utf-8", newline="") as f:
362 f.write(asm)
363 with warnings.catch_warnings():
364 warnings.simplefilter("ignore", ResourceWarning)
365 spv = rdna2spirv.translate(_CS_PATH)
366 gc.collect()
367 return si.run_workgroup(
368 spv, group_size, subgroup_size,
369 inputs_for=lambda i: {"%wg_id": (0, 0, 0), "%local_id": (i, 0, 0)},
370 push_constants=VSHARP + [0] * 28,
371 memory=memory,
372 )
373
374
375# -----------------------------------------------------------------------------
376# 1. Reference Oracle Self-Tests
377# -----------------------------------------------------------------------------
378
379class OracleSelfTests(unittest.TestCase):
380 def test_hand_worked_rcp_f32_and_f16_match_fraction_oracles(self):
381 for name, x_bits, want in RCP_F32_HAND_WORKED:
382 with self.subTest(kind="f32", name=name):
383 self.assertEqual(ref_rcp_f32(x_bits), want)
384 for name, h_bits, want in RCP_F16_HAND_WORKED:
385 with self.subTest(kind="f16", name=name):
386 self.assertEqual(ref_rcp_f16(h_bits), want)
387
388
389# -----------------------------------------------------------------------------
390# 2. Direct OpFDiv Unit Tests in spirv_mini_interp.py
391# -----------------------------------------------------------------------------
392
393FDIV_HEADER = """\
394OpCapability Shader
395OpMemoryModel Logical GLSL450
396OpEntryPoint Fragment %main "main" %out
397%void = OpTypeVoid
398%fn = OpTypeFunction %void
399%uint = OpTypeInt 32 0
400%float = OpTypeFloat 32
401%v2float = OpTypeVector %float 2
402%_ptr_Output_uint = OpTypePointer Output %uint
403%out = OpVariable %_ptr_Output_uint Output
404%_ptr_PC = OpTypePointer PushConstant %uint
405%pc = OpVariable %_ptr_PC PushConstant
406%c0 = OpConstant %uint 0
407%c1 = OpConstant %uint 1
408%c2 = OpConstant %uint 2
409%c3 = OpConstant %uint 3
410%f0 = OpConstant %float 0
411%f0p5 = OpConstant %float 0.5
412%f1 = OpConstant %float 1
413%f2 = OpConstant %float 2
414%f3 = OpConstant %float 3
415%f4 = OpConstant %float 4
416%f255 = OpConstant %float 255
417%u_neg0 = OpConstant %uint 2147483648
418%u_inf = OpConstant %uint 2139095040
419%u_ninf = OpConstant %uint 4286578688
420%u_qnan = OpConstant %uint 2143289344
421%u_snan = OpConstant %uint 2139095041
422%u_fltmax = OpConstant %uint 2139095039
423%u_nfltmax = OpConstant %uint 4286578687
424%main = OpFunction %void None %fn
425%entry = OpLabel
426%fm0 = OpBitcast %float %u_neg0
427%inf = OpBitcast %float %u_inf
428%ninf = OpBitcast %float %u_ninf
429%qnan = OpBitcast %float %u_qnan
430%snan = OpBitcast %float %u_snan
431%fltmax = OpBitcast %float %u_fltmax
432%nfltmax = OpBitcast %float %u_nfltmax
433%fm2 = OpFNegate %float %f2
434%fm3 = OpFNegate %float %f3
435%fm1 = OpFNegate %float %f1
436"""
437FDIV_FOOTER = "OpReturn\nOpFunctionEnd\n"
438
439
440def run_fdiv_scalar(num: str, den: str) -> int:
441 text = (
442 FDIV_HEADER
443 + f"%r = OpFDiv %float {num} {den}\n"
444 + "%res = OpBitcast %uint %r\n"
445 + "OpStore %out %res\n"
446 + FDIV_FOOTER
447 )
448 return si.run_fragment(text)["%out"][0]
449
450
451def run_fdiv_vec2(n0: str, n1: str, d0: str, d1: str) -> tuple[int, int]:
452 hdr = FDIV_HEADER.replace(
453 'OpEntryPoint Fragment %main "main" %out',
454 'OpEntryPoint Fragment %main "main" %out %out1',
455 ).replace(
456 "%out = OpVariable %_ptr_Output_uint Output",
457 "%out = OpVariable %_ptr_Output_uint Output\n%out1 = OpVariable %_ptr_Output_uint Output",
458 )
459 body = (
460 f"%vn = OpCompositeConstruct %v2float {n0} {n1}\n"
461 + f"%vd = OpCompositeConstruct %v2float {d0} {d1}\n"
462 + "%vr = OpFDiv %v2float %vn %vd\n"
463 + "%r0 = OpCompositeExtract %float %vr 0\n"
464 + "%r1 = OpCompositeExtract %float %vr 1\n"
465 + "%b0 = OpBitcast %uint %r0\n"
466 + "%b1 = OpBitcast %uint %r1\n"
467 + "OpStore %out %b0\n"
468 + "OpStore %out1 %b1\n"
469 )
470 res = si.run_fragment(hdr + body + FDIV_FOOTER)
471 return res["%out"][0], res["%out1"][0]
472
473
474class OpFDivInterpreterTests(unittest.TestCase):
475 def test_scalar_finite_signed_zero_inf_and_overflow(self):
476 cases = (
477 ("%f1", "%f4", f32_bits(0.25)),
478 ("%fm3", "%f2", f32_bits(-1.5)),
479 ("%f3", "%f255", 0x3C40C0C1),
480 # Signed zero dividends keep exact IEEE sign rules.
481 ("%f0", "%f2", 0x00000000),
482 ("%f0", "%fm2", 0x80000000),
483 ("%fm0", "%f2", 0x80000000),
484 ("%fm0", "%fm2", 0x00000000),
485 # Division by +-inf -> +-0.0.
486 ("%f1", "%inf", 0x00000000),
487 ("%fm1", "%inf", 0x80000000),
488 ("%f1", "%ninf", 0x80000000),
489 ("%fm1", "%ninf", 0x00000000),
490 ("%f0", "%ninf", 0x80000000),
491 ("%fm0", "%inf", 0x80000000),
492 ("%fm0", "%ninf", 0x00000000),
493 # +-inf divided by finite non-zero -> +-inf.
494 ("%inf", "%f2", 0x7F800000),
495 ("%inf", "%fm2", 0xFF800000),
496 ("%ninf", "%f2", 0xFF800000),
497 ("%ninf", "%fm2", 0x7F800000),
498 # Binary32 overflow -> +-inf.
499 ("%fltmax", "%f0p5", 0x7F800000),
500 ("%nfltmax", "%f0p5", 0xFF800000),
501 )
502 for num, den, want in cases:
503 with self.subTest(num=num, den=den):
504 self.assertEqual(run_fdiv_scalar(num, den), want)
505
506 def test_scalar_inf_over_inf_and_nan_propagation(self):
507 nan_cases = (
508 ("%inf", "%inf"),
509 ("%inf", "%ninf"),
510 ("%ninf", "%inf"),
511 ("%ninf", "%ninf"),
512 ("%qnan", "%f2"),
513 ("%f2", "%qnan"),
514 ("%qnan", "%inf"),
515 ("%inf", "%qnan"),
516 ("%f0", "%qnan"),
517 ("%snan", "%f2"),
518 ("%f2", "%snan"),
519 )
520 for num, den in nan_cases:
521 with self.subTest(num=num, den=den):
522 got = run_fdiv_scalar(num, den)
523 self.assertTrue(is_f32_nan_bits(got), f"expected NaN for {num}/{den}, got {got:#010x}")
524
525 def test_vector_v2float_division(self):
526 self.assertEqual(run_fdiv_vec2("%f1", "%fm3", "%f4", "%fm2"), (f32_bits(0.25), f32_bits(1.5)))
527 self.assertEqual(run_fdiv_vec2("%f1", "%fm0", "%ninf", "%ninf"), (0x80000000, 0x00000000))
528 g0, g1 = run_fdiv_vec2("%f1", "%inf", "%ninf", "%ninf")
529 self.assertEqual(g0, 0x80000000)
530 self.assertTrue(is_f32_nan_bits(g1), f"expected NaN in lane 1, got {g1:#010x}")
531
532 def test_zero_divisor_and_non_float_are_rejected(self):
533 for num, den in (
534 ("%f1", "%f0"),
535 ("%f1", "%fm0"),
536 ("%fm1", "%f0"),
537 ("%fm1", "%fm0"),
538 ("%f0", "%f0"),
539 ("%fm0", "%fm0"),
540 ("%inf", "%f0"),
541 ("%qnan", "%f0"),
542 ("%qnan", "%fm0"),
543 ):
544 with self.subTest(num=num, den=den):
545 with self.assertRaises(si.UnsupportedConstruct):
546 run_fdiv_scalar(num, den)
547
548 for n0, n1, d0, d1 in (
549 ("%f1", "%f2", "%f0", "%f2"),
550 ("%f1", "%f2", "%f2", "%fm0"),
551 ):
552 with self.subTest(vec=(n0, n1, d0, d1)):
553 with self.assertRaises(si.UnsupportedConstruct):
554 run_fdiv_vec2(n0, n1, d0, d1)
555
556 with self.assertRaises(si.UnsupportedConstruct):
557 si.run_fragment(
558 FDIV_HEADER + "%res = OpFDiv %uint %c2 %c1\nOpStore %out %res\n" + FDIV_FOOTER
559 )
560
561
562# -----------------------------------------------------------------------------
563# 3. End-to-End v_rcp_f32 & v_rcp_iflag_f32 Value Tests
564# -----------------------------------------------------------------------------
565
566class RcpF32AndIflagExecutionTests(unittest.TestCase):
567 OPS = ("v_rcp_f32", "v_rcp_iflag_f32")
568
569 def test_hand_worked_and_edge_values_across_encodings(self):
570 for op in self.OPS:
571 for suffix in ("_e32", "_e64", ""):
572 for name, x_bits, want in RCP_F32_HAND_WORKED:
573 with self.subTest(op=op + suffix, case=name):
574 got = run_op(f"{op}{suffix} v0, v1", x_bits)
575 self.assertEqual(got, want)
576
577 def test_nan_inputs_preserve_nan(self):
578 for op in self.OPS:
579 for suffix in ("_e32", "_e64"):
580 for x_bits in (0x7FC00000, 0xFFC00001, 0x7F800001, 0xFF800001):
581 with self.subTest(op=op + suffix, x=hex(x_bits)):
582 got = run_op(f"{op}{suffix} v0, v1", x_bits)
583 self.assertTrue(is_f32_nan_bits(got), f"expected NaN, got {got:#010x}")
584
585 def test_zero_inputs_raise_unsupported_construct(self):
586 for op in self.OPS:
587 for suffix in ("_e32", "_e64"):
588 for x_bits in (0x00000000, 0x80000000):
589 with self.subTest(op=op + suffix, x=hex(x_bits)):
590 with self.assertRaises(si.UnsupportedConstruct):
591 run_op(f"{op}{suffix} v0, v1", x_bits)
592 with self.subTest(op=op, mod="-|0|"):
593 with self.assertRaises(si.UnsupportedConstruct):
594 run_op(f"{op}_e64 v0, -|0|", 0)
595
596 def test_vop3_output_and_source_modifiers(self):
597 cases = (
598 # (insn_suffix_and_src, v1_bits, scale, clamp)
599 ("v1 clamp", f32_bits(0.5), Fraction(1), True),
600 ("v1 clamp", f32_bits(-0.5), Fraction(1), True),
601 ("v1 clamp", f32_bits(4.0), Fraction(1), True),
602 ("v1 mul:2", f32_bits(4.0), Fraction(2), False),
603 ("v1 mul:2", f32_bits(-0.5), Fraction(2), False),
604 ("v1 mul:4", f32_bits(4.0), Fraction(4), False),
605 ("v1 mul:4", f32_bits(-2.0), Fraction(4), False),
606 ("v1 div:2", f32_bits(2.0), Fraction(1, 2), False),
607 ("v1 div:2", f32_bits(-0.5), Fraction(1, 2), False),
608 # omod applies before clamp: 1/0.5 * 0.5 = 1.0; 1/4.0 * 2 = 0.5; 1/0.5 * 2 -> clamped 1.0
609 ("v1 mul:2 clamp", f32_bits(0.5), Fraction(2), True),
610 ("v1 mul:2 clamp", f32_bits(4.0), Fraction(2), True),
611 ("v1 mul:2 clamp", f32_bits(-0.5), Fraction(2), True),
612 ("v1 clamp div:2", f32_bits(0.5), Fraction(1, 2), True),
613 ("v1 clamp div:2", f32_bits(-0.5), Fraction(1, 2), True),
614 )
615 for op in self.OPS:
616 for args, x_bits, scale, clamp in cases:
617 with self.subTest(op=op, args=args, x=hex(x_bits)):
618 got = run_op(f"{op}_e64 v0, {args}", x_bits)
619 want = ref_rcp_f32(x_bits, scale=scale, clamp=clamp)
620 self.assertEqual(got, want)
621
622 # Source modifiers (-v1, |v1|, -|v1|) alone and combined with output modifiers.
623 src_cases = (
624 ("-v1", f32_bits(2.0), f32_bits(-0.5)),
625 ("|v1|", f32_bits(-4.0), f32_bits(0.25)),
626 ("-|v1|", f32_bits(-2.0), f32_bits(-0.5)),
627 ("-|v1|", f32_bits(2.0), f32_bits(-0.5)),
628 ("-v1 clamp", f32_bits(-0.5), f32_bits(1.0)),
629 ("|v1| mul:2", f32_bits(-0.5), f32_bits(4.0)),
630 ("-|v1| mul:2 clamp", f32_bits(0.5), f32_bits(0.0)),
631 ("-|v1| div:2", f32_bits(-0.5), f32_bits(-1.0)),
632 )
633 for op in self.OPS:
634 for args, x_bits, want in src_cases:
635 with self.subTest(op=op, args=args, x=hex(x_bits)):
636 self.assertEqual(run_op(f"{op}_e64 v0, {args}", x_bits), want)
637
638 def test_inline_constants_literals_sgprs_and_aliasing(self):
639 for op in self.OPS:
640 # Inline float constants, VOP3 constant modifiers, and 32-bit literal.
641 self.assertEqual(run_op(f"{op}_e32 v0, 0.5", 0), f32_bits(2.0))
642 self.assertEqual(run_op(f"{op}_e32 v0, -0.5", 0), f32_bits(-2.0))
643 self.assertEqual(run_op(f"{op}_e32 v0, 4.0", 0), f32_bits(0.25))
644 self.assertEqual(run_op(f"{op}_e64 v0, -|2.0|", 0), f32_bits(-0.5))
645 self.assertEqual(run_op(f"{op}_e64 v0, neg(0x3f800000)", 0), f32_bits(-1.0))
646 self.assertEqual(run_op(f"{op}_e32 v0, 0x40400000", 0), 0x3EAAAAAB)
647
648 # SGPR source and modified SGPR source.
649 self.assertEqual(run_op(f"{op}_e32 v0, s4", 0, s4=f32_bits(-4.0)), f32_bits(-0.25))
650 self.assertEqual(run_op(f"{op}_e64 v0, |s4| mul:2", 0, s4=f32_bits(-4.0)), f32_bits(0.5))
651
652 # In-place aliasing: dst == src.
653 self.assertEqual(run_ps_v0(["v_mov_b32 v0, 0x40000000", f"{op}_e32 v0, v0"]), f32_bits(0.5))
654 self.assertEqual(run_ps_v0(["v_mov_b32 v0, 0xc0800000", f"{op}_e64 v0, -v0 mul:4"]), f32_bits(1.0))
655
656
657# -----------------------------------------------------------------------------
658# 4. End-to-End v_rcp_f16 Value Tests
659# -----------------------------------------------------------------------------
660
661class RcpF16ExecutionTests(unittest.TestCase):
662 def test_hand_worked_values_across_e32_e64_and_bare(self):
663 for suffix in ("_e32", "_e64", ""):
664 for name, h_bits, want_half in RCP_F16_HAND_WORKED:
665 with self.subTest(suffix=suffix, case=name):
666 got = run_op(f"v_rcp_f16{suffix} v0, v1", 0xCAFE0000 | h_bits)
667 self.assertEqual(got, merge_half(OLD, want_half, 0))
668
669 def test_nan_preserves_nan_and_other_half(self):
670 for suffix in ("_e32", "_e64"):
671 for h in (H_QNAN, H_NEG_QNAN, H_SNAN):
672 with self.subTest(suffix=suffix, h=hex(h)):
673 got = run_op(f"v_rcp_f16{suffix} v0, v1", 0xCAFE0000 | h)
674 self.assertEqual(got & 0xFFFF0000, OLD & 0xFFFF0000)
675 self.assertTrue(is_f16_nan(got & 0xFFFF), f"expected NaN in low half, got {got:#010x}")
676
677 def test_zero_inputs_raise_unsupported_construct(self):
678 for line, v1 in (
679 ("v_rcp_f16_e32 v0, v1", (H_1P0 << 16) | H_POS_ZERO),
680 ("v_rcp_f16_e32 v0, v1", (H_1P0 << 16) | H_NEG_ZERO),
681 ("v_rcp_f16_e64 v0, v1 op_sel:[1,0]", (H_POS_ZERO << 16) | H_1P0),
682 ("v_rcp_f16_e64 v0, v1 op_sel:[1,1]", (H_NEG_ZERO << 16) | H_1P0),
683 ):
684 with self.subTest(line=line, v1=hex(v1)):
685 with self.assertRaises(si.UnsupportedConstruct):
686 run_op(line, v1)
687
688 def test_op_sel_all_combinations(self):
689 # v1 = (hi: -4.0, lo: 0.5) -> rcp(hi) = -0.25, rcp(lo) = 2.0.
690 v1 = (H_NEG_4P0 << 16) | H_0P5
691 for src_hi, dst_hi in itertools.product((0, 1), repeat=2):
692 h_in = H_NEG_4P0 if src_hi else H_0P5
693 line = f"v_rcp_f16_e64 v0, v1 op_sel:[{src_hi},{dst_hi}]"
694 with self.subTest(line=line):
695 self.assertEqual(run_op(line, v1), merge_half(OLD, ref_rcp_f16(h_in), dst_hi))
696
697 def test_vop3_source_and_output_modifiers(self):
698 v1 = (H_NEG_0P5 << 16) | H_4P0
699 self.assertEqual(run_op("v_rcp_f16_e64 v0, -v1 op_sel:[0,0]", v1), merge_half(OLD, H_NEG_0P25, 0))
700 self.assertEqual(run_op("v_rcp_f16_e64 v0, |v1| op_sel:[1,1]", v1), merge_half(OLD, H_2P0, 1))
701 self.assertEqual(run_op("v_rcp_f16_e64 v0, -|v1| op_sel:[1,0]", v1), merge_half(OLD, H_NEG_2P0, 0))
702
703 # Output modifiers scale first, then clamp to [0.0, 1.0], then pack to f16 keeping the other half.
704 self.assertEqual(run_op("v_rcp_f16_e64 v0, v1 mul:2", v1), merge_half(OLD, H_0P5, 0))
705 self.assertEqual(run_op("v_rcp_f16_e64 v0, v1 mul:4", v1), merge_half(OLD, H_1P0, 0))
706 self.assertEqual(run_op("v_rcp_f16_e64 v0, v1 div:2", v1), merge_half(OLD, 0x3000, 0)) # 0.125
707 self.assertEqual(run_op("v_rcp_f16_e64 v0, v1 op_sel:[1,1] mul:2", v1), merge_half(OLD, H_NEG_4P0, 1))
708 self.assertEqual(run_op("v_rcp_f16_e64 v0, v1 op_sel:[1,1] clamp", v1), merge_half(OLD, H_POS_ZERO, 1))
709 self.assertEqual(run_op("v_rcp_f16_e64 v0, |v1| op_sel:[1,0] mul:2 clamp", v1), merge_half(OLD, H_1P0, 0))
710 self.assertEqual(run_op("v_rcp_f16_e64 v0, |v1| op_sel:[1,1] clamp div:2", v1), merge_half(OLD, H_1P0, 1))
711
712 def test_inline_constants_sgpr_and_aliasing(self):
713 self.assertEqual(run_op("v_rcp_f16_e32 v0, 0.5", 0), merge_half(OLD, H_2P0, 0))
714 self.assertEqual(run_op("v_rcp_f16_e32 v0, -0.5", 0), merge_half(OLD, H_NEG_2P0, 0))
715 self.assertEqual(run_op("v_rcp_f16_e64 v0, -1.0", 0), merge_half(OLD, H_NEG_1P0, 0))
716 self.assertEqual(run_op("v_rcp_f16_e64 v0, -|0x4000|", 0), merge_half(OLD, H_NEG_0P5, 0))
717
718 s4 = (H_NEG_4P0 << 16) | H_0P5
719 self.assertEqual(run_op("v_rcp_f16_e32 v0, s4", 0, s4=s4), merge_half(OLD, H_2P0, 0))
720 self.assertEqual(run_op("v_rcp_f16_e64 v0, s4 op_sel:[1,1]", 0, s4=s4), merge_half(OLD, H_NEG_0P25, 1))
721
722 # In-place aliasing: dst == src reading one half and writing the other keeps the original unread half.
723 v0_init = (H_0P5 << 16) | H_4P0
724 self.assertEqual(
725 run_ps_v0([f"v_mov_b32 v0, {v0_init:#x}", "v_rcp_f16_e64 v0, v0 op_sel:[1,0]"]),
726 (H_0P5 << 16) | H_2P0,
727 )
728 self.assertEqual(
729 run_ps_v0([f"v_mov_b32 v0, {v0_init:#x}", "v_rcp_f16_e32 v0, v0"]),
730 (H_0P5 << 16) | H_0P25,
731 )
732
733
734# -----------------------------------------------------------------------------
735# 5. EXEC Masking & Negative Control Tests
736# -----------------------------------------------------------------------------
737
738class RcpExecMaskingTests(unittest.TestCase):
739 def test_single_lane_exec_masking(self):
740 for line in (
741 "v_rcp_f32_e32 v0, v1",
742 "v_rcp_iflag_f32_e32 v0, v1",
743 "v_rcp_f16_e32 v0, v1",
744 "v_rcp_f16_e64 v0, v1 op_sel:[1,1]",
745 ):
746 with self.subTest(line=line):
747 got = run_ps_v0([
748 f"v_mov_b32 v1, {(H_2P0 << 16) | H_4P0:#x}",
749 f"v_mov_b32 v0, {OLD:#x}",
750 "s_mov_b32 exec_lo, 0",
751 line,
752 "s_mov_b32 exec_lo, 1",
753 ])
754 self.assertEqual(got, OLD)
755
756 # Disabled ops leave v0 unchanged; re-enabling EXEC executes the subsequent op.
757 got_toggled = run_ps_v0([
758 f"v_mov_b32 v1, {(H_0P5 << 16) | H_4P0:#x}",
759 f"v_mov_b32 v0, {OLD:#x}",
760 "s_mov_b32 exec_lo, 0",
761 "v_rcp_f16_e64 v0, v1 op_sel:[0,0]",
762 "v_rcp_f16_e64 v0, v1 op_sel:[1,1]",
763 "s_mov_b32 exec_lo, 1",
764 "v_rcp_f16_e64 v0, v1 op_sel:[1,0]",
765 ])
766 self.assertEqual(got_toggled, merge_half(OLD, H_2P0, 0))
767
768 def test_multilane_compute_exec_masking(self):
769 # 4 lanes in wave32: disable odd lanes (lane & 1 != 0) before executing v_rcp_*.
770 # Active even lanes (0, 2) compute the reciprocal; inactive odd lanes (1, 3) keep OLD.
771 cases = (
772 ("v_rcp_f32_e32 v3, v2", f32_bits(4.0), f32_bits(0.25)),
773 ("v_rcp_iflag_f32_e64 v3, v2 mul:2", f32_bits(4.0), f32_bits(0.5)),
774 ("v_rcp_f16_e64 v3, v2 op_sel:[1,1]", (H_0P5 << 16) | H_4P0, merge_half(OLD, H_2P0, 1)),
775 )
776 for insn, src_word, active_want in cases:
777 with self.subTest(insn=insn):
778 mem = {}
779 lines = [
780 "v_lshlrev_b32 v4, 2, v0", # lane byte offset = lane * 4
781 f"v_mov_b32 v2, {src_word:#x}",
782 f"v_mov_b32 v3, {OLD:#x}",
783 "v_and_b32 v5, v0, 1",
784 "v_cmpx_eq_u32 v5, 0", # keep even lanes active
785 insn,
786 "s_mov_b32 exec_lo, -1",
787 "buffer_store_dword v3, v4, s[0:3], 0 offen",
788 ]
789 run_cs(lines, group_size=4, subgroup_size=32, memory=mem)
790 self.assertEqual(
791 [mem[4 * i] for i in range(4)],
792 [active_want, OLD, active_want, OLD],
793 )
794
795
796class NegativeControlTests(unittest.TestCase):
797 def test_sabotaged_spirv_is_detected(self):
798 cases = (
799 ("v_rcp_f32_e32 v0, v1", f32_bits(4.0), f32_bits(0.25)),
800 ("v_rcp_iflag_f32_e64 v0, v1 mul:2", f32_bits(4.0), f32_bits(0.5)),
801 ("v_rcp_f16_e64 v0, v1 op_sel:[0,1]", (H_1P0 << 16) | H_4P0, merge_half(OLD, H_0P25, 1)),
802 )
803 for line, v1_bits, want in cases:
804 with self.subTest(line=line):
805 spv = translate_ps([f"v_mov_b32 v0, {OLD:#x}", f"v_mov_b32 v1, {v1_bits:#x}", line])
806 self.assertEqual(si.run_fragment(spv)["%out_mrt0"][0], want)
807 bad, n = re.subn(r"OpFDiv %float %f1\b", "OpFMul %float %f1", spv, count=1)
808 self.assertEqual(n, 1)
809 self.assertNotEqual(si.run_fragment(bad)["%out_mrt0"][0], want)
810
811 # Sabotaging FClamp on v_rcp_iflag_f32_e64 clamp changes clamped 1/0.5 = 2.0 -> 1.0.
812 spv_clamp = translate_ps([
813 f"v_mov_b32 v0, {OLD:#x}",
814 f"v_mov_b32 v1, {f32_bits(0.5):#x}",
815 "v_rcp_iflag_f32_e64 v0, v1 clamp",
816 ])
817 self.assertEqual(si.run_fragment(spv_clamp)["%out_mrt0"][0], f32_bits(1.0))
818 bad_clamp, n = re.subn(r"OpExtInst %float %glsl FClamp (%\w+) %f0 %f1", r"OpCopyObject %float \1", spv_clamp)
819 self.assertEqual(n, 1)
820 self.assertEqual(si.run_fragment(bad_clamp)["%out_mrt0"][0], f32_bits(2.0))
821
822
823if __name__ == "__main__":
824 unittest.main()
diff --git a/tests/semantic/test_value_semantics.py b/tests/semantic/test_value_semantics.py
index e90163cdd..32cf911db 100644
--- a/tests/semantic/test_value_semantics.py
+++ b/tests/semantic/test_value_semantics.py
@@ -493,6 +493,30 @@ class TranslatorValueSemantics(unittest.TestCase):
493 with self.subTest(address=address): 493 with self.subTest(address=address):
494 self.assertEqual(f"{memory.get(address, 0):#010x}", f"{want:#010x}") 494 self.assertEqual(f"{memory.get(address, 0):#010x}", f"{want:#010x}")
495 495
496 def test_signed_typed_buffers(self):
497 spv = support.translate_fixture("cs_fmt_sint32", fssm=CS_BOUNDS_FSSM)
498 memory = {}
499 support.run_fragment(
500 spv, inputs={"%wg_id": (0, 0, 0), "%local_id": (0, 0, 0)},
501 push_constants=[0, 0, 0x100, 0x31016FAC] + [0] * 28, memory=memory)
502 expected = {
503 0x0C: 1, # MUBUF integer DST_SEL=1
504 0x18: 0xFFFFFFFD, # MUBUF 96-bit format, third component
505 0x34: 0x7FFFFFFF, 0x38: 0, # MTBUF 64-bit format with absent third component
506 0x48: 0xFFFFFFFD, 0x4C: 0, # MTBUF 96-bit format with absent fourth component
507 0x58: 0xFFFFFFFD, 0x5C: 17, # MTBUF 128-bit format
508 0x60: 0x7FFF8000, 0x64: 0x0011FFFD,
509 0x68: 0x7FFF8000, 0x6C: 0x0011FFFD,
510 0x70: 0xFFFFFFFD, 0x74: 0xFFFFFFFD,
511 0x90: 0x80000000, 0xA8: 0xFFFFFFFD, 0xBC: 17,
512 0xC0: 0xFFFFFFFD, 0xC4: 0xFFFF8000, 0xC8: 0xFFFFFFFD,
513 }
514 for address, word in expected.items():
515 with self.subTest(address=hex(address)):
516 self.assertEqual(memory.get(address), word)
517 for address in (0x98, 0xAC, 0xCC):
518 self.assertNotIn(address, memory)
519
496 def test_s_ff0_s_ff1_read_an_immediate_as_a_value(self): 520 def test_s_ff0_s_ff1_read_an_immediate_as_a_value(self):
497 # SHADER-46: an inline constant or literal is a 32-bit value. Read as a lane mask (all ones or zero from 521 # SHADER-46: an inline constant or literal is a 32-bit value. Read as a lane mask (all ones or zero from
498 # bit 0), s_ff0 of 61 and of 0x0000ffff gave -1; the s_ff1 words guard the path it already got right. 522 # bit 0), s_ff0 of 61 and of 0x0000ffff gave -1; the s_ff1 words guard the path it already got right.
diff --git a/tests/semantic/test_vop3_const_mods.py b/tests/semantic/test_vop3_const_mods.py
index 2d07d1fb7..052457f41 100644
--- a/tests/semantic/test_vop3_const_mods.py
+++ b/tests/semantic/test_vop3_const_mods.py
@@ -178,11 +178,14 @@ class F16AndMixConstModifierTests(unittest.TestCase):
178 ]) 178 ])
179 self.assertEqual(got[:3], [0x4000BC00, 0x00007C01, 0x7C01FC01]) 179 self.assertEqual(got[:3], [0x4000BC00, 0x00007C01, 0x7C01FC01])
180 180
181 def test_v_pack_b32_f16_abs_is_still_rejected(self): 181 def test_v_pack_b32_f16_abs_clears_the_sign_of_the_packed_half(self):
182 # Only `neg` is measured on this instruction; `abs` would be a guessed sign clear, so it stays refused. 182 # `abs` is the ISA's sign clear (|S|), applied before `neg`; it has no hardware run of this instruction yet.
183 with self.assertRaises(rdna2spirv.Unsupported): 183 got = run([
184 translate(["v_pack_b32_f16 v0, abs(0x3c00), 1.0"]) 184 "v_mov_b32 v1, 0xbc00",
185 185 "v_pack_b32_f16 v0, abs(0xbc00), 0x4000", # +1.0h in the low half, 2.0h in the high one
186 "v_pack_b32_f16 v2, -abs(v1), v1", # clear then flip the low half; src1 stays -1.0h
187 ])
188 self.assertEqual(got[:3], [0x40003C00, 0x0000BC00, 0xBC00BC00])
186 189
187class F64ConstModifierStructureTests(unittest.TestCase): 190class F64ConstModifierStructureTests(unittest.TestCase):
188 def test_f64_emits_fabs_then_fnegate_for_neg_abs_const(self): 191 def test_f64_emits_fabs_then_fnegate_for_neg_abs_const(self):
diff --git a/tests/semantic/test_w64x_scalar_load_order.py b/tests/semantic/test_w64x_scalar_load_order.py
new file mode 100644
index 000000000..1621afaa7
--- /dev/null
+++ b/tests/semantic/test_w64x_scalar_load_order.py
@@ -0,0 +1,133 @@
1"""--wave64-emulate: a scalar load (s_load / s_buffer_load) is ordered with the wave's vector stores (#1587).
2
3On hardware a wave issues its instructions in order, so every lane's `buffer_store` is done (`s_waitcnt vmcnt(0)`)
4before the wave's `s_load` of the same address. Under `--wave64-emulate` the two halves of a wave can run in two
532-wide subgroups, which order memory only at the barrier between rounds (docs/design.md, "Wave64 emulation"). Until
6#1587 a scalar load was not one of the accesses `Gen.x_memory_order` cuts a round at, so a store and a later scalar
7load of the same wave sat in one segment, and the other half could load before this half had stored:
8`tools/valu_fuzz.py --family mem --emulate` found lanes 32-63 reading the buffer's fill pattern after an
9`s_buffer_load` / `s_load` of the slot lane 0 had just written (the slot comes from `v_readfirstlane_b32`, which
10the emulation already reads over the whole wave).
11
12The interpreters here don't run workgroup barriers, so this checks the rule on the emitted rounds: the SPIR-V of every
13segment (a case of the round loop's `OpSwitch %pcv`) may not access buffer memory (the PhysicalStorageBuffer pointers
14both the vector and the scalar memory ops go through) in a conflicting order: no access after a write, no write after
15a read. The programs are written here; no game data.
16"""
17import os
18import re
19import struct
20import sys
21import unittest
22
23HERE = os.path.dirname(os.path.abspath(__file__))
24if HERE not in sys.path:
25 sys.path.insert(0, HERE) # python -I leaves the script's folder off sys.path
26
27import support # noqa: E402 (support puts tools/ on sys.path, honouring LEONIDA_TOOLS_DIR)
28
29rdna2spirv = support.rdna2spirv
30
31# s[0:3] is the output V# (4 user SGPRs); s[8:9] a 64-bit pointer to the same memory, s[12:15] a V# of it for
32# s_buffer_load. Every access is one dword, so one instruction is one OpLoad or OpStore.
33HEAD = ["s_mov_b64 exec, -1", "s_mov_b32 s8, 0", "s_mov_b32 s9, 0",
34 "s_mov_b32 s12, 0", "s_mov_b32 s13, 0", "s_mov_b32 s14, 0x1000", "s_mov_b32 s15, 0x31016FAC",
35 "v_lshlrev_b32_e32 v1, 2, v0", # v1 = the lane's byte offset
36 # as in the fuzz program, before any memory op: s16 = the byte offset of the wave's first lane
37 "v_readfirstlane_b32 s16, v1"]
38STORE = ["buffer_store_dword v0, v1, s[0:3], 0 offen", "s_waitcnt vmcnt(0)"]
39SLOAD = ["s_load_dword s10, s[8:9], 0x0", "s_waitcnt lgkmcnt(0)", "v_mov_b32_e32 v2, s10"]
40# The fuzz program's shape: the slot of the wave's first lane, from v_readfirstlane_b32, as the soffset.
41SBUF = ["s_buffer_load_dword s10, s[12:15], s16 offset:0x0", "s_waitcnt lgkmcnt(0)",
42 "v_mov_b32_e32 v2, s10"]
43TAIL = ["buffer_store_dword v2, v1, s[0:3], 0 offen offset:256", "s_endpgm"]
44
45
46def fssm(threads=64):
47 """Compute header: COMPUTE_PGM_RSRC2 0x8088 (4 user SGPRs, TGID_X), one wave of `threads`."""
48 return bytes(0x138) + struct.pack("<4I", 0x8088, threads, 1, 1)
49
50
51def translate(lines, emulate=True):
52 prev = rdna2spirv.WAVE64_EMULATE
53 rdna2spirv.WAVE64_EMULATE = emulate
54 try:
55 spv = support.translate_lines("cs_w64x_sload_order", lines, fssm=fssm())
56 finally:
57 rdna2spirv.WAVE64_EMULATE = prev
58 assert rdna2spirv.translate.last_gen.wave64, "the test program must translate as wave64"
59 return spv
60
61
62def segments(spv):
63 """{segment label: ["r"/"w", ...]}: the buffer accesses of each case of the round loop's switch, in order."""
64 lines = spv.splitlines()
65 sw = next((ln.split() for ln in lines if ln.split()[:2] == ["OpSwitch", "%pcv"]), None)
66 assert sw is not None, "no round-loop switch: not an emulated translation"
67 labels = set(sw[4::2])
68 psb = set()
69 out, cur = {}, None
70 for ln in lines:
71 t = ln.split()
72 if len(t) >= 3 and t[1] == "=" and t[2] == "OpLabel":
73 if t[0] in labels:
74 cur = out.setdefault(t[0], [])
75 elif t[0] == sw[3]: # the default label ends the cases
76 cur = None
77 continue
78 if cur is None:
79 continue
80 if len(t) >= 4 and t[2] == "OpAccessChain" and t[3] == "%_ptr_PSB_uint":
81 psb.add(t[0])
82 elif len(t) >= 5 and t[2] == "OpLoad" and t[4] in psb:
83 cur.append("r")
84 elif len(t) >= 2 and t[0] == "OpStore" and t[1] in psb:
85 cur.append("w")
86 return out
87
88
89def conflicts(segs):
90 """The segments where an access follows a write, or a write follows a read (x_memory_order's rule)."""
91 bad = []
92 for lab, acc in segs.items():
93 s = "".join(acc)
94 if re.search(r"w.", s) or re.search(r"r.*w", s):
95 bad.append((lab, s))
96 return bad
97
98
99class ScalarLoadOrderTests(unittest.TestCase):
100 def check_ordered(self, lines, accesses):
101 segs = segments(translate(lines))
102 self.assertEqual(sum(len(a) for a in segs.values()), accesses, segs) # every access was found
103 self.assertEqual(conflicts(segs), [], segs)
104 return segs
105
106 def test_store_then_s_load(self):
107 # read after write: the store's round ends before the load
108 self.check_ordered(HEAD + STORE + SLOAD + TAIL, 3)
109
110 def test_store_then_s_buffer_load_at_the_first_lane_slot(self):
111 # the #1587 program shape: buffer_store, then v_readfirstlane_b32 + s_buffer_load
112 self.check_ordered(HEAD + STORE + SBUF + TAIL, 3)
113
114 def test_s_load_then_store(self):
115 # write after read: the other half's store may not land before this half's scalar load
116 self.check_ordered(HEAD + SLOAD + STORE + ["s_endpgm"], 2)
117
118 def test_reads_share_a_round(self):
119 # loads alone never conflict: two scalar loads and a vector load stay in one segment
120 lines = HEAD + SLOAD + ["s_load_dword s11, s[8:9], 0x4", "s_waitcnt lgkmcnt(0)",
121 "buffer_load_dword v3, v1, s[0:3], 0 offen", "s_waitcnt vmcnt(0)", "s_endpgm"]
122 segs = self.check_ordered(lines, 3)
123 self.assertIn(["r", "r", "r"], segs.values(), segs)
124
125 def test_native_wave64_is_unchanged(self):
126 # without the flag there are no rounds: the store and the load are one straight run
127 spv = translate(HEAD + STORE + SLOAD + TAIL, emulate=False)
128 self.assertNotIn("%pcv", spv)
129 self.assertNotIn("OpControlBarrier", spv)
130
131
132if __name__ == "__main__":
133 unittest.main()
diff --git a/tests/test_anim_rigs.py b/tests/test_anim_rigs.py
new file mode 100644
index 000000000..7ae94fb61
--- /dev/null
+++ b/tests/test_anim_rigs.py
@@ -0,0 +1,134 @@
1"""Synthetic tests for tools/anim_rigs.py.
2
3 python -I tests/test_anim_rigs.py
4
5Every byte here is built by the test: a fake RPF9 data area with two rig dictionaries and one clip dictionary
6(the builders of tests/test_anim_clips.py), and a small rig-set JSON in the shape `anim_index.py --rigs` writes.
7No game file or game asset name is used.
8"""
9import json
10import os
11import struct
12import subprocess
13import sys
14import tempfile
15import unittest
16
17ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
18TOOL = os.path.join(ROOT, "tools", "anim_rigs.py")
19sys.path.insert(0, os.path.join(ROOT, "tools"))
20sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
21
22import anim_rigs # noqa: E402
23from anim_index import joaat32 # noqa: E402
24from test_anim_clips import Page, two_sequence_dictionary, write_rpf # noqa: E402
25
26KIND_A, KIND_B = joaat32("kind_a"), joaat32("kind_b")
27
28
29def rig_block(page, tables, version=2):
30 """`RIG` + version, u32 length, 8 filler bytes, then each table {kind, 0xC + 8n, n, word} + n items."""
31 body = bytearray(b"\x11" * 8)
32 for kind, items in tables:
33 body += struct.pack("<4I", kind, 0xC + 8 * len(items), len(items), 0x0300)
34 body += b"".join(struct.pack("<II", h, 0x0300 + i) for i, h in enumerate(items))
35 return page.alloc(MAGIC_V(version) + struct.pack("<I", len(body)) + bytes(body))
36
37
38def MAGIC_V(version):
39 return b"RIG" + bytes([version])
40
41
42def rig_dictionary(name, rigs):
43 """rigs: {rig path: [(kind, [item hashes])]}. The root's own +0x70 holds `RIG` + version like the real ones."""
44 p = Page()
45 pm = p.alloc(bytes(16))
46 p.b[pm + 8], p.b[pm + 9] = 1, 0
47 p.ptr(8, pm)
48 p.string(0x38, name)
49 struct.pack_into("<I", p.b, 0x68, joaat32(name))
50 p.b[0x70:0x74] = MAGIC_V(2)
51 items = []
52 for path, tables in rigs.items():
53 value = p.alloc(bytes(0x90))
54 p.ptr(value + 0x20, rig_block(p, tables))
55 items.append((joaat32(path), value))
56 p.atmap(0x48, items)
57 return bytes(p.b)
58
59
60RIGS = {
61 "src@one": {"anim/rig/x/a": [(KIND_A, [1, 2, 3])], "anim/rig/x/b": [(KIND_A, [4]), (KIND_B, [5, 6])]},
62 "src@two": {"anim/rig/y/c": [(KIND_B, [7, 8])], "anim/rig/y/unused": [(KIND_A, [9])]},
63}
64RIGSETS = {"rbf0": {"rigsets": [
65 {"key": "anim/rigset/ped/p", "entries": [
66 {"source": "src@one", "rig": "anim/rig/x/a", "group": "pose"},
67 {"source": "src@one", "rig": "anim/rig/x/b", "group": "deformation"},
68 {"source": "src@two", "rig": "anim/rig/y/c", "group": "facial"}]},
69 {"key": "anim/rigset/object/o", "entries": [
70 {"source": "src@two", "rig": "anim/rig/x/a", "group": "pose"}, # rig is in the other dictionary
71 {"source": "src@none", "rig": "anim/rig/z/q", "group": "pose"}, # no dictionary has this name
72 {"source": "src@one", "rig": "anim/rig/x/missing", "group": "pose"}]},
73]}}
74
75
76class RigDictionaryTest(unittest.TestCase):
77 def setUp(self):
78 self.tmp = tempfile.TemporaryDirectory()
79 self.rpf = os.path.join(self.tmp.name, "synthetic.rpf")
80 self.rigs = os.path.join(self.tmp.name, "rigs.json")
81 with open(self.rigs, "w", encoding="utf-8") as f:
82 json.dump(RIGSETS, f)
83 streams = [rig_dictionary(name, rigs) for name, rigs in RIGS.items()] + [two_sequence_dictionary()]
84 self.offsets = write_rpf(self.rpf, streams)
85
86 def tearDown(self):
87 self.tmp.cleanup()
88
89 def test_scan_reads_only_rig_dictionaries(self):
90 dicts, summary = anim_rigs.scan(self.rpf)
91 self.assertEqual([d["name"] for d in dicts], ["src@one", "src@two"])
92 self.assertEqual([d["offset"] for d in dicts], self.offsets[:2])
93 c = summary["counts"]
94 self.assertEqual((c["rig_dictionaries"], c["rig_dictionary_hash_matches_name"], c["entries"],
95 c["entries_with_block"], c["entries_key_high_zero"], c["block_version:2"]), (2, 2, 4, 4, 4, 4))
96 self.assertEqual((c["tables"], c[f"table_kind:0x{KIND_A:08x}"], c[f"table_kind:0x{KIND_B:08x}"]), (5, 3, 2))
97 self.assertEqual((c[f"table_items:0x{KIND_A:08x}"], c[f"table_items:0x{KIND_B:08x}"]), (5, 4))
98
99 def test_entry_keys_and_tables(self):
100 dicts, _ = anim_rigs.scan(self.rpf)
101 one = {e["key"]: e["tables"] for e in dicts[0]["entries"]}
102 self.assertEqual(one, {joaat32("anim/rig/x/a"): [(KIND_A, 3)],
103 joaat32("anim/rig/x/b"): [(KIND_A, 1), (KIND_B, 2)]})
104
105 def test_join_rbf0(self):
106 dicts, _ = anim_rigs.scan(self.rpf)
107 self.assertEqual(anim_rigs.join_rbf0(dicts, RIGSETS), {
108 "distinct_rigs": 6, "in_another_dictionary": 1, "key_missing": 1, "keys": 4,
109 "keys_named_by_an_entry": 3, "no_dictionary_named_source": 1, "resolved": 3})
110
111 def test_bad_block_is_reported_not_raised(self):
112 page = bytearray(rig_dictionary("src@bad", {"anim/rig/b": [(KIND_A, [1])]}))
113 at = page.rfind(b"RIG\x02")
114 page[at:at + 3] = b"XYZ"
115 rpf = os.path.join(self.tmp.name, "bad.rpf")
116 write_rpf(rpf, [bytes(page)])
117 dicts, summary = anim_rigs.scan(rpf)
118 self.assertEqual(summary["counts"]["rig_dictionaries_unparsed"], 1)
119 self.assertIn("no RIG block", dicts[0]["error"])
120
121 def test_cli_writes_counts_only(self):
122 out = os.path.join(self.tmp.name, "out.json")
123 r = subprocess.run([sys.executable, "-I", TOOL, self.rpf, out, "--rigs", self.rigs],
124 capture_output=True, text=True)
125 self.assertEqual(r.returncode, 0, r.stderr)
126 with open(out, encoding="utf-8") as f:
127 doc = json.load(f)
128 self.assertEqual(doc["summary"]["rbf0_join"]["resolved"], 3)
129 self.assertEqual([row["entries"] for row in doc["rig_dictionaries"]], [2, 2])
130 self.assertNotIn("tables", json.dumps(doc["rig_dictionaries"]))
131
132
133if __name__ == "__main__":
134 unittest.main()
diff --git a/tests/test_awc_opus.py b/tests/test_awc_opus.py
index 76b26ff0c..aebdd0fd8 100644
--- a/tests/test_awc_opus.py
+++ b/tests/test_awc_opus.py
@@ -393,8 +393,9 @@ class ExportBankTest(unittest.TestCase):
393 self.assertEqual(last["serial"], 3) 393 self.assertEqual(last["serial"], 3)
394 394
395 def test_stereo_plain_stream_length_is_per_channel(self): 395 def test_stereo_plain_stream_length_is_per_channel(self):
396 # A stereo format tag stores interleaved samples. Three 960-frame stereo packets carry 396 # A stereo format tag stores interleaved samples: 3840 counts = 1920 frames per channel.
397 # 2880 frames per channel; the declared 3840 is twice the real per-channel length. 397 # Three 960-frame packets carry 2880 frames per channel, so the declared 1920 trims
398 # 960 frames of payload; the point is the halving, not a realistic stream length.
398 packet = bytes([0x9C]) # CELT 20 ms, code 0, stereo bit: 960 frames per channel 399 packet = bytes([0x9C]) # CELT 20 ms, code 0, stereo bit: 960 frames per channel
399 opus = bytearray(3 * 2048) 400 opus = bytearray(3 * 2048)
400 for block in range(3): 401 for block in range(3):
@@ -414,8 +415,8 @@ class ExportBankTest(unittest.TestCase):
414 415
415 def test_declared_samples_are_48khz_frames_not_scaled_by_rate(self): 416 def test_declared_samples_are_48khz_frames_not_scaled_by_rate(self):
416 # Four 960-frame packets are 3840 frames; the tag declares 2880 real frames and a 32 kHz 417 # Four 960-frame packets are 3840 frames; the tag declares 2880 real frames and a 32 kHz
417 # source rate. Scaling by 48000/32000 would make the length 4320, so the last granule 418 # source rate. Scaling by 48000/32000 would make the target 4320, above the payload, so
418 # would stay at 312 + 3840 and the padding would not be trimmed. 419 # the old code kept all 3840 packet frames (granule 3840, 3528 after the pre-skip).
419 packet = bytes([0x08]) # SILK 20 ms, code 0: 960 frames 420 packet = bytes([0x08]) # SILK 20 ms, code 0: 960 frames
420 opus = bytearray(4 * 2048) 421 opus = bytearray(4 * 2048)
421 for block in range(4): 422 for block in range(4):
@@ -431,12 +432,13 @@ class ExportBankTest(unittest.TestCase):
431 pages = parse_ogg_pages(f.read()) 432 pages = parse_ogg_pages(f.read())
432 self.assertEqual(pages[-1]["granule"], 312 + 2880) 433 self.assertEqual(pages[-1]["granule"], 312 + 2880)
433 434
434 def test_format_block_per_channel_frame_count_is_used(self): 435 def test_inconsistent_format_frame_count_falls_back(self):
435 # +0x0C is the per-channel Opus frame count and wins over dividing the +0 count: 436 # +0x0C is authoritative only when it agrees with the interleaved +0 count:
436 # 9999 interleaved samples / 2 would be 4999 frames and would not trim the padding. 437 # 1920 * 2 != 9999, so the block is malformed and +0 / channels (4999) is used
438 # instead of silently truncating the real audio.
437 packet = bytes([0x9C]) # CELT 20 ms, code 0, stereo bit: 960 frames per channel 439 packet = bytes([0x9C]) # CELT 20 ms, code 0, stereo bit: 960 frames per channel
438 opus = bytearray(3 * 2048) 440 opus = bytearray(6 * 2048)
439 for block in range(3): 441 for block in range(6):
440 struct.pack_into("<H", opus, block * 2048, len(packet)) 442 struct.pack_into("<H", opus, block * 2048, len(packet))
441 opus[block * 2048 + 2:block * 2048 + 2 + len(packet)] = packet 443 opus[block * 2048 + 2:block * 2048 + 2 + len(packet)] = packet
442 fmt = bytearray(format_block(9999, 48000, 0x0B, 2)) 444 fmt = bytearray(format_block(9999, 48000, 0x0B, 2))
@@ -449,8 +451,69 @@ class ExportBankTest(unittest.TestCase):
449 awc.export_bank(path, self.out) 451 awc.export_bank(path, self.out)
450 with open(os.path.join(self.out, "frames", "0000000B.ogg"), "rb") as f: 452 with open(os.path.join(self.out, "frames", "0000000B.ogg"), "rb") as f:
451 pages = parse_ogg_pages(f.read()) 453 pages = parse_ogg_pages(f.read())
454 self.assertEqual(pages[-1]["granule"], 312 + 4999)
455
456 def test_consistent_format_frame_count_is_used(self):
457 # 3840 interleaved stereo samples = 1920 per channel, and +0x0C agrees.
458 packet = bytes([0x9C]) # CELT 20 ms, code 0, stereo bit: 960 frames per channel
459 opus = bytearray(3 * 2048)
460 for block in range(3):
461 struct.pack_into("<H", opus, block * 2048, len(packet))
462 opus[block * 2048 + 2:block * 2048 + 2 + len(packet)] = packet
463 fmt = bytearray(format_block(3840, 48000, 0x0B, 2))
464 struct.pack_into("<I", fmt, 12, 1920)
465 bank = build_bank([(12, bytes(fmt), bytes(opus))])
466 path = os.path.join(self.tmp.name, "frames_ok.awc")
467 with open(path, "wb") as f:
468 f.write(bank)
469
470 awc.export_bank(path, self.out)
471 with open(os.path.join(self.out, "frames_ok", "0000000C.ogg"), "rb") as f:
472 pages = parse_ogg_pages(f.read())
452 self.assertEqual(pages[-1]["granule"], 312 + 1920) 473 self.assertEqual(pages[-1]["granule"], 312 + 1920)
453 474
475 def test_eos_page_is_emitted_at_the_trim_point(self):
476 # 27 packets of 160 bytes / 960 frames: the 26th packet crosses the target
477 # (312 + 24000 = 24312) and would otherwise flush a full page first. The EOS
478 # page must carry the reaching packet and drop the 27th padding packet, not
479 # emit a later page whose granule is smaller than the previous one.
480 packet = bytes([0x08]) + bytes(159) # SILK 20 ms, 960 frames
481 packets = [packet] * 27
482 path = os.path.join(self.tmp.name, "trim.ogg")
483 awc.write_ogg_opus(path, packets, 1, 21, 24000)
484 with open(path, "rb") as f:
485 pages = parse_ogg_pages(f.read())
486 audio = pages[2:]
487 granules = [p["granule"] for p in audio]
488 self.assertEqual(granules, sorted(granules))
489 self.assertEqual(audio[-1]["granule"], 312 + 24000)
490 self.assertEqual(audio[-1]["flags"] & 0x04, 0x04)
491 self.assertEqual(sum(1 for p in audio for value in p["lacing"] if value < 255), 26)
492
493 def test_pre_skip_larger_than_the_stream_is_clamped(self):
494 # Six 960-frame packets are 5760 samples; a pre-skip of 65535 would put the
495 # EOS granule below the pre-skip and make the stream undecodable.
496 packet = bytes([0x08])
497 packets = [packet] * 6
498 path = os.path.join(self.tmp.name, "preskip.ogg")
499 awc.write_ogg_opus(path, packets, 1, 23, 4800, pre_skip=65535)
500 with open(path, "rb") as f:
501 pages = parse_ogg_pages(f.read())
502 self.assertEqual(struct.unpack_from("<H", pages[0]["body"], 10)[0], 5760)
503 self.assertGreaterEqual(pages[-1]["granule"], 5760)
504 with self.assertRaises(ValueError):
505 awc.write_ogg_opus(path, packets, 1, 24, 4800, pre_skip=65536)
506
507 def test_empty_packet_list_writes_an_eos_page(self):
508 # No audio packets is still a valid empty stream: the EOS flag must be present.
509 path = os.path.join(self.tmp.name, "empty.ogg")
510 self.assertEqual(awc.write_ogg_opus(path, [], 1, 25, 0), 0)
511 with open(path, "rb") as f:
512 pages = parse_ogg_pages(f.read())
513 self.assertEqual(len(pages), 3)
514 self.assertEqual(pages[-1]["flags"] & 0x04, 0x04)
515 self.assertEqual(pages[-1]["granule"], 0)
516
454 def test_cli_pre_skip_override(self): 517 def test_cli_pre_skip_override(self):
455 bank, _, _ = self.make_bank() 518 bank, _, _ = self.make_bank()
456 subprocess.run([sys.executable, "-I", awc.__file__, bank, self.out, "--jobs", "1", "--pre-skip", "0"], 519 subprocess.run([sys.executable, "-I", awc.__file__, bank, self.out, "--jobs", "1", "--pre-skip", "0"],
diff --git a/tests/test_build_runtime_fallback.py b/tests/test_build_runtime_fallback.py
index 93457d1c7..75d938fdc 100644
--- a/tests/test_build_runtime_fallback.py
+++ b/tests/test_build_runtime_fallback.py
@@ -41,6 +41,11 @@ class FallbackBuildsTheHarnesses(unittest.TestCase):
41 with self.subTest(source=name): 41 with self.subTest(source=name):
42 self.assertTrue((ROOT / "runtime" / "test" / name).is_file()) 42 self.assertTrue((ROOT / "runtime" / "test" / name).is_file())
43 43
44 def test_build_cmd_sets_utf8_codepage_for_ninja_showincludes(self):
45 text = SCRIPT.read_text(encoding="utf-8")
46 self.assertIn("chcp 65001 >nul", text)
47 self.assertLess(text.index("chcp 65001 >nul"), text.index('call `"$vcvars`"'))
48
44 49
45if __name__ == "__main__": 50if __name__ == "__main__":
46 unittest.main() 51 unittest.main()
diff --git a/tests/test_calibrated_texture_extra.py b/tests/test_calibrated_texture_extra.py
new file mode 100644
index 000000000..115611a8e
--- /dev/null
+++ b/tests/test_calibrated_texture_extra.py
@@ -0,0 +1,2192 @@
1"""Expanded stdlib-only unit tests for tools/calibrated_texture.py.
2
3Covers native loader wiring, array validation, zig/distance/accumulate helpers,
4tile address mapping, BC1/BC3/BC4/BC5/BC7 block rebuilders, LocalDecoder chunk
5decoding/caching/surface/DDS export paths, error handling, and CLI integration
6using synthetic pools/profiles and unittest.mock (no game data).
7
8 python -I tests/test_calibrated_texture_extra.py -v
9"""
10from __future__ import annotations
11
12import bisect
13from contextlib import contextmanager, redirect_stderr, redirect_stdout
14import ctypes
15import hashlib
16import importlib.util
17import io
18import json
19import math
20import os
21from pathlib import Path
22import struct
23import sys
24import tempfile
25import unittest
26from unittest import mock
27import zlib
28
29ROOT = Path(__file__).resolve().parents[1]
30TOOLS_DIR = ROOT / "tools"
31TESTS_DIR = ROOT / "tests"
32for _p in (str(TESTS_DIR), str(TOOLS_DIR)):
33 if _p not in sys.path:
34 sys.path.insert(0, _p)
35
36import bcpack # noqa: E402
37import bcpack_tables # noqa: E402
38import bcpack_tables_bptc as _bptc # noqa: E402
39import test_bcpack as tb # noqa: E402
40import test_ttpf_mips as ttm # noqa: E402
41import tex_headers # noqa: E402
42import ttpf_mips as ttpf # noqa: E402
43from test_calibrated_texture import synthetic_profile # noqa: E402
44
45
46# ---------------------------------------------------------------------------
47# Minimal pure-stdlib NumPy shim for environments without NumPy installed.
48# Only used when importlib.util.find_spec("numpy") is None.
49# ---------------------------------------------------------------------------
50
51class _FakeDType:
52 """Minimal NumPy-like dtype descriptor supporting integers, bool, float, str, and Vn."""
53
54 _SPEC = {
55 "bool": ("b", 1, "?", False, False),
56 "b1": ("b", 1, "?", False, False),
57 "int8": ("i", 1, "b", True, False),
58 "i1": ("i", 1, "b", True, False),
59 "uint8": ("u", 1, "B", False, False),
60 "u1": ("u", 1, "B", False, False),
61 "int16": ("i", 2, "<h", True, False),
62 "i2": ("i", 2, "<h", True, False),
63 "<i2": ("i", 2, "<h", True, False),
64 "uint16": ("u", 2, "<H", False, False),
65 "u2": ("u", 2, "<H", False, False),
66 "<u2": ("u", 2, "<H", False, False),
67 "int32": ("i", 4, "<i", True, False),
68 "i4": ("i", 4, "<i", True, False),
69 "<i4": ("i", 4, "<i", True, False),
70 "uint32": ("u", 4, "<I", False, False),
71 "u4": ("u", 4, "<I", False, False),
72 "<u4": ("u", 4, "<I", False, False),
73 "int64": ("i", 8, "<q", True, False),
74 "i8": ("i", 8, "<q", True, False),
75 "<i8": ("i", 8, "<q", True, False),
76 "uint64": ("u", 8, "<Q", False, False),
77 "u8": ("u", 8, "<Q", False, False),
78 "<u8": ("u", 8, "<Q", False, False),
79 "float64": ("f", 8, "<d", True, True),
80 "f8": ("f", 8, "<d", True, True),
81 "str": ("U", 4, None, False, False),
82 "object": ("O", 8, None, False, False),
83 }
84
85 def __init__(self, spec):
86 if isinstance(spec, _FakeDType):
87 self.name = spec.name
88 self.kind = spec.kind
89 self.itemsize = spec.itemsize
90 self._struct = spec._struct
91 self.signed = spec.signed
92 self.is_float = spec.is_float
93 return
94 if spec is bool:
95 key = "bool"
96 elif spec is int:
97 key = "int64"
98 elif spec is float:
99 key = "float64"
100 elif spec is str:
101 key = "str"
102 else:
103 key = str(spec)
104 if key.startswith("V") and key[1:].isdigit():
105 n = int(key[1:])
106 self.name = key
107 self.kind = "V"
108 self.itemsize = n
109 self._struct = None
110 self.signed = False
111 self.is_float = False
112 return
113 if key not in self._SPEC:
114 raise TypeError(f"Unsupported fake dtype: {spec!r}")
115 kind, size, fmt, signed, is_float = self._SPEC[key]
116 self.name = key
117 self.kind = kind
118 self.itemsize = size
119 self._struct = struct.Struct(fmt) if fmt else None
120 self.signed = signed
121 self.is_float = is_float
122
123 def cast_val(self, v):
124 if self.kind == "b":
125 return bool(v)
126 if self.kind == "V":
127 if isinstance(v, (bytes, bytearray)):
128 b = bytes(v)
129 elif isinstance(v, int) and v == 0:
130 b = b"\x00" * self.itemsize
131 else:
132 raise TypeError(f"Cannot store {v!r} in {self.name}")
133 if len(b) != self.itemsize:
134 raise ValueError(f"Expected {self.itemsize} bytes, got {len(b)}")
135 return b
136 if self.kind in "iu":
137 iv = int(v)
138 bits = self.itemsize * 8
139 mask = (1 << bits) - 1
140 iv &= mask
141 if self.signed:
142 sign = 1 << (bits - 1)
143 iv = (iv ^ sign) - sign
144 return iv
145 if self.kind == "f":
146 return float(v)
147 return v
148
149 def __eq__(self, other):
150 if isinstance(other, _FakeDType):
151 return (self.kind, self.itemsize) == (other.kind, other.itemsize)
152 return NotImplemented
153
154 def __repr__(self):
155 return f"_FakeDType({self.name!r})"
156
157
158def _normalize_dtype(dtype):
159 return dtype if isinstance(dtype, _FakeDType) else _FakeDType(dtype)
160
161
162def _promote_dtype(a, b):
163 da = _normalize_dtype(a)
164 db = _normalize_dtype(b)
165 if da == db:
166 return da
167 if da.kind == "b":
168 return db
169 if db.kind == "b":
170 return da
171 if da.kind == "f" or db.kind == "f":
172 return _FakeDType("float64")
173 if da.kind == db.kind:
174 return da if da.itemsize >= db.itemsize else db
175 u_dt, i_dt = (da, db) if da.kind == "u" else (db, da)
176 if u_dt.itemsize >= i_dt.itemsize:
177 if u_dt.itemsize == 8:
178 return _FakeDType("uint64")
179 return _FakeDType(f"int{max(i_dt.itemsize, u_dt.itemsize * 2) * 8}")
180 return i_dt
181
182
183def _infer_dtype(flat_vals):
184 if not flat_vals:
185 return _FakeDType("int64")
186 kinds = set()
187 for v in flat_vals:
188 if isinstance(v, (bytes, bytearray)):
189 kinds.add(("V", len(v)))
190 elif isinstance(v, bool):
191 kinds.add("b")
192 elif isinstance(v, int):
193 kinds.add("i")
194 elif isinstance(v, float):
195 kinds.add("f")
196 elif isinstance(v, str):
197 kinds.add("U")
198 else:
199 kinds.add("O")
200 if len(kinds) == 1:
201 k = next(iter(kinds))
202 if isinstance(k, tuple) and k[0] == "V":
203 return _FakeDType(f"V{k[1]}")
204 if k == "b":
205 return _FakeDType("bool")
206 if k == "i":
207 lo = min(flat_vals)
208 hi = max(flat_vals)
209 if -0x8000000000000000 <= lo and hi <= 0x7FFFFFFFFFFFFFFF:
210 return _FakeDType("int64")
211 return _FakeDType("uint64")
212 if k == "f":
213 return _FakeDType("float64")
214 if k == "U":
215 return _FakeDType("str")
216 if kinds <= {"b", "i"}:
217 return _FakeDType("int64")
218 if kinds <= {"b", "i", "f"}:
219 return _FakeDType("float64")
220 return _FakeDType("object")
221
222
223def _flatten_nested(obj):
224 if isinstance(obj, _FakeArray):
225 return obj.shape, obj._flat_list(), obj.dtype
226 if isinstance(obj, (list, tuple)):
227 if not obj:
228 return (0,), [], None
229 sub_shapes = []
230 items = []
231 sub_dtypes = []
232 for elem in obj:
233 if isinstance(elem, (list, tuple, _FakeArray)):
234 sh, fl, dt = _flatten_nested(elem)
235 sub_shapes.append(sh)
236 items.extend(fl)
237 if dt is not None:
238 sub_dtypes.append(dt)
239 else:
240 sub_shapes.append(())
241 items.append(elem)
242 if len(set(sub_shapes)) != 1:
243 raise ValueError("inhomogeneous shape")
244 shape = (len(obj),) + sub_shapes[0]
245 dt = sub_dtypes[0] if sub_dtypes and all(d == sub_dtypes[0] for d in sub_dtypes) else None
246 return shape, items, dt
247 return (), [obj], None
248
249
250def _shape_strides(shape):
251 strides = [1] * len(shape)
252 for i in range(len(shape) - 2, -1, -1):
253 strides[i] = strides[i + 1] * shape[i + 1]
254 return tuple(strides)
255
256
257def _broadcast_shapes(s1, s2):
258 n = max(len(s1), len(s2))
259 p1 = (1,) * (n - len(s1)) + s1
260 p2 = (1,) * (n - len(s2)) + s2
261 out = []
262 for a, b in zip(p1, p2):
263 if a == b:
264 out.append(a)
265 elif a == 1:
266 out.append(b)
267 elif b == 1:
268 out.append(a)
269 else:
270 raise ValueError(f"operands could not be broadcast together with shapes {s1} {s2}")
271 return tuple(out)
272
273
274def _broadcast_index(out_coord, target_shape):
275 pad = len(out_coord) - len(target_shape)
276 res = []
277 for c, dim in zip(out_coord[pad:], target_shape):
278 res.append(0 if dim == 1 else c)
279 return tuple(res)
280
281
282def _unravel(flat_idx, shape):
283 if not shape:
284 return ()
285 coords = [0] * len(shape)
286 rem = flat_idx
287 for ax in range(len(shape) - 1, -1, -1):
288 dim = shape[ax]
289 coords[ax] = rem % dim
290 rem //= dim
291 return tuple(coords)
292
293
294def _ravel_coord(coord, strides):
295 return sum(c * s for c, s in zip(coord, strides))
296
297
298class _FakeCtypesView:
299 def __init__(self, arr):
300 self._arr = arr
301
302 @property
303 def data(self):
304 return ctypes.addressof(self._arr._buf)
305
306
307class _FakeFlat:
308 def __init__(self, arr):
309 self._arr = arr
310
311 def __getitem__(self, idx):
312 return self._arr.ravel()[idx]
313
314 def __setitem__(self, idx, value):
315 indices = idx._flat_list() if isinstance(idx, _FakeArray) else list(idx)
316 vals = value._flat_list() if isinstance(value, _FakeArray) else (
317 list(value) if isinstance(value, (list, tuple)) else [value] * len(indices)
318 )
319 if len(vals) == 1 and len(indices) != 1:
320 vals = vals * len(indices)
321 for pos, val in zip(indices, vals):
322 self._arr._set_flat(int(pos), val)
323
324
325class _FakeArray:
326 """Pure-Python contiguous ndarray subset backed by a live ctypes byte buffer."""
327
328 def __init__(self, shape, dtype, flat_vals=None, raw_bytes=None):
329 self.shape = tuple(shape)
330 self.dtype = _normalize_dtype(dtype)
331 self.size = math.prod(self.shape) if self.shape else 1
332 self.ndim = len(self.shape)
333 self._strides = _shape_strides(self.shape)
334 total_bytes = self.size * self.dtype.itemsize
335 if self.dtype.kind in "UO":
336 self._buf = None
337 self._obj_data = list(flat_vals) if flat_vals is not None else [None] * self.size
338 return
339 self._obj_data = None
340 self._buf = (ctypes.c_ubyte * max(1, total_bytes))()
341 if raw_bytes is not None:
342 if len(raw_bytes) != total_bytes:
343 raise ValueError(f"Expected {total_bytes} raw bytes, got {len(raw_bytes)}")
344 if total_bytes:
345 ctypes.memmove(self._buf, raw_bytes, total_bytes)
346 elif flat_vals is not None:
347 for i, val in enumerate(flat_vals):
348 self._set_flat(i, val)
349
350 def _get_flat(self, i):
351 if i < 0:
352 i += self.size
353 if not 0 <= i < self.size:
354 raise IndexError(i)
355 if self._obj_data is not None:
356 return self._obj_data[i]
357 sz = self.dtype.itemsize
358 if self.dtype.kind == "V":
359 return bytes(self._buf[i * sz : (i + 1) * sz])
360 return self.dtype._struct.unpack_from(self._buf, i * sz)[0]
361
362 def _set_flat(self, i, val):
363 if i < 0:
364 i += self.size
365 if not 0 <= i < self.size:
366 raise IndexError(i)
367 if self._obj_data is not None:
368 self._obj_data[i] = val
369 return
370 coerced = self.dtype.cast_val(val)
371 sz = self.dtype.itemsize
372 if self.dtype.kind == "V":
373 for b_i, byte in enumerate(coerced):
374 self._buf[i * sz + b_i] = byte
375 else:
376 self.dtype._struct.pack_into(self._buf, i * sz, coerced)
377
378 def _flat_list(self):
379 return [self._get_flat(i) for i in range(self.size)]
380
381 def _get_coord(self, coord):
382 return self._get_flat(_ravel_coord(coord, self._strides))
383
384 def _set_coord(self, coord, val):
385 self._set_flat(_ravel_coord(coord, self._strides), val)
386
387 @property
388 def ctypes(self):
389 return _FakeCtypesView(self)
390
391 @property
392 def flat(self):
393 return _FakeFlat(self)
394
395 @property
396 def T(self):
397 return self.transpose(*reversed(range(self.ndim)))
398
399 def __len__(self):
400 if self.ndim == 0:
401 raise TypeError("len() of unsized object")
402 return self.shape[0]
403
404 def __iter__(self):
405 if self.ndim == 0:
406 raise TypeError("iteration over a 0-d array")
407 for i in range(self.shape[0]):
408 yield self[i]
409
410 def __int__(self):
411 if self.size != 1:
412 raise TypeError("only length-1 arrays can be converted to Python scalars")
413 return int(self._get_flat(0))
414
415 def __index__(self):
416 if self.size != 1 or self.dtype.kind not in "iu":
417 raise TypeError("only integer scalar arrays can be converted to a scalar index")
418 return int(self._get_flat(0))
419
420 def __bool__(self):
421 if self.size != 1:
422 raise ValueError("The truth value of an array with more than one element is ambiguous")
423 return bool(self._get_flat(0))
424
425 def copy(self):
426 if self._obj_data is not None:
427 return _FakeArray(self.shape, self.dtype, flat_vals=list(self._obj_data))
428 return _FakeArray(self.shape, self.dtype, raw_bytes=self.tobytes())
429
430 def tobytes(self):
431 if self._obj_data is not None:
432 raise TypeError("cannot convert object/str array to bytes")
433 n = self.size * self.dtype.itemsize
434 return bytes(memoryview(self._buf)[:n])
435
436 def tolist(self):
437 def _build(offset, shape):
438 if not shape:
439 return self._get_flat(offset)
440 step = math.prod(shape[1:]) if len(shape) > 1 else 1
441 return [_build(offset + i * step, shape[1:]) for i in range(shape[0])]
442 return _build(0, self.shape)
443
444 def astype(self, dtype):
445 dt = _normalize_dtype(dtype)
446 return _FakeArray(self.shape, dt, flat_vals=self._flat_list())
447
448 def ravel(self):
449 return _FakeArray((self.size,), self.dtype, raw_bytes=self.tobytes()) if self._buf is not None else _FakeArray((self.size,), self.dtype, flat_vals=self._flat_list())
450
451 def reshape(self, *newshape):
452 if len(newshape) == 1 and isinstance(newshape[0], (tuple, list)):
453 newshape = tuple(newshape[0])
454 shape = list(newshape)
455 if -1 in shape:
456 neg_idx = shape.index(-1)
457 known = math.prod(d for d in shape if d != -1)
458 shape[neg_idx] = self.size // known
459 shape = tuple(shape)
460 if math.prod(shape) != self.size:
461 raise ValueError(f"cannot reshape array of size {self.size} into shape {shape}")
462 if self._buf is not None:
463 return _FakeArray(shape, self.dtype, raw_bytes=self.tobytes())
464 return _FakeArray(shape, self.dtype, flat_vals=self._flat_list())
465
466 def transpose(self, *axes):
467 if len(axes) == 1 and isinstance(axes[0], (tuple, list)):
468 axes = tuple(axes[0])
469 if not axes:
470 axes = tuple(reversed(range(self.ndim)))
471 new_shape = tuple(self.shape[a] for a in axes)
472 vals = []
473 for idx in range(self.size):
474 coord = _unravel(idx, new_shape)
475 src = [0] * self.ndim
476 for new_ax, old_ax in enumerate(axes):
477 src[old_ax] = coord[new_ax]
478 vals.append(self._get_coord(tuple(src)))
479 return _FakeArray(new_shape, self.dtype, flat_vals=vals)
480
481 def any(self):
482 return any(bool(v) for v in self._flat_list())
483
484 def all(self):
485 return all(bool(v) for v in self._flat_list())
486
487 def max(self):
488 vals = self._flat_list()
489 if not vals:
490 raise ValueError("zero-size array to reduction operation maximum which has no identity")
491 return max(vals)
492
493 def min(self):
494 vals = self._flat_list()
495 if not vals:
496 raise ValueError("zero-size array to reduction operation minimum which has no identity")
497 return min(vals)
498
499 # --- Indexing ---
500 def _parse_key(self, key):
501 if not isinstance(key, tuple):
502 key = (key,)
503 # Fast path: single boolean mask matching array shape or leading axis
504 if len(key) == 1 and isinstance(key[0], _FakeArray) and key[0].dtype.kind == "b":
505 return ("bool_mask", key[0])
506 if len(key) == 1 and isinstance(key[0], (list, tuple)) and key[0] and all(isinstance(v, bool) for v in key[0]):
507 return ("bool_mask", _fake_asarray(key[0], dtype="bool"))
508
509 # General multi-axis key supporting int, slice, None, and integer fancy indexers
510 items = list(key)
511 non_none = [x for x in items if x is not None]
512 while len(non_none) < self.ndim:
513 items.append(slice(None))
514 non_none.append(slice(None))
515 return ("axes", items)
516
517 def __getitem__(self, key):
518 kind, parsed = self._parse_key(key)
519 if kind == "bool_mask":
520 mask = parsed
521 if mask.shape == self.shape:
522 vals = [v for v, m in zip(self._flat_list(), mask._flat_list()) if m]
523 return _FakeArray((len(vals),), self.dtype, flat_vals=vals)
524 if mask.ndim == 1 and len(mask) == self.shape[0]:
525 tail_shape = self.shape[1:]
526 tail_size = math.prod(tail_shape) if tail_shape else 1
527 vals = []
528 rows = 0
529 for r, keep in enumerate(mask._flat_list()):
530 if keep:
531 rows += 1
532 base = r * tail_size
533 for off in range(tail_size):
534 vals.append(self._get_flat(base + off))
535 return _FakeArray((rows,) + tail_shape, self.dtype, flat_vals=vals)
536 raise IndexError("boolean index did not match indexed array")
537
538 # Separate axes into newaxis, slice, int, or fancy integer array
539 fancy_positions = []
540 axis = 0
541 axis_specs = []
542 for item in parsed:
543 if item is None:
544 axis_specs.append(("newaxis", None))
545 continue
546 dim = self.shape[axis]
547 if isinstance(item, slice):
548 axis_specs.append(("slice", range(*item.indices(dim))))
549 elif isinstance(item, int) or (isinstance(item, _FakeArray) and item.ndim == 0 and item.dtype.kind in "iu"):
550 idx = int(item)
551 if idx < 0:
552 idx += dim
553 if not 0 <= idx < dim:
554 raise IndexError(idx)
555 axis_specs.append(("int", idx))
556 else:
557 arr = item if isinstance(item, _FakeArray) else _fake_asarray(item)
558 if arr.dtype.kind not in "iu":
559 raise IndexError("arrays used as indices must be of integer type")
560 fancy_positions.append((len(axis_specs), dim, arr))
561 axis_specs.append(("fancy", arr))
562 axis += 1
563
564 if not fancy_positions:
565 out_shape = []
566 ranges = []
567 for sp_kind, sp_val in axis_specs:
568 if sp_kind == "newaxis":
569 out_shape.append(1)
570 ranges.append([0])
571 elif sp_kind == "slice":
572 out_shape.append(len(sp_val))
573 ranges.append(list(sp_val))
574 else:
575 ranges.append([sp_val])
576 if not out_shape:
577 coord = tuple(r[0] for r in ranges)
578 return self._get_coord(coord)
579 vals = []
580 total = math.prod(out_shape)
581 for idx in range(total):
582 oc = _unravel(idx, tuple(out_shape))
583 src = []
584 oi = 0
585 for sp_kind, sp_val in axis_specs:
586 if sp_kind == "newaxis":
587 oi += 1
588 elif sp_kind == "slice":
589 src.append(sp_val[oc[oi]])
590 oi += 1
591 else:
592 src.append(sp_val)
593 vals.append(self._get_coord(tuple(src)))
594 return _FakeArray(tuple(out_shape), self.dtype, flat_vals=vals)
595
596 # Broadcast all fancy arrays together
597 bshape = ()
598 for _, _, arr in fancy_positions:
599 bshape = _broadcast_shapes(bshape, arr.shape)
600 contiguous_fancy = [p for p, _, _ in fancy_positions] == list(
601 range(fancy_positions[0][0], fancy_positions[0][0] + len(fancy_positions))
602 )
603 # Build output shape
604 out_shape = []
605 fancy_inserted = False
606 slice_ranges = {}
607 for pos, (sp_kind, sp_val) in enumerate(axis_specs):
608 if sp_kind == "newaxis":
609 out_shape.append(1)
610 elif sp_kind == "slice":
611 out_shape.append(len(sp_val))
612 slice_ranges[pos] = list(sp_val)
613 elif sp_kind == "fancy":
614 if contiguous_fancy:
615 if not fancy_inserted:
616 out_shape.extend(bshape)
617 fancy_inserted = True
618 else:
619 if not fancy_inserted:
620 out_shape = list(bshape) + out_shape
621 fancy_inserted = True
622
623 # Map each output coordinate to source coordinate
624 total = math.prod(out_shape) if out_shape else 1
625 vals = []
626 b_start = 0 if not contiguous_fancy else sum(
627 1 for p, (k, _) in enumerate(axis_specs[: fancy_positions[0][0]]) if k in ("newaxis", "slice")
628 )
629 b_len = len(bshape)
630 for flat_i in range(total):
631 oc = _unravel(flat_i, tuple(out_shape))
632 b_coord = oc[b_start : b_start + b_len]
633 src = []
634 oi = 0 if contiguous_fancy else b_len
635 for pos, (sp_kind, sp_val) in enumerate(axis_specs):
636 if sp_kind == "newaxis":
637 oi += 1
638 elif sp_kind == "slice":
639 src.append(slice_ranges[pos][oc[oi]])
640 oi += 1
641 elif sp_kind == "int":
642 src.append(sp_val)
643 elif sp_kind == "fancy":
644 if pos == fancy_positions[0][0] and contiguous_fancy:
645 oi += b_len
646 dim = self.shape[len(src)]
647 fc = _broadcast_index(b_coord, sp_val.shape)
648 idx_v = int(sp_val._get_coord(fc)) if sp_val.ndim else int(sp_val._get_flat(0))
649 if idx_v < 0:
650 idx_v += dim
651 if not 0 <= idx_v < dim:
652 raise IndexError(idx_v)
653 src.append(idx_v)
654 vals.append(self._get_coord(tuple(src)))
655 if not out_shape:
656 return vals[0]
657 return _FakeArray(tuple(out_shape), self.dtype, flat_vals=vals)
658
659 def __setitem__(self, key, value):
660 kind, parsed = self._parse_key(key)
661 if kind == "bool_mask":
662 mask = parsed
663 rhs = value if isinstance(value, _FakeArray) else _fake_asarray(value, dtype=self.dtype)
664 if mask.shape == self.shape:
665 k = 0
666 for i, m in enumerate(mask._flat_list()):
667 if m:
668 v = rhs._get_flat(0) if rhs.size == 1 else rhs._get_flat(k)
669 self._set_flat(i, v)
670 k += 1
671 return
672 if mask.ndim == 1 and len(mask) == self.shape[0]:
673 tail_shape = self.shape[1:]
674 tail_size = math.prod(tail_shape) if tail_shape else 1
675 n_true = sum(1 for m in mask._flat_list() if m)
676 target_shape = (n_true,) + tail_shape
677 b_shape = _broadcast_shapes(target_shape, rhs.shape)
678 if b_shape != target_shape:
679 raise ValueError(f"cannot broadcast {rhs.shape} to {target_shape}")
680 t_idx = 0
681 for r, keep in enumerate(mask._flat_list()):
682 if keep:
683 base = r * tail_size
684 for off in range(tail_size):
685 tc = (t_idx,) + _unravel(off, tail_shape)
686 rc = _broadcast_index(tc, rhs.shape)
687 self._set_flat(base + off, rhs._get_coord(rc) if rhs.ndim else rhs._get_flat(0))
688 t_idx += 1
689 return
690 raise IndexError("boolean index did not match indexed array")
691
692 # Concrete axis assignment (ints and slices)
693 slices = []
694 sub_shape = []
695 axis = 0
696 for item in parsed:
697 if item is None:
698 continue
699 dim = self.shape[axis]
700 if isinstance(item, slice):
701 rng = list(range(*item.indices(dim)))
702 slices.append(rng)
703 sub_shape.append(len(rng))
704 else:
705 idx = int(item)
706 if idx < 0:
707 idx += dim
708 if not 0 <= idx < dim:
709 raise IndexError(idx)
710 slices.append([idx])
711 axis += 1
712 rhs = value if isinstance(value, _FakeArray) else _fake_asarray(value, dtype=self.dtype)
713 sub_shape = tuple(sub_shape)
714 if not sub_shape:
715 coord = tuple(r[0] for r in slices)
716 self._set_coord(coord, rhs._get_flat(0) if rhs.size == 1 else rhs)
717 return
718 total = math.prod(sub_shape)
719 for fi in range(total):
720 sc = _unravel(fi, sub_shape)
721 dst = []
722 si = 0
723 for rng in slices:
724 if len(rng) == 1 and len(sub_shape) < len(slices):
725 dst.append(rng[0])
726 else:
727 dst.append(rng[sc[si]])
728 si += 1
729 # Re-derive dst accurately:
730 dst = []
731 si = 0
732 for ax_i, item in enumerate(parsed):
733 if item is None:
734 continue
735 if isinstance(item, slice):
736 dst.append(slices[ax_i][sc[si]])
737 si += 1
738 else:
739 dst.append(slices[ax_i][0])
740 rc = _broadcast_index(sc, rhs.shape)
741 self._set_coord(tuple(dst), rhs._get_coord(rc) if rhs.ndim else rhs._get_flat(0))
742
743 # --- Operators ---
744 def _binop(self, other, fn, out_dtype=None):
745 rhs = other if isinstance(other, _FakeArray) else _fake_asarray(other)
746 bshape = _broadcast_shapes(self.shape, rhs.shape)
747 dt = _normalize_dtype(out_dtype) if out_dtype is not None else _promote_dtype(self.dtype, rhs.dtype)
748 total = math.prod(bshape) if bshape else 1
749 vals = []
750 for i in range(total):
751 oc = _unravel(i, bshape)
752 a_val = self._get_coord(_broadcast_index(oc, self.shape)) if self.ndim else self._get_flat(0)
753 b_val = rhs._get_coord(_broadcast_index(oc, rhs.shape)) if rhs.ndim else rhs._get_flat(0)
754 vals.append(fn(a_val, b_val))
755 return _FakeArray(bshape, dt, flat_vals=vals)
756
757 def _rbinop(self, other, fn, out_dtype=None):
758 lhs = other if isinstance(other, _FakeArray) else _fake_asarray(other)
759 return lhs._binop(self, fn, out_dtype=out_dtype)
760
761 def _ibop(self, other, fn):
762 res = self._binop(other, fn, out_dtype=self.dtype)
763 for i, v in enumerate(res._flat_list()):
764 self._set_flat(i, v)
765 return self
766
767 def __add__(self, o): return self._binop(o, lambda a, b: a + b)
768 def __radd__(self, o): return self._rbinop(o, lambda a, b: a + b)
769 def __iadd__(self, o): return self._ibop(o, lambda a, b: a + b)
770 def __sub__(self, o): return self._binop(o, lambda a, b: a - b)
771 def __rsub__(self, o): return self._rbinop(o, lambda a, b: a - b)
772 def __mul__(self, o): return self._binop(o, lambda a, b: a * b)
773 def __rmul__(self, o): return self._rbinop(o, lambda a, b: a * b)
774 def __floordiv__(self, o): return self._binop(o, lambda a, b: a // b)
775 def __mod__(self, o): return self._binop(o, lambda a, b: a % b)
776 def __imod__(self, o): return self._ibop(o, lambda a, b: a % b)
777 def __lshift__(self, o): return self._binop(o, lambda a, b: a << b)
778 def __rlshift__(self, o):
779 # Preserve self's integer dtype when shifting a scalar 1 << uint64_arr
780 rhs_arr = o if isinstance(o, _FakeArray) else _fake_asarray(o, dtype=self.dtype)
781 return rhs_arr._binop(self, lambda a, b: a << b, out_dtype=self.dtype)
782 def __rshift__(self, o): return self._binop(o, lambda a, b: a >> b)
783 def __and__(self, o): return self._binop(o, lambda a, b: a & b)
784 def __or__(self, o): return self._binop(o, lambda a, b: a | b)
785 def __ior__(self, o): return self._ibop(o, lambda a, b: a | b)
786 def __xor__(self, o): return self._binop(o, lambda a, b: a ^ b)
787 def __lt__(self, o): return self._binop(o, lambda a, b: a < b, out_dtype="bool")
788 def __le__(self, o): return self._binop(o, lambda a, b: a <= b, out_dtype="bool")
789 def __gt__(self, o): return self._binop(o, lambda a, b: a > b, out_dtype="bool")
790 def __ge__(self, o): return self._binop(o, lambda a, b: a >= b, out_dtype="bool")
791 def __eq__(self, o): return self._binop(o, lambda a, b: a == b, out_dtype="bool")
792 def __ne__(self, o): return self._binop(o, lambda a, b: a != b, out_dtype="bool")
793
794 def __neg__(self):
795 return _FakeArray(self.shape, self.dtype, flat_vals=[-v for v in self._flat_list()])
796
797 def __invert__(self):
798 if self.dtype.kind == "b":
799 return _FakeArray(self.shape, self.dtype, flat_vals=[not v for v in self._flat_list()])
800 return _FakeArray(self.shape, self.dtype, flat_vals=[~v for v in self._flat_list()])
801
802 def __matmul__(self, other):
803 rhs = other if isinstance(other, _FakeArray) else _fake_asarray(other)
804 dt = _promote_dtype(self.dtype, rhs.dtype)
805 if self.ndim == 2 and rhs.ndim == 1 and self.shape[1] == rhs.shape[0]:
806 m, k = self.shape
807 r_vals = rhs._flat_list()
808 s_vals = self._flat_list()
809 out = [sum(s_vals[i * k + j] * r_vals[j] for j in range(k)) for i in range(m)]
810 return _FakeArray((m,), dt, flat_vals=out)
811 raise ValueError(f"Unsupported matmul shapes {self.shape} @ {rhs.shape}")
812
813
814def _fake_asarray(values, dtype=None):
815 if isinstance(values, _FakeArray):
816 if dtype is None or values.dtype == _normalize_dtype(dtype):
817 return values
818 return values.astype(dtype)
819 shape, flat, sub_dt = _flatten_nested(values)
820 dt = _normalize_dtype(dtype) if dtype is not None else (sub_dt or _infer_dtype(flat))
821 return _FakeArray(shape, dt, flat_vals=flat)
822
823
824def _fake_array(values, dtype=None):
825 arr = _fake_asarray(values, dtype=dtype)
826 return arr.copy()
827
828
829def _fake_ascontiguousarray(values, dtype=None):
830 return _fake_asarray(values, dtype=dtype).copy()
831
832
833def _fake_zeros(shape, dtype="float64"):
834 sh = (int(shape),) if isinstance(shape, int) else tuple(shape)
835 dt = _normalize_dtype(dtype)
836 n = math.prod(sh) if sh else 1
837 if dt.kind == "V":
838 return _FakeArray(sh, dt, flat_vals=[b"\x00" * dt.itemsize] * n)
839 return _FakeArray(sh, dt, flat_vals=[0] * n)
840
841
842def _fake_empty(shape, dtype="float64"):
843 return _fake_zeros(shape, dtype=dtype)
844
845
846def _fake_frombuffer(buf, dtype="uint8"):
847 raw = bytes(buf)
848 dt = _normalize_dtype(dtype)
849 if len(raw) % dt.itemsize != 0:
850 raise ValueError("buffer size must be a multiple of element size")
851 return _FakeArray((len(raw) // dt.itemsize,), dt, raw_bytes=raw)
852
853
854def _fake_arange(start, stop=None, step=1, dtype=None):
855 if stop is None:
856 start, stop = 0, start
857 vals = list(range(int(start), int(stop), int(step)))
858 return _FakeArray((len(vals),), dtype or "int64", flat_vals=vals)
859
860
861def _fake_any(arr):
862 return _fake_asarray(arr).any()
863
864
865def _fake_all(arr):
866 return _fake_asarray(arr).all()
867
868
869def _fake_unique(arr):
870 vals = sorted(set(_fake_asarray(arr)._flat_list()))
871 dt = arr.dtype if isinstance(arr, _FakeArray) else _infer_dtype(vals)
872 return _FakeArray((len(vals),), dt, flat_vals=vals)
873
874
875def _fake_searchsorted(a, v, side="left"):
876 edges = _fake_asarray(a)._flat_list()
877 queries = _fake_asarray(v)
878 fn = bisect.bisect_right if side == "right" else bisect.bisect_left
879 res = [fn(edges, x) for x in queries._flat_list()]
880 return _FakeArray(queries.shape, "int64", flat_vals=res)
881
882
883def _fake_roll(a, shift):
884 arr = _fake_asarray(a)
885 vals = arr._flat_list()
886 n = len(vals)
887 if n == 0:
888 return arr.copy()
889 s = shift % n
890 rolled = vals[-s:] + vals[:-s] if s else list(vals)
891 return _FakeArray(arr.shape, arr.dtype, flat_vals=rolled)
892
893
894def _fake_column_stack(tup):
895 cols = [_fake_asarray(c) for c in tup]
896 n = cols[0].shape[0]
897 dt = cols[0].dtype
898 for c in cols[1:]:
899 dt = _promote_dtype(dt, c.dtype)
900 flat = []
901 for r in range(n):
902 for c in cols:
903 flat.append(c._get_flat(r))
904 return _FakeArray((n, len(cols)), dt, flat_vals=flat)
905
906
907class _FakeBitwiseOr:
908 @staticmethod
909 def reduce(arr, axis=0):
910 a = _fake_asarray(arr)
911 if axis < 0:
912 axis += a.ndim
913 out_shape = tuple(d for i, d in enumerate(a.shape) if i != axis)
914 dim = a.shape[axis]
915 total = math.prod(out_shape) if out_shape else 1
916 vals = []
917 for idx in range(total):
918 oc = _unravel(idx, out_shape)
919 acc = 0
920 for k in range(dim):
921 src = list(oc)
922 src.insert(axis, k)
923 acc |= a._get_coord(tuple(src))
924 vals.append(acc)
925 return _FakeArray(out_shape, a.dtype, flat_vals=vals)
926
927
928def _make_fake_numpy():
929 import types
930 mod = types.ModuleType("numpy")
931 mod.array = _fake_array
932 mod.asarray = _fake_asarray
933 mod.ascontiguousarray = _fake_ascontiguousarray
934 mod.zeros = _fake_zeros
935 mod.empty = _fake_empty
936 mod.frombuffer = _fake_frombuffer
937 mod.arange = _fake_arange
938 mod.any = _fake_any
939 mod.all = _fake_all
940 mod.unique = _fake_unique
941 mod.searchsorted = _fake_searchsorted
942 mod.roll = _fake_roll
943 mod.column_stack = _fake_column_stack
944 mod.bitwise_or = _FakeBitwiseOr()
945 mod.ndarray = _FakeArray
946 return mod
947
948
949def _load_calibrated_texture():
950 """Load tools/calibrated_texture.py using real NumPy if present, else the stdlib shim."""
951 if importlib.util.find_spec("numpy") is not None:
952 import calibrated_texture
953 return calibrated_texture, False
954 fake_np = _make_fake_numpy()
955 spec = importlib.util.spec_from_file_location(
956 "calibrated_texture", str(TOOLS_DIR / "calibrated_texture.py")
957 )
958 mod = importlib.util.module_from_spec(spec)
959 with mock.patch.dict(sys.modules, {"numpy": fake_np}):
960 spec.loader.exec_module(mod)
961 return mod, True
962
963
964ct, _USING_FAKE_NP = _load_calibrated_texture()
965np = ct.np
966
967
968# ---------------------------------------------------------------------------
969# Synthetic RDS5 / ETPF pool and BCPack stream builders (no game data)
970# ---------------------------------------------------------------------------
971
972def write_custom_pool(path, records, chunks):
973 """Write a synthetic RDS5/ETPF pool with arbitrary `(codec, payload, virt_size)` chunks."""
974 count = len(chunks) + 2
975 table_end = 24 + (count - 1) * 8
976 etpf = ttpf.align(table_end, 256)
977 area = len(records) * 24
978 metadata = 16 + area + len(records) * 32
979 padded = ttpf.align(metadata, 4096)
980
981 source = etpf + padded
982 virt = padded
983 entries = []
984 packed_chunks = []
985 for codec, payload, vsize_chunk in chunks:
986 assert vsize_chunk > 0 and vsize_chunk % 4096 == 0
987 if codec == 0:
988 assert len(payload) == vsize_chunk
989 pad = 0
990 else:
991 pad = (-len(payload)) % 256
992 entries.append((source // 256) | (codec << 26) | ((virt // 4096) << 30) | (pad << 52))
993 packed_chunks.append((source, payload))
994 source += len(payload) + pad
995 virt += vsize_chunk
996
997 vsize = virt
998 entries.append((source // 256) | ((vsize // 4096) << 30))
999
1000 header = bytearray(24)
1001 header[0:4] = b"RDS5"
1002 struct.pack_into("<I", header, 4, count)
1003 struct.pack_into("<Q", header, 8, vsize | (22 << 56))
1004 struct.pack_into("<I", header, 16, (count + 31) // 32)
1005 struct.pack_into("<I", header, 20, 0)
1006
1007 blob = bytearray(source)
1008 blob[0:24] = header
1009 for i, e in enumerate(entries):
1010 struct.pack_into("<Q", blob, 24 + i * 8, e)
1011 blob[etpf : etpf + 4] = b"ETPF"
1012 struct.pack_into("<III", blob, etpf + 4, 634, len(records), area)
1013 for i, rec in enumerate(records):
1014 blob[etpf + 16 + i * 16 : etpf + 16 + (i + 1) * 16] = rec
1015 struct.pack_into("<Q", blob, etpf + 16 + len(records) * 16 + i * 8, 0x1000 + i)
1016 for src, payload in packed_chunks:
1017 blob[src : src + len(payload)] = payload
1018 Path(path).write_bytes(bytes(blob))
1019 return padded
1020
1021
1022def _bc3_profile_from_tables():
1023 alpha = [a0 | (a1 << 3) for a0, a1 in bcpack_tables.BC3_ALPHA_PAIR]
1024 endpoints = {"-512": [0, 0, 0, 128, 0, 0, 0, 128]}
1025 for k, vals in (bcpack_tables.BC3_HISTORY_CONFIRMED | bcpack_tables.BC3_HISTORY_PROVISIONAL).items():
1026 a0, a1, r0, g0, b0, r1, g1, b1 = vals
1027 endpoints[str(k - 256)] = [r0, g0, b0, a0, r1, g1, b1, a1]
1028 return {
1029 "endpoints": endpoints,
1030 "color": list(bcpack_tables.BC3_COLOUR_QUADRANT),
1031 "alpha": alpha,
1032 }
1033
1034
1035def _bc1_profile_with_confirmed():
1036 prof = synthetic_profile()
1037 for entry, vals in bcpack_tables.BC1_HISTORY_CONFIRMED.items():
1038 prof["bc1"]["endpoints"][256 - entry] = list(vals)
1039 return prof
1040
1041
1042def _empty_bc7_section():
1043 return {
1044 "labels": [[0, 0, 0, 0] for _ in range(1024)],
1045 "anchors": [1] * 128,
1046 "seeds": {
1047 "base": [[[0, 8] for _ in range(56)] for _ in range(256)],
1048 "secondary": [[[0, 8] for _ in range(56)] for _ in range(256)],
1049 "early": [[[0, 8] for _ in range(56)] for _ in range(256)],
1050 "refined": [[[0, 8] for _ in range(56)] for _ in range(256)],
1051 },
1052 "adjustments": {},
1053 }
1054
1055
1056def _encode_bc4_from_lanes(lanes):
1057 return tb.encode_lanes(lanes, 4)
1058
1059
1060def _encode_bc5_from_lanes(lanes):
1061 return tb.encode_lanes(lanes, 5)
1062
1063
1064def _encode_bc3_from_lanes(lanes):
1065 return tb.encode_lanes(lanes, 3)
1066
1067
1068def _encode_bc6h_solid(nblocks):
1069 # Self-contained mode-11 (1-region, 4-bit index) zero-delta blocks.
1070 # For di=0, iref[0]=8; shift anchor pixel 0 by -8 so index 0 clears the anchor bit.
1071 lanes = [[0] * (2 * nblocks) for _ in range(16)]
1072 ix0 = tb._pack_ix_pair(tb._zig(-8), 0, 0)
1073 for i in range(nblocks):
1074 lanes[15][2 * i] = 10 # mode 11
1075 lanes[2][2 * i] = tb._zig(100 + (i & 15))
1076 lanes[11][2 * i] = ix0
1077 return tb.encode_lanes(lanes, 6)
1078
1079
1080def _encode_bc7_mode6_solid(nblocks):
1081 blk = ttm.solid_bc7(180, 90, 45)
1082 return tb.encode_bc7_mode6_blocks(blk * nblocks)
1083
1084
1085@contextmanager
1086def _fake_native_context(*, unpack_fn=None, rebuild_fn=None):
1087 """Patch ct.native() with a mock library supporting ctypes pointer reads/writes."""
1088 lib = mock.MagicMock()
1089 if unpack_fn is None:
1090 lib.unpack.side_effect = lambda *args: -1
1091 else:
1092 lib.unpack.side_effect = unpack_fn
1093 if rebuild_fn is not None:
1094 lib.rebuild.side_effect = rebuild_fn
1095 else:
1096 lib.rebuild.side_effect = lambda *args: None
1097 with mock.patch.object(ct, "native", return_value=lib):
1098 yield lib
1099
1100
1101def _read_u8_buf(ptr, n):
1102 return bytes((ctypes.c_ubyte * n).from_address(ptr)) if n else b""
1103
1104
1105def _write_u8_buf(ptr, data):
1106 if data:
1107 ctypes.memmove(ptr, data, len(data))
1108
1109
1110# ---------------------------------------------------------------------------
1111# Tests
1112# ---------------------------------------------------------------------------
1113
1114class TestNativeLoader(unittest.TestCase):
1115 def setUp(self):
1116 ct.native.cache_clear()
1117 self.addCleanup(ct.native.cache_clear)
1118
1119 def test_platform_library_names_and_ctypes_signatures(self):
1120 cases = (
1121 ("win32", "bcpack_calibration.dll"),
1122 ("darwin", "libbcpack_calibration.dylib"),
1123 ("linux", "libbcpack_calibration.so"),
1124 ("freebsd14", "libbcpack_calibration.so"),
1125 )
1126 expected_dir = Path(ct.__file__).with_name("bcpack_calibration") / "target/release"
1127 for plat, filename in cases:
1128 with self.subTest(platform=plat):
1129 ct.native.cache_clear()
1130 fake_lib = mock.MagicMock()
1131 with mock.patch.object(ct.sys, "platform", plat), \
1132 mock.patch.object(ct.ctypes, "CDLL", return_value=fake_lib) as cdll:
1133 got = ct.native()
1134 self.assertIs(got, fake_lib)
1135 cdll.assert_called_once_with(str(expected_dir / filename))
1136 self.assertEqual(
1137 fake_lib.unpack.argtypes,
1138 [
1139 ctypes.c_char_p,
1140 ctypes.c_size_t,
1141 ctypes.c_char_p,
1142 ctypes.c_size_t,
1143 ctypes.c_size_t,
1144 ctypes.c_void_p,
1145 ],
1146 )
1147 self.assertIs(fake_lib.unpack.restype, ctypes.c_ssize_t)
1148 self.assertEqual(
1149 fake_lib.rebuild.argtypes,
1150 [ctypes.c_void_p, ctypes.c_size_t] + [ctypes.c_void_p] * 5,
1151 )
1152 self.assertIsNone(fake_lib.rebuild.restype)
1153
1154 def test_native_caches_until_cleared_and_propagates_oserror(self):
1155 fake_lib = mock.MagicMock()
1156 with mock.patch.object(ct.ctypes, "CDLL", return_value=fake_lib) as cdll:
1157 self.assertIs(ct.native(), fake_lib)
1158 self.assertIs(ct.native(), fake_lib)
1159 self.assertEqual(cdll.call_count, 1)
1160 ct.native.cache_clear()
1161 self.assertIs(ct.native(), fake_lib)
1162 self.assertEqual(cdll.call_count, 2)
1163
1164 ct.native.cache_clear()
1165 with mock.patch.object(ct.ctypes, "CDLL", side_effect=OSError("missing dll")) as cdll:
1166 with self.assertRaises(OSError):
1167 ct.native()
1168 with self.assertRaises(OSError):
1169 ct.native()
1170 self.assertEqual(cdll.call_count, 2)
1171
1172
1173class TestArrayAndMathHelpers(unittest.TestCase):
1174 def test_array_validation_and_contiguous_conversion(self):
1175 arr = ct.array([[0, 255], [-1, 128]], (2, 2), "int16", -1, 255)
1176 self.assertEqual(arr.shape, (2, 2))
1177 self.assertEqual(arr.dtype.kind, "i")
1178 self.assertEqual(arr.tobytes(), struct.pack("<4h", 0, 255, -1, 128))
1179
1180 # Unsigned boundary 0..65535
1181 u = ct.array([0, 65535], (2,), "uint16", 0, 65535)
1182 self.assertEqual(u.tobytes(), struct.pack("<2H", 0, 65535))
1183
1184 # Transposed non-contiguous input becomes contiguous in row-major order.
1185 src = np.array([[1, 2], [3, 4]]).T
1186 contig = ct.array(src, (2, 2), "uint8", 0, 10)
1187 self.assertEqual(contig.tobytes(), bytes([1, 3, 2, 4]))
1188
1189 # Invalid shape, type, and out-of-range values
1190 for bad_val, shape, dt, lo, hi in (
1191 ([1, 2, 3], (2, 2), "int32", 0, 10),
1192 ([1.0, 2.0], (2,), "int32", 0, 10),
1193 ([True, False], (2,), "uint8", 0, 1),
1194 (["1", "2"], (2,), "uint8", 0, 10),
1195 ([-2, 0], (2,), "int16", -1, 10),
1196 ([0, 256], (2,), "uint8", 0, 255),
1197 ):
1198 with self.subTest(bad_val=bad_val, shape=shape):
1199 with self.assertRaisesRegex(ValueError, "Invalid calibration field"):
1200 ct.array(bad_val, shape, dt, lo, hi)
1201
1202 def test_unzig_matches_bcpack(self):
1203 vals = list(range(256))
1204 got = ct.unzig(np.array(vals, dtype="int32")).tolist()
1205 self.assertEqual(got, [bcpack._unzig(v) for v in vals])
1206 self.assertEqual(ct.unzig(0), 0)
1207 self.assertEqual(ct.unzig(1), -1)
1208 self.assertEqual(ct.unzig(2), 1)
1209 self.assertEqual(ct.unzig(255), -128)
1210
1211 def test_distance_exhaustive_inter8_and_lane_selection(self):
1212 pairs = [(a, b) for a in range(16) for b in range(16)]
1213 # Shape (256, 2, 2): put pair in lane 1 and zero in lane 0.
1214 syms = [[[0, a], [0, b]] for a, b in pairs]
1215 arr = np.array(syms, dtype="uint8")
1216 self.assertEqual(ct.distance(arr, 0).tolist(), [0] * 256)
1217 self.assertEqual(ct.distance(arr, 1).tolist(), [bcpack._inter8(a, b) for a, b in pairs])
1218
1219 def test_accumulate_chains_zero_and_external_roots(self):
1220 # Empty input
1221 empty_r = ct.accumulate(np.array([], dtype="int32"), np.zeros((0, 2), dtype="int32"))
1222 self.assertEqual(empty_r.shape, (0,))
1223
1224 # Block 0: d=0 (-512); Block 1->0->-512; Block 2->1->0; Block 3->2->1->0 (depth 3);
1225 # Block 4: d=10 (external -> root = 4 - 10 = -6); Block 5->4 (root = -6).
1226 distances = np.array([0, 1, 1, 1, 10, 1, 2, 0], dtype="int32")
1227 residuals = np.array(
1228 [[10, 1], [2, 3], [4, 5], [6, 7], [100, 200], [5, -10], [7, 8], [9, 10]],
1229 dtype="int32",
1230 )
1231 roots = ct.accumulate(distances, residuals)
1232 self.assertEqual(roots.tolist(), [-512, -512, -512, -512, -6, -6, -6, -512])
1233 self.assertEqual(
1234 residuals.tolist(),
1235 [[10, 1], [12, 4], [16, 9], [22, 16], [100, 200], [105, 190], [107, 208], [9, 10]],
1236 )
1237
1238 def test_addresses_matches_detile_across_4k_and_64k_tiles(self):
1239 ct.addresses.cache_clear()
1240 for tile in (4096, 65536):
1241 for fmt, bs in ((71, 8), (98, 16)):
1242 with self.subTest(tile=tile, bs=bs):
1243 lay = ttpf.surface_layout(256, 192, fmt, 8, tile)
1244 bw, bh = lay["block_w"], lay["block_h"]
1245 for mip in (lay["mips"][0], lay["mips"][-1]):
1246 w, h = mip["blocks_w"], mip["blocks_h"]
1247 x0, y0 = mip["tile_x"], mip["tile_y"]
1248 got = ct.addresses(tile, bs, bw, bh, w, h, x0, y0).tolist()
1249 # Compare against ttpf.detile by placing unique byte markers at each offset.
1250 # Note detile checks offset within mip["region"]; fill a synthetic region with
1251 # 8-byte / 16-byte tagged offsets.
1252 region = bytearray(mip["region"])
1253 for off in range(0, len(region), bs):
1254 struct.pack_into("<Q", region, off, off)
1255 detiled = ttpf.detile(lay, mip, bytes(region))
1256 expected = [
1257 struct.unpack_from("<Q", detiled, i * bs)[0] for i in range(w * h)
1258 ]
1259 self.assertEqual(got, expected)
1260 info_before = ct.addresses.cache_info()
1261 ct.addresses(4096, 8, 32, 16, 4, 4, 0, 0)
1262 ct.addresses(4096, 8, 32, 16, 4, 4, 0, 0)
1263 info_after = ct.addresses.cache_info()
1264 self.assertEqual(info_after.hits, info_before.hits + 1)
1265
1266
1267class TestBlockRebuildersParity(unittest.TestCase):
1268 def test_bc1_blocks_parity_chains_and_missing_history(self):
1269 prof = _bc1_profile_with_confirmed()
1270 seeds = ct.array(prof["bc1"]["endpoints"], (256, 6), "int32", -1, 63)
1271 selectors = ct.array(prof["bc1"]["selectors"], (4, 256), "uint32", 0, 0xFFFFFFFF)
1272
1273 # Block 0: external confirmed entry 1 (d=255 -> 256+0-255=1 -> age=255)
1274 # Block 1: d=1 -> chains onto Block 0 (external root)
1275 # Block 2: d=0 -> self-contained with negative endpoint wrap
1276 # Block 3: d=1 -> chains onto Block 2
1277 lanes = [
1278 [tb._zig(-1), tb._zig(1), 0, tb._zig(1)], # l0: -1 mod 256 = 255
1279 [0, 0, 0, 0],
1280 [tb._zig(2), tb._zig(-3), tb._zig(-1), tb._zig(4)],
1281 [tb._zig(-4), tb._zig(5), tb._zig(-2), tb._zig(10)],
1282 [tb._zig(1), tb._zig(2), tb._zig(-3), tb._zig(7)],
1283 [tb._zig(-1), tb._zig(3), tb._zig(-5), tb._zig(2)],
1284 [tb._zig(6), tb._zig(-2), tb._zig(-1), tb._zig(8)],
1285 [tb._zig(0), tb._zig(1), tb._zig(-2), tb._zig(3)],
1286 [0, 17, 128, 255],
1287 [1, 33, 64, 200],
1288 [2, 99, 150, 10],
1289 [3, 210, 44, 77],
1290 ]
1291 sy = np.ascontiguousarray(np.asarray(lanes, dtype="uint8").T)
1292 got = ct.bc1_blocks(sy, (seeds, selectors))
1293 expected = bcpack._bc1_blocks(lanes, 4, None)
1294 self.assertEqual(got, expected)
1295
1296 # Missing external history (provisional entry 6 -> age 250 has -1 in seeds) raises ValueError.
1297 bad_seeds = ct.array([[-1] * 6 for _ in range(256)], (256, 6), "int32", -1, 63)
1298 lanes_ext = [[tb._zig(-6)] if k == 0 else [0] for k in range(12)]
1299 sy_ext = np.ascontiguousarray(np.asarray(lanes_ext, dtype="uint8").T)
1300 with self.assertRaisesRegex(ValueError, "Missing BC1 endpoint history"):
1301 ct.bc1_blocks(sy_ext, (bad_seeds, selectors))
1302
1303 # Self-contained stream (d=0) succeeds even with -1 in all external seeds.
1304 lanes_self = [[k * 3 % 32] for k in range(12)]
1305 lanes_self[0] = [0]
1306 lanes_self[1] = [0]
1307 sy_self = np.ascontiguousarray(np.asarray(lanes_self, dtype="uint8").T)
1308 self.assertEqual(ct.bc1_blocks(sy_self, (bad_seeds, selectors)), bcpack._bc1_blocks(lanes_self, 1, None))
1309
1310 def test_bc7_blocks_invokes_native_rebuild(self):
1311 sy = np.array([[i for i in range(16)] for _ in range(4)], dtype="uint8") # 2 blocks
1312 labels = ct.array([[1, 2, 0, 0] for _ in range(1024)], (1024, 4), "int16", -1, 255)
1313 anchors = ct.array([7] * 128, (128,), "uint16", 0, 65535)
1314 seed = ct.array([[[0, 8] for _ in range(56)] for _ in range(256)], (256, 56, 2), "uint8", 0, 255)
1315
1316 b0 = bytes(range(16))
1317 b1 = bytes(range(16, 32))
1318 seen = {}
1319
1320 def fake_rebuild(s_ptr, count, lab_ptr, seed_ptr, anc_ptr, out_ptr, ok_ptr):
1321 seen["args"] = (s_ptr, count, lab_ptr, seed_ptr, anc_ptr, out_ptr, ok_ptr)
1322 seen["s_bytes"] = _read_u8_buf(s_ptr, count * 32)
1323 _write_u8_buf(out_ptr, b0 + b1)
1324 _write_u8_buf(ok_ptr, bytes([1, 0]))
1325
1326 with _fake_native_context(rebuild_fn=fake_rebuild) as lib:
1327 out, ok = ct.bc7_blocks(sy, (labels, anchors), seed)
1328 self.assertEqual(lib.rebuild.call_count, 1)
1329 self.assertEqual(seen["args"][1], 2)
1330 self.assertEqual(seen["args"][2], labels.ctypes.data)
1331 self.assertEqual(seen["args"][3], seed.ctypes.data)
1332 self.assertEqual(seen["args"][4], anchors.ctypes.data)
1333 self.assertEqual(seen["s_bytes"], sy.tobytes())
1334 self.assertEqual(out.tobytes(), b0 + b1)
1335 self.assertEqual(ok.tolist(), [True, False])
1336
1337 # Zero blocks
1338 empty_sy = np.zeros((0, 16), dtype="uint8")
1339 with _fake_native_context() as lib:
1340 out0, ok0 = ct.bc7_blocks(empty_sy, (labels, anchors), seed)
1341 self.assertEqual(out0.shape, (0,))
1342 self.assertEqual(ok0.shape, (0,))
1343 self.assertEqual(lib.rebuild.call_args[0][1], 0)
1344
1345 def test_scalar_bc4_parity_and_missing_slot(self):
1346 table = dict(bcpack_tables.BC4_HISTORY_PROVISIONAL)
1347 # Block 0: d=0; Block 1: d=1; Block 2: external slot 25 (d=256+2-25=233 -> unzig(-23))
1348 d2 = tb._zig(-23)
1349 lanes = [
1350 [0, tb._zig(1), d2],
1351 [0, 0, 0],
1352 [tb._zig(30), tb._zig(-50), tb._zig(-100)],
1353 [tb._zig(-120), tb._zig(45), tb._zig(20)],
1354 [0, 12, 33], [1, 15, 44], [2, 20, 55], [3, 25, 63],
1355 [4, 30, 7], [5, 35, 8], [6, 40, 9], [7, 45, 10],
1356 ]
1357 sy = np.ascontiguousarray(np.asarray(lanes, dtype="uint8").T)
1358 got = ct.scalar_bc4(sy, table)
1359 expected = bcpack._bc4_blocks(lanes, 3, set())
1360 self.assertEqual(got, expected)
1361
1362 with self.assertRaises(KeyError):
1363 ct.scalar_bc4(sy, {})
1364
1365 def test_local_bc5_parity_and_missing_slot(self):
1366 # Block 0: confirmed entry 182 (d=256+0-182=74)
1367 # Block 1: d=1 (chains onto Block 0)
1368 # Block 2: provisional entry 3 (d=256+2-3=255 -> -1 mod 256)
1369 # Block 3: distance=0 (seed 128)
1370 # local_bc5 uses compatibility endpoint ordering where s[:, 0, 2:4] holds
1371 # (r0, r1) and s[:, 1, 2:4] holds (g0, g1), while selector lanes 4..11
1372 # match bcpack._bc5_blocks identically.
1373 d0a, d0b = tb._deint4(tb._zig(74) & 255)
1374 d1a, d1b = tb._deint4(tb._zig(1) & 255)
1375 d2a, d2b = tb._deint4(tb._zig(-1) & 255)
1376 lanes = [[] for _ in range(12)]
1377 lanes[0] = [d0a, d0b, d1a, d1b, d2a, d2b, 0, 0]
1378 lanes[1] = [0] * 8
1379 lanes[2] = [tb._zig(10), tb._zig(-20), tb._zig(5), tb._zig(-15), tb._zig(30), tb._zig(40), tb._zig(-60), tb._zig(70)]
1380 lanes[3] = [tb._zig(-5), tb._zig(25), tb._zig(-10), tb._zig(35), tb._zig(-40), tb._zig(12), tb._zig(80), tb._zig(-90)]
1381 for ln in range(4, 12):
1382 lanes[ln] = [(ln * 7 + k * 5) & 63 for k in range(8)]
1383 sy = np.ascontiguousarray(np.asarray(lanes, dtype="uint8").T)
1384 got = ct.local_bc5(sy)
1385
1386 # Verify selector bytes (bytes 2..7 and 10..15 of each 16-byte block) match bcpack._bc5_blocks,
1387 # and endpoint bytes match the compatibility ordering against BC5_HISTORY_* tables.
1388 ref = bcpack._bc5_blocks(lanes, 4, set())
1389 self.assertEqual(len(got), 64)
1390 h182 = bcpack_tables.BC5_HISTORY_CONFIRMED[182]
1391 h3 = bcpack_tables.BC5_HISTORY_PROVISIONAL[3]
1392 # Block 0: base h182 reshaped (2, 2) -> [[h182[0], h182[1]], [h182[2], h182[3]]]
1393 b0_ep = (
1394 (h182[0] + 10) % 256,
1395 (h182[1] - 5) % 256,
1396 (h182[2] - 20) % 256,
1397 (h182[3] + 25) % 256,
1398 )
1399 # Block 1: chains onto Block 0
1400 b1_ep = (
1401 (b0_ep[0] + 5) % 256,
1402 (b0_ep[1] - 10) % 256,
1403 (b0_ep[2] - 15) % 256,
1404 (b0_ep[3] + 35) % 256,
1405 )
1406 # Block 2: base h3
1407 b2_ep = (
1408 (h3[0] + 30) % 256,
1409 (h3[1] - 40) % 256,
1410 (h3[2] + 40) % 256,
1411 (h3[3] + 12) % 256,
1412 )
1413 # Block 3: d=0 -> seed (128, 128, 128, 128)
1414 b3_ep = ((128 - 60) % 256, (128 + 80) % 256, (128 + 70) % 256, (128 - 90) % 256)
1415 for bi, ep in enumerate((b0_ep, b1_ep, b2_ep, b3_ep)):
1416 off = bi * 16
1417 self.assertEqual((got[off], got[off + 1], got[off + 8], got[off + 9]), ep)
1418 self.assertEqual(got[off + 2 : off + 8], ref[off + 2 : off + 8])
1419 self.assertEqual(got[off + 10 : off + 16], ref[off + 10 : off + 16])
1420
1421 # Unknown history entry 1 (neither confirmed nor provisional) raises KeyError.
1422 u0a, u0b = tb._deint4(tb._zig(-1) & 255)
1423 bad_lanes = [[u0a, u0b] if k == 0 else [0, 0] for k in range(12)]
1424 bad_sy = np.ascontiguousarray(np.asarray(bad_lanes, dtype="uint8").T)
1425 with self.assertRaises(KeyError):
1426 ct.local_bc5(bad_sy)
1427
1428 def test_local_bc3_parity_and_missing_slot(self):
1429 profile = _bc3_profile_from_tables()
1430 # Block 0: d=0 (slot -512)
1431 # Block 1: d=1 (chains onto Block 0)
1432 # Block 2: provisional entry 26 (d=256+2-26=232 -> unzig(-24) & 255)
1433 d0a, d0b = 0, 0
1434 d1a, d1b = tb._deint4(tb._zig(1) & 255)
1435 d2a, d2b = tb._deint4(tb._zig(-24) & 255)
1436 lanes = [[] for _ in range(12)]
1437 lanes[0] = [d0a, d0b, d1a, d1b, d2a, d2b]
1438 lanes[1] = [0] * 6
1439 lanes[2] = [tb._zig(20), tb._zig(-30), tb._zig(5), tb._zig(-10), tb._zig(40), tb._zig(-50)]
1440 for ln in range(3, 7):
1441 lanes[ln] = [(ln * 11 + k * 7) & 63 for k in range(6)]
1442 lanes[7] = [tb._zig(7), tb._zig(-3), tb._zig(4), tb._zig(-2), tb._zig(12), tb._zig(-8)]
1443 lanes[8] = [tb._zig(-15), tb._zig(22), tb._zig(3), tb._zig(-9), tb._zig(18), tb._zig(25)]
1444 lanes[9] = [tb._zig(9), tb._zig(-12), tb._zig(-1), tb._zig(6), tb._zig(-14), tb._zig(11)]
1445 lanes[10] = [12, 45, 78, 123, 200, 251]
1446 lanes[11] = [33, 67, 101, 144, 188, 229]
1447
1448 sy = np.ascontiguousarray(np.asarray(lanes, dtype="uint8").T)
1449 got = ct.local_bc3(sy, profile)
1450 expected = bcpack._bc3_blocks(lanes, 3, set())
1451 self.assertEqual(got, expected)
1452
1453 with self.assertRaises(KeyError):
1454 ct.local_bc3(sy, {"endpoints": {}, "color": profile["color"], "alpha": profile["alpha"]})
1455
1456
1457class TestLocalDecoder(unittest.TestCase):
1458 def setUp(self):
1459 tmp = tempfile.TemporaryDirectory()
1460 self.addCleanup(tmp.cleanup)
1461 self.root = Path(tmp.name)
1462
1463 def _open_pool(self, name, records, chunks):
1464 path = self.root / name
1465 base = write_custom_pool(path, records, chunks)
1466 pool = ttpf.Pool(str(path))
1467 self.addCleanup(pool.close)
1468 return pool, base
1469
1470 def test_init_rejects_bad_calibration_versions_and_isolates_cache(self):
1471 pool, base = self._open_pool(
1472 "raw.ttpf",
1473 [ttm.pack_etpf_record(64, 64, 1, 0, 71, 1, 1, 4, 4096)],
1474 [(0, b"\xAA" * 4096, 4096)],
1475 )
1476 for bad in (None, [], "v1", 1, {}, {"version": 0}, {"version": 2}, {"version": "1"}):
1477 with self.subTest(bad=bad):
1478 with self.assertRaisesRegex(ValueError, "Unsupported calibration version"):
1479 ct.LocalDecoder(pool, bad)
1480
1481 dec1 = ct.LocalDecoder(pool, {"version": 1})
1482 dec2 = ct.LocalDecoder(pool, {"version": 1})
1483 self.assertEqual(dec1.edges.tolist(), [base, base + 4096])
1484 b1, m1 = dec1.read_chunk(0, 8, "base")
1485 self.assertIsNone(m1)
1486 self.assertEqual(len(b1), 512)
1487 self.assertEqual(dec1.read_chunk.cache_info().currsize, 1)
1488 self.assertEqual(dec2.read_chunk.cache_info().currsize, 0)
1489
1490 def test_seed_validation_precision_and_caching(self):
1491 pool, _ = self._open_pool(
1492 "dummy.ttpf",
1493 [ttm.pack_etpf_record(64, 64, 1, 0, 98, 1, 1, 4, 4096)],
1494 [(0, b"\x00" * 4096, 4096)],
1495 )
1496 cal = {"version": 1, "bc7": _empty_bc7_section()}
1497 dec = ct.LocalDecoder(pool, cal)
1498 s1 = dec.seed("base")
1499 s2 = dec.seed("base")
1500 self.assertIs(s1, s2)
1501 with self.assertRaises(KeyError):
1502 dec.seed("nonexistent")
1503
1504 cal["bc7"]["seeds"]["bad_prec"] = [[[0, 9] for _ in range(56)] for _ in range(256)]
1505 with self.assertRaisesRegex(ValueError, "Invalid history precision"):
1506 dec.seed("bad_prec")
1507
1508 def test_symbols_native_fallback_compatibility_and_errors(self):
1509 # Build a valid 64x64 1-mip BC1 BCPack chunk (512 blocks = 4096 bytes)
1510 layout = ttpf.surface_layout(64, 64, 71, 1, 4096)
1511 linear = ttm.solid_chain(layout, 71)[0]
1512 tiled = bytearray(layout["size"])
1513 ttm.retile_to(layout, layout["mips"][0], linear, tiled)
1514 packed_bc1 = tb.encode_bc1_blocks(bytes(tiled))
1515 chunk_sha = hashlib.sha256(packed_bc1).hexdigest()
1516
1517 # Chunk 0: valid BC1 BCPack
1518 # Chunk 1: valid BC1 BCPack with an extra trailing 0x00 byte so decode_lanes consumes < packed
1519 # Chunk 2: valid BC4 BCPack (unused compatibility branch when codec != 1)
1520 bc4_lanes = [[0] * 512 for _ in range(12)]
1521 packed_bc4 = _encode_bc4_from_lanes(bc4_lanes)
1522 pool, _ = self._open_pool(
1523 "syms.ttpf",
1524 [ttm.pack_etpf_record(64, 64, 1, 0, 71, 1, 1, 4, 4096)],
1525 [
1526 (1, packed_bc1, 4096),
1527 (1, packed_bc1 + b"\x00", 4096),
1528 (4, packed_bc4, 4096),
1529 ],
1530 )
1531
1532 # 1. Native unpack succeeds (returns packed) -> bcpack.decode_lanes is NOT called.
1533 dec_nat = ct.LocalDecoder(pool, {"version": 1})
1534 expected_lanes, _ = bcpack.decode_lanes(packed_bc1, 1, 4096)
1535 expected_sy = np.ascontiguousarray(np.asarray(expected_lanes, dtype="uint8").T)
1536
1537 def fake_unpack(raw, packed, widths_bytes, nlanes, nsym, sy_ptr):
1538 self.assertEqual(raw, packed_bc1)
1539 self.assertEqual(packed, len(packed_bc1))
1540 self.assertEqual(widths_bytes, bytes(w - 1 for w in bcpack.LANE_WIDTHS[1]))
1541 self.assertEqual(nlanes, 12)
1542 self.assertEqual(nsym, 512)
1543 _write_u8_buf(sy_ptr, expected_sy.tobytes())
1544 return packed
1545
1546 with _fake_native_context(unpack_fn=fake_unpack), \
1547 mock.patch.object(bcpack, "decode_lanes", side_effect=AssertionError("unexpected fallback")):
1548 got_sy = dec_nat.symbols(0)
1549 self.assertEqual(got_sy.tobytes(), expected_sy.tobytes())
1550
1551 # 2. Native unpack returns -1 -> falls back to bcpack.decode_lanes.
1552 with _fake_native_context():
1553 got_fallback = dec_nat.symbols(0)
1554 self.assertEqual(got_fallback.tobytes(), expected_sy.tobytes())
1555
1556 # 3. Trailing unstripped zero byte makes consumed != packed -> ValueError.
1557 with _fake_native_context():
1558 with self.assertRaisesRegex(ValueError, "Entropy decode failed for chunk 1"):
1559 dec_nat.symbols(1)
1560
1561 # 4. Compatibility rotation on codec 1 rotates selected flat positions left by 1.
1562 cycle = [1, 5, 13]
1563 dec_rot = ct.LocalDecoder(pool, {"version": 1, "compatibility": {chunk_sha: cycle}})
1564 with _fake_native_context():
1565 rotated = dec_rot.symbols(0)
1566 flat_orig = expected_sy.ravel().tolist()
1567 flat_rot = rotated.ravel().tolist()
1568 self.assertEqual(flat_rot[1], flat_orig[5])
1569 self.assertEqual(flat_rot[5], flat_orig[13])
1570 self.assertEqual(flat_rot[13], flat_orig[1])
1571 for idx in range(len(flat_orig)):
1572 if idx not in cycle:
1573 self.assertEqual(flat_rot[idx], flat_orig[idx])
1574
1575 # 5. Compatibility rotation errors (duplicate, out-of-range, negative, non-int including bool).
1576 for bad_cycle in ([0, 0], [-1], [expected_sy.size], [True], [1.0], ["0"]):
1577 with self.subTest(bad_cycle=bad_cycle):
1578 dec_bad = ct.LocalDecoder(
1579 pool, {"version": 1, "compatibility": {chunk_sha: bad_cycle}}
1580 )
1581 with _fake_native_context():
1582 with self.assertRaisesRegex(ValueError, "Invalid symbol rotation"):
1583 dec_bad.symbols(0)
1584
1585 # 6. Compatibility does NOT run for non-BC1 codecs, empty cycle, or unknown sha.
1586 bc4_sha = hashlib.sha256(packed_bc4).hexdigest()
1587 dec_bc4 = ct.LocalDecoder(pool, {"version": 1, "compatibility": {bc4_sha: [0, 0]}})
1588 with _fake_native_context():
1589 sy4 = dec_bc4.symbols(2)
1590 self.assertEqual(sy4.shape, (512, 12))
1591
1592 dec_noop = ct.LocalDecoder(
1593 pool,
1594 {"version": 1, "compatibility": {chunk_sha: [], "0" * 64: [0, 1]}},
1595 )
1596 with _fake_native_context():
1597 self.assertEqual(dec_noop.symbols(0).tobytes(), expected_sy.tobytes())
1598
1599 def test_read_chunk_errors_and_all_codecs(self):
1600 # Raw (codec 0), zlib (codec 8), and bad-length zlib chunk
1601 raw_bytes = bytes((i & 0xFF) for i in range(4096))
1602 zlib_bytes = zlib.compress(raw_bytes)
1603 bad_zlib = zlib.compress(raw_bytes[:2048])
1604
1605 # Codec 6 (BC6H) and Codec 7 (BC7)
1606 packed_bc6h = _encode_bc6h_solid(256)
1607 packed_bc7 = _encode_bc7_mode6_solid(256)
1608
1609 pool, _ = self._open_pool(
1610 "codecs.ttpf",
1611 [ttm.pack_etpf_record(64, 64, 1, 0, 71, 1, 1, 4, 4096)],
1612 [
1613 (0, raw_bytes, 4096),
1614 (8, zlib_bytes, 4096),
1615 (8, bad_zlib, 4096),
1616 (6, packed_bc6h, 4096),
1617 (7, packed_bc7, 4096),
1618 ],
1619 )
1620 cal = {
1621 "version": 1,
1622 "bc6h": {},
1623 "bc7": _empty_bc7_section(),
1624 }
1625 dec = ct.LocalDecoder(pool, cal)
1626
1627 # Size/block-size/codec mismatches (including unknown codec 99)
1628 with self.assertRaisesRegex(ValueError, "Block size and codec disagree"):
1629 dec.read_chunk(0, 7, "base") # 4096 % 7 != 0
1630 with self.assertRaisesRegex(ValueError, "Block size and codec disagree"):
1631 dec.read_chunk(3, 8, "base") # codec 6 is 16-byte blocks, not 8
1632 orig_chunks = list(pool.chunks)
1633 try:
1634 pool.chunks = orig_chunks + [(0, 4096, 0, 4096, 99, 0)]
1635 with self.assertRaisesRegex(ValueError, "Block size and codec disagree"):
1636 dec.read_chunk(len(orig_chunks), 16, "base")
1637 finally:
1638 pool.chunks = orig_chunks
1639
1640 # Raw & zlib
1641 b_raw, m_raw = dec.read_chunk(0, 8, "base")
1642 self.assertIsNone(m_raw)
1643 self.assertEqual(b_raw.tobytes(), raw_bytes)
1644 b_z, m_z = dec.read_chunk(1, 16, "base")
1645 self.assertIsNone(m_z)
1646 self.assertEqual(b_z.tobytes(), raw_bytes)
1647 with self.assertRaisesRegex(ValueError, "Invalid raw chunk length"):
1648 dec.read_chunk(2, 8, "base")
1649
1650 # BC6H delegates to bcpack._bc6h_blocks
1651 with _fake_native_context():
1652 b6, m6 = dec.read_chunk(3, 16, "base")
1653 self.assertIsNone(m6)
1654 self.assertEqual(b6.tobytes(), bcpack.decode(packed_bc6h, 6, 4096))
1655
1656 # BC7 profile cascades: early (1 call), base (early stop if all valid), base->secondary, refined->3
1657 call_seeds = []
1658
1659 def rebuild_early_stop(s_ptr, count, lab_ptr, seed_ptr, anc_ptr, out_ptr, ok_ptr):
1660 call_seeds.append(_read_u8_buf(seed_ptr, 8))
1661 _write_u8_buf(out_ptr, b"\x11" * (count * 16))
1662 _write_u8_buf(ok_ptr, b"\x01" * count)
1663
1664 with _fake_native_context(rebuild_fn=rebuild_early_stop):
1665 b7_base, m7_base = dec.read_chunk(4, 16, "base")
1666 self.assertEqual(len(call_seeds), 1)
1667 self.assertTrue(m7_base.all())
1668 self.assertEqual(b7_base.tobytes(), b"\x11" * 4096)
1669
1670 call_seeds.clear()
1671 dec.read_chunk(4, 16, "early")
1672 self.assertEqual(len(call_seeds), 1)
1673
1674 # Partial fill across base -> secondary -> refined
1675 cal2 = {"version": 1, "bc7": _empty_bc7_section()}
1676 # Mark first byte of each seed so mocked rebuild distinguishes them
1677 cal2["bc7"]["seeds"]["base"][0][0] = [1, 8]
1678 cal2["bc7"]["seeds"]["secondary"][0][0] = [2, 8]
1679 cal2["bc7"]["seeds"]["refined"][0][0] = [3, 8]
1680 dec2 = ct.LocalDecoder(pool, cal2)
1681 seen_tags = []
1682
1683 def rebuild_cascading(s_ptr, count, lab_ptr, seed_ptr, anc_ptr, out_ptr, ok_ptr):
1684 tag = _read_u8_buf(seed_ptr, 1)[0]
1685 seen_tags.append(tag)
1686 out_buf = bytearray(count * 16)
1687 ok_buf = bytearray(count)
1688 for idx in range(count):
1689 if (tag == 1 and idx % 3 == 0) or (tag == 2 and idx % 3 == 1):
1690 out_buf[idx * 16 : (idx + 1) * 16] = bytes([tag]) * 16
1691 ok_buf[idx] = 1
1692 elif tag == 3 and idx == 2:
1693 out_buf[idx * 16 : (idx + 1) * 16] = bytes([3]) * 16
1694 ok_buf[idx] = 1
1695 _write_u8_buf(out_ptr, bytes(out_buf))
1696 _write_u8_buf(ok_ptr, bytes(ok_buf))
1697
1698 with _fake_native_context(rebuild_fn=rebuild_cascading):
1699 blocks, valid = dec2.read_chunk(4, 16, "refined")
1700 self.assertEqual(seen_tags, [1, 2, 3])
1701 self.assertTrue(bool(valid[0]) and bool(valid[1]) and bool(valid[2]))
1702 self.assertFalse(bool(valid[5])) # 5 % 3 == 2, != 2
1703 self.assertEqual(blocks.tobytes()[:48], b"\x01" * 16 + b"\x02" * 16 + b"\x03" * 16)
1704
1705 def test_surface_bounds_multichunk_and_bc7_adjustments(self):
1706 # Chunk 0: 4096 bytes raw (bs=16, 256 blocks)
1707 # Chunk 1: 4096 bytes BC7 (bs=16, 256 blocks)
1708 c0 = b"".join(bytes([i & 0xFF]) * 16 for i in range(256))
1709 c1 = _encode_bc7_mode6_solid(256)
1710 pool, base = self._open_pool(
1711 "surface.ttpf",
1712 [ttm.pack_etpf_record(64, 64, 1, 0, 98, 1, 1, 4, 4096)],
1713 [(0, c0, 4096), (7, c1, 4096)],
1714 )
1715 cal = {"version": 1, "bc7": _empty_bc7_section()}
1716 dec = ct.LocalDecoder(pool, cal)
1717
1718 # Empty address array returns empty bytes cleanly
1719 self.assertEqual(dec.surface(np.array([], dtype="int64"), 16, "base"), b"")
1720
1721 # Out of bounds
1722 for bad_at in ([base - 16], [base + 8192], [base, base + 10000]):
1723 with self.subTest(bad_at=bad_at):
1724 with self.assertRaisesRegex(ValueError, "Texture exceeds virtual pool"):
1725 dec.surface(np.array(bad_at, dtype="int64"), 16, "base")
1726
1727 # Non-monotonic multi-chunk lookup where unreferenced blocks in chunk 1 remain unresolved
1728 def rebuild_partial(s_ptr, count, lab_ptr, seed_ptr, anc_ptr, out_ptr, ok_ptr):
1729 seed_bytes = _read_u8_buf(seed_ptr, 256 * 56 * 2)
1730 # Check if adjustment patched seed[7, 3] = (99, 8)
1731 patched = seed_bytes[(7 * 56 + 3) * 2 : (7 * 56 + 3) * 2 + 2] == bytes([99, 8])
1732 out_buf = bytearray(count * 16)
1733 ok_buf = bytearray(count)
1734 for idx in range(count):
1735 if idx == 10:
1736 out_buf[idx * 16 : (idx + 1) * 16] = b"\xAA" * 16
1737 ok_buf[idx] = 1
1738 elif idx == 20 and patched:
1739 out_buf[idx * 16 : (idx + 1) * 16] = b"\xBB" * 16
1740 ok_buf[idx] = 1
1741 _write_u8_buf(out_ptr, bytes(out_buf))
1742 _write_u8_buf(ok_ptr, bytes(ok_buf))
1743
1744 with _fake_native_context(rebuild_fn=rebuild_partial):
1745 # Request block 10 of chunk 1 (resolved), block 5 of chunk 0, block 0 of chunk 0
1746 at_ok = np.array([base + 4096 + 10 * 16, base + 5 * 16, base], dtype="int64")
1747 got_ok = dec.surface(at_ok, 16, "base")
1748 self.assertEqual(got_ok, b"\xAA" * 16 + bytes([5]) * 16 + bytes([0]) * 16)
1749
1750 # Request unresolved block 20 with profile != "refined" -> Missing calibrated blocks
1751 at_miss = np.array([base + 4096 + 10 * 16, base + 4096 + 20 * 16], dtype="int64")
1752 with self.assertRaisesRegex(ValueError, "Missing calibrated blocks"):
1753 dec.surface(at_miss, 16, "base")
1754
1755 # Refined profile: compute exact sha256 key expected by LocalDecoder.surface
1756 sy1 = dec.symbols(1)
1757 miss_ix = np.array([20], dtype="<i8")
1758 adj_key = hashlib.sha256(sy1.tobytes() + miss_ix.tobytes()).hexdigest()
1759
1760 # Bad fitted endpoint bounds
1761 for bad_adj in (
1762 [(256, 0, 0)],
1763 [(-1, 0, 0)],
1764 [(0, 24, 0)],
1765 [(0, -1, 0)],
1766 [(0, 0, 256)],
1767 [(0, 0, -1)],
1768 ):
1769 cal["bc7"]["adjustments"][adj_key] = bad_adj
1770 with self.assertRaisesRegex(ValueError, "Invalid fitted endpoint"):
1771 dec.surface(at_miss, 16, "refined")
1772
1773 # Valid bounds that still fail to resolve block 20 -> Incomplete calibrated endpoints
1774 cal["bc7"]["adjustments"][adj_key] = [(7, 3, 42)]
1775 with self.assertRaisesRegex(ValueError, "Incomplete calibrated endpoints"):
1776 dec.surface(at_miss, 16, "refined")
1777
1778 # Valid adjustment resolves block 20 without mutating cached refined seed!
1779 cal["bc7"]["adjustments"][adj_key] = [(7, 3, 99)]
1780 got_ref = dec.surface(at_miss, 16, "refined")
1781 self.assertEqual(got_ref, b"\xAA" * 16 + b"\xBB" * 16)
1782 self.assertEqual(dec.seed("refined").tobytes()[(7 * 56 + 3) * 2 : (7 * 56 + 3) * 2 + 2], b"\x00\x08")
1783
1784 def test_dds_end_to_end_codecs_and_layouts(self):
1785 # 1. BC3 (fmt 77, codec 3), BC4 (fmt 80, codec 4), BC5 (fmt 83, codec 5),
1786 # BC6H (fmt 95, codec 6), BC7 (fmt 98, codec 7) across 4K/64K, partial mips,
1787 # non-square, all-tail, single-mip, and multi-chunk spans.
1788 for fmt, codec, w, h, mips, mode in (
1789 (77, 3, 64, 32, 6, 4), # BC3, 4K tile, non-square
1790 (80, 4, 16, 16, 5, 4), # BC4, 4K tile, all-tail (first_tail == 0)
1791 (83, 5, 64, 64, 1, 4), # BC5, 4K tile, single-mip
1792 (95, 6, 64, 64, 5, 4), # BC6H, 4K tile
1793 (98, 7, 16, 16, 1, 0), # BC7, 64K tile, small single-mip
1794 ):
1795 with self.subTest(fmt=fmt, codec=codec, dims=(w, h, mips)):
1796 tile = ttpf.tile_bytes(mode)
1797 lay = ttpf.surface_layout(w, h, fmt, mips, tile)
1798 linear = ttm.solid_chain(lay, fmt)
1799 tiled = bytearray(lay["size"])
1800 for m in lay["mips"]:
1801 ttm.retile_to(lay, m, linear[m["index"]], tiled)
1802
1803 eb = lay["element_bytes"]
1804 nblocks = lay["size"] // eb
1805 if codec == 3:
1806 inv_pair = {p: i for i, p in enumerate(bcpack_tables.BC3_ALPHA_PAIR)}
1807 inv_quad = {v: i for i, v in enumerate(bcpack_tables.BC3_COLOUR_QUADRANT)}
1808 lanes = [[] for _ in range(12)]
1809 prev = (128, 128, 0, 0, 0, 0, 0, 0)
1810 for i in range(nblocks):
1811 blk = tiled[i * 16 : (i + 1) * 16]
1812 a0, a1 = blk[0], blk[1]
1813 abits = int.from_bytes(blk[2:8], "little")
1814 c0, c1, r0, r1, r2, r3 = struct.unpack_from("<HHBBBB", blk, 8)
1815 ep = (
1816 a0, a1,
1817 (c0 >> 11) & 31, (c0 >> 5) & 63, c0 & 31,
1818 (c1 >> 11) & 31, (c1 >> 5) & 63, c1 & 31,
1819 )
1820 mods = bcpack._BC3_MODS
1821 deltas = [((ep[k] - prev[k] + mods[k] // 2) % mods[k]) - mods[k] // 2 for k in range(8)]
1822 # Use d=0 on block 0, d=1 afterwards
1823 if i == 0:
1824 lanes[0].extend([0, 0])
1825 else:
1826 d1a, d1b = tb._deint4(tb._zig(1) & 255)
1827 lanes[0].extend([d1a, d1b])
1828 lanes[1].extend([0, 0])
1829 lanes[2].extend([tb._zig(deltas[0]), tb._zig(deltas[1])])
1830 for r in range(4):
1831 row = (abits >> (12 * r)) & 0xFFF
1832 lanes[3 + r].extend([
1833 inv_pair[(row & 7, (row >> 3) & 7)],
1834 inv_pair[((row >> 6) & 7, (row >> 9) & 7)],
1835 ])
1836 lanes[7].extend([tb._zig(deltas[2]), tb._zig(deltas[5])])
1837 lanes[8].extend([tb._zig(deltas[3]), tb._zig(deltas[6])])
1838 lanes[9].extend([tb._zig(deltas[4]), tb._zig(deltas[7])])
1839 qa = (r0 & 15) | ((r1 & 15) << 4)
1840 qb = (r0 >> 4) | ((r1 >> 4) << 4)
1841 qc = (r2 & 15) | ((r3 & 15) << 4)
1842 qd = (r2 >> 4) | ((r3 >> 4) << 4)
1843 lanes[10].extend([inv_quad[qa], inv_quad[qb]])
1844 lanes[11].extend([inv_quad[qc], inv_quad[qd]])
1845 prev = ep
1846 packed_chunk = _encode_bc3_from_lanes(lanes)
1847 elif codec == 4:
1848 inv_pair = {p: i for i, p in enumerate(bcpack_tables.BC4_PAIR)}
1849 lanes = [[] for _ in range(12)]
1850 for i in range(nblocks):
1851 blk = tiled[i * 8 : (i + 1) * 8]
1852 a0, a1 = blk[0], blk[1]
1853 bits = int.from_bytes(blk[2:8], "little")
1854 lanes[0].append(0)
1855 lanes[1].append(0)
1856 lanes[2].append(tb._zig(((a0 - 128 + 128) % 256) - 128))
1857 lanes[3].append(tb._zig(((a1 - 128 + 128) % 256) - 128))
1858 for r in range(4):
1859 row = (bits >> (12 * r)) & 0xFFF
1860 lanes[4 + 2 * r].append(inv_pair[(row & 7, (row >> 3) & 7)])
1861 lanes[4 + 2 * r + 1].append(inv_pair[((row >> 6) & 7, (row >> 9) & 7)])
1862 packed_chunk = _encode_bc4_from_lanes(lanes)
1863 elif codec == 5:
1864 inv_pair = {p: i for i, p in enumerate(bcpack_tables.BC5_PAIR)}
1865 lanes = [[] for _ in range(12)]
1866 for i in range(nblocks):
1867 blk = tiled[i * 16 : (i + 1) * 16]
1868 r0, r1 = blk[0], blk[1]
1869 br = int.from_bytes(blk[2:8], "little")
1870 g0, g1 = blk[8], blk[9]
1871 bg = int.from_bytes(blk[10:16], "little")
1872 lanes[0].extend([0, 0])
1873 lanes[1].extend([0, 0])
1874 # Compatibility endpoint ordering: half 0 -> (r0, r1), half 1 -> (g0, g1)
1875 lanes[2].extend([tb._zig(((r0 - 128 + 128) % 256) - 128), tb._zig(((g0 - 128 + 128) % 256) - 128)])
1876 lanes[3].extend([tb._zig(((r1 - 128 + 128) % 256) - 128), tb._zig(((g1 - 128 + 128) % 256) - 128)])
1877 for ch, bval in enumerate((br, bg)):
1878 for r in range(4):
1879 row = (bval >> (12 * r)) & 0xFFF
1880 lanes[4 + 4 * ch + r].extend([
1881 inv_pair[(row & 7, (row >> 3) & 7)],
1882 inv_pair[((row >> 6) & 7, (row >> 9) & 7)],
1883 ])
1884 packed_chunk = _encode_bc5_from_lanes(lanes)
1885 elif codec == 6:
1886 # Use raw solid BC6H blocks with mode 0x0F? Simpler: encode mode-11 blocks and
1887 # verify decoded DDS payload matches bcpack.decode(packed_chunk, 6, ...).
1888 packed_chunk = _encode_bc6h_solid(nblocks)
1889 decoded_bc6 = bcpack.decode(packed_chunk, 6, lay["size"])
1890 linear = {m["index"]: ttpf.detile(lay, m, decoded_bc6[m["offset"] : m["offset"] + m["region"]]) for m in lay["mips"]}
1891 elif codec == 7:
1892 # Ensure padding blocks are valid mode-6 for encoder
1893 pad_blk = (1 << 6).to_bytes(16, "little")
1894 for off in range(0, len(tiled), 16):
1895 if tiled[off : off + 16] == b"\x00" * 16:
1896 tiled[off : off + 16] = pad_blk
1897 packed_chunk = tb.encode_bc7_mode6_blocks(bytes(tiled))
1898
1899 pool, base = self._open_pool(
1900 f"pool_{fmt}.ttpf",
1901 [ttm.pack_etpf_record(w, h, mips, 0, fmt, 1, 1, mode, 4096)],
1902 [(codec, packed_chunk, lay["size"])],
1903 )
1904 cal = {
1905 "version": 1,
1906 "bc3": _bc3_profile_from_tables(),
1907 "bc4": {"custom": {str(k): list(v) for k, v in bcpack_tables.BC4_HISTORY_PROVISIONAL.items()}},
1908 "bc6h": {},
1909 "bc7": _empty_bc7_section(),
1910 "entries": {Path(pool.path).name: {"0": "custom"}},
1911 }
1912
1913 def rebuild_from_tiled(s_ptr, count, lab_ptr, seed_ptr, anc_ptr, out_ptr, ok_ptr, _t=bytes(tiled)):
1914 _write_u8_buf(out_ptr, _t[: count * 16])
1915 _write_u8_buf(ok_ptr, b"\x01" * count)
1916
1917 dec = ct.LocalDecoder(pool, cal)
1918 with _fake_native_context(rebuild_fn=rebuild_from_tiled):
1919 dds = dec.dds(0)
1920 # Partial mips when mips > 1
1921 if mips > 1:
1922 dds_part = dec.dds(0, mips=2)
1923 hdr_p = tex_headers.parse_dds_header(dds_part)
1924 self.assertEqual(hdr_p["mips"], 2)
1925 self.assertEqual(dds_part[148:], linear[0] + linear[1])
1926
1927 hdr = tex_headers.parse_dds_header(dds)
1928 self.assertEqual(hdr["width"], w)
1929 self.assertEqual(hdr["height"], h)
1930 self.assertEqual(hdr["mips"], mips)
1931 self.assertEqual(hdr["dxgi_format"], fmt)
1932 self.assertEqual(hdr["array_size"], 1)
1933 self.assertEqual(dds[148:], b"".join(linear[i] for i in range(mips)))
1934
1935 def test_dds_multichunk_and_2d_array_and_validation_errors(self):
1936 # 2D texture spanning 2 chunks (raw + zlib) plus 2D array and invalid descriptors
1937 lay = ttpf.surface_layout(64, 64, 71, 5, 4096) # size = 8192 = 2 * 4096 pages
1938 lin = ttm.solid_chain(lay, 71)
1939 tiled = bytearray(lay["size"])
1940 for m in lay["mips"]:
1941 ttm.retile_to(lay, m, lin[m["index"]], tiled)
1942
1943 # 2-slice 2D array using slice-major layout expected by LocalDecoder.dds
1944 arr_lay = ttpf.surface_layout(32, 32, 71, 4, 4096) # 4096 bytes per slice
1945 s0 = bytearray(4096)
1946 s1 = bytearray(4096)
1947 lin0 = ttm.solid_chain(arr_lay, 71, color_fn=lambda x, y, bw, bh: (255, 0, 0))
1948 lin1 = ttm.solid_chain(arr_lay, 71, color_fn=lambda x, y, bw, bh: (0, 255, 0))
1949 for m in arr_lay["mips"]:
1950 ttm.retile_to(arr_lay, m, lin0[m["index"]], s0)
1951 ttm.retile_to(arr_lay, m, lin1[m["index"]], s1)
1952
1953 p_dummy = self.root / "multi.ttpf"
1954 chunk0 = bytes(tiled[:4096])
1955 chunk1 = zlib.compress(bytes(tiled[4096:]))
1956 chunk2 = bytes(s0 + s1)
1957 base0 = ttpf.align(16 + 7 * 24 + 7 * 32, 4096)
1958 # Keep records in non-decreasing base order so Pool.span() maps rec0 and rec1 accurately.
1959 rec_unmapped = ttm.pack_etpf_record(32, 32, 1, 0, 71, 1, 1, 4, 0)
1960 rec0 = ttm.pack_etpf_record(64, 64, 5, 0, 71, 1, 1, 4, base0)
1961 rec_bad_fmt = ttm.pack_etpf_record(32, 32, 1, 0, 28, 1, 1, 4, base0)
1962 rec_bad_dim = ttm.pack_etpf_record(32, 32, 1, 0, 71, 6, 2, 18, base0)
1963 rec_huge = ttm.pack_etpf_record(16384, 16384, 1, 0, 98, 2, 1, 4, base0)
1964 rec1 = ttm.pack_etpf_record(32, 32, 4, 0, 71, 2, 1, 4, base0 + 8192)
1965 rec_cross = ttm.pack_etpf_record(256, 256, 7, 1, 71, 1, 1, 4, base0 + 8192)
1966
1967 write_custom_pool(
1968 p_dummy,
1969 [rec_unmapped, rec0, rec_bad_fmt, rec_bad_dim, rec_huge, rec1, rec_cross],
1970 [(0, chunk0, 4096), (8, chunk1, 4096), (0, chunk2, 8192)],
1971 )
1972 pool = ttpf.Pool(str(p_dummy))
1973 self.addCleanup(pool.close)
1974 dec = ct.LocalDecoder(pool, {"version": 1})
1975
1976 # Multi-chunk 2D texture (index 1)
1977 dds0 = dec.dds(1)
1978 self.assertEqual(dds0[148:], b"".join(lin[i] for i in range(5)))
1979
1980 # 2D array (depth=2, index 5)
1981 dds1 = dec.dds(5)
1982 hdr1 = tex_headers.parse_dds_header(dds1)
1983 self.assertEqual((hdr1["array_size"], hdr1["mips"]), (2, 4))
1984 expected_arr = b"".join(lin0[i] for i in range(4)) + b"".join(lin1[i] for i in range(4))
1985 self.assertEqual(dds1[148:], expected_arr)
1986
1987 # Error paths
1988 with self.assertRaisesRegex(ValueError, "supported BCn 2D texture or array"):
1989 dec.dds(2)
1990 with self.assertRaisesRegex(ValueError, "supported BCn 2D texture or array"):
1991 dec.dds(3)
1992 for bad_mips in (0, -1, 6):
1993 with self.assertRaisesRegex(ValueError, "Mip count outside descriptor range"):
1994 dec.dds(1, mips=bad_mips)
1995 with self.assertRaisesRegex(ValueError, "Texture has no mapped allocation"):
1996 dec.dds(0)
1997 with self.assertRaisesRegex(ValueError, "Texture crosses its allocation boundary"):
1998 dec.dds(6)
1999 with self.assertRaisesRegex(ValueError, "DDS exceeds output limit"):
2000 dec.dds(4)
2001
2002 def test_dds_no_tail_64k_tile_layout(self):
2003 # 512x256 BC7 (fmt 98, bs=16, 64K tile -> bw=64, bh=64) with 2 mips:
2004 # mip 0 is 128x64 blocks (2 tiles), mip 1 is 64x32 blocks (> bw//2=32 -> 1 tile), so tail == 2 == levels.
2005 lay = ttpf.surface_layout(512, 256, 98, 2, 65536)
2006 self.assertEqual(lay["first_tail"], 2)
2007 lin0 = bytes([0xAA] * (128 * 64 * 16))
2008 lin1 = bytes([0xBB] * (64 * 32 * 16))
2009 tiled = bytearray(lay["size"])
2010 ttm.retile_to(lay, lay["mips"][0], lin0, tiled)
2011 ttm.retile_to(lay, lay["mips"][1], lin1, tiled)
2012 pool, _ = self._open_pool(
2013 "notail.ttpf",
2014 [ttm.pack_etpf_record(512, 256, 2, 0, 98, 1, 1, 0, 4096)],
2015 [(8, zlib.compress(bytes(tiled)), lay["size"])],
2016 )
2017 dec = ct.LocalDecoder(pool, {"version": 1})
2018 dds = dec.dds(0)
2019 self.assertEqual(dds[148:], lin0 + lin1)
2020
2021 def test_all_supported_formats_and_entries_fallback(self):
2022 self.assertEqual(ct.LocalDecoder.formats, frozenset((71, 72, 77, 78, 80, 83, 95, 96, 98, 99)))
2023 base0 = ttpf.align(16 + 10 * 24 + 10 * 32, 4096)
2024 records = [
2025 ttm.pack_etpf_record(16, 16, 1, 0, fmt, 1, 1, 4, base0)
2026 for fmt in sorted(ct.LocalDecoder.formats)
2027 ]
2028 pool, _ = self._open_pool("all_fmts.ttpf", records, [(0, b"\x5A" * 4096, 4096)])
2029 dec = ct.LocalDecoder(
2030 pool,
2031 {"version": 1, "entries": {"other.ttpf": {"0": "early"}, "all_fmts.ttpf": {"9": "custom"}}},
2032 )
2033 seen_profiles = []
2034 orig_surface = dec.surface
2035
2036 def spy_surface(at, bs, profile):
2037 seen_profiles.append(profile)
2038 return orig_surface(at, bs, profile)
2039
2040 with mock.patch.object(dec, "surface", side_effect=spy_surface):
2041 for idx, fmt in enumerate(sorted(ct.LocalDecoder.formats)):
2042 dds = dec.dds(idx)
2043 hdr = tex_headers.parse_dds_header(dds)
2044 bs = 8 if fmt in (71, 72, 80) else 16
2045 self.assertEqual(hdr["dxgi_format"], fmt)
2046 self.assertEqual(hdr["pitch_linear"], 4 * 4 * bs)
2047 self.assertEqual(dds[148:], b"\x5A" * (16 * bs))
2048 self.assertEqual(seen_profiles, ["base"] * 9 + ["custom"])
2049
2050 def test_invalid_bc1_and_bc7_config_shapes(self):
2051 bc1_packed = tb.encode_bc1_blocks(b"\x00" * 4096)
2052 bc7_packed = _encode_bc7_mode6_solid(256)
2053 pool, _ = self._open_pool(
2054 "bad_cfg.ttpf",
2055 [ttm.pack_etpf_record(64, 64, 1, 0, 71, 1, 1, 4, 4096)],
2056 [(1, bc1_packed, 4096), (7, bc7_packed, 4096)],
2057 )
2058 bad_bc1 = ct.LocalDecoder(
2059 pool, {"version": 1, "bc1": {"endpoints": [[0] * 6], "selectors": [[0] * 256] * 4}}
2060 )
2061 with _fake_native_context(), self.assertRaisesRegex(ValueError, "Invalid calibration field"):
2062 bad_bc1.read_chunk(0, 8, "base")
2063
2064 bad_bc7 = ct.LocalDecoder(
2065 pool, {"version": 1, "bc7": {"labels": [[0, 0, 0, 0]], "anchors": [0] * 128}}
2066 )
2067 with _fake_native_context(), self.assertRaisesRegex(ValueError, "Invalid calibration field"):
2068 bad_bc7.read_chunk(1, 16, "base")
2069
2070
2071class TestExportFileAndCli(unittest.TestCase):
2072 def setUp(self):
2073 tmp = tempfile.TemporaryDirectory()
2074 self.addCleanup(tmp.cleanup)
2075 self.root = Path(tmp.name)
2076 self.pool_path = self.root / "pool.ttpf"
2077 self.lay, self.linear, _ = ttm.build_bc1_bcpack_pool(self.pool_path)
2078 self.profile = self.root / "profile.json"
2079 self.profile.write_text(json.dumps(synthetic_profile()), encoding="utf-8")
2080
2081 def test_export_file_atomic_link_replace_and_cleanup(self):
2082 pool = ttpf.Pool(str(self.pool_path))
2083 self.addCleanup(pool.close)
2084 out = self.root / "out.dds"
2085
2086 # 1. Create new file (force=False)
2087 with _fake_native_context():
2088 rc = ct.export_file(pool, 0, out, None, False, self.profile)
2089 self.assertEqual(rc, 0)
2090 data = out.read_bytes()
2091 self.assertEqual(data[:4], b"DDS ")
2092 self.assertEqual(data[148:], b"".join(self.linear[i] for i in sorted(self.linear)))
2093 # No leftover temporary files
2094 self.assertEqual(sorted(p.name for p in self.root.iterdir()), ["out.dds", "pool.ttpf", "profile.json"])
2095
2096 # 2. Existing target with force=False raises FileExistsError, keeps target intact, cleans tmp
2097 out.write_bytes(b"SENTINEL")
2098 with _fake_native_context():
2099 with self.assertRaises(FileExistsError):
2100 ct.export_file(pool, 0, out, None, False, self.profile)
2101 self.assertEqual(out.read_bytes(), b"SENTINEL")
2102 self.assertEqual(sorted(p.name for p in self.root.iterdir()), ["out.dds", "pool.ttpf", "profile.json"])
2103
2104 # 3. Existing target with force=True replaces target atomically and cleans tmp
2105 with _fake_native_context():
2106 rc_force = ct.export_file(pool, 0, out, 2, True, self.profile)
2107 self.assertEqual(rc_force, 0)
2108 replaced = out.read_bytes()
2109 self.assertEqual(tex_headers.parse_dds_header(replaced)["mips"], 2)
2110 self.assertEqual(replaced[148:], self.linear[0] + self.linear[1])
2111 self.assertEqual(sorted(p.name for p in self.root.iterdir()), ["out.dds", "pool.ttpf", "profile.json"])
2112
2113 # 4. Cache is cleared even if dds() fails
2114 clear_calls = []
2115
2116 with _fake_native_context(), \
2117 mock.patch.object(ct.LocalDecoder, "dds", side_effect=ValueError("boom")):
2118 orig_init = ct.LocalDecoder.__init__
2119
2120 def tracked_init(self_dec, p, c):
2121 orig_init(self_dec, p, c)
2122 orig_cc = self_dec.read_chunk.cache_clear
2123 self_dec.read_chunk.cache_clear = lambda: (clear_calls.append(1), orig_cc())[1]
2124
2125 with mock.patch.object(ct.LocalDecoder, "__init__", tracked_init):
2126 with self.assertRaisesRegex(ValueError, "boom"):
2127 ct.export_file(pool, 0, self.root / "unused.dds", None, False, self.profile)
2128 self.assertEqual(len(clear_calls), 1)
2129
2130 # 5. Missing or invalid profile JSON
2131 with self.assertRaises(FileNotFoundError):
2132 ct.export_file(pool, 0, self.root / "u.dds", None, False, self.root / "missing.json")
2133 bad_json = self.root / "bad.json"
2134 bad_json.write_text("{not json", encoding="utf-8")
2135 with self.assertRaises(json.JSONDecodeError):
2136 ct.export_file(pool, 0, self.root / "u.dds", None, False, bad_json)
2137
2138 def test_ttpf_mips_cli_calibration_paths(self):
2139 out = self.root / "cli.dds"
2140
2141 def run_cli(*argv):
2142 out_buf, err_buf = io.StringIO(), io.StringIO()
2143 with mock.patch.dict(sys.modules, {"calibrated_texture": ct}), \
2144 _fake_native_context(), \
2145 redirect_stdout(out_buf), redirect_stderr(err_buf):
2146 rc = ttpf.main(list(argv))
2147 return rc, out_buf.getvalue(), err_buf.getvalue()
2148
2149 # Success
2150 rc, _, err = run_cli("export", str(self.pool_path), "0", str(out), "--calibration", str(self.profile))
2151 self.assertEqual(rc, 0, err)
2152 dds = out.read_bytes()
2153 self.assertEqual(dds[:4], b"DDS ")
2154 self.assertEqual(dds[148:], b"".join(self.linear[i] for i in sorted(self.linear)))
2155
2156 # Refuses overwrite without --force
2157 out.write_bytes(b"KEEP_ME")
2158 rc2, _, err2 = run_cli("export", str(self.pool_path), "0", str(out), "--calibration", str(self.profile))
2159 self.assertEqual(rc2, 2)
2160 self.assertIn("calibrated export failed", err2)
2161 self.assertNotIn("Traceback", err2)
2162 self.assertEqual(out.read_bytes(), b"KEEP_ME")
2163
2164 # Overwrites with --force and --mips
2165 rc3, _, err3 = run_cli(
2166 "export", str(self.pool_path), "0", str(out),
2167 "--calibration", str(self.profile), "--mips", "1", "--force",
2168 )
2169 self.assertEqual(rc3, 0, err3)
2170 self.assertEqual(tex_headers.parse_dds_header(out.read_bytes())["mips"], 1)
2171
2172 # Rejects --calibration + --history together
2173 rc4, _, err4 = run_cli(
2174 "export", str(self.pool_path), "0", str(out),
2175 "--calibration", str(self.profile), "--history", str(self.profile), "--force",
2176 )
2177 self.assertEqual(rc4, 2)
2178 self.assertIn("choose either --calibration or --history", err4)
2179
2180 # Bad profile version returns exit code 2 cleanly
2181 self.profile.write_text('{"version": 99}', encoding="utf-8")
2182 rc5, _, err5 = run_cli(
2183 "export", str(self.pool_path), "0", str(out),
2184 "--calibration", str(self.profile), "--force",
2185 )
2186 self.assertEqual(rc5, 2)
2187 self.assertIn("Unsupported calibration version", err5)
2188 self.assertNotIn("Traceback", err5)
2189
2190
2191if __name__ == "__main__":
2192 unittest.main()
diff --git a/tests/test_cf_ref_edge_fixes.py b/tests/test_cf_ref_edge_fixes.py
new file mode 100644
index 000000000..2ea11772f
--- /dev/null
+++ b/tests/test_cf_ref_edge_fixes.py
@@ -0,0 +1,294 @@
1"""Regression tests for tools/cf_ref.py s_cmp_* validation and exec_hi/vcc_hi mask ops.
2
3Standard library only; uses hand-written synthetic .s listings (no game data, GPU, or llvm-mc).
4
5Run from the repository root:
6 python -I tests/test_cf_ref_edge_fixes.py -v
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"))
15
16import cf_ref # noqa: E402
17import cpu_ref # noqa: E402
18from shader_ir import parse_file # noqa: E402
19
20MASK32 = 0xFFFFFFFF
21MASK64 = 0xFFFFFFFFFFFFFFFF
22_VOP3_NO_E64 = {"v_mul_lo_u32", "v_mbcnt_lo_u32_b32", "v_mbcnt_hi_u32_b32"}
23
24
25def _enc_bytes(size):
26 return "; encoding: [" + ",".join(["0x00"] * size) + "]"
27
28
29def _guess_size(text):
30 op = text.split()[0]
31 if op == "exp" or op.endswith("_e64") or op in _VOP3_NO_E64:
32 return 8
33 for tok in text.replace(",", " ").split()[1:]:
34 if tok.startswith("0x") or (tok.lstrip("-").isdigit() and not (-16 <= int(tok) <= 64)):
35 return 8
36 return 4
37
38
39def assemble(items, name="test"):
40 pc = 0
41 labels = {}
42 sized = []
43 for item in items:
44 if isinstance(item, tuple) and item[0] == "lbl":
45 labels[item[1]] = pc
46 continue
47 if isinstance(item, tuple) and item[0] == "br":
48 sized.append((item, pc, 4))
49 pc += 4
50 else:
51 text, size = item if isinstance(item, tuple) else (item, _guess_size(item))
52 sized.append((text, pc, size))
53 pc += size
54
55 lines = [f"; {name} code 0x0..0x{pc:x}"]
56 for item, at, size in sized:
57 if isinstance(item, tuple) and item[0] == "br":
58 _, op, target = item
59 delta = labels[target] - (at + 4)
60 if delta % 4 != 0:
61 raise ValueError(f"branch target {target} is not 4-byte aligned")
62 text = f"{op} {delta // 4}"
63 else:
64 text = item
65 lines.append(f"\t{text} {_enc_bytes(size)}")
66 return "\n".join(lines) + "\n"
67
68
69def lane_id_prologue(wave):
70 insns = ["v_mbcnt_lo_u32_b32 v0, -1, 0"]
71 if wave == 64:
72 insns.append("v_mbcnt_hi_u32_b32 v0, -1, v0")
73 return insns
74
75
76class CfRefEdgeFixesTests(unittest.TestCase):
77 def setUp(self):
78 self.tmp = tempfile.TemporaryDirectory(prefix="cf-ref-edge-")
79 self.addCleanup(self.tmp.cleanup)
80 self.n = 0
81
82 def write_items(self, items):
83 self.n += 1
84 path = os.path.join(self.tmp.name, f"t{self.n}.s")
85 with open(path, "w", encoding="utf-8", newline="\n") as f:
86 f.write(assemble(items, name=f"t{self.n}"))
87 return path
88
89 def run_items(self, items, wave=32):
90 return cf_ref.run(self.write_items(items), wave=wave)
91
92 def test_s_cmp_unknown_condition_raises_unsupported(self):
93 bad_ops = [
94 "s_cmp_bad_u32 s0, s1",
95 "s_cmp_bad_i32 s0, s1",
96 "s_cmp_tru_u32 s0, s1",
97 "s_cmp_f_i32 s0, s1",
98 "s_cmp_foo s0, s1",
99 "s_cmp_eq_u64 s[0:1], s[2:3]",
100 "s_cmp_lt_f32 s0, s1",
101 ]
102 for insn in bad_ops:
103 mnemonic = insn.split()[0]
104 with self.subTest(insn=insn):
105 with self.assertRaises(cpu_ref.Unsupported) as cm:
106 self.run_items([insn, "s_endpgm"], wave=32)
107 self.assertIn(mnemonic, str(cm.exception))
108
109 def test_wave64_exec_hi_mov_preserves_lo_and_controls_upper_lanes(self):
110 # Set exec_lo to lanes {0, 1} and exec_hi to lanes {32, 34}, preserving exec_lo.
111 # Then verify active lanes 32..63 run, inactive ones do not, and exec_hi clears cleanly.
112 res = self.run_items(lane_id_prologue(64) + [
113 "v_mov_b32 v1, 0",
114 "v_mov_b32 v2, 0",
115 "v_mov_b32 v3, 0",
116 "s_cmp_eq_u32 1, 1", # SCC = 1; s_mov_b32 exec_hi must preserve SCC
117 "s_mov_b32 exec_lo, 0x00000003",
118 "s_mov_b32 exec_hi, 0x00000005",
119 "s_mov_b32 s0, scc",
120 "v_mov_b32 v1, 77",
121 "exp mrt0 v0, v1, v2, v3 done vm",
122 "s_mov_b32 exec_hi, 0",
123 "s_endpgm",
124 ], wave=64)
125 self.assertEqual(res["sgpr"][0], 1)
126 self.assertEqual(sorted(res["exports"]), [0, 1, 32, 34])
127 for lane in (0, 1, 32, 34):
128 self.assertEqual(res["exports"][lane], (lane, 77, 0, 0))
129 self.assertEqual(res["exec"], 0x0000000000000003)
130
131 # exec_lo == 0 and exec_hi != 0 must keep EXECZ == 0 (s_cbranch_execnz taken).
132 res_nz = self.run_items([
133 "s_mov_b32 s0, 0",
134 "s_mov_b32 exec_lo, 0",
135 "s_mov_b32 exec_hi, 0x00010000",
136 ("br", "s_cbranch_execz", "bad"),
137 ("br", "s_cbranch_execnz", "ok"),
138 ("lbl", "bad"),
139 "s_mov_b32 s0, 999",
140 ("lbl", "ok"),
141 "s_add_u32 s0, s0, 1",
142 "s_mov_b32 exec_hi, 0",
143 ("br", "s_cbranch_execnz", "bad2"),
144 "s_add_u32 s0, s0, 2",
145 ("lbl", "bad2"),
146 "s_endpgm",
147 ], wave=64)
148 self.assertEqual(res_nz["sgpr"][0], 3)
149 self.assertEqual(res_nz["exec"], 0)
150
151 def test_wave64_vcc_hi_mov_preserves_lo_and_drives_upper_lanes(self):
152 # Write vcc_lo (lanes 1, 3) then vcc_hi (lanes 33, 63); low 32 bits must stay intact
153 # and VOP2 v_cndmask_b32 must see vcc[63:32] on lanes 32..63.
154 res = self.run_items(lane_id_prologue(64) + [
155 "s_cmp_eq_u32 1, 1", # SCC = 1; s_mov_b32 vcc_hi must preserve SCC
156 "s_mov_b32 vcc_lo, 0x0000000a",
157 "s_mov_b32 vcc_hi, 0x80000002",
158 "s_mov_b32 s0, scc",
159 "v_mov_b32 v1, 10",
160 "v_mov_b32 v2, 20",
161 "v_cndmask_b32 v3, v1, v2",
162 "v_mov_b32 v4, 0",
163 "exp mrt0 v0, v3, v4, v4 done vm",
164 "s_endpgm",
165 ], wave=64)
166 self.assertEqual(res["sgpr"][0], 1)
167 self.assertEqual(res["vcc"], (0x80000002 << 32) | 0x0000000A)
168 for lane in range(64):
169 want = 20 if lane in (1, 3, 33, 63) else 10
170 self.assertEqual(res["exports"][lane][1], want)
171
172 # vcc_lo == 0 and vcc_hi != 0 must keep VCCZ == 0 in wave64; clearing vcc_hi sets VCCZ == 1.
173 res_vccz = self.run_items([
174 "s_mov_b32 s0, 0",
175 "s_mov_b32 vcc_lo, 0",
176 "s_mov_b32 vcc_hi, 0x10",
177 ("br", "s_cbranch_vccz", "bad"),
178 "s_add_u32 s0, s0, 1",
179 "s_mov_b32 vcc_hi, 0",
180 ("br", "s_cbranch_vccnz", "bad"),
181 "s_add_u32 s0, s0, 2",
182 ("br", "s_cbranch_vccz", "done"),
183 ("lbl", "bad"),
184 "s_mov_b32 s0, 999",
185 ("lbl", "done"),
186 "s_endpgm",
187 ], wave=64)
188 self.assertEqual(res_vccz["sgpr"][0], 3)
189 self.assertEqual(res_vccz["vcc"], 0)
190
191 def test_read_exec_hi_and_vcc_hi_in_scalar_ops_wave64(self):
192 res = self.run_items([
193 "s_mov_b32 exec_lo, 0x11223344",
194 "s_mov_b32 exec_hi, 0x55667788",
195 "s_mov_b32 vcc_lo, 0xaabbccdd",
196 "s_mov_b32 vcc_hi, 0x0f0f0f0f",
197 "s_cmp_eq_u32 1, 2", # SCC = 0; s_mov_b32 must preserve SCC
198 "s_mov_b32 s4, vcc_hi",
199 "s_mov_b32 s5, exec_hi",
200 "s_mov_b32 s6, scc",
201 "s_and_b32 s7, exec_hi, 0x00ff00ff",
202 "s_mov_b32 s8, scc",
203 "s_or_b32 vcc_hi, vcc_hi, 0xf0000000",
204 "s_mov_b32 s9, scc",
205 "s_xnor_b32 s10, exec_hi, 0x55667788", # 32-bit exact complement of XOR -> 0xffffffff -> SCC=1
206 "s_mov_b32 s11, scc",
207 "s_xor_b32 s12, exec_hi, 0x55667788", # 0 -> SCC=0
208 "s_mov_b32 s13, scc",
209 "s_xnor_b32 s14, exec_hi, 0xaa998877", # 0 -> SCC=0 (verifies 32-bit mask, not 64-bit)
210 "s_mov_b32 s15, scc",
211 "s_cmp_eq_u32 vcc_hi, 0xff0f0f0f",
212 "s_mov_b32 s16, scc",
213 "s_cmp_lg_u32 exec_hi, 0x55667788",
214 "s_mov_b32 s17, scc",
215 "s_mov_b32 exec_lo, -1",
216 "s_mov_b32 exec_hi, 0",
217 "s_xnor_b32 s18, exec_hi, -1", # 32-bit -1 -> ~(0 ^ 0xffffffff) = 0, SCC=0
218 "s_mov_b32 s19, scc",
219 "s_mov_b32 exec_hi, -1",
220 "s_xor_b32 s20, exec_hi, -1", # 32-bit -1 -> 0xffffffff ^ 0xffffffff = 0, SCC=0
221 "s_mov_b32 s21, scc",
222 "s_endpgm",
223 ], wave=64)
224 self.assertEqual(res["sgpr"][4], 0x0F0F0F0F)
225 self.assertEqual(res["sgpr"][5], 0x55667788)
226 self.assertEqual(res["sgpr"][6], 0)
227 self.assertEqual(res["sgpr"][7], 0x00660088)
228 self.assertEqual(res["sgpr"][8], 1)
229 self.assertEqual(res["sgpr"][9], 1)
230 self.assertEqual(res["sgpr"][10], 0xFFFFFFFF)
231 self.assertEqual(res["sgpr"][11], 1)
232 self.assertEqual(res["sgpr"][12], 0)
233 self.assertEqual(res["sgpr"][13], 0)
234 self.assertEqual(res["sgpr"][14], 0)
235 self.assertEqual(res["sgpr"][15], 0)
236 self.assertEqual(res["sgpr"][16], 1)
237 self.assertEqual(res["sgpr"][17], 0)
238 self.assertEqual(res["sgpr"][18], 0)
239 self.assertEqual(res["sgpr"][19], 0)
240 self.assertEqual(res["sgpr"][20], 0)
241 self.assertEqual(res["sgpr"][21], 0)
242 self.assertEqual(res["vcc"], (0xFF0F0F0F << 32) | 0xAABBCCDD)
243 self.assertEqual(res["exec"], MASK64)
244
245 # Full-wave 64-bit register names in _b32 SOP2 ops remain rejected in wave64.
246 with self.assertRaises(cpu_ref.Unsupported):
247 self.run_items(["s_and_b32 vcc, vcc, exec", "s_endpgm"], wave=64)
248
249 def test_wave32_exec_hi_keeps_upper_half_zero_and_vcc_hi_is_scalar(self):
250 # Wave32 runs with EXEC[63:32] == 0 so lanes 32-63 never execute even if exec_hi is written.
251 # vcc_hi holds its own 32-bit value independently of wave32 VCC[31:0] / VCCZ.
252 items = lane_id_prologue(32) + [
253 "s_mov_b32 exec_lo, 0x0000000f",
254 "s_mov_b32 exec_hi, 0xffffffff",
255 "s_or_b32 exec_hi, exec_hi, 0x1",
256 "s_mov_b32 s0, exec_hi",
257 "s_and_b32 s1, exec_hi, 1",
258 "s_mov_b32 s2, scc",
259 "s_mov_b32 vcc_lo, 0x00000005",
260 "s_mov_b32 vcc_hi, 0xdeadbeef",
261 "s_mov_b32 s3, vcc_hi",
262 "s_and_b32 s4, vcc_hi, 0x0000ffff",
263 "s_mov_b32 vcc_lo, 0",
264 ("br", "s_cbranch_vccnz", "bad"),
265 "s_and_saveexec_b32 vcc_hi, 0x00000003",
266 "s_mov_b32 s5, vcc_hi",
267 "s_mov_b32 exec_lo, vcc_hi",
268 "v_mov_b32 v1, 1",
269 "v_mov_b32 v2, 2",
270 "v_mov_b32 v3, 3",
271 "exp mrt0 v0, v1, v2, v3 done vm",
272 ("br", "s_branch", "done"),
273 ("lbl", "bad"),
274 "s_mov_b32 s3, 0",
275 ("lbl", "done"),
276 "s_endpgm",
277 ]
278 path = self.write_items(items)
279 machine = cf_ref.WaveMachine(parse_file(path), wave=32)
280 res = machine.run()
281 self.assertEqual(machine.exec >> 32, 0)
282 self.assertEqual(res["exec"], 0x0000000F)
283 self.assertEqual(res["vcc"], 0)
284 self.assertEqual(res["sgpr"][0], 0)
285 self.assertEqual(res["sgpr"][1], 0)
286 self.assertEqual(res["sgpr"][2], 0)
287 self.assertEqual(res["sgpr"][3], 0xDEADBEEF)
288 self.assertEqual(res["sgpr"][4], 0x0000BEEF)
289 self.assertEqual(res["sgpr"][5], 0x0000000F)
290 self.assertEqual(sorted(res["exports"]), [0, 1, 2, 3])
291
292
293if __name__ == "__main__":
294 unittest.main()
diff --git a/tests/test_csv_line_endings.py b/tests/test_csv_line_endings.py
new file mode 100644
index 000000000..8b883349d
--- /dev/null
+++ b/tests/test_csv_line_endings.py
@@ -0,0 +1,70 @@
1"""CSV reports must have the same bytes on every platform.
2
3`csv.writer` defaults to `lineterminator="\\r\\n"`, so a tool that leaves it at the default writes CRLF on Windows and
4LF everywhere else, and the same archive gives different report bytes depending on the machine that exported it.
5`tools/awc_manifest.py` and `tools/awc_shorts.py` pass `lineterminator="\\n"` and `tools/bink_index.py` documents why
6its stdout writer needs it; this test keeps every other writer on the same convention. No game files are read.
7"""
8import os
9import re
10import subprocess
11import sys
12import tempfile
13import unittest
14
15ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
16TOOLS = os.path.join(ROOT, "tools")
17
18# Every csv writer call in tools/, with the two lines that may continue it.
19WRITER = re.compile(r"\bcsv\.(?:Dict)?[Ww]riter\(")
20
21
22def writer_calls():
23 """Yield (file, line number, the call's source text) for every csv writer constructed in tools/."""
24 for name in sorted(os.listdir(TOOLS)):
25 if not name.endswith(".py"):
26 continue
27 path = os.path.join(TOOLS, name)
28 with open(path, encoding="utf-8") as f:
29 lines = f.read().splitlines()
30 for index, line in enumerate(lines):
31 if WRITER.search(line):
32 yield name, index + 1, "\n".join(lines[index:index + 3])
33
34
35class CsvTerminatorTest(unittest.TestCase):
36 def test_every_csv_writer_sets_an_lf_terminator(self):
37 missing = [f"{name}:{line}" for name, line, source in writer_calls()
38 if 'lineterminator="\\n"' not in source]
39 self.assertEqual(missing, [], "csv writers without lineterminator='\\n' (CRLF on Windows)")
40
41 def run_tool(self, tool, source):
42 out = os.path.join(self.work, os.path.splitext(tool)[0] + ".csv")
43 result = subprocess.run([sys.executable, "-I", os.path.join(TOOLS, tool), source, out],
44 capture_output=True, text=True, check=False)
45 self.assertEqual(result.returncode, 0, result.stderr)
46 self.assertTrue(os.path.isfile(out), result.stdout)
47 with open(out, "rb") as f:
48 return f.read()
49
50 def setUp(self):
51 self.temp = tempfile.TemporaryDirectory()
52 self.work = self.temp.name
53 self.source = os.path.join(self.work, "empty")
54 os.makedirs(self.source)
55
56 def tearDown(self):
57 self.temp.cleanup()
58
59 def test_csv_reports_have_no_carriage_return(self):
60 # These three scan a folder and write a header even when it holds nothing, so they need no archive.
61 for tool in ("page_index.py", "rbf0_index.py", "restofworld_index.py"):
62 with self.subTest(tool=tool):
63 data = self.run_tool(tool, self.source)
64 self.assertNotIn(b"\r", data, f"{tool} wrote a carriage return")
65 self.assertTrue(data.endswith(b"\n"), f"{tool} did not end its last row with a newline")
66 self.assertTrue(data.count(b"\n") >= 1)
67
68
69if __name__ == "__main__":
70 unittest.main()
diff --git a/tests/test_d3d12_xs_surface.py b/tests/test_d3d12_xs_surface.py
index 536a2673a..754355d30 100644
--- a/tests/test_d3d12_xs_surface.py
+++ b/tests/test_d3d12_xs_surface.py
@@ -82,4 +82,9 @@ if __name__ == "__main__":
82 errors, checked, _um = S.check_sdk() 82 errors, checked, _um = S.check_sdk()
83 assert errors == [], errors 83 assert errors == [], errors
84 assert checked == 83 84 assert checked == 83
85 if os.environ.get("SCARAB_REF"):
86 errors, _notes = S.check_scarab(os.environ["SCARAB_REF"])
87 assert errors == [], errors
88 else:
89 print("SCARAB cross-check skipped: SCARAB_REF is not set")
85 print("ok") 90 print("ok")
diff --git a/tests/test_f16_hw_words.py b/tests/test_f16_hw_words.py
index 249e2c932..917ee1fb7 100644
--- a/tests/test_f16_hw_words.py
+++ b/tests/test_f16_hw_words.py
@@ -35,6 +35,9 @@ HARDWARE = {
35 "ps_f16_const": (0xAAAA3D00, 0x38005555, 0xAAAA3800, 0x3F000000), 35 "ps_f16_const": (0xAAAA3D00, 0x38005555, 0xAAAA3800, 0x3F000000),
36 "ps_f16_const2": (0x42003D00, 0x3D004200, 0xAAAABC00, 3), 36 "ps_f16_const2": (0x42003D00, 0x3D004200, 0xAAAABC00, 3),
37 "ps_f16_pack": (0x34003C00, 0x38003400, 0x34000000, 0x44004200), 37 "ps_f16_pack": (0x34003C00, 0x38003400, 0x34000000, 0x44004200),
38 # neg/abs on the selected half: a sign flip / clear before packing (SHADER-260; the rule was measured on
39 # gfx1036 and these words follow it, they are not a direct readback of this shader)
40 "ps_f16_pack_mods": (0x4400B400, 0xC4003400, 0x4400C200, 0xB400B400),
38} 41}
39OLD = 0xAAAA5555 42OLD = 0xAAAA5555
40 43
@@ -137,9 +140,18 @@ def ref_pack():
137 (v0 & w) << 16 | const(2.0) >> 16, (v1 & w) << 16 | v0 >> 16) 140 (v0 & w) << 16 | const(2.0) >> 16, (v1 & w) << 16 | v0 >> 16)
138 141
139 142
143def ref_pack_mods():
144 # -v / |v| on the selected half: NEG flips bit 15, ABS clears it, ABS first.
145 v0, v1, w = 0x42003400, 0x34004400, 0xFFFF
146 lo0, hi0, lo1, hi1 = v0 & w, v0 >> 16, v1 & w, v1 >> 16
147 return (lo0 ^ 0x8000 | (lo1 & 0x7FFF) << 16, lo0 | (lo1 ^ 0x8000) << 16,
148 hi0 ^ 0x8000 | lo1 << 16, lo0 ^ 0x8000 | (hi1 ^ 0x8000) << 16)
149
150
140REFERENCE = {"ps_f16_med3_opsel": ref_med3_opsel, "ps_f16_med3_mods": ref_med3_mods, "ps_f16_vop2": ref_vop2, 151REFERENCE = {"ps_f16_med3_opsel": ref_med3_opsel, "ps_f16_med3_mods": ref_med3_mods, "ps_f16_vop2": ref_vop2,
141 "ps_f16_vop2b": ref_vop2b, "ps_f16_vop1": ref_vop1, "ps_f16_vop1b": ref_vop1b, 152 "ps_f16_vop2b": ref_vop2b, "ps_f16_vop1": ref_vop1, "ps_f16_vop1b": ref_vop1b,
142 "ps_f16_const": ref_const, "ps_f16_const2": ref_const2, "ps_f16_pack": ref_pack} 153 "ps_f16_const": ref_const, "ps_f16_const2": ref_const2, "ps_f16_pack": ref_pack,
154 "ps_f16_pack_mods": ref_pack_mods}
143NAMES = sorted(HARDWARE) 155NAMES = sorted(HARDWARE)
144 156
145 157
diff --git a/tests/test_f16_op_sel.py b/tests/test_f16_op_sel.py
index 9db45e65f..64041e7e7 100644
--- a/tests/test_f16_op_sel.py
+++ b/tests/test_f16_op_sel.py
@@ -40,6 +40,8 @@ def left_shifts(spv):
40OPS = [ 40OPS = [
41 ("v_fma_f16", "v_fma_f16 v3, v1, v1, v1", 3), 41 ("v_fma_f16", "v_fma_f16 v3, v1, v1, v1", 3),
42 ("v_med3_f16", "v_med3_f16 v3, v1, v1, v1", 3), 42 ("v_med3_f16", "v_med3_f16 v3, v1, v1, v1", 3),
43 ("v_min3_f16", "v_min3_f16 v3, v1, v1, v1", 3),
44 ("v_max3_f16", "v_max3_f16 v3, v1, v1, v1", 3),
43 ("v_add_f16", "v_add_f16_e64 v3, v1, v1", 2), 45 ("v_add_f16", "v_add_f16_e64 v3, v1, v1", 2),
44 ("v_sub_f16", "v_sub_f16_e64 v3, v1, v1", 2), 46 ("v_sub_f16", "v_sub_f16_e64 v3, v1, v1", 2),
45 ("v_subrev_f16", "v_subrev_f16_e64 v3, v1, v1", 2), 47 ("v_subrev_f16", "v_subrev_f16_e64 v3, v1, v1", 2),
diff --git a/tests/test_f16_op_sel_values.py b/tests/test_f16_op_sel_values.py
index 6435652df..d1ae359db 100644
--- a/tests/test_f16_op_sel_values.py
+++ b/tests/test_f16_op_sel_values.py
@@ -29,6 +29,8 @@ OPS = {
29 "v_min_f16": ("v_min_f16_e64 v3, {0}, {1}", 2, min), 29 "v_min_f16": ("v_min_f16_e64 v3, {0}, {1}", 2, min),
30 "v_fma_f16": ("v_fma_f16 v3, {0}, {1}, {2}", 3, lambda a, b, c: a * b + c), 30 "v_fma_f16": ("v_fma_f16 v3, {0}, {1}, {2}", 3, lambda a, b, c: a * b + c),
31 "v_med3_f16": ("v_med3_f16 v3, {0}, {1}, {2}", 3, median), 31 "v_med3_f16": ("v_med3_f16 v3, {0}, {1}, {2}", 3, median),
32 "v_min3_f16": ("v_min3_f16 v3, {0}, {1}, {2}", 3, min),
33 "v_max3_f16": ("v_max3_f16 v3, {0}, {1}, {2}", 3, max),
32 "v_sqrt_f16": ("v_sqrt_f16_e64 v3, {0}", 1, lambda a: a ** 0.5), 34 "v_sqrt_f16": ("v_sqrt_f16_e64 v3, {0}", 1, lambda a: a ** 0.5),
33 "v_rcp_f16": ("v_rcp_f16_e64 v3, {0}", 1, lambda a: 1 / a), 35 "v_rcp_f16": ("v_rcp_f16_e64 v3, {0}", 1, lambda a: 1 / a),
34} 36}
diff --git a/tests/test_fma_mix_probe.py b/tests/test_fma_mix_probe.py
index db85fcd08..46c49f0cd 100644
--- a/tests/test_fma_mix_probe.py
+++ b/tests/test_fma_mix_probe.py
@@ -65,14 +65,13 @@ class Inputs(unittest.TestCase):
65 65
66 66
67class Translator(unittest.TestCase): 67class Translator(unittest.TestCase):
68 def test_translator_rounds_twice(self): 68 def test_translator_rounds_once(self):
69 # docs/design.md, Known approximations: nearest-mode v_fma_mix* takes the f32 Fma and then narrows. If the 69 # docs/design.md, Known approximations: v_fma_mix* rounds once straight to f16 (measured on RDNA2 hardware).
70 # translator is changed to round once (after a hardware measurement), this test and that sentence change too.
71 got = probe.run_translator() 70 got = probe.run_translator()
72 rule, _ = probe.verdict(list(zip(probe.CASES, got))) 71 rule, _ = probe.verdict(list(zip(probe.CASES, got)))
73 self.assertEqual(rule, probe.DOUBLE) 72 self.assertEqual(rule, probe.SINGLE)
74 for case, w in zip(probe.CASES, got): 73 for case, w in zip(probe.CASES, got):
75 self.assertEqual(w, word(case, BY_HAND[case.name][1]), case.name) 74 self.assertEqual(w, word(case, BY_HAND[case.name][0]), case.name)
76 75
77 def test_compute_listing_gives_the_pixel_shader_words(self): 76 def test_compute_listing_gives_the_pixel_shader_words(self):
78 # The Vulkan side's shader (operands from user SGPRs, one store per case) on the CPU interpreter, with the 77 # The Vulkan side's shader (operands from user SGPRs, one store per case) on the CPU interpreter, with the
@@ -149,7 +148,7 @@ class Command(unittest.TestCase):
149 with contextlib.redirect_stdout(buf): 148 with contextlib.redirect_stdout(buf):
150 rc = probe.main([]) 149 rc = probe.main([])
151 self.assertEqual(rc, 0) 150 self.assertEqual(rc, 0)
152 self.assertIn("translator: follows double rounding", buf.getvalue()) 151 self.assertIn("translator: follows single rounding", buf.getvalue())
153 152
154 def test_unknown_side_and_missing_build_are_usage_errors(self): 153 def test_unknown_side_and_missing_build_are_usage_errors(self):
155 import contextlib 154 import contextlib
diff --git a/tests/test_fspx_unpack.py b/tests/test_fspx_unpack.py
index 3c9c843fc..6d42dab37 100644
--- a/tests/test_fspx_unpack.py
+++ b/tests/test_fspx_unpack.py
@@ -227,6 +227,24 @@ class Cli(unittest.TestCase):
227 self.assertEqual(code, 1) 227 self.assertEqual(code, 1)
228 self.assertIn("FSPX status 5", err) 228 self.assertIn("FSPX status 5", err)
229 229
230 def test_short_kind0_unpacks_without_keyerror(self):
231 with tempfile.TemporaryDirectory() as t:
232 src = os.path.join(t, "short.fspx")
233 with open(src, "wb") as f:
234 f.write(make_fspx([(0, struct.pack("<2I", 1, 2)), (6, program())]))
235 out = os.path.join(t, "out")
236 code, _, err = self.run_tool(src, "--out", out)
237 self.assertEqual(code, 0)
238 self.assertEqual(err, "")
239 with open(os.path.join(out, "index.json"), encoding="utf-8") as f:
240 index = json.load(f)
241 self.assertEqual(len(index), 1)
242 self.assertNotIn("threads", index[0])
243 self.assertNotIn("wave32", index[0])
244 with open(os.path.join(out, "fspx", "short.json"), encoding="utf-8") as f:
245 meta = json.load(f)
246 self.assertEqual(meta["words"], [1, 2])
247
230 248
231class TranslatorSidecars(unittest.TestCase): 249class TranslatorSidecars(unittest.TestCase):
232 """rdna2spirv reads an FSPX program's code and dispatch state from fspx/ when there is no FSSM blob.""" 250 """rdna2spirv reads an FSPX program's code and dispatch state from fspx/ when there is no FSSM blob."""
diff --git a/tests/test_gamedata_index.py b/tests/test_gamedata_index.py
index 1409150dd..832926511 100644
--- a/tests/test_gamedata_index.py
+++ b/tests/test_gamedata_index.py
@@ -150,6 +150,25 @@ class GamedataIndexTest(unittest.TestCase):
150 self.assertEqual(rows[0]["root"], "RootA") 150 self.assertEqual(rows[0]["root"], "RootA")
151 self.assertEqual(rows[0]["type"], "xml") 151 self.assertEqual(rows[0]["type"], "xml")
152 152
153 def test_printable_page_directory_stream_is_not_xml(self):
154 # A resource stream with the "0DRP" page marker at +16 whose first 4 KiB are over 95% printable and hold a
155 # "<": data.rpf's 337 such streams were reported as incomplete XML with no root.
156 head = bytes(8) + bytes.fromhex("80ca005000000000") + b"0DRP" + bytes(12)
157 page = head + (b"<abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ>" * 80)[:4096 - len(head)]
158 page += bytes(512)
159 tool = load_tool()
160 self.assertGreater(tool.printable(page), 0.95) # the heuristic alone would call it text
161 self.add(page)
162 self.finish()
163 out = os.path.join(self.root, "index.json")
164 p = self.run_tool(self.carve, "--json", out)
165 self.assertEqual(p.returncode, 0, p.stdout + p.stderr)
166 with open(out, encoding="utf-8") as f:
167 data = json.load(f)
168 self.assertNotIn("xml", data["summary"]["types"])
169 self.assertEqual(data["summary"]["xml_incomplete"], 0)
170 self.assertEqual([(r["type"], r["detail"]) for r in data["rows"]], [("other", "0DRP")])
171
153 def test_archive_runs_the_carver_and_reads_roots(self): 172 def test_archive_runs_the_carver_and_reads_roots(self):
154 xml = b'<?xml version="1.0"?>\n<RootA><!-- synthetic fixture, longer than 64 bytes --><Item value="1"/></RootA>' 173 xml = b'<?xml version="1.0"?>\n<RootA><!-- synthetic fixture, longer than 64 bytes --><Item value="1"/></RootA>'
155 blob = b"\x00\x01\x02binary\xff" * 32 174 blob = b"\x00\x01\x02binary\xff" * 32
diff --git a/tests/test_hashdict.py b/tests/test_hashdict.py
index c517f6a92..b9cc76a9a 100644
--- a/tests/test_hashdict.py
+++ b/tests/test_hashdict.py
@@ -359,6 +359,32 @@ class CarveAndExtraCLITest(unittest.TestCase):
359 self.assertEqual(p_lookup.returncode, 0, p_lookup.stderr) 359 self.assertEqual(p_lookup.returncode, 0, p_lookup.stderr)
360 self.assertIn(f"{lookup_hash} model_prop", p_lookup.stdout) 360 self.assertIn(f"{lookup_hash} model_prop", p_lookup.stdout)
361 361
362 def test_one_archive_folder_is_harvested_as_that_archive(self):
363 # <work>/carve/common (its own index.json, as the gamedata_* tools take it) used to give an empty
364 # dictionary with exit 0: only <carve>/<archive>/index.json was looked for.
365 p = self.run_tool(os.path.join(self.carve_dir, "common"), "--out", self.out_json)
366 self.assertEqual(p.returncode, 0, p.stderr)
367 self.assertIn("common: ", p.stdout)
368 with open(self.out_json, encoding="utf-8") as f:
369 d = json.load(f)
370 self.assertEqual(d.get(f"{hashdict.joaat('common_archive_asset'):08x}"), "common_archive_asset")
371 self.assertNotIn(f"{hashdict.joaat('bink2_skipped_asset'):08x}", d)
372 # An archive outside --archives still contributes only its PSIN/RBF0 blobs.
373 p = self.run_tool(os.path.join(self.carve_dir, "custom_pack"), "--out", self.out_json)
374 self.assertEqual(p.returncode, 0, p.stderr)
375 with open(self.out_json, encoding="utf-8") as f:
376 self.assertEqual(json.load(f), {f"{hashdict.joaat('pso_metadata_token'):08x}": "pso_metadata_token"})
377
378 def test_out_naming_a_one_archive_index_is_refused(self):
379 index = os.path.join(self.carve_dir, "common", "index.json")
380 with open(index, "rb") as f:
381 before = f.read()
382 p = self.run_tool(os.path.join(self.carve_dir, "common"), "--out", index)
383 self.assertEqual(p.returncode, 2, p.stderr)
384 self.assertIn("is one of the inputs", p.stderr)
385 with open(index, "rb") as f:
386 self.assertEqual(f.read(), before)
387
362 def test_build_requires_an_explicit_carve_directory(self): 388 def test_build_requires_an_explicit_carve_directory(self):
363 empty = os.path.join(self.dir, "empty") 389 empty = os.path.join(self.dir, "empty")
364 os.mkdir(empty) 390 os.mkdir(empty)
diff --git a/tests/test_imhex_patterns.py b/tests/test_imhex_patterns.py
new file mode 100644
index 000000000..9e0cc1cca
--- /dev/null
+++ b/tests/test_imhex_patterns.py
@@ -0,0 +1,170 @@
1"""Tests for the ImHex patterns in tools/imhex.
2
3 python -I tests/test_imhex_patterns.py
4
5Every byte here is built by the test: no game file, name or path is used. The RBF0 inputs are first checked with
6tools/rbf0_index.py, the repository's own parser. When ImHex is installed, each pattern then runs on the same bytes
7through ImHex's pattern-language CLI (`imhex --pl format ... -f json`) and the decoded fields are compared with the
8parser's result. ImHex is found through LEONIDA_IMHEX, then PATH, then its default Windows install folder; without it
9the ImHex half is skipped and the rest still runs.
10"""
11import json
12import os
13import shutil
14import struct
15import subprocess
16import sys
17import tempfile
18import unittest
19
20ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
21PATTERNS = os.path.join(ROOT, "tools", "imhex")
22sys.path.insert(0, os.path.join(ROOT, "tools"))
23
24import rbf0_index # noqa: E402
25
26
27def find_imhex():
28 candidates = [os.environ.get("LEONIDA_IMHEX"), shutil.which("imhex")]
29 if os.name == "nt":
30 candidates.append(os.path.join(os.environ.get("ProgramFiles", r"C:\Program Files"), "ImHex", "imhex.exe"))
31 for c in candidates:
32 if c and os.path.isfile(c):
33 return c
34 return None
35
36
37IMHEX = find_imhex()
38
39
40# ---- synthetic inputs ------------------------------------------------------------------------------------------
41
42def _name(name):
43 return struct.pack("<H", len(name)) + name
44
45
46def rbf0_stream(wide):
47 """One resource with every record type of docs/rbf0.md section 3, then bytes past the root close."""
48 q, d = ("Q", "d") if wide else ("I", "f")
49 q, d, d3 = "<" + q, "<" + d, "<" + d * 3
50 out = b"RBF0" + (rbf0_index.PROLOGUE if wide else b"")
51 out += bytes([0, 0x00]) + _name(b"root") + struct.pack("<HHH", 0, 0, 1)
52 out += bytes([1, 0x10]) + _name(b"count") + struct.pack(q, 7) # the root's one attribute
53 out += bytes([2, 0x00]) + _name(b"item") + struct.pack("<HHH", 0, 0, 0)
54 out += bytes([3, 0x40]) + _name(b"scale") + struct.pack(d, 1.5)
55 out += bytes([4, 0x50]) + _name(b"pos") + struct.pack(d3, 1.0, -2.0, 0.25)
56 out += bytes([5, 0x60]) + _name(b"label") + struct.pack("<H", 5) + b"probe"
57 out += bytes([6, 0x20]) + _name(b"flag") + bytes([6, 0x30]) # new, then reused
58 out += bytes([3, 0x10]) + struct.pack(q, 9) # reused with another type
59 out += bytes([0xFD, 0xFF]) + struct.pack("<I", 5) + b"text\x00"
60 out += b"\xff\xff" # close item
61 out += b"\xff\xff" # close root: the end
62 return out + b"\x00\x11\x22\x33" # not part of the resource
63
64
65def rpf9_archive(data_offset=0x100, size=0x140):
66 head = b"9FPR" + struct.pack("<III", data_offset, 0x11, 0x22)
67 toc = bytes((i * 37) & 0xFF for i in range(data_offset - len(head)))
68 body = b"\x78\x9c" + bytes(size - data_offset - 2)
69 return head + toc + body
70
71
72def pragma_magic(pattern):
73 """The bytes of `#pragma magic [ .. ] @ 0x00` in a pattern file."""
74 with open(os.path.join(PATTERNS, pattern), encoding="utf-8") as f:
75 for line in f:
76 if line.startswith("#pragma magic"):
77 inside = line[line.index("[") + 1:line.index("]")]
78 return bytes(int(b, 16) for b in inside.split())
79 return None
80
81
82# ---- tests -----------------------------------------------------------------------------------------------------
83
84class InputsAndMagic(unittest.TestCase):
85 """Runs everywhere: the synthetic inputs are valid RBF0 by the repository's parser, and the magics agree."""
86
87 def test_synthetic_streams_parse(self):
88 for wide in (True, False):
89 r = rbf0_index.parse_rbf0(rbf0_stream(wide)[:-4])
90 self.assertEqual(r["status"], "ok", r["error"])
91 self.assertEqual(r["layout"], "wide-64" if wide else "narrow-32")
92 self.assertEqual(r["elements"], 2)
93 self.assertEqual(r["descriptors"], 7)
94
95 def test_pattern_magics(self):
96 self.assertEqual(pragma_magic("rbf0.hexpat"), rbf0_index.MAGIC)
97 self.assertEqual(pragma_magic("rpf9.hexpat"), b"9FPR") # RPF9 stored little-endian (docs/rpf.md)
98
99
100@unittest.skipUnless(IMHEX, "ImHex is not installed (set LEONIDA_IMHEX to imhex.exe)")
101class PatternsInImHex(unittest.TestCase):
102 def setUp(self):
103 self.tmp = tempfile.TemporaryDirectory()
104 self.addCleanup(self.tmp.cleanup)
105
106 def run_pattern(self, pattern, data):
107 """Returns (decoded JSON or None, combined output)."""
108 src = os.path.join(self.tmp.name, "input.bin")
109 out = os.path.join(self.tmp.name, "out.json")
110 if os.path.exists(out):
111 os.remove(out)
112 with open(src, "wb") as f:
113 f.write(data)
114 cmd = [IMHEX, "--pl", "format", "-i", src, "-p", os.path.join(PATTERNS, pattern), "-o", out, "-f", "json"]
115 includes = os.path.join(os.path.dirname(IMHEX), "includes")
116 if os.path.isdir(includes):
117 cmd += ["-I", includes]
118 p = subprocess.run(cmd, capture_output=True, text=True, timeout=120)
119 log = p.stdout + p.stderr
120 if not os.path.exists(out):
121 return None, log
122 with open(out, encoding="utf-8") as f:
123 return json.load(f), log
124
125 def check_rbf0(self, wide):
126 data = rbf0_stream(wide)
127 ref = rbf0_index.parse_rbf0(data[:-4])
128 got, log = self.run_pattern("rbf0.hexpat", data)
129 self.assertIsNotNone(got, log)
130 self.assertEqual("prologue" in got["header"], wide)
131 records = got["records"]
132
133 names = [r["name"] for r in records if "name" in r]
134 self.assertEqual(names, ref["descriptor_names"])
135 self.assertEqual(sum(1 for r in records if r["index"] < 0xFD and r["type"] == 0x00), ref["elements"])
136 ints = [r["value_int"] for r in records if "value_int" in r]
137 self.assertEqual(ints, ref["ints"])
138 floats = []
139 for r in records:
140 floats += [r["value_float"]] if "value_float" in r else r.get("value_vec3", [])
141 self.assertEqual(floats, ref["floats"])
142 strings = [r.get("value_string", r.get("text", "")) for r in records if "value_string" in r or "text" in r]
143 self.assertEqual([s.split("%00")[0] for s in strings], ref["strings"])
144 self.assertEqual([r["attribute_count"] for r in records if "attribute_count" in r], [1, 0])
145 # The pattern stops where the root closes, as parse_rbf0 does: the 4 trailing bytes are not records.
146 self.assertEqual(records[-1]["index"], 0xFF)
147 self.assertEqual(sum(1 for r in records if r["index"] == 0xFF), 2)
148
149 def test_rbf0_wide(self):
150 self.check_rbf0(wide=True)
151
152 def test_rbf0_narrow(self):
153 self.check_rbf0(wide=False)
154
155 def test_rpf9_header_and_opaque_toc(self):
156 got, log = self.run_pattern("rpf9.hexpat", rpf9_archive(data_offset=0x100))
157 self.assertIsNotNone(got, log)
158 self.assertEqual(got["header"]["magic"], "9FPR")
159 self.assertEqual(got["header"]["data_offset"], 0x100)
160 self.assertEqual((got["header"]["u32_08"], got["header"]["u32_0c"]), (0x11, 0x22))
161 self.assertEqual(len(got["header_rest_and_toc"]), 0x100 - 0x10)
162
163 def test_rpf9_rejects_a_data_offset_past_the_end(self):
164 got, log = self.run_pattern("rpf9.hexpat", rpf9_archive(data_offset=0x100, size=0x140)[:0x20])
165 self.assertIsNone(got)
166 self.assertIn("data offset is outside the file", log)
167
168
169if __name__ == "__main__":
170 unittest.main()
diff --git a/tests/test_int_hw_probe.py b/tests/test_int_hw_probe.py
new file mode 100644
index 000000000..f2287f9a6
--- /dev/null
+++ b/tests/test_int_hw_probe.py
@@ -0,0 +1,119 @@
1"""Unit tests for tools/int_hw_probe.py (SHADER-137). Standard library only; no GPU or game files needed."""
2import io
3import json
4import os
5import sys
6import tempfile
7import unittest
8import unittest.mock
9from contextlib import redirect_stderr, redirect_stdout
10from pathlib import Path
11
12ROOT = Path(__file__).resolve().parents[1]
13TOOLS = ROOT / "tools"
14sys.dont_write_bytecode = True
15if str(TOOLS) not in sys.path:
16 sys.path.insert(0, str(TOOLS))
17
18import int_hw_probe as probe # noqa: E402
19from hw_oracle import runner as hw_runner # noqa: E402
20
21
22class IntHwProbeTests(unittest.TestCase):
23 def test_cases_unique_and_nonempty(self):
24 cases = probe.build_cases()
25 self.assertGreaterEqual(len(cases), 80)
26 names = [c.name for c in cases]
27 self.assertEqual(len(names), len(set(names)))
28 groups = {c.group for c in cases}
29 self.assertGreaterEqual(len(groups), 19)
30 for key in probe.KNOWN_DIVERGENCES:
31 self.assertIn(key, names)
32
33 def test_wave32_and_wave64_placeholder_expansion(self):
34 by_name = {c.name: c for c in probe.build_cases()}
35 c = by_name["v_mad_u64_u32_inactive_lane"]
36 w32 = "\n".join(c.lines(wave=32))
37 w64 = "\n".join(c.lines(wave=64))
38 self.assertIn("s_mov_b32 s14, exec_lo", w32)
39 self.assertIn("v_mad_u64_u32 v[8:9], vcc_lo", w32)
40 self.assertIn("s_mov_b64 s[14:15], exec", w64)
41 self.assertIn("v_mad_u64_u32 v[8:9], vcc,", w64)
42 self.assertNotIn("{", w32)
43 self.assertNotIn("{", w64)
44
45 def test_self_test_and_translator_groups(self):
46 buf = io.StringIO()
47 with redirect_stdout(buf):
48 rc = probe.main(["--self-test"])
49 self.assertEqual(rc, 0)
50 self.assertIn("self-test:", buf.getvalue())
51
52 def test_list_groups_and_unknown_group(self):
53 out, err = io.StringIO(), io.StringIO()
54 with redirect_stdout(out):
55 rc = probe.main(["--list-groups"])
56 self.assertEqual(rc, 0)
57 self.assertIn("valu_cvt_pknorm", out.getvalue())
58
59 with redirect_stderr(err):
60 rc = probe.main(["--group", "does_not_exist"])
61 self.assertEqual(rc, 2)
62 self.assertIn("unknown group", err.getvalue())
63
64 def test_hw_unavailable_returns_77(self):
65 err = io.StringIO()
66 with unittest.mock.patch.object(hw_runner, "open_oracle", side_effect=hw_runner.Unavailable("no GPU")):
67 with redirect_stderr(err):
68 rc = probe.main(["--oracle", "hw", "--group", "salu_bfe_past31"])
69 self.assertEqual(rc, 77)
70 self.assertIn("no GPU", err.getvalue())
71
72 def test_known_divergence_vs_strict_and_json_output(self):
73 # Mock hardware oracle returning the measured gfx1035 words for valu_cvt_flr_rpi.
74 measured = {
75 "v_cvt_rpi_precision": [0x00000000, 0x00800001, 0x00FFFFFF, 0x00000000],
76 "v_cvt_flr_rpi_nan_inf": [0x7FFFFFFF, 0x80000000, 0x7FFFFFFF, 0x80000000],
77 "v_cvt_i32_f32_nan_control": [0x00000000, 0x00000000, 0x00000000, 0x00000000],
78 "v_cvt_flr_edges": [0xFFFFFFFE, 0x7FFFFFFF, 0x80000000, 0x7FFFFFFF],
79 }
80 fake_hw = ("device=mock arch=gfx1035", {32: measured, 64: measured})
81 with tempfile.TemporaryDirectory() as tmp:
82 jpath = os.path.join(tmp, "out.json")
83 out = io.StringIO()
84 with unittest.mock.patch.object(probe, "run_hw", return_value=fake_hw):
85 with redirect_stdout(out):
86 rc = probe.main(["--oracle", "both", "--group", "valu_cvt_flr_rpi", "--json", jpath])
87 self.assertEqual(rc, 0)
88 self.assertIn("2 match, 2 known divergence, 0 unexpected mismatch, 0 wave32/64 diff", out.getvalue())
89 data = json.loads(Path(jpath).read_text(encoding="utf-8"))
90 self.assertEqual(data["device"], "device=mock arch=gfx1035")
91 self.assertEqual(len(data["cases"]), 4)
92
93 out2 = io.StringIO()
94 with unittest.mock.patch.object(probe, "run_hw", return_value=fake_hw):
95 with redirect_stdout(out2):
96 rc_strict = probe.main(["--oracle", "both", "--group", "valu_cvt_flr_rpi", "--strict"])
97 self.assertEqual(rc_strict, 1)
98
99 err = io.StringIO()
100 with unittest.mock.patch.object(probe, "run_hw", return_value=fake_hw):
101 with redirect_stderr(err):
102 rc_dir = probe.main(["--oracle", "both", "--group", "valu_cvt_flr_rpi", "--json", tmp])
103 self.assertEqual(rc_dir, 2)
104
105 def test_unexpected_mismatch_and_wave_diff_fail(self):
106 bad_hw = ("device=mock arch=gfx1035", {
107 32: {"s_bfe_i32_past31": [1, 2, 3, 4], "s_bfe_u32_past31": [0, 0, 0, 0], "s_bfe_i32_width0": [0, 0, 0, 0]},
108 64: {"s_bfe_i32_past31": [1, 2, 3, 5], "s_bfe_u32_past31": [0, 0, 0, 0], "s_bfe_i32_width0": [0, 0, 0, 0]},
109 })
110 out = io.StringIO()
111 with unittest.mock.patch.object(probe, "run_hw", return_value=bad_hw):
112 with redirect_stdout(out):
113 rc = probe.main(["--oracle", "both", "--group", "salu_bfe_past31"])
114 self.assertEqual(rc, 1)
115 self.assertIn("WAVE_DIFF", out.getvalue())
116
117
118if __name__ == "__main__":
119 unittest.main()
diff --git a/tests/test_make_game_assets_pools.py b/tests/test_make_game_assets_pools.py
index 9716b5ad7..0de945dfe 100644
--- a/tests/test_make_game_assets_pools.py
+++ b/tests/test_make_game_assets_pools.py
@@ -39,7 +39,7 @@ class AssetsPoolsTest(unittest.TestCase):
39 pass 39 pass
40 40
41 def pool(self, rel, size=100): 41 def pool(self, rel, size=100):
42 path = os.path.join(self.game, rel) 42 path = os.path.join(self.game, *rel.split("/"))
43 os.makedirs(os.path.dirname(path), exist_ok=True) 43 os.makedirs(os.path.dirname(path), exist_ok=True)
44 with open(path, "wb") as f: 44 with open(path, "wb") as f:
45 f.write(b"x" * size) 45 f.write(b"x" * size)
diff --git a/tests/test_make_game_preflight.py b/tests/test_make_game_preflight.py
index eb6964bb1..f1950cd34 100644
--- a/tests/test_make_game_preflight.py
+++ b/tests/test_make_game_preflight.py
@@ -654,9 +654,26 @@ class PathAndGameSelectionTest(PreflightTestBase):
654 self.assert_fails(make_game.choose_game, 654 self.assert_fails(make_game.choose_game,
655 match="More than one copy found: choose one with --game.") 655 match="More than one copy found: choose one with --game.")
656 656
657 def default_out_in(self, platform, icloud_documents):
658 """default_out() with a temporary home folder; icloud_documents makes the folder macOS keeps in iCloud
659 Drive when Desktop & Documents sync is on (~/Library/Mobile Documents/com~apple~CloudDocs/Documents)."""
660 with tempfile.TemporaryDirectory() as home:
661 if icloud_documents:
662 os.makedirs(os.path.join(home, "Library", "Mobile Documents", "com~apple~CloudDocs", "Documents"))
663 with mock.patch.object(make_game.os.path, "expanduser", lambda p: home + p[1:] if p.startswith("~") else p), \
664 mock.patch.object(make_game.sys, "platform", platform):
665 return os.path.relpath(make_game.default_out(), home)
666
657 def test_default_out_matches_documents_folder(self): 667 def test_default_out_matches_documents_folder(self):
658 expected = os.path.join(os.path.expanduser("~"), "Documents", "Leonida") 668 for platform in ("win32", "linux", "darwin"):
659 self.assertEqual(make_game.default_out(), expected) 669 self.assertEqual(self.default_out_in(platform, False), os.path.join("Documents", "Leonida"), platform)
670
671 def test_default_out_leaves_icloud_synced_documents_on_a_mac(self):
672 # Before: with iCloud Desktop & Documents sync on, ~/Documents/Leonida (and its work folder, hundreds of GB
673 # made from the game) went into iCloud Drive, which uploads it and can evict the work files from the disk.
674 self.assertEqual(self.default_out_in("darwin", True), "Leonida")
675 # Only macOS keeps Documents in iCloud Drive this way; elsewhere the folder means nothing.
676 self.assertEqual(self.default_out_in("linux", True), os.path.join("Documents", "Leonida"))
660 677
661 def test_constants_definitions(self): 678 def test_constants_definitions(self):
662 self.assertEqual(make_game.STAGES, ["check", "shaders", "assets", "runtime", "pipelines"]) 679 self.assertEqual(make_game.STAGES, ["check", "shaders", "assets", "runtime", "pipelines"])
diff --git a/tests/test_make_game_wave64.py b/tests/test_make_game_wave64.py
index 4a37bfb1e..3e2bfa939 100644
--- a/tests/test_make_game_wave64.py
+++ b/tests/test_make_game_wave64.py
@@ -118,6 +118,20 @@ class DetectionGapsTest(unittest.TestCase):
118 text = real_format(("Big GPU", 64, ALL)) + "VkPhysicalDeviceProperties:\n\tdeviceName = Old GPU\n" 118 text = real_format(("Big GPU", 64, ALL)) + "VkPhysicalDeviceProperties:\n\tdeviceName = Old GPU\n"
119 self.assertIsNone(make_game.smallest_max_subgroup(text)) # one device says nothing: unknown, so on 119 self.assertIsNone(make_game.smallest_max_subgroup(text)) # one device says nothing: unknown, so on
120 120
121 def test_a_layered_api_name_is_not_another_device(self):
122 # VK_KHR_maintenance7 lists a layered driver's underlying API (MoltenVK on Metal) with its own deviceName,
123 # indented deeper and printed before the subgroup block: it is the same device, not one without a size.
124 layered = ("GPU0:\nVkPhysicalDeviceProperties:\n\tdeviceName = Apple M2 Max\n"
125 "VkPhysicalDeviceLayeredApiPropertiesListKHR:\n\tpLayeredApis: count = 1\n\t\t0:\n"
126 "\t\t\tlayeredAPI = PHYSICAL_DEVICE_LAYERED_API_METAL_KHR\n\t\t\tdeviceName = Apple M2 Max\n"
127 "VkPhysicalDeviceSubgroupSizeControlProperties:\n\tmaxSubgroupSize = 32\n")
128 self.assertEqual(make_game.smallest_max_subgroup(layered), 32)
129 layered_json = ('{"VkPhysicalDeviceProperties": {\n\t\t"deviceName": "Apple M2 Max"},\n'
130 '\t"VkPhysicalDeviceLayeredApiPropertiesListKHR": {"pLayeredApis": [\n'
131 '\t\t\t{"layeredAPI": 3,\n\t\t\t "deviceName": "Apple M2 Max"}]},\n'
132 '\t"VkPhysicalDeviceSubgroupSizeControlProperties": {\n\t\t"maxSubgroupSize": 32}}')
133 self.assertEqual(make_game.smallest_max_subgroup(layered_json), 32)
134
121 def test_a_device_printing_the_size_twice_does_not_hide_one_that_prints_none(self): 135 def test_a_device_printing_the_size_twice_does_not_hide_one_that_prints_none(self):
122 twice = ("VkPhysicalDeviceProperties:\n\tdeviceName = A\n" 136 twice = ("VkPhysicalDeviceProperties:\n\tdeviceName = A\n"
123 "VkPhysicalDeviceSubgroupSizeControlProperties:\n\tmaxSubgroupSize = 64\n" 137 "VkPhysicalDeviceSubgroupSizeControlProperties:\n\tmaxSubgroupSize = 64\n"
@@ -163,6 +177,46 @@ class DetectionGapsTest(unittest.TestCase):
163 self.assertTrue(self.decide(real_format(("A", 32, ALL)), '{"native64": true}')) # vulkaninfo wins: on 177 self.assertTrue(self.decide(real_format(("A", 32, ALL)), '{"native64": true}')) # vulkaninfo wins: on
164 178
165 179
180class Rdna2AmdWindowsTest(unittest.TestCase):
181 """#857: AMD's Windows compiler for RDNA2 crashes on emulated LDS compute shaders. When the runtime's GPU is one
182 and runs wave64 natively, auto leaves emulation off even if another device (an Intel iGPU) is 32-wide."""
183
184 RX6700 = '{"device": "AMD Radeon RX 6700", "native64": true, "rdna2_amd_windows": true}'
185
186 def decide(self, vulkaninfo, tool, mode="auto"):
187 def fake_run(args, **kw):
188 if os.path.basename(str(args[-1])) == "vk_subgroup_info.py":
189 return subprocess.CompletedProcess(args, 0 if "native64" in tool else 1, stdout=tool, stderr="")
190 return subprocess.CompletedProcess(args, 0, stdout=vulkaninfo, stderr="")
191 logged = []
192 with mock.patch.object(make_game.shutil, "which", return_value="vulkaninfo"), \
193 mock.patch.object(make_game.subprocess, "run", side_effect=fake_run), \
194 mock.patch.object(make_game, "log", logged.append):
195 return make_game.wave64_emulate(mode), logged
196
197 def test_intel_igpu_and_rdna2_card_leaves_it_off(self):
198 on, logged = self.decide(real_format(("Intel iGPU", 32, ALL), ("AMD Radeon RX 6700", 64, ALL)), self.RX6700)
199 self.assertFalse(on)
200 self.assertIn("#857", logged[-1])
201 self.assertIn("AMD Radeon RX 6700", logged[-1])
202
203 def test_other_runtime_gpus_keep_emulation_on(self):
204 two = real_format(("Intel iGPU", 32, ALL), ("Big GPU", 64, ALL))
205 for label, tool in (("rdna3", '{"native64": true, "rdna2_amd_windows": false}'),
206 ("older_tool_without_the_key", '{"native64": true}'),
207 ("rdna2_without_native64", '{"native64": false, "rdna2_amd_windows": true}'),
208 ("unreadable", '{"error": "no Vulkan loader found"}'),
209 ("not_json", "not json")):
210 with self.subTest(case=label):
211 self.assertTrue(self.decide(two, tool)[0])
212
213 def test_rdna2_only_pc_is_unchanged(self):
214 self.assertFalse(self.decide(real_format(("AMD Radeon RX 6700", 64, ALL)), self.RX6700)[0])
215
216 def test_explicit_on_is_taken_as_given(self):
217 self.assertTrue(self.decide(real_format(("AMD Radeon RX 6700", 64, ALL)), self.RX6700, mode="on")[0])
218
219
166class KeepEmulatedFlagTest(unittest.TestCase): 220class KeepEmulatedFlagTest(unittest.TestCase):
167 """Only the default auto may keep emulated shaders; an explicit on or off is taken as given.""" 221 """Only the default auto may keep emulated shaders; an explicit on or off is taken as given."""
168 222
diff --git a/tests/test_manifest.py b/tests/test_manifest.py
index ae335871a..52afc1cbc 100644
--- a/tests/test_manifest.py
+++ b/tests/test_manifest.py
@@ -401,9 +401,9 @@ class ManifestAtomicCreateTest(unittest.TestCase):
401 f.write(b"atomic create payload") 401 f.write(b"atomic create payload")
402 self.out = os.path.join(self.tmp.name, "manifest.json") 402 self.out = os.path.join(self.tmp.name, "manifest.json")
403 403
404 def create(self): 404 def create(self, jobs=1):
405 with contextlib.redirect_stdout(io.StringIO()): 405 with contextlib.redirect_stdout(io.StringIO()):
406 return manifest.create(self.pkg, self.out, jobs=1) 406 return manifest.create(self.pkg, self.out, jobs=jobs)
407 407
408 def test_create_preserves_an_existing_partial_sibling(self): 408 def test_create_preserves_an_existing_partial_sibling(self):
409 sibling = self.out + ".partial" 409 sibling = self.out + ".partial"
@@ -452,6 +452,55 @@ class ManifestAtomicCreateTest(unittest.TestCase):
452 self.assertEqual(self.create(), 0) 452 self.assertEqual(self.create(), 0)
453 self.assertEqual(sorted(manifest.load_manifest(self.out)), ["added.dat", "sample.dat"]) 453 self.assertEqual(sorted(manifest.load_manifest(self.out)), ["added.dat", "sample.dat"])
454 454
455 def test_size_change_before_open_keeps_the_previous_manifest(self):
456 self.assertEqual(self.create(), 0)
457 with open(self.out, "rb") as f:
458 previous = f.read()
459 source = os.path.join(self.pkg, "sample.dat")
460
461 def open_after_growth(path, mode, **kwargs):
462 if path == source and mode == "rb":
463 with open(source, "ab") as f:
464 f.write(b"more bytes")
465 return open(path, mode, **kwargs)
466
467 for jobs in (1, 2):
468 with self.subTest(jobs=jobs):
469 with patch.object(manifest, "open", side_effect=open_after_growth, create=True):
470 with self.assertRaisesRegex(manifest.ManifestError, r"sample\.dat.*changed"):
471 self.create(jobs=jobs)
472 with open(self.out, "rb") as f:
473 self.assertEqual(f.read(), previous)
474
475 def test_same_size_change_during_read_keeps_the_previous_manifest(self):
476 self.assertEqual(self.create(), 0)
477 with open(self.out, "rb") as f:
478 previous = f.read()
479 source = os.path.join(self.pkg, "sample.dat")
480
481 def open_with_edit(path, mode, **kwargs):
482 stream = open(path, mode, **kwargs)
483 if path == source and mode == "rb":
484 original_read = stream.read
485
486 def read_then_edit(size):
487 chunk = original_read(size)
488 stream.read = original_read
489 stamp = os.stat(source)
490 with open(source, "r+b") as f:
491 f.write(b"X")
492 os.utime(source, ns=(stamp.st_atime_ns, stamp.st_mtime_ns + 2_000_000_000))
493 return chunk
494
495 stream.read = read_then_edit
496 return stream
497
498 with patch.object(manifest, "open", side_effect=open_with_edit, create=True):
499 with self.assertRaisesRegex(manifest.ManifestError, r"sample\.dat.*changed"):
500 self.create()
501 with open(self.out, "rb") as f:
502 self.assertEqual(f.read(), previous)
503
455 504
456class ManifestBelowNormalTest(unittest.TestCase): 505class ManifestBelowNormalTest(unittest.TestCase):
457 def test_below_normal_callable(self): 506 def test_below_normal_callable(self):
diff --git a/tests/test_navmesh_index.py b/tests/test_navmesh_index.py
index a420adc90..ef720db70 100644
--- a/tests/test_navmesh_index.py
+++ b/tests/test_navmesh_index.py
@@ -217,6 +217,41 @@ class NavmeshIndexTest(unittest.TestCase):
217 with open(carved, "rb") as f: 217 with open(carved, "rb") as f:
218 self.assertEqual(f.read(), page(pages=4), f"{flag} touched the input") 218 self.assertEqual(f.read(), page(pages=4), f"{flag} touched the input")
219 219
220 def test_report_path_linked_to_a_scanned_file_is_scanned_input(self):
221 # Before: a report path the pattern doesn't match was let through even when it is the same file as one the
222 # scan reads. A hard link does that on any filesystem, and so does PAGE.BIN for page.bin on a
223 # case-insensitive macOS or Linux volume, where fnmatch doesn't fold case: the report truncated the input.
224 folder = os.path.join(self.root, "carve")
225 os.makedirs(folder)
226 carved = os.path.join(folder, "page.bin")
227 with open(carved, "wb") as f:
228 f.write(page(pages=4))
229 linked = os.path.join(folder, "report.json")
230 try:
231 os.link(carved, linked)
232 except (OSError, NotImplementedError) as e:
233 self.skipTest(f"no hard links here: {e}")
234 module = load_tool_module()
235 self.assertTrue(module.is_scanned_input(linked, folder, None))
236 for flag in ("--out", "--csv"):
237 r = subprocess.run([sys.executable, "-I", TOOL, folder, flag, linked],
238 cwd=ROOT, capture_output=True, text=True, check=False)
239 self.assertEqual(r.returncode, 2, r.stderr)
240 self.assertIn("would overwrite the input", r.stderr)
241 with open(carved, "rb") as f:
242 self.assertEqual(f.read(), page(pages=4), f"{flag} touched the input")
243
244 def test_unscanned_file_in_input_folder_is_not_scanned_input(self):
245 folder = os.path.join(self.root, "carve")
246 os.makedirs(folder)
247 with open(os.path.join(folder, "page.bin"), "wb") as f:
248 f.write(page(pages=4))
249 report = os.path.join(folder, "report.json")
250 with open(report, "wb") as f:
251 f.write(b"previous report")
252 module = load_tool_module()
253 self.assertFalse(module.is_scanned_input(report, folder, None))
254
220 def test_sibling_folder_with_shared_prefix_is_not_scanned_input(self): 255 def test_sibling_folder_with_shared_prefix_is_not_scanned_input(self):
221 folder = os.path.join(self.root, "carve") 256 folder = os.path.join(self.root, "carve")
222 sibling = os.path.join(self.root, "carve2") 257 sibling = os.path.join(self.root, "carve2")
diff --git a/tests/test_opus_tags.py b/tests/test_opus_tags.py
index 13c9720c9..3eb8215eb 100644
--- a/tests/test_opus_tags.py
+++ b/tests/test_opus_tags.py
@@ -139,6 +139,17 @@ class TestFolder(unittest.TestCase):
139 self.assertEqual(self.tags("story", "bank_02", "1FFFFFFF.ogg"), ["TITLE=door_slam_03"]) 139 self.assertEqual(self.tags("story", "bank_02", "1FFFFFFF.ogg"), ["TITLE=door_slam_03"])
140 self.assertEqual(self.tags("story", "bank_01", "00000123.ogg"), []) 140 self.assertEqual(self.tags("story", "bank_01", "00000123.ogg"), [])
141 141
142 def test_duplicate_id_stream_gets_the_same_tags(self):
143 # awc_opus.py names a bank's second stream with an id already used <id>~2 (export_stems); it has the same
144 # id, so it is the same name and dialogue line.
145 stem = awc_opus.export_stems([0x0ABCDEF1, 0x0ABCDEF1])[1]
146 make_ogg(os.path.join(self.opus, "story", "bank_01", stem + ".ogg"))
147 dialogue, langs = T.load_dialogue(self.dialogue)
148 stats = T.tag_folder(self.opus, T.load_names(self.names, "story"), dialogue, langs)
149 self.assertEqual((stats["ogg files"], stats["tagged"], stats["without a name"]), (4, 3, 1))
150 self.assertEqual(self.tags("story", "bank_01", stem + ".ogg"), self.tags("story", "bank_01", "0ABCDEF1.ogg"))
151 self.assertIn("TITLE=heistau_abcd_01", self.tags("story", "bank_01", stem + ".ogg"))
152
142 def test_second_run_replaces_its_own_tags(self): 153 def test_second_run_replaces_its_own_tags(self):
143 names = T.load_names(self.names, "story") 154 names = T.load_names(self.names, "story")
144 T.tag_folder(self.opus, names) 155 T.tag_folder(self.opus, names)
diff --git a/tests/test_pe_inspect.py b/tests/test_pe_inspect.py
index f4dd76356..0534be001 100644
--- a/tests/test_pe_inspect.py
+++ b/tests/test_pe_inspect.py
@@ -636,5 +636,33 @@ class TruncatedImageTest(unittest.TestCase):
636 self.assertLessEqual(len(exports), pe_inspect.MAX_ENTRIES + 2) 636 self.assertLessEqual(len(exports), pe_inspect.MAX_ENTRIES + 2)
637 637
638 638
639class DeclaredOptionalHeaderSizeTest(unittest.TestCase):
640 """Reject optional headers smaller than the fields the parser reads."""
641
642 def test_declared_optional_header_too_small(self):
643 for is64 in (False, True):
644 for declared_size in (0, 2, 71):
645 with self.subTest(is64=is64, declared_size=declared_size):
646 data = bytearray(build_image(is64=is64))
647 pe_offset = struct.unpack_from("<I", data, 0x3C)[0]
648 struct.pack_into("<H", data, pe_offset + 20, declared_size)
649
650 with self.assertRaisesRegex(
651 pe_inspect.PeFormatError, "truncated optional header"
652 ):
653 pe_inspect.PeImage(bytes(data))
654
655 def test_declared_optional_header_extends_beyond_file(self):
656 for is64 in (False, True):
657 with self.subTest(is64=is64):
658 data = bytearray(build_image(is64=is64))
659 pe_offset = struct.unpack_from("<I", data, 0x3C)[0]
660 struct.pack_into("<H", data, pe_offset + 20, 0xFFFF)
661
662 with self.assertRaisesRegex(
663 pe_inspect.PeFormatError, "truncated optional header"
664 ):
665 pe_inspect.PeImage(bytes(data))
666
639if __name__ == "__main__": 667if __name__ == "__main__":
640 unittest.main() 668 unittest.main()
diff --git a/tests/test_rdna2spirv_cli.py b/tests/test_rdna2spirv_cli.py
index 64dfca3bb..353f79cdb 100644
--- a/tests/test_rdna2spirv_cli.py
+++ b/tests/test_rdna2spirv_cli.py
@@ -215,6 +215,34 @@ class ValidatedOutput(unittest.TestCase):
215 self.assertEqual(json.loads(self.index.read_text(encoding="utf-8")), previous) 215 self.assertEqual(json.loads(self.index.read_text(encoding="utf-8")), previous)
216 self.assertEqual(other.read_bytes(), b"unrelated module") 216 self.assertEqual(other.read_bytes(), b"unrelated module")
217 217
218 def test_unsupported_clears_retried_shader_but_preserves_unrelated_output(self):
219 # s_barrier is compute-only, so this PS is Unsupported before any SPIR-V tool runs. A module an
220 # earlier run published for it must not survive: the index is make_game.py's proof of completion.
221 self.src.write_text("\ts_barrier\n\ts_endpgm\n", encoding="utf-8")
222 other = self.out / "cs_other.spv"
223 other.write_bytes(b"unrelated module")
224 previous = {"cs_other": {"stage": "cs"}}
225 self.module.write_bytes(b"old module")
226 self.index.write_text(json.dumps({**previous, "ps_fixture": {"stage": "ps"}}), encoding="utf-8")
227 output = self.translate()
228 self.assertIn("s_barrier outside compute", output)
229 self.assertFalse(self.module.exists())
230 self.assertEqual(json.loads(self.index.read_text(encoding="utf-8")), previous)
231 self.assertEqual(other.read_bytes(), b"unrelated module")
232 self.assertEqual(list(self.out.glob("*.tmp")), [])
233
234 def test_translator_error_clears_retried_shader(self):
235 self.module.write_bytes(b"old module")
236 self.index.write_text(json.dumps({"ps_fixture": {"stage": "ps"}}), encoding="utf-8")
237 output = io.StringIO()
238 with mock.patch.object(rdna2spirv, "translate", side_effect=ValueError("synthetic translator error")), \
239 mock.patch.object(sys, "argv", [TOOL, str(self.src), "--out", str(self.out)]), \
240 redirect_stdout(output):
241 rdna2spirv.main()
242 self.assertIn("translator error ValueError", output.getvalue())
243 self.assertFalse(self.module.exists())
244 self.assertEqual(json.loads(self.index.read_text(encoding="utf-8")), {})
245
218 def test_validation_success_publishes_binary_and_metadata(self): 246 def test_validation_success_publishes_binary_and_metadata(self):
219 self.assertIn("1 pass spirv-val", self.translate()) 247 self.assertIn("1 pass spirv-val", self.translate())
220 self.assertEqual(self.module.read_bytes(), b"new module") 248 self.assertEqual(self.module.read_bytes(), b"new module")
@@ -223,3 +251,26 @@ class ValidatedOutput(unittest.TestCase):
223 251
224if __name__ == "__main__": 252if __name__ == "__main__":
225 unittest.main() 253 unittest.main()
254
255
256class EmptyShader(unittest.TestCase):
257 """A .s with no tab-indented instruction parses to an empty shader.
258
259 It used to translate to a module that passes spirv-val, lands in index.json and does no work at all, which is
260 what a hand-written or re-indented .s looks like: found while writing a fixture with spaces instead of tabs.
261 """
262
263 def test_no_instructions_is_reported_and_no_module_is_published(self):
264 with tempfile.TemporaryDirectory() as tmp:
265 src = os.path.join(tmp, "disasm")
266 os.mkdir(src)
267 with open(os.path.join(src, "ps_empty.s"), "w", encoding="utf-8") as f:
268 f.write("; ps_empty code 0x0..0x0 (synthetic), gfx1013, 0 invalid words\n s_endpgm\n")
269 with open(os.path.join(tmp, "ps_empty.dxbc"), "wb") as f:
270 f.write(b"DXBC" + bytes(28))
271 out = os.path.join(tmp, "spirv")
272 p = subprocess.run([sys.executable, "-I", TOOL, src, "--out", out], capture_output=True, text=True)
273 self.assertEqual(p.returncode, 0, p.stderr)
274 self.assertIn("0 translated", p.stdout, p.stdout)
275 self.assertIn("no instructions (nothing tab-indented?)", p.stdout, p.stdout)
276 self.assertFalse(os.path.exists(os.path.join(out, "ps_empty.spv")))
diff --git a/tests/test_run_gpu_tests.py b/tests/test_run_gpu_tests.py
index 69a9fafba..b431ced6a 100644
--- a/tests/test_run_gpu_tests.py
+++ b/tests/test_run_gpu_tests.py
@@ -303,5 +303,49 @@ class Wave32LaneDumps(unittest.TestCase):
303 self.assertIsNone(rgt.narrow_subgroup_skip(out)) 303 self.assertIsNone(rgt.narrow_subgroup_skip(out))
304 304
305 305
306class ComputedIJWithoutPerVertexInputs(unittest.TestCase):
307 """ps_ij_computed (SHADER-177): without PerVertexKHR inputs (--bary-fallback, --f16-interp-fallback, the latter on
308 by default on MoltenVK) the translator refuses the computed I/J pair, so there is no .spv. Both runners SKIP it
309 there, before their missing-.spv check; a missing .spv without a fallback stays a translation failure."""
310 NAME = "ps_ij_computed"
311
312 def run_suite(self, bary, f16):
313 with tempfile.TemporaryDirectory() as tmp:
314 args = SimpleNamespace(filter=self.NAME, build=tmp, llvm_mc="unused")
315 env = {"LEONIDA_BARY_FALLBACK": "1" if bary else "0", "LEONIDA_F16_INTERP_FALLBACK": "1" if f16 else "0"}
316 out = io.StringIO()
317 with (patch.dict(rgt.os.environ, env),
318 patch.object(rgt, "assemble_to_s", side_effect=lambda _mc, _src, dst, _name: Path(dst).touch()),
319 patch.object(rgt, "spirv_as"),
320 patch.object(rgt, "run_cmd", return_value=(0, "1 shaders: 0 translated, 0 pass spirv-val")), # refused
321 contextlib.redirect_stdout(out), contextlib.redirect_stderr(out)):
322 rc = rgt.run_suite(args, tmp)
323 return rc, out.getvalue()
324
325 def test_run_gpu_tests_skips_under_either_fallback(self):
326 for bary, f16 in ((True, False), (False, True)):
327 with self.subTest(bary=bary, f16=f16):
328 rc, out = self.run_suite(bary, f16)
329 self.assertIn("SKIP (computed I/J pairs need PerVertexKHR inputs", out)
330 self.assertIn("0/1 passed, 1 skipped", out)
331 self.assertNotIn("missing .spv", out)
332 self.assertEqual(rc, 0, out)
333
334 def test_run_gpu_tests_missing_spv_without_fallback_still_fails(self):
335 rc, out = self.run_suite(False, False)
336 self.assertIn("missing .spv (translation failed)", out)
337 self.assertEqual(rc, 1, out)
338
339 def test_check_py_skips_before_its_spv_check(self):
340 import check
341 with tempfile.TemporaryDirectory() as tmp:
342 for bary, f16 in ((True, False), (False, True)):
343 with self.subTest(bary=bary, f16=f16), \
344 patch.object(check, "BARY_FALLBACK", bary), patch.object(check, "F16_HALVES", f16):
345 self.assertIsInstance(check.pixel_test("unused", tmp, self.NAME), check.Skip)
346 with patch.object(check, "BARY_FALLBACK", False), patch.object(check, "F16_HALVES", False):
347 self.assertEqual(check.pixel_test("unused", tmp, self.NAME), f"missing {self.NAME}.spv")
348
349
306if __name__ == "__main__": 350if __name__ == "__main__":
307 unittest.main() 351 unittest.main()
diff --git a/tests/test_run_wine_tests.py b/tests/test_run_wine_tests.py
index 165eb25b3..c37f525f4 100644
--- a/tests/test_run_wine_tests.py
+++ b/tests/test_run_wine_tests.py
@@ -211,6 +211,70 @@ class RunTestTest(unittest.TestCase):
211 os.path.normcase(os.path.realpath(self.artifact / "sub"))) 211 os.path.normcase(os.path.realpath(self.artifact / "sub")))
212 212
213 213
214@unittest.skipIf(os.name == "nt", "the runner and its dosdevices links are for Linux and macOS")
215class DriveMapTest(unittest.TestCase):
216 def setUp(self):
217 self._tmp = tempfile.TemporaryDirectory()
218 base = Path(self._tmp.name)
219 self.root = base / "checkout"
220 (self.root / "runtime" / "build" / "generated").mkdir(parents=True)
221 (self.root / "runtime" / "build" / "generated" / "cs.spv").write_text("spirv", encoding="utf-8")
222 self.prefix = base / "prefix"
223 (self.prefix / "dosdevices").mkdir(parents=True)
224 self.link = self.prefix / "dosdevices" / "d:"
225
226 def tearDown(self):
227 self._tmp.cleanup()
228
229 def test_the_drive_leads_to_the_checkout_and_is_removed_afterwards(self):
230 with rwt.DriveMap("D:/a/Leonida/Leonida", str(self.root), str(self.prefix)) as drive:
231 seen = self.link / "a" / "Leonida" / "Leonida" / "runtime" / "build" / "generated" / "cs.spv"
232 self.assertEqual(seen.read_text(encoding="utf-8"), "spirv")
233 self.assertIn("drive d: maps", drive.note)
234 scratch = drive.scratch
235 self.assertFalse(os.path.lexists(self.link))
236 self.assertFalse(os.path.exists(scratch))
237 self.assertTrue((self.root / "runtime" / "build" / "generated" / "cs.spv").is_file()) # links only
238
239 def test_backslashes_and_a_lower_case_drive_are_accepted(self):
240 with rwt.DriveMap("d:\\work\\leonida\\", str(self.root), str(self.prefix)):
241 self.assertTrue((self.link / "work" / "leonida" / "runtime" / "build").is_dir())
242
243 def test_a_drive_the_prefix_already_has_is_left_alone(self):
244 other = self.prefix / "elsewhere"
245 other.mkdir()
246 os.symlink(other, self.link)
247 with rwt.DriveMap("D:/a/Leonida/Leonida", str(self.root), str(self.prefix)) as drive:
248 self.assertIn("already set", drive.note)
249 self.assertEqual(os.readlink(self.link), str(other))
250
251 def test_no_prefix_or_no_drive_letter_maps_nothing(self):
252 with rwt.DriveMap("D:/a/b", str(self.root), str(self.prefix / "absent")) as drive:
253 self.assertIn("no Wine prefix", drive.note)
254 with rwt.DriveMap("/home/runner/work", str(self.root), str(self.prefix)) as drive:
255 self.assertIn("no drive letter", drive.note)
256 self.assertFalse(os.path.lexists(self.link))
257
258 def test_main_maps_the_drive_while_the_tests_run(self):
259 # The "Wine" here is the Python interpreter, so the program reads the drive through its dosdevices link, which
260 # is where Wine resolves D:/win/root/... too.
261 probe = self.root / "probe.py"
262 target = self.link / "win" / "root" / "runtime" / "build" / "generated" / "cs.spv"
263 probe.write_text(f"import sys\nsys.exit(0 if open({str(target)!r}).read() == 'spirv' else 1)\n", encoding="utf-8")
264 listing = self.root / "ctest.json"
265 listing.write_text(json.dumps({"tests": [ctest_entry("compiled_in_path", [WINDOWS_ROOT + "/probe.py"])]}),
266 encoding="utf-8")
267 argv = ["run_wine_tests.py", "--tests", str(listing), "--windows-root", WINDOWS_ROOT,
268 "--root", str(self.root), "--wine", sys.executable.replace(os.sep, "/")]
269 out = io.StringIO()
270 with mock.patch.dict(os.environ, {"WINEPREFIX": str(self.prefix)}), mock.patch.object(sys, "argv", argv), \
271 contextlib.redirect_stdout(out):
272 code = rwt.main()
273 self.assertEqual(code, 0, out.getvalue())
274 self.assertIn("[PASS] compiled_in_path", out.getvalue())
275 self.assertFalse(os.path.lexists(self.link))
276
277
214class MainTest(unittest.TestCase): 278class MainTest(unittest.TestCase):
215 def setUp(self): 279 def setUp(self):
216 self._tmp = tempfile.TemporaryDirectory() 280 self._tmp = tempfile.TemporaryDirectory()
@@ -219,6 +283,10 @@ class MainTest(unittest.TestCase):
219 self.artifact.mkdir() 283 self.artifact.mkdir()
220 for name, code in (("ok.py", 0), ("bad.py", 1)): 284 for name, code in (("ok.py", 0), ("bad.py", 1)):
221 (self.artifact / name).write_text(f"import sys\nsys.exit({code})\n", encoding="utf-8") 285 (self.artifact / name).write_text(f"import sys\nsys.exit({code})\n", encoding="utf-8")
286 # main() maps the checkout's drive into $WINEPREFIX: keep it away from a real prefix (~/.wine).
287 env = mock.patch.dict(os.environ, {"WINEPREFIX": str(self.root / "no-prefix")})
288 env.start()
289 self.addCleanup(env.stop)
222 290
223 def tearDown(self): 291 def tearDown(self):
224 self._tmp.cleanup() 292 self._tmp.cleanup()
diff --git a/tests/test_shader_checks.py b/tests/test_shader_checks.py
index 0f97716ab..c4bd7c042 100644
--- a/tests/test_shader_checks.py
+++ b/tests/test_shader_checks.py
@@ -29,11 +29,12 @@ WAVE32_WORDS = {n: w for n, w in check.CS_DUMPS if n in check.WAVE32_DUMPS and n
29 29
30# All check.py cases, including the four vk_store_test shaders and the three mesh fixtures, and TEST-184's 30# All check.py cases, including the four vk_store_test shaders and the three mesh fixtures, and TEST-184's
31# vk_store_test "words" fixtures and image_get_lod draws. 31# vk_store_test "words" fixtures and image_get_lod draws.
32TOTAL = (len(check.COMPUTE) + 3 + len(check.CS_DUMPS) + len(check.W64X_DUMPS) + len(check.W64X_PARTIAL) + 4 32TOTAL = (len(check.COMPUTE) + 4 + len(check.CS_DUMPS) + len(check.W64X_DUMPS) + len(check.W64X_PARTIAL) + 4
33 + len(check.PIXEL_TESTS) + len(check.CLIP_TESTS) + len(check.BOUNDS) + len(check.GLOBAL_OFFSET) 33 + len(check.PIXEL_TESTS) + len(check.CLIP_TESTS) + len(check.BOUNDS) + len(check.GLOBAL_OFFSET)
34 + len(check.MIP_TEST_PASSES) + len(check.GRADIENT_TESTS) 34 + len(check.MIP_TEST_PASSES) + len(check.GRADIENT_TESTS)
35 + len(check.STORE_WORDS) + len(check.GET_LOD_TESTS) 35 + len(check.STORE_WORDS) + len(check.GET_LOD_TESTS)
36 + len(check.TEXTURE_CONSTANTS) + 9) # three mesh fixtures, ps_tex, four compute fixtures and ps_ssharp 36 + len(check.TEXTURE_CONSTANTS) + 10) # three mesh fixtures, ps_tex, ps_imgatomic, four compute fixtures and
37 # ps_ssharp
37CVT = {bits: [u, s] for bits, u, s in check.CVT_F32_SAT_CASES} 38CVT = {bits: [u, s] for bits, u, s in check.CVT_F32_SAT_CASES}
38 39
39 40
@@ -65,6 +66,10 @@ class Wave64Checks(unittest.TestCase):
65 if fmt[1] is not None: 66 if fmt[1] is not None:
66 dump.write_bytes(fmt[1]) 67 dump.write_bytes(fmt[1])
67 return fmt[0], "out[0..7] = 0 0 0 0 0 0 0 0\n" # stdout is not the oracle 68 return fmt[0], "out[0..7] = 0 0 0 0 0 0 0 0\n" # stdout is not the oracle
69 if name == "cs_fmt_sint32":
70 self.assertEqual((args, env["VKC_OUT_WORDS"]), (("1", "dump"), "64"))
71 Path(env["VKC_DUMP"]).write_bytes(struct.pack("<64I", *check.FMT_SINT32_WORDS))
72 return 0, ""
68 if name == "cs_fmt_xy_xyz": 73 if name == "cs_fmt_xy_xyz":
69 self.assertEqual((args, env["VKC_OUT_WORDS"]), (("1", "dump"), "192")) 74 self.assertEqual((args, env["VKC_OUT_WORDS"]), (("1", "dump"), "192"))
70 Path(env["VKC_DUMP"]).write_bytes(GOOD_XY_XYZ) 75 Path(env["VKC_DUMP"]).write_bytes(GOOD_XY_XYZ)
@@ -322,6 +327,24 @@ class PixelDeviceLimits(unittest.TestCase):
322 self.assertIsInstance(problem, check.Skip) 327 self.assertIsInstance(problem, check.Skip)
323 self.assertIn("no subgroup width", problem) 328 self.assertIn("no subgroup width", problem)
324 329
330 @staticmethod
331 def readlane_pixels(words=(0x40000079, 0x40000010, 0x40000064, 0x400000be)):
332 return struct.pack("<4I", *words) * (64 * 64)
333
334 def test_wave64_pixel_shader_skips_where_64_cannot_be_required(self):
335 out = "device: fake (subgroup 8..8)\nok 64x64\n"
336 problem = self.run_pixel("ps_w64x_readlane", 0, out, data=self.readlane_pixels((0, 0, 0, 0)))
337 self.assertIsInstance(problem, check.Skip)
338 self.assertIn("64-wide fragment subgroup", problem)
339 self.assertIn("8..8", problem)
340
341 def test_wave64_pixel_shader_is_judged_when_64_was_required(self):
342 out = "device: fake (subgroup 32..64)\nfragment subgroup size: 64 required\nok 64x64\n"
343 self.assertEqual(self.run_pixel("ps_w64x_readlane", 0, out, data=self.readlane_pixels()), "")
344 problem = self.run_pixel("ps_w64x_readlane", 0, out, data=self.readlane_pixels((0, 0, 0, 0)))
345 self.assertNotIsInstance(problem, check.Skip)
346 self.assertIn("pixels differ", problem)
347
325 def test_bitmask_perm_skips_when_variable_device_runs_narrow_fragment_subgroup(self): 348 def test_bitmask_perm_skips_when_variable_device_runs_narrow_fragment_subgroup(self):
326 out = "device: Intel(R) HD Graphics 530 (subgroup 8..32)\nok 64x64\n" 349 out = "device: Intel(R) HD Graphics 530 (subgroup 8..32)\nok 64x64\n"
327 for width in (8, 16): 350 for width in (8, 16):
diff --git a/tests/test_shader_link_check.py b/tests/test_shader_link_check.py
new file mode 100644
index 000000000..cbaf7a39f
--- /dev/null
+++ b/tests/test_shader_link_check.py
@@ -0,0 +1,459 @@
1"""Shader-stage matching with hand-written modules and a synthetic pipeline manifest."""
2import contextlib
3import io
4import json
5from pathlib import Path
6import struct
7import subprocess
8import sys
9import tempfile
10import unittest
11from unittest.mock import patch
12
13ROOT = Path(__file__).resolve().parents[1]
14sys.path.insert(0, str(ROOT / "tools"))
15import shader_link_check as link # noqa: E402
16import spirv_interface as spv # noqa: E402
17import spirv_stubs # noqa: E402
18
19
20class ModuleFixture:
21 """Binary interface declarations. Drivers are exercised by separate GLSL fixtures."""
22
23 MODELS = {"vs": 0, "gs": 3, "ms": 5365, "ps": 4, "cs": 5}
24
25 def __init__(self, stage, start_id=1):
26 self.stage = stage
27 self.next_id = start_id
28 self.code = []
29 self.entries = []
30 self.ids = []
31 self.uint = self.emit_type(spv.OP_TYPE_INT, 32, 0)
32
33 def allocate(self):
34 self.next_id += 1
35 return self.next_id - 1
36
37 def emit(self, opcode, *args):
38 self.code.extend([((len(args) + 1) << 16) | opcode, *args])
39
40 def emit_type(self, opcode, *args):
41 result = self.allocate()
42 self.emit(opcode, result, *args)
43 return result
44
45 def literal(self, value):
46 result = self.allocate()
47 self.emit(spv.OP_CONSTANT, self.uint, result, value)
48 return result
49
50 def numeric(self, width=32, components=1, kind="f"):
51 if kind == "f":
52 element = self.emit_type(spv.OP_TYPE_FLOAT, width)
53 else:
54 element = self.emit_type(spv.OP_TYPE_INT, width, int(kind == "i"))
55 return element if components == 1 else self.emit_type(spv.OP_TYPE_VECTOR, element, components)
56
57 def array(self, element, length):
58 return self.emit_type(spv.OP_TYPE_ARRAY, element, self.literal(length))
59
60 def decorate(self, identifier, decoration, *operands):
61 self.emit(spv.OP_DECORATE, identifier, decoration, *operands)
62
63 def member(self, identifier, member, decoration, *operands):
64 self.emit(spv.OP_MEMBER_DECORATE, identifier, member, decoration, *operands)
65
66 def variable(self, storage, shape, location=None, component=None, index=None, *flags):
67 pointer = self.emit_type(spv.OP_TYPE_POINTER, storage, shape)
68 identifier = self.allocate()
69 self.emit(spv.OP_VARIABLE, pointer, identifier, storage)
70 self.ids.append(identifier)
71 for decoration, value in ((spv.DEC_LOCATION, location), (spv.DEC_COMPONENT, component),
72 (spv.DEC_INDEX, index)):
73 if value is not None:
74 self.decorate(identifier, decoration, value)
75 for decoration in flags:
76 self.decorate(identifier, decoration)
77 return identifier
78
79 def entry(self, name, ids, stage=None):
80 raw = name.encode("utf-8") + b"\x00"
81 raw += bytes(-len(raw) % 4)
82 string = struct.unpack(f"<{len(raw) // 4}I", raw)
83 function = self.allocate()
84 args = (self.MODELS[stage or self.stage], function, *string, *ids)
85 self.entries.extend([((len(args) + 1) << 16) | spv.OP_ENTRY_POINT, *args])
86
87 def binary(self, big_endian=False):
88 if not self.entries:
89 self.entry("main", self.ids)
90 words = [spv.SPIRV_MAGIC, 0x00010500, 0, self.next_id, 0, *self.entries, *self.code]
91 endian = ">" if big_endian else "<"
92 return struct.pack(f"{endian}{len(words)}I", *words)
93
94 def reflect(self, entry="main", **kwargs):
95 return spv.reflect_module(self.binary(), entry=entry, **kwargs)
96
97
98def simple(stage, storage, location, component=None, width=32, components=4, kind="f", array_count=None):
99 shader = ModuleFixture(stage, start_id=5 if storage == spv.STORAGE_INPUT else 1)
100 shape = shader.numeric(width, components, kind)
101 if array_count is not None:
102 shape = shader.array(shape, array_count)
103 shader.variable(storage, shape, location, component)
104 return shader
105
106
107def output(location=0, **kwargs):
108 return simple("vs", spv.STORAGE_OUTPUT, location, **kwargs)
109
110
111def input(location=0, **kwargs):
112 return simple("ps", spv.STORAGE_INPUT, location, **kwargs)
113
114
115def kinds(producer, consumer, **kwargs):
116 return [item.kind for item in link.compare_stages(producer.reflect(), consumer.reflect(), **kwargs)]
117
118
119class ReflectTest(unittest.TestCase):
120 def test_reads_other_byte_order(self):
121 shader = output()
122 self.assertEqual(spv.reflect_module(shader.binary(big_endian=True)), shader.reflect())
123
124 def test_skips_correctly_decorated_builtins(self):
125 shader = ModuleFixture("vs")
126 position = shader.variable(spv.STORAGE_OUTPUT, shader.numeric(32, 4))
127 shader.decorate(position, spv.DEC_BUILTIN, 0)
128 self.assertEqual(shader.reflect().outputs, ())
129
130 def test_skips_builtin_block(self):
131 shader = ModuleFixture("gs")
132 block = shader.emit_type(spv.OP_TYPE_STRUCT, shader.numeric(32, 4))
133 shader.decorate(block, spv.DEC_BLOCK)
134 shader.member(block, 0, spv.DEC_BUILTIN, 0)
135 shader.variable(spv.STORAGE_INPUT, shader.array(block, 3))
136 self.assertEqual(shader.reflect().inputs, ())
137
138 def test_missing_location_is_an_error(self):
139 shader = ModuleFixture("vs")
140 shader.variable(spv.STORAGE_OUTPUT, shader.numeric())
141 with self.assertRaisesRegex(spv.InterfaceError, "missing a Location"):
142 shader.reflect()
143
144 def test_64_bit_vector_spans_locations_and_can_share_remaining_components(self):
145 shader = output(width=64, components=3)
146 shader.variable(spv.STORAGE_OUTPUT, shader.numeric(32, 2), 1, 2)
147 declarations = shader.reflect().outputs
148 self.assertEqual(len(declarations), 2)
149 used = list(declarations[0].varyings[0].occupied())
150 self.assertEqual(used[-1], spv.Address(1, 1))
151
152 def test_rejects_component_overlap(self):
153 shader = output(width=64, components=3)
154 shader.variable(spv.STORAGE_OUTPUT, shader.numeric(), 1, 1)
155 with self.assertRaisesRegex(spv.InterfaceError, "overlap.*location 1, component 1"):
156 shader.reflect()
157
158 def test_keeps_fragment_dual_source_outputs_separate(self):
159 shader = ModuleFixture("ps")
160 shape = shader.numeric(32, 4)
161 shader.variable(spv.STORAGE_OUTPUT, shape, 0, index=0)
162 shader.variable(spv.STORAGE_OUTPUT, shape, 0, index=1)
163 self.assertEqual([d.varyings[0].address.index for d in shader.reflect().outputs], [0, 1])
164
165 def test_rejects_vector_that_spills_32_bits_into_another_location(self):
166 shader = input(component=2, components=3)
167 with self.assertRaisesRegex(spv.InterfaceError, "extends beyond its Location"):
168 shader.reflect()
169
170 def test_rejects_unbounded_expansion(self):
171 shader = output(array_count=spv.MAX_EXPANDED_LOCATIONS + 1)
172 with self.assertRaisesRegex(spv.InterfaceError, "too many interface locations"):
173 shader.reflect()
174
175 def test_uses_selected_entry_interface_ids(self):
176 shader = ModuleFixture("ps")
177 first = shader.variable(spv.STORAGE_INPUT, shader.numeric(), 2)
178 second = shader.variable(spv.STORAGE_INPUT, shader.numeric(), 6)
179 shader.entry("main", [first])
180 shader.entry("other", [second])
181 self.assertEqual(shader.reflect().inputs[0].varyings[0].address.location, 2)
182 self.assertEqual(shader.reflect("other").inputs[0].varyings[0].address.location, 6)
183
184 def test_same_name_in_different_stages_requires_stage_to_select(self):
185 shader = ModuleFixture("vs")
186 shader.entry("main", [])
187 shader.entry("main", [], stage="ps")
188 with self.assertRaisesRegex(spv.InterfaceError, "ambiguous"):
189 shader.reflect()
190 self.assertEqual(shader.reflect(stage="ps").stage, "ps")
191
192 def test_entry_can_reference_resources_other_than_io(self):
193 shader = ModuleFixture("ps")
194 shader.variable(2, shader.numeric()) # Uniform, a different interface.
195 self.assertEqual(shader.reflect().inputs, ())
196
197 def test_grouped_decorations_apply_to_members_and_variables(self):
198 shader = ModuleFixture("vs")
199 struct_type = shader.emit_type(spv.OP_TYPE_STRUCT, shader.numeric(32, 2))
200 shader.decorate(struct_type, spv.DEC_BLOCK)
201 block = shader.variable(spv.STORAGE_OUTPUT, struct_type)
202 scalar = shader.variable(spv.STORAGE_OUTPUT, shader.numeric())
203 group = shader.allocate()
204 shader.emit(spv.OP_DECORATION_GROUP, group)
205 shader.decorate(group, spv.DEC_LOCATION, 2)
206 shader.emit(spv.OP_GROUP_MEMBER_DECORATE, group, struct_type, 0)
207 shader.emit(spv.OP_GROUP_DECORATE, group, scalar)
208 component_group = shader.allocate()
209 shader.emit(spv.OP_DECORATION_GROUP, component_group)
210 shader.decorate(component_group, spv.DEC_COMPONENT, 2)
211 shader.emit(spv.OP_GROUP_DECORATE, component_group, scalar)
212 declarations = shader.reflect().outputs
213 self.assertEqual([d.symbol for d in declarations], [block, scalar])
214 self.assertEqual([d.varyings[0].address for d in declarations], [spv.Address(2), spv.Address(2, 2)])
215
216 def test_conflicting_decoration_group_is_rejected(self):
217 shader = output()
218 group = shader.allocate()
219 shader.emit(spv.OP_DECORATION_GROUP, group)
220 shader.decorate(group, spv.DEC_LOCATION, 5)
221 shader.emit(spv.OP_GROUP_DECORATE, group, shader.ids[0])
222 with self.assertRaisesRegex(spv.InterfaceError, "conflicting Location"):
223 shader.reflect()
224
225 def test_malformed_header_instruction_and_references(self):
226 shader = output()
227 with self.assertRaisesRegex(spv.InterfaceError, "complete"):
228 spv.reflect_module(shader.binary() + b"\x00")
229 with self.assertRaisesRegex(spv.InterfaceError, "magic"):
230 spv.reflect_module(b"\x00" * 4 + shader.binary()[4:])
231 with self.assertRaisesRegex(spv.InterfaceError, "instruction length"):
232 spv.reflect_module(shader.binary()[:-4])
233 with self.assertRaisesRegex(spv.InterfaceError, "instruction length"):
234 spv.reflect_module(shader.binary() + bytes(4))
235 missing = ModuleFixture("vs")
236 missing.entry("main", [missing.allocate()])
237 with self.assertRaisesRegex(spv.InterfaceError, "missing variable"):
238 missing.reflect()
239
240 def test_passthrough_geometry_gets_explicit_unsupported_diagnostic(self):
241 shader = simple("gs", spv.STORAGE_INPUT, 0, array_count=3)
242 shader.decorate(shader.ids[0], spv.DEC_PASSTHROUGH_NV)
243 with self.assertRaisesRegex(spv.InterfaceError, "passthrough"):
244 shader.reflect()
245
246
247class LinkingTest(unittest.TestCase):
248 def test_matches_the_projects_generated_partner_modules(self):
249 vertex = spv.reflect_module(spirv_stubs.build_vs_stub([2, 9]), stage="vs")
250 pixel = spv.reflect_module(spirv_stubs.build_ps_stub([9, 2], flat_locations=[2]), stage="ps")
251 self.assertEqual(link.compare_stages(vertex, pixel), [])
252
253 def test_numeric_match_ignores_module_local_ids_and_optional_component_zero(self):
254 self.assertEqual(kinds(output(), input(component=0)), [])
255
256 def test_unconsumed_outputs_are_allowed(self):
257 producer = output()
258 producer.variable(spv.STORAGE_OUTPUT, producer.numeric(), 7)
259 self.assertEqual(kinds(producer, input()), [])
260
261 def test_missing_output_and_conflicting_start_are_distinct(self):
262 self.assertEqual(kinds(output(), input(3)), ["missing-output"])
263 self.assertEqual(kinds(output(), input(component=2, components=2)), ["location-mismatch"])
264
265 def test_float_width_and_integer_sign_are_part_of_type(self):
266 self.assertEqual(kinds(output(components=2, width=16), input(components=2)), ["type-mismatch"])
267 self.assertEqual(kinds(output(components=2, kind="u"), input(components=2, kind="i")), ["type-mismatch"])
268
269 def test_maintenance4_relaxes_only_a_wider_vector_output(self):
270 self.assertEqual(kinds(output(), input(components=2)), ["type-mismatch"])
271 self.assertEqual(kinds(output(), input(components=2), maintenance4=True), [])
272 self.assertEqual(kinds(output(components=2), input(), maintenance4=True), ["type-mismatch"])
273 self.assertEqual(kinds(output(), input(components=1), maintenance4=True), ["type-mismatch"])
274
275 def test_maintenance4_does_not_unwrap_and_relax_aggregate_shapes(self):
276 producer = output(array_count=3)
277 consumer = input(components=2, array_count=3)
278 self.assertEqual(kinds(producer, consumer, maintenance4=True), ["type-mismatch"])
279 self.assertEqual(kinds(output(), simple("gs", spv.STORAGE_INPUT, 0, components=2, array_count=3),
280 maintenance4=True), ["type-mismatch"])
281
282 def test_geometry_input_strips_outer_array_only(self):
283 geometry = ModuleFixture("gs")
284 member = geometry.array(geometry.numeric(32, 4), 2)
285 geometry.variable(spv.STORAGE_INPUT, geometry.array(member, 3), 0)
286 self.assertEqual(kinds(output(array_count=2), geometry), [])
287 self.assertEqual(kinds(output(array_count=3), geometry), ["type-mismatch"])
288
289 def test_fragment_per_vertex_matches_non_array_vertex_output(self):
290 fragment = simple("ps", spv.STORAGE_INPUT, 0, array_count=3)
291 fragment.decorate(fragment.ids[0], spv.DEC_PER_VERTEX)
292 self.assertEqual(kinds(output(), fragment), [])
293 self.assertEqual(kinds(output(array_count=3), fragment), ["type-mismatch"])
294
295 def test_mesh_primitive_output_matches_fragment_domain(self):
296 mesh = simple("ms", spv.STORAGE_OUTPUT, 0, array_count=37)
297 mesh.decorate(mesh.ids[0], spv.DEC_PER_PRIMITIVE)
298 fragment = input()
299 self.assertEqual(kinds(mesh, fragment), ["per-primitive-mismatch"])
300 fragment.decorate(fragment.ids[0], spv.DEC_PER_PRIMITIVE)
301 self.assertEqual(kinds(mesh, fragment), [])
302
303 def test_matching_structure_members_keep_order_and_locations(self):
304 def block(stage, storage, locations):
305 shader = ModuleFixture(stage)
306 shape = shader.emit_type(spv.OP_TYPE_STRUCT, shader.numeric(32, 2), shader.numeric(32, 2))
307 shader.decorate(shape, spv.DEC_BLOCK)
308 for i, location in enumerate(locations):
309 shader.member(shape, i, spv.DEC_LOCATION, location)
310 shader.variable(storage, shape)
311 return shader
312
313 producer = block("vs", spv.STORAGE_OUTPUT, (1, 3))
314 self.assertEqual(kinds(producer, block("ps", spv.STORAGE_INPUT, (1, 3))), [])
315 self.assertEqual(kinds(producer, block("ps", spv.STORAGE_INPUT, (1, 2))), ["location-mismatch"])
316 self.assertEqual(kinds(producer, block("ps", spv.STORAGE_INPUT, (3, 1))), ["location-mismatch"])
317 self.assertEqual(kinds(producer, input(location=1, components=2)), ["structure-mismatch"])
318
319 def test_location_on_structure_allocates_consecutive_members(self):
320 shader = ModuleFixture("vs")
321 wide = shader.numeric(64, 3)
322 shape = shader.emit_type(spv.OP_TYPE_STRUCT, wide, shader.numeric())
323 shader.variable(spv.STORAGE_OUTPUT, shape, 5)
324 declarations = shader.reflect().outputs
325 self.assertEqual([v.address.location for v in declarations[0].varyings], [5, 7])
326
327 def test_matrix_and_array_of_columns_are_distinct_types(self):
328 vertices = ModuleFixture("vs")
329 column = vertices.numeric(32, 2)
330 vertices.variable(spv.STORAGE_OUTPUT, vertices.emit_type(spv.OP_TYPE_MATRIX, column, 3), 0)
331 fragment = ModuleFixture("ps")
332 column = fragment.numeric(32, 2)
333 fragment.variable(spv.STORAGE_INPUT, fragment.emit_type(spv.OP_TYPE_MATRIX, column, 3), 0)
334 self.assertEqual(kinds(vertices, fragment), [])
335 self.assertEqual(kinds(vertices, input(components=2, array_count=3)), ["type-mismatch"])
336
337
338class CommandLineTest(unittest.TestCase):
339 def setUp(self):
340 directory = tempfile.TemporaryDirectory()
341 self.addCleanup(directory.cleanup)
342 self.directory = Path(directory.name)
343 self.vs = self.module("vertex", output())
344 self.ps = self.module("pixel", input())
345 self.bad = self.module("bad_pixel", input(location=8))
346 self.manifest = self.directory / "pairs.json"
347 self.report = self.directory / "report.json"
348
349 def module(self, name, builder):
350 path = self.directory / (name + ".spv")
351 path.write_bytes(builder.binary())
352 return path
353
354 def command(self, *args):
355 return subprocess.run([sys.executable, "-I", ROOT / "tools" / "shader_link_check.py", *args],
356 capture_output=True, text=True, timeout=15)
357
358 def write_manifest(self, *items):
359 self.manifest.write_text(json.dumps({"version": 1, "pipelines": items}), encoding="utf-8")
360
361 def run_batch(self, *extra):
362 return self.command("batch", self.manifest, "--shader-dir", self.directory, *extra)
363
364 def test_direct_match(self):
365 result = self.command("check", "--vs", self.vs, "--ps", self.ps)
366 self.assertEqual(result.returncode, 0, result.stderr)
367 self.assertIn("compatible (1 links checked)", result.stdout)
368
369 def test_incompatible_pipeline_returns_one_and_reports_location(self):
370 result = self.command("check", "--vs", self.vs, "--ps", self.bad)
371 self.assertEqual(result.returncode, 1)
372 self.assertIn("vs -> ps at location 8, component 0 [missing-output]", result.stdout)
373
374 def test_wrong_stage_and_missing_module_return_two(self):
375 result = self.command("check", "--vs", self.ps, "--ps", self.directory / "missing.spv")
376 self.assertEqual(result.returncode, 2)
377 self.assertIn("is ps, expected vs", result.stdout)
378 self.assertIn("[module-error]", result.stdout)
379 self.assertNotIn("Traceback", result.stderr)
380
381 def test_invalid_slot_combination_returns_two(self):
382 result = self.command("check", "--vs", self.vs, "--ms", self.vs, "--ps", self.ps)
383 self.assertEqual(result.returncode, 2)
384 self.assertIn("expected vs+ps", result.stderr)
385
386 def test_batch_checks_other_pipelines_after_an_error_and_reports_all(self):
387 self.write_manifest({"name": "broken", "vs": "vertex", "ps": "missing"},
388 {"name": "bad", "vs": "vertex", "ps": "bad_pixel"},
389 {"name": "valid", "vs": "vertex", "ps": "pixel"})
390 result = self.run_batch("--report", self.report, "--quiet")
391 self.assertEqual(result.returncode, 2, result.stderr)
392 self.assertNotIn("valid: compatible", result.stdout)
393 report = json.loads(self.report.read_bytes())
394 self.assertEqual(report["summary"], {"compatible": 1, "incompatible": 1, "invalid": 1})
395 self.assertEqual([pipeline["name"] for pipeline in report["pipelines"]], ["broken", "bad", "valid"])
396 self.assertEqual(report["pipelines"][1]["problems"][0]["location"]["location"], 8)
397 self.assertNotIn(b"\r\n", self.report.read_bytes())
398
399 def test_three_stage_chain_does_not_compare_across_geometry(self):
400 geometry = simple("gs", spv.STORAGE_INPUT, 0, array_count=3)
401 geometry.variable(spv.STORAGE_OUTPUT, geometry.numeric(32, 4), 8)
402 gs = self.module("geometry", geometry)
403 result = self.command("check", "--vs", self.vs, "--gs", gs, "--ps", self.bad)
404 self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
405 self.assertIn("compatible (2 links checked)", result.stdout)
406
407 def test_alternate_entry_names_are_resolved_per_stage(self):
408 shader = input()
409 shader.entry("ColorMain", shader.ids)
410 self.module("alternative", shader)
411 self.write_manifest({"name": "alt", "vs": "vertex", "ps": {"shader": "alternative", "entry": "ColorMain"}})
412 result = self.run_batch()
413 self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
414
415 def test_bad_manifest_fields_return_clean_error(self):
416 cases = [
417 {"version": True, "pipelines": []},
418 {"pipelines": [{"name": "x", "vs": "../vertex", "ps": "pixel"}]},
419 {"pipelines": [{"name": "x", "vs": "vertex", "ps": "pixel"}] * 2},
420 {"pipelines": [{"name": "x", "vs": "vertex", "ps": {"path": "pixel.spv"}}]},
421 ]
422 for document in cases:
423 with self.subTest(document=document):
424 self.manifest.write_text(json.dumps(document), encoding="utf-8")
425 result = self.run_batch()
426 self.assertEqual(result.returncode, 2)
427 self.assertIn("shader_link_check: error:", result.stderr)
428 self.assertNotIn("Traceback", result.stderr)
429
430 def test_report_preserves_inputs(self):
431 original = self.vs.read_bytes()
432 result = self.command("check", "--vs", self.vs, "--ps", self.ps, "--report", self.vs)
433 self.assertEqual(result.returncode, 2)
434 self.assertEqual(self.vs.read_bytes(), original)
435 self.write_manifest({"name": "x", "vs": "vertex", "ps": "pixel"})
436 result = self.run_batch("--report", self.manifest)
437 self.assertEqual(result.returncode, 2)
438 self.assertTrue(json.loads(self.manifest.read_text())["pipelines"])
439
440 def test_inspect_keeps_types_and_components(self):
441 shader = self.module("with_component", input(location=3, component=2, components=2))
442 result = self.command("inspect", shader)
443 self.assertEqual(result.returncode, 0)
444 self.assertEqual(json.loads(result.stdout)["inputs"][0]["varyings"],
445 [{"location": 3, "component": 2, "index": 0, "type": "vec2<f32>",
446 "per_primitive": False}])
447
448 def test_shader_is_reflected_once_for_repeated_pipelines(self):
449 self.write_manifest(*({"name": f"pair-{i}", "vs": "vertex", "ps": "pixel"} for i in range(20)))
450 output_stream = io.StringIO()
451 with patch.object(link, "reflect_module", wraps=link.reflect_module) as reflect:
452 with contextlib.redirect_stdout(output_stream):
453 result = link.main(["batch", str(self.manifest), "--shader-dir", str(self.directory), "--quiet"])
454 self.assertEqual(result, 0)
455 self.assertEqual(reflect.call_count, 2)
456
457
458if __name__ == "__main__":
459 unittest.main(verbosity=2)
diff --git a/tests/test_spirv_gs_to_compute.py b/tests/test_spirv_gs_to_compute.py
index c551051cb..6439177a9 100644
--- a/tests/test_spirv_gs_to_compute.py
+++ b/tests/test_spirv_gs_to_compute.py
@@ -134,3 +134,11 @@ def test_phi_from_entry_block_names_the_split_block(tmp_path):
134 subprocess.run(["spirv-as", str(sa), "-o", str(sv), "--target-env", "vulkan1.2"], check=True) 134 subprocess.run(["spirv-as", str(sa), "-o", str(sv), "--target-env", "vulkan1.2"], check=True)
135 r = subprocess.run(["spirv-val", "--target-env", "vulkan1.2", str(sv)], capture_output=True, text=True) 135 r = subprocess.run(["spirv-val", "--target-env", "vulkan1.2", str(sv)], capture_output=True, text=True)
136 assert r.returncode == 0, r.stderr 136 assert r.returncode == 0, r.stderr
137
138
139def test_help_is_a_clean_exit_zero(capsys):
140 for flag in ("-h", "--help"):
141 assert gsc.main(["spirv_gs_to_compute.py", flag]) == 0
142 out = capsys.readouterr().out
143 assert "spirv_gs_to_compute.py in.spv out.spv" in out
144 assert "SPIRV-Tools" in out
diff --git a/tests/test_spirv_metal_set0.py b/tests/test_spirv_metal_set0.py
index 93b5286bd..e2ffe24a5 100644
--- a/tests/test_spirv_metal_set0.py
+++ b/tests/test_spirv_metal_set0.py
@@ -56,3 +56,9 @@ def test_rewrite_sizes_arrays_and_spaces_bindings():
56 assert "msl_arr_b2" not in out 56 assert "msl_arr_b2" not in out
57 # each new type comes after the pointer type it replaces, so its operands are already declared 57 # each new type comes after the pointer type it replaces, so its operands are already declared
58 assert out.index("%ptr_img = OpTypePointer") < out.index("%msl_cap_b0") 58 assert out.index("%ptr_img = OpTypePointer") < out.index("%msl_cap_b0")
59
60
61def test_help_is_a_clean_exit_zero(capsys):
62 for flag in ("-h", "--help"):
63 assert m.main(["spirv_metal_set0.py", flag]) == 0
64 assert "Usage: spirv_metal_set0.py" in capsys.readouterr().out
diff --git a/tests/test_spirv_metal_set0_extra.py b/tests/test_spirv_metal_set0_extra.py
new file mode 100644
index 000000000..5b03f429e
--- /dev/null
+++ b/tests/test_spirv_metal_set0_extra.py
@@ -0,0 +1,1043 @@
1"""Expanded stdlib-only unit tests for tools/spirv_metal_set0.py.
2
3Covers bindless capacity parsing from vulkan_bindless.h and custom headers,
4metal_ids() layout math, rewrite() across all 26 bindings, non-set-0 /
5push-constant / non-runtime-array / pre-sized / raw-ID / error branches,
6synthetic SPIR-V binary word header/magic/endianness/bounds handling,
7out-of-place vs in-place CLI execution via mocked spirv-dis/spirv-as,
8--print-layout, invalid argument handling, and __main__ entry guard.
9
10Standard library only; no spirv-dis/spirv-as/spirv-val binary, no GPU,
11and no game data.
12
13 python -I tests/test_spirv_metal_set0_extra.py -v
14"""
15import contextlib
16import io
17import os
18import re
19import runpy
20import struct
21import subprocess
22import sys
23import tempfile
24import unittest
25from unittest import mock
26import warnings
27
28ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
29TOOLS_DIR = os.path.join(ROOT, "tools")
30TOOL_PATH = os.path.join(TOOLS_DIR, "spirv_metal_set0.py")
31if TOOLS_DIR not in sys.path:
32 sys.path.insert(0, TOOLS_DIR)
33
34import spirv_metal_set0 as m # noqa: E402
35
36
37SPIRV_MAGIC = 0x07230203
38SPIRV_VERSION_1_0 = 0x00010000
39SPIRV_VERSION_1_5 = 0x00010500
40
41OP_MEMORY_MODEL = 14
42OP_CAPABILITY = 17
43OP_TYPE_VOID = 19
44OP_TYPE_INT = 21
45OP_TYPE_FLOAT = 22
46OP_TYPE_IMAGE = 25
47OP_TYPE_SAMPLER = 26
48OP_TYPE_ARRAY = 28
49OP_TYPE_RUNTIME_ARRAY = 29
50OP_TYPE_STRUCT = 30
51OP_TYPE_POINTER = 32
52OP_CONSTANT = 43
53OP_VARIABLE = 59
54OP_DECORATE = 71
55
56CAP_SHADER = 1
57CAP_RUNTIME_DESCRIPTOR_ARRAY = 5301
58ADDR_LOGICAL = 0
59MEM_GLSL450 = 1
60
61DEC_BLOCK = 2
62DEC_BINDING = 33
63DEC_DESCRIPTOR_SET = 34
64
65SC_UNIFORM_CONSTANT = 0
66SC_PUSH_CONSTANT = 9
67SC_STORAGE_BUFFER = 12
68
69STORAGE_CLASS_BY_NAME = {
70 "UniformConstant": SC_UNIFORM_CONSTANT,
71 "PushConstant": SC_PUSH_CONSTANT,
72 "StorageBuffer": SC_STORAGE_BUFFER,
73}
74STORAGE_CLASS_BY_CODE = {v: k for k, v in STORAGE_CLASS_BY_NAME.items()}
75
76DIM_BY_CODE = {0: "1D", 1: "2D", 2: "3D"}
77DIM_BY_NAME = {v: k for k, v in DIM_BY_CODE.items()}
78
79FMT_BY_CODE = {0: "Unknown", 33: "R32ui"}
80FMT_BY_NAME = {v: k for k, v in FMT_BY_CODE.items()}
81
82
83def _encode_inst(opcode: int, *operands: int) -> list[int]:
84 """Encode one SPIR-V instruction into 32-bit binary words."""
85 wc = 1 + len(operands)
86 return [(wc << 16) | opcode, *operands]
87
88
89def _pack_spv(
90 inst_words: list[int],
91 *,
92 version: int = SPIRV_VERSION_1_5,
93 generator: int = 0,
94 bound: int | None = None,
95 schema: int = 0,
96 endian: str = "<",
97) -> bytes:
98 """Pack a 5-word SPIR-V header and instruction stream into binary bytes."""
99 if bound is None:
100 max_id = 0
101 pos = 0
102 while pos < len(inst_words):
103 wc = inst_words[pos] >> 16
104 op = inst_words[pos] & 0xFFFF
105 if wc < 1 or pos + wc > len(inst_words):
106 break
107 ops = inst_words[pos + 1 : pos + wc]
108 if op in (OP_TYPE_VOID, OP_TYPE_INT, OP_TYPE_FLOAT, OP_TYPE_IMAGE, OP_TYPE_SAMPLER,
109 OP_TYPE_ARRAY, OP_TYPE_RUNTIME_ARRAY, OP_TYPE_STRUCT, OP_TYPE_POINTER):
110 max_id = max(max_id, ops[0])
111 elif op in (OP_CONSTANT, OP_VARIABLE):
112 max_id = max(max_id, ops[1])
113 elif op == OP_DECORATE:
114 max_id = max(max_id, ops[0])
115 pos += wc
116 bound = max_id + 1
117 words = [SPIRV_MAGIC, version, generator, bound, schema, *inst_words]
118 return struct.pack(f"{endian}{len(words)}I", *words)
119
120
121def _decode_spv(data: bytes) -> tuple[tuple[int, int, int, int, int], list[tuple[int, list[int]]]]:
122 """Validate SPIR-V binary header/endianness/word-bounds and decode instructions."""
123 if len(data) < 20 or len(data) % 4 != 0:
124 raise ValueError(f"invalid SPIR-V byte length: {len(data)}")
125 words = list(struct.unpack(f"<{len(data) // 4}I", data))
126 magic, version, generator, bound, schema = words[:5]
127 if magic == 0x03022307:
128 raise ValueError("wrong endianness (big-endian SPIR-V magic)")
129 if magic != SPIRV_MAGIC:
130 raise ValueError(f"bad SPIR-V magic: {magic:#010x}")
131 if bound < 1:
132 raise ValueError(f"invalid SPIR-V ID bound: {bound}")
133 if schema != 0:
134 raise ValueError(f"unsupported non-zero schema: {schema}")
135 insts = []
136 pos = 5
137 while pos < len(words):
138 wc = words[pos] >> 16
139 op = words[pos] & 0xFFFF
140 if wc < 1 or pos + wc > len(words):
141 raise ValueError(f"truncated or zero-length instruction at word {pos}")
142 insts.append((op, words[pos + 1 : pos + wc]))
143 pos += wc
144 return (magic, version, generator, bound, schema), insts
145
146
147def _synthetic_spv_to_disasm(data: bytes) -> str:
148 """Decode synthetic SPIR-V binary words into spirv-dis-style assembly text."""
149 header, insts = _decode_spv(data)
150 _, version, generator, bound, schema = header
151 major = (version >> 16) & 0xFF
152 minor = (version >> 8) & 0xFF
153 lines = [
154 "; SPIR-V",
155 f"; Version: {major}.{minor}",
156 f"; Generator: {generator}",
157 f"; Bound: {bound}",
158 f"; Schema: {schema}",
159 ]
160 indent = " " * 15
161 def lhs(res_id: int) -> str:
162 return f"%{res_id}".rjust(12)
163
164 for op, ops in insts:
165 if op == OP_CAPABILITY:
166 name = {CAP_SHADER: "Shader", CAP_RUNTIME_DESCRIPTOR_ARRAY: "RuntimeDescriptorArray"}[ops[0]]
167 lines.append(f"{indent}OpCapability {name}")
168 elif op == OP_MEMORY_MODEL:
169 lines.append(f"{indent}OpMemoryModel Logical GLSL450")
170 elif op == OP_DECORATE:
171 if ops[1] == DEC_DESCRIPTOR_SET:
172 lines.append(f"{indent}OpDecorate %{ops[0]} DescriptorSet {ops[2]}")
173 elif ops[1] == DEC_BINDING:
174 lines.append(f"{indent}OpDecorate %{ops[0]} Binding {ops[2]}")
175 elif ops[1] == DEC_BLOCK:
176 lines.append(f"{indent}OpDecorate %{ops[0]} Block")
177 else:
178 raise ValueError(f"unsupported decoration {ops[1]}")
179 elif op == OP_TYPE_VOID:
180 lines.append(f"{lhs(ops[0])} = OpTypeVoid")
181 elif op == OP_TYPE_INT:
182 lines.append(f"{lhs(ops[0])} = OpTypeInt {ops[1]} {ops[2]}")
183 elif op == OP_TYPE_FLOAT:
184 lines.append(f"{lhs(ops[0])} = OpTypeFloat {ops[1]}")
185 elif op == OP_TYPE_IMAGE:
186 dim = DIM_BY_CODE[ops[2]]
187 fmt = FMT_BY_CODE[ops[7]]
188 lines.append(
189 f"{lhs(ops[0])} = OpTypeImage %{ops[1]} {dim} {ops[3]} {ops[4]} {ops[5]} {ops[6]} {fmt}"
190 )
191 elif op == OP_TYPE_SAMPLER:
192 lines.append(f"{lhs(ops[0])} = OpTypeSampler")
193 elif op == OP_TYPE_ARRAY:
194 lines.append(f"{lhs(ops[0])} = OpTypeArray %{ops[1]} %{ops[2]}")
195 elif op == OP_TYPE_RUNTIME_ARRAY:
196 lines.append(f"{lhs(ops[0])} = OpTypeRuntimeArray %{ops[1]}")
197 elif op == OP_TYPE_STRUCT:
198 members = " ".join(f"%{m_id}" for m_id in ops[1:])
199 lines.append(f"{lhs(ops[0])} = OpTypeStruct {members}".rstrip())
200 elif op == OP_TYPE_POINTER:
201 sc = STORAGE_CLASS_BY_CODE[ops[1]]
202 lines.append(f"{lhs(ops[0])} = OpTypePointer {sc} %{ops[2]}")
203 elif op == OP_CONSTANT:
204 lines.append(f"{lhs(ops[1])} = OpConstant %{ops[0]} {ops[2]}")
205 elif op == OP_VARIABLE:
206 sc = STORAGE_CLASS_BY_CODE[ops[2]]
207 lines.append(f"{lhs(ops[1])} = OpVariable %{ops[0]} {sc}")
208 else:
209 raise ValueError(f"unsupported opcode {op}")
210 return "\n".join(lines) + "\n"
211
212
213def _synthetic_disasm_to_spv(text: str, target_env: str) -> bytes:
214 """Assemble synthetic spirv-dis text (including rewritten %msl_* IDs) into SPIR-V words."""
215 id_map: dict[str, int] = {}
216 next_id = 1
217
218 def resolve(tok: str) -> int:
219 nonlocal next_id
220 if tok in id_map:
221 return id_map[tok]
222 if tok[1:].isdigit():
223 val = int(tok[1:])
224 id_map[tok] = val
225 next_id = max(next_id, val + 1)
226 return val
227 val = next_id
228 next_id += 1
229 id_map[tok] = val
230 return val
231
232 # Pre-register numeric IDs so newly synthesized %msl_* names never collide.
233 for tok in re.findall(r"%\S+", text):
234 if tok[1:].isdigit():
235 resolve(tok)
236
237 inst_words: list[int] = []
238 for raw in text.splitlines():
239 line = raw.strip()
240 if not line or line.startswith(";"):
241 continue
242 if line.startswith("OpCapability "):
243 cap = {"Shader": CAP_SHADER, "RuntimeDescriptorArray": CAP_RUNTIME_DESCRIPTOR_ARRAY}[line.split()[1]]
244 inst_words.extend(_encode_inst(OP_CAPABILITY, cap))
245 elif line == "OpMemoryModel Logical GLSL450":
246 inst_words.extend(_encode_inst(OP_MEMORY_MODEL, ADDR_LOGICAL, MEM_GLSL450))
247 elif line.startswith("OpDecorate "):
248 parts = line.split()
249 tid = resolve(parts[1])
250 if parts[2] == "DescriptorSet":
251 inst_words.extend(_encode_inst(OP_DECORATE, tid, DEC_DESCRIPTOR_SET, int(parts[3])))
252 elif parts[2] == "Binding":
253 inst_words.extend(_encode_inst(OP_DECORATE, tid, DEC_BINDING, int(parts[3])))
254 elif parts[2] == "Block":
255 inst_words.extend(_encode_inst(OP_DECORATE, tid, DEC_BLOCK))
256 else:
257 raise ValueError(f"unsupported OpDecorate: {line}")
258 else:
259 lhs, rhs = [p.strip() for p in line.split("=", 1)]
260 rid = resolve(lhs)
261 parts = rhs.split()
262 opname = parts[0]
263 if opname == "OpTypeVoid":
264 inst_words.extend(_encode_inst(OP_TYPE_VOID, rid))
265 elif opname == "OpTypeInt":
266 inst_words.extend(_encode_inst(OP_TYPE_INT, rid, int(parts[1]), int(parts[2])))
267 elif opname == "OpTypeFloat":
268 inst_words.extend(_encode_inst(OP_TYPE_FLOAT, rid, int(parts[1])))
269 elif opname == "OpTypeImage":
270 inst_words.extend(_encode_inst(
271 OP_TYPE_IMAGE,
272 rid,
273 resolve(parts[1]),
274 DIM_BY_NAME[parts[2]],
275 int(parts[3]),
276 int(parts[4]),
277 int(parts[5]),
278 int(parts[6]),
279 FMT_BY_NAME[parts[7]],
280 ))
281 elif opname == "OpTypeSampler":
282 inst_words.extend(_encode_inst(OP_TYPE_SAMPLER, rid))
283 elif opname == "OpTypeArray":
284 inst_words.extend(_encode_inst(OP_TYPE_ARRAY, rid, resolve(parts[1]), resolve(parts[2])))
285 elif opname == "OpTypeRuntimeArray":
286 inst_words.extend(_encode_inst(OP_TYPE_RUNTIME_ARRAY, rid, resolve(parts[1])))
287 elif opname == "OpTypeStruct":
288 inst_words.extend(_encode_inst(OP_TYPE_STRUCT, rid, *[resolve(p) for p in parts[1:]]))
289 elif opname == "OpTypePointer":
290 inst_words.extend(_encode_inst(OP_TYPE_POINTER, rid, STORAGE_CLASS_BY_NAME[parts[1]], resolve(parts[2])))
291 elif opname == "OpConstant":
292 inst_words.extend(_encode_inst(OP_CONSTANT, resolve(parts[1]), rid, int(parts[2])))
293 elif opname == "OpVariable":
294 inst_words.extend(_encode_inst(OP_VARIABLE, resolve(parts[1]), rid, STORAGE_CLASS_BY_NAME[parts[2]]))
295 else:
296 raise ValueError(f"unsupported op: {line}")
297
298 ver = SPIRV_VERSION_1_5 if target_env == "spv1.5" else SPIRV_VERSION_1_0
299 return _pack_spv(inst_words, version=ver, bound=next_id)
300
301
302def _build_mixed_bindless_spv_words() -> list[int]:
303 """Build synthetic SPIR-V instruction words with set-0, set-1, and PushConstant resources."""
304 # IDs:
305 # 1=uint, 2=float, 3=img2d, 4=smp, 5=rt_img, 6=rt_smp, 7=ptr_img, 8=ptr_smp
306 # 9=rt_map, 10=struct_map, 11=ptr_map, 12=ptr_pc_u32
307 # 13=images (set 0, b0), 14=samplers (set 0, b1), 15=desc_map (set 0, b2)
308 # 16=push_consts, 17=set1_var (set 1, b0)
309 words: list[int] = []
310 words.extend(_encode_inst(OP_CAPABILITY, CAP_SHADER))
311 words.extend(_encode_inst(OP_CAPABILITY, CAP_RUNTIME_DESCRIPTOR_ARRAY))
312 words.extend(_encode_inst(OP_MEMORY_MODEL, ADDR_LOGICAL, MEM_GLSL450))
313 words.extend(_encode_inst(OP_DECORATE, 13, DEC_DESCRIPTOR_SET, 0))
314 words.extend(_encode_inst(OP_DECORATE, 13, DEC_BINDING, 0))
315 words.extend(_encode_inst(OP_DECORATE, 14, DEC_DESCRIPTOR_SET, 0))
316 words.extend(_encode_inst(OP_DECORATE, 14, DEC_BINDING, 1))
317 words.extend(_encode_inst(OP_DECORATE, 15, DEC_DESCRIPTOR_SET, 0))
318 words.extend(_encode_inst(OP_DECORATE, 15, DEC_BINDING, 2))
319 words.extend(_encode_inst(OP_DECORATE, 10, DEC_BLOCK))
320 words.extend(_encode_inst(OP_DECORATE, 17, DEC_DESCRIPTOR_SET, 1))
321 words.extend(_encode_inst(OP_DECORATE, 17, DEC_BINDING, 0))
322 words.extend(_encode_inst(OP_TYPE_INT, 1, 32, 0))
323 words.extend(_encode_inst(OP_TYPE_FLOAT, 2, 32))
324 words.extend(_encode_inst(OP_TYPE_IMAGE, 3, 2, 1, 0, 0, 0, 1, 0))
325 words.extend(_encode_inst(OP_TYPE_SAMPLER, 4))
326 words.extend(_encode_inst(OP_TYPE_RUNTIME_ARRAY, 5, 3))
327 words.extend(_encode_inst(OP_TYPE_RUNTIME_ARRAY, 6, 4))
328 words.extend(_encode_inst(OP_TYPE_POINTER, 7, SC_UNIFORM_CONSTANT, 5))
329 words.extend(_encode_inst(OP_TYPE_POINTER, 8, SC_UNIFORM_CONSTANT, 6))
330 words.extend(_encode_inst(OP_TYPE_RUNTIME_ARRAY, 9, 1))
331 words.extend(_encode_inst(OP_TYPE_STRUCT, 10, 9))
332 words.extend(_encode_inst(OP_TYPE_POINTER, 11, SC_STORAGE_BUFFER, 10))
333 words.extend(_encode_inst(OP_TYPE_POINTER, 12, SC_PUSH_CONSTANT, 1))
334 words.extend(_encode_inst(OP_VARIABLE, 7, 13, SC_UNIFORM_CONSTANT))
335 words.extend(_encode_inst(OP_VARIABLE, 8, 14, SC_UNIFORM_CONSTANT))
336 words.extend(_encode_inst(OP_VARIABLE, 11, 15, SC_STORAGE_BUFFER))
337 words.extend(_encode_inst(OP_VARIABLE, 12, 16, SC_PUSH_CONSTANT))
338 words.extend(_encode_inst(OP_VARIABLE, 7, 17, SC_UNIFORM_CONSTANT))
339 return words
340
341
342def _make_fake_spirv_tools(dis_name="spirv-dis", asm_name="spirv-as"):
343 """Return a subprocess.run replacement backed by the synthetic SPIR-V binary codec."""
344 calls: list[list[str]] = []
345
346 def fake_run(cmd, check=False, capture_output=False, text=False, input=None):
347 calls.append(list(cmd))
348 exe = cmd[0]
349 if exe == dis_name:
350 in_path = cmd[1]
351 try:
352 with open(in_path, "rb") as f:
353 data = f.read()
354 disasm = _synthetic_spv_to_disasm(data)
355 except (OSError, ValueError) as exc:
356 if check:
357 raise subprocess.CalledProcessError(1, cmd, output="", stderr=str(exc)) from exc
358 return subprocess.CompletedProcess(cmd, 1, "", str(exc))
359 return subprocess.CompletedProcess(cmd, 0, disasm, "")
360 if exe == asm_name:
361 # Expect: [asm, "--target-env", target, "-", "-o", out_path]
362 target_env = cmd[cmd.index("--target-env") + 1]
363 out_path = cmd[cmd.index("-o") + 1]
364 try:
365 out_bytes = _synthetic_disasm_to_spv(input, target_env)
366 with open(out_path, "wb") as f:
367 f.write(out_bytes)
368 except (OSError, ValueError) as exc:
369 if check:
370 raise subprocess.CalledProcessError(1, cmd, output="", stderr=str(exc)) from exc
371 return subprocess.CompletedProcess(cmd, 1, "", str(exc))
372 return subprocess.CompletedProcess(cmd, 0, "", "")
373 raise AssertionError(f"unexpected subprocess command: {cmd!r}")
374
375 return fake_run, calls
376
377
378class TestCapacities(unittest.TestCase):
379 def test_default_bindless_header_all_26_entries_and_cross_check(self):
380 counts = m.capacities()
381 expected = [4096, 1024, 1, 1024, 1024] + [256] * 21
382 self.assertEqual(counts, expected)
383 self.assertEqual(len(counts), 26)
384 self.assertEqual(sum(counts), 12545)
385
386 with open(m.BINDLESS_H, encoding="utf-8") as f:
387 hdr = f.read()
388 self.assertIn("inline constexpr std::uint32_t binding_count = 26;", hdr)
389 self.assertIn("inline constexpr std::array<Binding, 26> bindings =", hdr)
390
391 def test_custom_header_parsing_variants(self):
392 cases = [
393 ("empty_table", "std::array<Binding, 0> bindings = {{}};\n", []),
394 (
395 "single_line",
396 "std::array<Binding, 1> bindings = {{{VK_DESCRIPTOR_TYPE_SAMPLER, 7}}};\n",
397 [7],
398 ),
399 (
400 "multiline_mixed_types_and_comments",
401 """
402 // unrelated header prefix
403 inline constexpr std::array<Binding, 4> bindings = {{
404 {VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 128},
405 {VK_DESCRIPTOR_TYPE_SAMPLER, 32},
406 {VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1},
407 {VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 64},
408 }};
409 """,
410 [128, 32, 1, 64],
411 ),
412 ]
413 with tempfile.TemporaryDirectory() as tmp:
414 for name, body, expected in cases:
415 with self.subTest(case=name):
416 p = os.path.join(tmp, f"{name}.h")
417 with open(p, "w", encoding="utf-8") as f:
418 f.write(body)
419 self.assertEqual(m.capacities(p), expected)
420
421 def test_missing_file_raises_file_not_found(self):
422 with tempfile.TemporaryDirectory() as tmp:
423 missing = os.path.join(tmp, "missing_bindless.h")
424 with self.assertRaises(FileNotFoundError):
425 m.capacities(missing)
426
427 def test_missing_or_mismatched_bindings_table_raises_system_exit(self):
428 bad_headers = [
429 ("empty_file", "", "no `bindings` table"),
430 ("wrong_type_name", "std::array<int, 1> bindings = {{ {VK_DESCRIPTOR_TYPE_SAMPLER, 4} }};", "no `bindings` table"),
431 (
432 "too_few_entries",
433 "std::array<Binding, 3> bindings = {{ {VK_DESCRIPTOR_TYPE_SAMPLER, 1}, {VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 2} }};",
434 "`bindings` declares 3 entries, found 2",
435 ),
436 (
437 "too_many_entries",
438 "std::array<Binding, 1> bindings = {{ {VK_DESCRIPTOR_TYPE_SAMPLER, 1}, {VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 2} }};",
439 "`bindings` declares 1 entries, found 2",
440 ),
441 (
442 "unmatched_entry_syntax",
443 "std::array<Binding, 1> bindings = {{ {NOT_A_VK_DESCRIPTOR, 1} }};",
444 "`bindings` declares 1 entries, found 0",
445 ),
446 ]
447 with tempfile.TemporaryDirectory() as tmp:
448 for name, body, msg_part in bad_headers:
449 with self.subTest(case=name):
450 p = os.path.join(tmp, f"{name}.h")
451 with open(p, "w", encoding="utf-8") as f:
452 f.write(body)
453 with self.assertRaises(SystemExit) as ctx:
454 m.capacities(p)
455 self.assertIn(p, str(ctx.exception))
456 self.assertIn(msg_part, str(ctx.exception))
457
458
459class TestMetalIds(unittest.TestCase):
460 def test_empty_single_and_zero_capacities(self):
461 self.assertEqual(m.metal_ids([]), [])
462 self.assertEqual(m.metal_ids([42]), [0])
463 self.assertEqual(m.metal_ids([10, 0, 5, 0, 1]), [0, 10, 10, 15, 15])
464
465 def test_vulkan_bindless_ids_contiguous_and_non_overlapping(self):
466 counts = m.capacities()
467 ids = m.metal_ids(counts)
468 self.assertEqual(len(ids), 26)
469 self.assertEqual(ids[0], 0)
470 self.assertEqual(ids[:6], [0, 4096, 5120, 5121, 6145, 7169])
471 self.assertEqual(ids[8], 7937)
472 self.assertEqual(ids[20], 11009)
473 self.assertEqual(ids[25], 12289)
474 for b in range(len(counts) - 1):
475 self.assertEqual(ids[b + 1], ids[b] + counts[b])
476 self.assertEqual(ids[-1] + counts[-1], sum(counts))
477
478 seen_total = 0
479 for b in range(len(counts)):
480 if b > 0:
481 self.assertGreater(ids[b], ids[b - 1] + counts[b - 1] - 1)
482 seen_total += counts[b]
483 self.assertEqual(seen_total, 12545)
484
485
486class TestRewrite(unittest.TestCase):
487 def test_all_26_vulkan_bindless_bindings(self):
488 counts = m.capacities()
489 ids = m.metal_ids(counts)
490 lines = [
491 " OpCapability Shader",
492 " OpCapability RuntimeDescriptorArray",
493 " OpMemoryModel Logical GLSL450",
494 ]
495 for b in range(26):
496 lines.append(f" OpDecorate %v{b} DescriptorSet 0")
497 lines.append(f" OpDecorate %v{b} Binding {b}")
498 lines.extend([
499 " %uint = OpTypeInt 32 0",
500 " %float = OpTypeFloat 32",
501 " %img2d = OpTypeImage %float 2D 0 0 0 1 Unknown",
502 " %smp = OpTypeSampler",
503 " %rt_map = OpTypeRuntimeArray %uint",
504 " %map = OpTypeStruct %rt_map",
505 " %ptr_map = OpTypePointer StorageBuffer %map",
506 ])
507 for b in range(26):
508 if b == 2:
509 continue
510 elem = "%smp" if b == 1 else "%img2d"
511 lines.append(f" %rt_b{b} = OpTypeRuntimeArray {elem}")
512 lines.append(f" %ptr_b{b} = OpTypePointer UniformConstant %rt_b{b}")
513 for b in range(26):
514 if b == 2:
515 lines.append(" %v2 = OpVariable %ptr_map StorageBuffer")
516 else:
517 lines.append(f" %v{b} = OpVariable %ptr_b{b} UniformConstant")
518
519 out = m.rewrite("\n".join(lines) + "\n", counts)
520 out_lines = out.splitlines()
521
522 for b in range(26):
523 self.assertIn(f" OpDecorate %v{b} Binding {ids[b]}", out_lines)
524 if b == 2:
525 self.assertIn(" %v2 = OpVariable %ptr_map StorageBuffer", out_lines)
526 self.assertNotIn("%msl_cap_b2 ", out)
527 self.assertNotIn("%msl_arr_b2 ", out)
528 self.assertNotIn("%msl_ptr_b2 ", out)
529 else:
530 elem = "%smp" if b == 1 else "%img2d"
531 cap_line = f"%msl_cap_b{b} = OpConstant %uint {counts[b]}"
532 arr_line = f"%msl_arr_b{b} = OpTypeArray {elem} %msl_cap_b{b}"
533 ptr_line = f"%msl_ptr_b{b} = OpTypePointer UniformConstant %msl_arr_b{b}"
534 orig_ptr_line = f" %ptr_b{b} = OpTypePointer UniformConstant %rt_b{b}"
535 idx = out_lines.index(orig_ptr_line)
536 self.assertEqual(out_lines[idx + 1 : idx + 4], [cap_line, arr_line, ptr_line])
537 self.assertIn(f" %v{b} = OpVariable %msl_ptr_b{b} UniformConstant", out_lines)
538
539 def test_push_constants_and_other_descriptor_sets_untouched(self):
540 module = """\
541 OpDecorate %set0_img DescriptorSet 0
542 OpDecorate %set0_img Binding 0
543 OpDecorate %set0_smp DescriptorSet 0
544 OpDecorate %set0_smp Binding 1
545 OpDecorate %set1_in DescriptorSet 1
546 OpDecorate %set1_in Binding 0
547 OpDecorate %set1_high DescriptorSet 1
548 OpDecorate %set1_high Binding 99
549 OpDecorate %set2_uc DescriptorSet 2
550 OpDecorate %set2_uc Binding 0
551 %uint = OpTypeInt 32 0
552 %float = OpTypeFloat 32
553 %img2d = OpTypeImage %float 2D 0 0 0 1 Unknown
554 %smp = OpTypeSampler
555 %rt_img = OpTypeRuntimeArray %img2d
556 %rt_smp = OpTypeRuntimeArray %smp
557 %ptr_img = OpTypePointer UniformConstant %rt_img
558 %ptr_smp = OpTypePointer UniformConstant %rt_smp
559 %ptr_pc = OpTypePointer PushConstant %uint
560 %ptr_s1hi = OpTypePointer UniformConstant %rt_img
561 %ptr_s2uc = OpTypePointer UniformConstant %rt_img
562 %set0_img = OpVariable %ptr_img UniformConstant
563 %set0_smp = OpVariable %ptr_smp UniformConstant
564 %user_data = OpVariable %ptr_pc PushConstant
565 %set1_in = OpVariable %ptr_img StorageBuffer
566 %set1_high = OpVariable %ptr_s1hi UniformConstant
567 %set2_uc = OpVariable %ptr_s2uc UniformConstant
568"""
569 out = m.rewrite(module, [8, 4])
570 self.assertIn("OpDecorate %set0_img Binding 0", out)
571 self.assertIn("OpDecorate %set0_smp Binding 8", out)
572 # Set 1 (including binding 99 >= len(counts)), Set 2, and PushConstant stay untouched.
573 self.assertIn("OpDecorate %set1_in DescriptorSet 1", out)
574 self.assertIn("OpDecorate %set1_in Binding 0", out)
575 self.assertIn("OpDecorate %set1_high DescriptorSet 1", out)
576 self.assertIn("OpDecorate %set1_high Binding 99", out)
577 self.assertIn("OpDecorate %set2_uc DescriptorSet 2", out)
578 self.assertIn("OpDecorate %set2_uc Binding 0", out)
579 self.assertIn("%user_data = OpVariable %ptr_pc PushConstant", out)
580 self.assertIn("%set1_in = OpVariable %ptr_img StorageBuffer", out)
581 self.assertIn("%set1_high = OpVariable %ptr_s1hi UniformConstant", out)
582 self.assertIn("%set2_uc = OpVariable %ptr_s2uc UniformConstant", out)
583
584 def test_non_runtime_array_set0_resources_rebind_without_retyping_or_uint32(self):
585 # No OpTypeInt 32 0 is present, yet none of these set-0 bindings use OpTypeRuntimeArray
586 # under OpTypePointer UniformConstant, so rewriting succeeds without raising.
587 module = """\
588 OpDecorate %single DescriptorSet 0
589 OpDecorate %single Binding 0
590 OpDecorate %fixed DescriptorSet 0
591 OpDecorate %fixed Binding 1
592 OpDecorate %ubo DescriptorSet 0
593 OpDecorate %ubo Binding 2
594 OpDecorate %mismatch DescriptorSet 0
595 OpDecorate %mismatch Binding 3
596 OpDecorate %dangling DescriptorSet 0
597 OpDecorate %dangling Binding 4
598 %float = OpTypeFloat 32
599 %img2d = OpTypeImage %float 2D 0 0 0 1 Unknown
600 %sint = OpTypeInt 32 1
601 %c16 = OpConstant %sint 16
602 %fixed_arr = OpTypeArray %img2d %c16
603 %ubo_blk = OpTypeStruct %float
604 %ptr_single = OpTypePointer UniformConstant %img2d
605 %ptr_fixed = OpTypePointer UniformConstant %fixed_arr
606 %ptr_ubo = OpTypePointer Uniform %ubo_blk
607 %ptr_mis_sb = OpTypePointer StorageBuffer %fixed_arr
608%ptr_dangling = OpTypePointer UniformConstant %missing_pointee
609 %single = OpVariable %ptr_single UniformConstant
610 %fixed = OpVariable %ptr_fixed UniformConstant
611 %ubo = OpVariable %ptr_ubo Uniform
612 %mismatch = OpVariable %ptr_mis_sb UniformConstant
613 %dangling = OpVariable %ptr_dangling UniformConstant
614"""
615 counts = [10, 20, 1, 5, 2]
616 out = m.rewrite(module, counts)
617 self.assertIn("OpDecorate %single Binding 0", out)
618 self.assertIn("OpDecorate %fixed Binding 10", out)
619 self.assertIn("OpDecorate %ubo Binding 30", out)
620 self.assertIn("OpDecorate %mismatch Binding 31", out)
621 self.assertIn("OpDecorate %dangling Binding 36", out)
622 self.assertIn("%single = OpVariable %ptr_single UniformConstant", out)
623 self.assertIn("%fixed = OpVariable %ptr_fixed UniformConstant", out)
624 self.assertIn("%ubo = OpVariable %ptr_ubo Uniform", out)
625 self.assertIn("%mismatch = OpVariable %ptr_mis_sb UniformConstant", out)
626 self.assertIn("%dangling = OpVariable %ptr_dangling UniformConstant", out)
627 self.assertNotIn("%msl_", out)
628
629 def test_partial_decorations_and_missing_var_def(self):
630 module = """\
631OpDecorate %only_set DescriptorSet 0
632OpDecorate %only_bind Binding 1
633OpDecorate %orphan DescriptorSet 0
634OpDecorate %orphan Binding 1
635%u = OpTypeInt 32 0
636"""
637 out = m.rewrite(module, [5, 7])
638 self.assertIn("OpDecorate %only_set DescriptorSet 0", out)
639 self.assertIn("OpDecorate %only_bind Binding 1", out)
640 self.assertIn("OpDecorate %orphan Binding 5", out)
641 self.assertNotIn("%msl_", out)
642
643 def test_raw_numeric_ids_custom_uint_and_crlf_and_shared_pointer(self):
644 module = (
645 "; Header comment\r\n"
646 "OpName %10 \"images\"\r\n"
647 "OpDecorate %10 DescriptorSet 0\r\n"
648 "OpDecorate %10 Binding 1\r\n"
649 "OpDecorate %11 DescriptorSet 0\r\n"
650 "OpDecorate %11 Binding 0\r\n"
651 "%1 = OpTypeVoid\r\n"
652 "%2 = OpTypeInt 32 1\r\n"
653 "%3 = OpTypeInt 64 0\r\n"
654 "%4 = OpTypeInt 32 0\r\n"
655 "%5 = OpTypeFloat 32\r\n"
656 "%6 = OpTypeImage %5 2D 0 0 0 1 Unknown\r\n"
657 "%7 = OpTypeRuntimeArray %6\r\n"
658 "%8 = OpTypePointer UniformConstant %7\r\n"
659 "%9 = OpTypePointer Function %5\r\n"
660 "%10 = OpVariable %8 UniformConstant\r\n"
661 "%11 = OpVariable %8 UniformConstant\r\n"
662 )
663 out = m.rewrite(module, [16, 8])
664 self.assertNotIn("\r\n", out)
665 self.assertTrue(out.endswith("\n"))
666 self.assertIn("OpDecorate %11 Binding 0", out)
667 self.assertIn("OpDecorate %10 Binding 16", out)
668 # First OpTypeInt 32 0 is %4 (not %2 signed or %3 64-bit).
669 self.assertIn("%msl_cap_b0 = OpConstant %4 16", out)
670 self.assertIn("%msl_cap_b1 = OpConstant %4 8", out)
671 self.assertIn("%11 = OpVariable %msl_ptr_b0 UniformConstant", out)
672 self.assertIn("%10 = OpVariable %msl_ptr_b1 UniformConstant", out)
673 # Sorted binding order (b0 then b1) inserted immediately after %8, not after %9.
674 lines = out.splitlines()
675 idx8 = lines.index("%8 = OpTypePointer UniformConstant %7")
676 self.assertEqual(lines[idx8 + 1 : idx8 + 7], [
677 "%msl_cap_b0 = OpConstant %4 16",
678 "%msl_arr_b0 = OpTypeArray %6 %msl_cap_b0",
679 "%msl_ptr_b0 = OpTypePointer UniformConstant %msl_arr_b0",
680 "%msl_cap_b1 = OpConstant %4 8",
681 "%msl_arr_b1 = OpTypeArray %6 %msl_cap_b1",
682 "%msl_ptr_b1 = OpTypePointer UniformConstant %msl_arr_b1",
683 ])
684 idx9 = lines.index("%9 = OpTypePointer Function %5")
685 self.assertEqual(lines[idx9 + 1], "%10 = OpVariable %msl_ptr_b1 UniformConstant")
686
687 def test_empty_and_no_set0_modules(self):
688 self.assertEqual(m.rewrite("", [4]), "\n")
689 plain = "OpCapability Shader\nOpMemoryModel Logical GLSL450\n"
690 self.assertEqual(m.rewrite(plain, [4]), plain)
691
692 def test_out_of_bounds_set0_binding_raises_system_exit(self):
693 for b, counts in ((2, [10, 20]), (26, m.capacities()), (100, m.capacities())):
694 with self.subTest(binding=b, count_len=len(counts)):
695 text = f"OpDecorate %bad DescriptorSet 0\nOpDecorate %bad Binding {b}\n"
696 with self.assertRaises(SystemExit) as ctx:
697 m.rewrite(text, counts)
698 self.assertIn("%bad", str(ctx.exception))
699 self.assertIn(f"binding {b}", str(ctx.exception))
700
701 def test_missing_uint32_type_raises_when_runtime_array_rewritten(self):
702 base = """\
703OpDecorate %images DescriptorSet 0
704OpDecorate %images Binding 0
705{int_decl}
706%float = OpTypeFloat 32
707%img2d = OpTypeImage %float 2D 0 0 0 1 Unknown
708%rt_img = OpTypeRuntimeArray %img2d
709%ptr_img = OpTypePointer UniformConstant %rt_img
710%images = OpVariable %ptr_img UniformConstant
711"""
712 for label, int_decl in (
713 ("no_int", ""),
714 ("signed_32", "%s32 = OpTypeInt 32 1"),
715 ("unsigned_64", "%u64 = OpTypeInt 64 0"),
716 ):
717 with self.subTest(case=label):
718 with self.assertRaises(SystemExit) as ctx:
719 m.rewrite(base.format(int_decl=int_decl), [4096])
720 self.assertIn("no 32-bit uint type", str(ctx.exception))
721
722
723class TestMainAndCli(unittest.TestCase):
724 def _call_main(self, argv):
725 out, err = io.StringIO(), io.StringIO()
726 # tools/spirv_metal_set0.py:31 uses open(path).read() without a context manager, which emits
727 # ResourceWarning under unittest's default filter on redirected stderr; isolate tool stderr here.
728 with warnings.catch_warnings():
729 warnings.simplefilter("ignore", ResourceWarning)
730 with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err):
731 code = m.main(argv)
732 return code, out.getvalue(), err.getvalue()
733
734 def test_print_layout_outputs_26_formatted_ranges_without_subprocess(self):
735 with mock.patch.object(m.subprocess, "run") as run_mock:
736 code, out, err = self._call_main(["spirv_metal_set0.py", "--print-layout"])
737 run_mock.assert_not_called()
738 self.assertEqual(code, 0)
739 self.assertEqual(err, "")
740 lines = out.splitlines()
741 self.assertEqual(len(lines), 26)
742 self.assertEqual(lines[0], "binding 0: 4096 descriptors at IDs 0..4095")
743 self.assertEqual(lines[1], "binding 1: 1024 descriptors at IDs 4096..5119")
744 self.assertEqual(lines[2], "binding 2: 1 descriptors at IDs 5120..5120")
745 self.assertEqual(lines[3], "binding 3: 1024 descriptors at IDs 5121..6144")
746 self.assertEqual(lines[4], "binding 4: 1024 descriptors at IDs 6145..7168")
747 self.assertEqual(lines[25], "binding 25: 256 descriptors at IDs 12289..12544")
748
749 def test_print_layout_uses_capacities_table(self):
750 with mock.patch.object(m, "capacities", return_value=[3, 1, 2]):
751 code, out, err = self._call_main(["spirv_metal_set0.py", "--print-layout"])
752 self.assertEqual(code, 0)
753 self.assertEqual(err, "")
754 self.assertEqual(out.splitlines(), [
755 "binding 0: 3 descriptors at IDs 0..2",
756 "binding 1: 1 descriptors at IDs 3..3",
757 "binding 2: 2 descriptors at IDs 4..5",
758 ])
759
760 def test_invalid_argc_returns_2_and_prints_usage_to_stderr(self):
761 bad_argvs = [
762 [],
763 ["spirv_metal_set0.py"],
764 ["spirv_metal_set0.py", "in.spv"],
765 ["spirv_metal_set0.py", "--unknown"],
766 ["spirv_metal_set0.py", "--print-layout", "in.spv", "out.spv"],
767 ["spirv_metal_set0.py", "in.spv", "out.spv", "extra"],
768 ]
769 for argv in bad_argvs:
770 with self.subTest(argv=argv), mock.patch.object(m.subprocess, "run") as run_mock:
771 code, out, err = self._call_main(argv)
772 run_mock.assert_not_called()
773 self.assertEqual(code, 2)
774 self.assertEqual(out, "")
775 self.assertIn("Usage: spirv_metal_set0.py in.spv out.spv", err)
776 self.assertIn("--print-layout", err)
777
778 def test_print_layout_with_extra_arg_falls_through_to_two_arg_mode(self):
779 with mock.patch.object(
780 m.subprocess,
781 "run",
782 side_effect=[
783 subprocess.CompletedProcess([], 0, "OpCapability Shader\n", ""),
784 subprocess.CompletedProcess([], 0, "", ""),
785 ],
786 ) as run_mock:
787 code, out, err = self._call_main(["spirv_metal_set0.py", "--print-layout", "out.spv"])
788 self.assertEqual((code, out, err), (0, "", ""))
789 self.assertEqual(run_mock.call_args_list[0].args[0], ["spirv-dis", "--print-layout"])
790 self.assertEqual(
791 run_mock.call_args_list[1].args[0],
792 ["spirv-as", "--target-env", "vulkan1.2", "-", "-o", "out.spv"],
793 )
794
795 def test_cli_subprocess_isolated_print_layout_and_bad_args(self):
796 r_layout = subprocess.run(
797 [sys.executable, "-I", TOOL_PATH, "--print-layout"],
798 capture_output=True,
799 text=True,
800 cwd=ROOT,
801 )
802 self.assertEqual(r_layout.returncode, 0, r_layout.stderr)
803 self.assertEqual(r_layout.stderr, "")
804 self.assertEqual(len(r_layout.stdout.splitlines()), 26)
805 self.assertEqual(r_layout.stdout.splitlines()[0], "binding 0: 4096 descriptors at IDs 0..4095")
806
807 for args in ([], ["only_one.spv"], ["a.spv", "b.spv", "c.spv"]):
808 with self.subTest(args=args):
809 r = subprocess.run(
810 [sys.executable, "-I", TOOL_PATH, *args],
811 capture_output=True,
812 text=True,
813 cwd=ROOT,
814 )
815 self.assertEqual(r.returncode, 2)
816 self.assertEqual(r.stdout, "")
817 self.assertIn("Usage: spirv_metal_set0.py in.spv out.spv", r.stderr)
818 self.assertNotIn("Traceback", r.stderr)
819
820 def test_synthetic_spv_out_of_place_and_in_place_binary_round_trip(self):
821 in_bytes = _pack_spv(_build_mixed_bindless_spv_words(), version=SPIRV_VERSION_1_5)
822 fake_run, calls = _make_fake_spirv_tools()
823
824 with tempfile.TemporaryDirectory() as tmp:
825 unicode_dir = os.path.join(tmp, "dir-\u00e9-\u2603")
826 os.makedirs(unicode_dir)
827 in_path = os.path.join(unicode_dir, "in.spv")
828 out_path = os.path.join(unicode_dir, "out.spv")
829 with open(in_path, "wb") as f:
830 f.write(in_bytes)
831
832 with mock.patch.dict(os.environ, {}, clear=False), \
833 mock.patch.object(m.subprocess, "run", side_effect=fake_run):
834 os.environ.pop("SPIRV_DIS", None)
835 os.environ.pop("SPIRV_AS", None)
836 code, out, err = self._call_main(["spirv_metal_set0.py", in_path, out_path])
837
838 self.assertEqual(code, 0)
839 self.assertEqual(out, "")
840 self.assertEqual(err, "")
841 self.assertEqual(calls, [
842 ["spirv-dis", in_path],
843 ["spirv-as", "--target-env", "spv1.5", "-", "-o", out_path],
844 ])
845
846 # Original input file is preserved untouched for out-of-place conversion.
847 with open(in_path, "rb") as f:
848 self.assertEqual(f.read(), in_bytes)
849
850 with open(out_path, "rb") as f:
851 out_bytes = f.read()
852 header, insts = _decode_spv(out_bytes)
853 self.assertEqual(header[0], SPIRV_MAGIC)
854 self.assertEqual(header[1], SPIRV_VERSION_1_5)
855 self.assertEqual(header[4], 0)
856
857 decs = [ops for op, ops in insts if op == OP_DECORATE]
858 bindings_by_id = {ops[0]: ops[2] for ops in decs if ops[1] == DEC_BINDING}
859 sets_by_id = {ops[0]: ops[2] for ops in decs if ops[1] == DEC_DESCRIPTOR_SET}
860 self.assertEqual(sets_by_id, {13: 0, 14: 0, 15: 0, 17: 1})
861 # Set-0 bindings rewritten per vulkan_bindless.h; set-1 binding 0 stays 0.
862 self.assertEqual(bindings_by_id, {13: 0, 14: 4096, 15: 5120, 17: 0})
863
864 consts = {ops[1]: ops[2] for op, ops in insts if op == OP_CONSTANT}
865 arrays = {ops[0]: (ops[1], consts[ops[2]]) for op, ops in insts if op == OP_TYPE_ARRAY}
866 ptrs = {ops[0]: (ops[1], ops[2]) for op, ops in insts if op == OP_TYPE_POINTER}
867 vars_by_id = {ops[1]: (ops[0], ops[2]) for op, ops in insts if op == OP_VARIABLE}
868
869 # %13 (images) and %14 (samplers) are retyped to sized arrays [4096] and [1024];
870 # %15 (desc_map StorageBuffer), %16 (PushConstant), and %17 (set 1) keep original types.
871 self.assertEqual(arrays[ptrs[vars_by_id[13][0]][1]], (3, 4096))
872 self.assertEqual(arrays[ptrs[vars_by_id[14][0]][1]], (4, 1024))
873 self.assertEqual(vars_by_id[15], (11, SC_STORAGE_BUFFER))
874 self.assertEqual(vars_by_id[16], (12, SC_PUSH_CONSTANT))
875 self.assertEqual(vars_by_id[17], (7, SC_UNIFORM_CONSTANT))
876
877 # In-place conversion: argv[1] == argv[2].
878 inplace_path = os.path.join(unicode_dir, "inplace.spv")
879 with open(inplace_path, "wb") as f:
880 f.write(in_bytes)
881 calls.clear()
882 with mock.patch.object(m.subprocess, "run", side_effect=fake_run):
883 code, out, err = self._call_main(["spirv_metal_set0.py", inplace_path, inplace_path])
884 self.assertEqual(code, 0)
885 self.assertEqual(out, "")
886 self.assertEqual(err, "")
887 self.assertEqual(calls, [
888 ["spirv-dis", inplace_path],
889 ["spirv-as", "--target-env", "spv1.5", "-", "-o", inplace_path],
890 ])
891 with open(inplace_path, "rb") as f:
892 self.assertEqual(f.read(), out_bytes)
893
894 def test_target_env_extraction_and_env_var_overrides(self):
895 cases = [
896 ("; Version: 1.0\n", "spv1.0"),
897 ("; SPIR-V\n; Version: 1.5\n", "spv1.5"),
898 ("; Version: 1.6\n", "spv1.6"),
899 ("; SPIR-V without version comment\n", "vulkan1.2"),
900 ]
901 for header_text, expected_target in cases:
902 with self.subTest(expected_target=expected_target):
903 disasm = header_text + "OpCapability Shader\n"
904 seen_cmds = []
905
906 def run_stub(cmd, check=False, capture_output=False, text=False, input=None):
907 seen_cmds.append((list(cmd), check, capture_output, text, input))
908 if len(seen_cmds) == 1:
909 return subprocess.CompletedProcess(cmd, 0, disasm, "")
910 return subprocess.CompletedProcess(cmd, 0, "", "")
911
912 with mock.patch.dict(os.environ, {"SPIRV_DIS": "/opt/bin/dis", "SPIRV_AS": "/opt/bin/as"}), \
913 mock.patch.object(m.subprocess, "run", side_effect=run_stub):
914 code, out, err = self._call_main(["spirv_metal_set0.py", "in.spv", "out.spv"])
915
916 self.assertEqual((code, out, err), (0, "", ""))
917 self.assertEqual(seen_cmds[0][0], ["/opt/bin/dis", "in.spv"])
918 self.assertTrue(seen_cmds[0][1])
919 self.assertTrue(seen_cmds[0][2])
920 self.assertTrue(seen_cmds[0][3])
921 self.assertEqual(seen_cmds[1][0], ["/opt/bin/as", "--target-env", expected_target, "-", "-o", "out.spv"])
922 self.assertTrue(seen_cmds[1][1])
923 self.assertTrue(seen_cmds[1][3])
924 self.assertEqual(seen_cmds[1][4], disasm)
925
926 def test_invalid_spirv_binary_words_and_missing_or_directory_paths(self):
927 fake_run, calls = _make_fake_spirv_tools()
928 valid_words = _build_mixed_bindless_spv_words()
929
930 bad_inputs = [
931 ("empty_file", b""),
932 ("truncated_header_8B", struct.pack("<2I", SPIRV_MAGIC, SPIRV_VERSION_1_5)),
933 ("unaligned_21B", _pack_spv([], bound=1) + b"\x00"),
934 ("big_endian_magic", struct.pack(">5I", SPIRV_MAGIC, SPIRV_VERSION_1_5, 0, 2, 0)),
935 ("wrong_magic", struct.pack("<5I", 0xDEADBEEF, SPIRV_VERSION_1_5, 0, 2, 0)),
936 ("non_zero_schema", _pack_spv([], bound=1, schema=1)),
937 ("zero_bound", _pack_spv([], bound=0)),
938 ("zero_word_count_inst", _pack_spv([OP_CAPABILITY], bound=2)),
939 ("truncated_inst_bounds", _pack_spv(valid_words[:-1], bound=18)),
940 ]
941 with tempfile.TemporaryDirectory() as tmp:
942 for label, blob in bad_inputs:
943 with self.subTest(case=label):
944 calls.clear()
945 in_path = os.path.join(tmp, f"{label}.spv")
946 out_path = os.path.join(tmp, f"{label}.out.spv")
947 with open(in_path, "wb") as f:
948 f.write(blob)
949 with mock.patch.object(m.subprocess, "run", side_effect=fake_run):
950 with self.assertRaises(subprocess.CalledProcessError):
951 m.main(["spirv_metal_set0.py", in_path, out_path])
952 self.assertEqual(calls, [["spirv-dis", in_path]])
953 self.assertFalse(os.path.exists(out_path))
954
955 # Missing input file and directory passed as input file both fail at spirv-dis.
956 missing_in = os.path.join(tmp, "does_not_exist.spv")
957 dir_in = os.path.join(tmp, "a_directory")
958 os.makedirs(dir_in)
959 for label, bad_path in (("missing_file", missing_in), ("directory_input", dir_in)):
960 with self.subTest(case=label):
961 calls.clear()
962 out_path = os.path.join(tmp, f"{label}.out.spv")
963 with mock.patch.object(m.subprocess, "run", side_effect=fake_run):
964 with self.assertRaises(subprocess.CalledProcessError):
965 m.main(["spirv_metal_set0.py", bad_path, out_path])
966 self.assertEqual(calls, [["spirv-dis", bad_path]])
967 self.assertFalse(os.path.exists(out_path))
968
969 def test_spirv_as_failure_missing_executable_and_rewrite_abort(self):
970 with tempfile.TemporaryDirectory() as tmp:
971 in_path = os.path.join(tmp, "in.spv")
972 out_path = os.path.join(tmp, "out.spv")
973 with open(in_path, "wb") as f:
974 f.write(_pack_spv(_build_mixed_bindless_spv_words()))
975
976 # 1. Missing spirv-dis binary raises FileNotFoundError before calling spirv-as.
977 with mock.patch.object(m.subprocess, "run", side_effect=FileNotFoundError("no spirv-dis")) as run_mock:
978 with self.assertRaises(FileNotFoundError):
979 m.main(["spirv_metal_set0.py", in_path, out_path])
980 self.assertEqual(run_mock.call_count, 1)
981 self.assertFalse(os.path.exists(out_path))
982
983 # 2. rewrite() SystemExit aborts before spirv-as is invoked.
984 bad_spv = _pack_spv([
985 *_encode_inst(OP_DECORATE, 2, DEC_DESCRIPTOR_SET, 0),
986 *_encode_inst(OP_DECORATE, 2, DEC_BINDING, 99),
987 ], bound=3)
988 with open(in_path, "wb") as f:
989 f.write(bad_spv)
990 fake_run, calls = _make_fake_spirv_tools()
991 with mock.patch.object(m.subprocess, "run", side_effect=fake_run):
992 with self.assertRaises(SystemExit) as ctx:
993 m.main(["spirv_metal_set0.py", in_path, out_path])
994 self.assertIn("binding 99", str(ctx.exception))
995 self.assertEqual(calls, [["spirv-dis", in_path]])
996 self.assertFalse(os.path.exists(out_path))
997
998 # 3. spirv-as failure raises CalledProcessError.
999 dis_ok = subprocess.CompletedProcess(["spirv-dis", in_path], 0, "; Version: 1.5\nOpCapability Shader\n", "")
1000 asm_fail = subprocess.CalledProcessError(1, ["spirv-as"], stderr="bad asm")
1001 with mock.patch.object(m.subprocess, "run", side_effect=[dis_ok, asm_fail]) as run_mock:
1002 with self.assertRaises(subprocess.CalledProcessError):
1003 m.main(["spirv_metal_set0.py", in_path, out_path])
1004 self.assertEqual(run_mock.call_count, 2)
1005
1006 def test_main_guard_handles_stdout_reconfigure_errors_and_exit_codes(self):
1007 class _Stream(io.StringIO):
1008 def __init__(self, exc):
1009 super().__init__()
1010 self._exc = exc
1011
1012 def reconfigure(self, **_kwargs):
1013 raise self._exc
1014
1015 for exc in (AttributeError("no reconfigure"), ValueError("bad"), OSError("io")):
1016 with self.subTest(exc=type(exc).__name__):
1017 out_stream = _Stream(exc)
1018 err_stream = io.StringIO()
1019 with warnings.catch_warnings():
1020 warnings.simplefilter("ignore", ResourceWarning)
1021 with mock.patch.object(sys, "argv", ["spirv_metal_set0.py", "--print-layout"]), \
1022 mock.patch.object(sys, "stdout", out_stream), \
1023 mock.patch.object(sys, "stderr", err_stream):
1024 with self.assertRaises(SystemExit) as ctx:
1025 runpy.run_path(TOOL_PATH, run_name="__main__")
1026 self.assertEqual(ctx.exception.code, 0)
1027 self.assertEqual(err_stream.getvalue(), "")
1028 self.assertEqual(len(out_stream.getvalue().splitlines()), 26)
1029
1030 err_stream = io.StringIO()
1031 with warnings.catch_warnings():
1032 warnings.simplefilter("ignore", ResourceWarning)
1033 with mock.patch.object(sys, "argv", ["spirv_metal_set0.py"]), \
1034 mock.patch.object(sys, "stdout", io.StringIO()), \
1035 mock.patch.object(sys, "stderr", err_stream):
1036 with self.assertRaises(SystemExit) as ctx:
1037 runpy.run_path(TOOL_PATH, run_name="__main__")
1038 self.assertEqual(ctx.exception.code, 2)
1039 self.assertIn("Usage: spirv_metal_set0.py in.spv out.spv", err_stream.getvalue())
1040
1041
1042if __name__ == "__main__":
1043 unittest.main()
diff --git a/tests/test_story_index.py b/tests/test_story_index.py
index d116637fe..97697e157 100644
--- a/tests/test_story_index.py
+++ b/tests/test_story_index.py
@@ -240,8 +240,8 @@ class ArchiveTest(unittest.TestCase):
240 class _FailingWriter: 240 class _FailingWriter:
241 """A csv writer that fails once the header and first row have hit the staged file.""" 241 """A csv writer that fails once the header and first row have hit the staged file."""
242 242
243 def __init__(self, fileobj): 243 def __init__(self, fileobj, **kwargs):
244 self._w = real_csv_writer(fileobj) 244 self._w = real_csv_writer(fileobj, **kwargs)
245 self._n = 0 245 self._n = 0
246 246
247 def writerow(self, row): 247 def writerow(self, row):
diff --git a/tests/test_tex_export.py b/tests/test_tex_export.py
index e639d0ed9..d42fae028 100644
--- a/tests/test_tex_export.py
+++ b/tests/test_tex_export.py
@@ -469,3 +469,79 @@ def test_stale_export_entry_is_not_counted(eq, tmp_path, monkeypatch, capsys):
469 out, code, text = png_main(tmp_path, monkeypatch, capsys, [t], carve, "--png") 469 out, code, text = png_main(tmp_path, monkeypatch, capsys, [t], carve, "--png")
470 assert text.splitlines()[0].startswith("1 textures: {'error:FileNotFoundError': 1}") 470 assert text.splitlines()[0].startswith("1 textures: {'error:FileNotFoundError': 1}")
471 assert text.splitlines()[1] == "png: {}" 471 assert text.splitlines()[1] == "png: {}"
472
473# ---- bad index / --out guards (#1607's class in main) ----
474
475def _argv(monkeypatch, index, carve, out, *extra):
476 monkeypatch.setattr(sys, "argv", ["tex_export.py", str(index), str(carve), str(out), *extra])
477
478
479def test_main_reports_a_non_list_index_as_one_error_line(tmp_path, monkeypatch, capsys):
480 index = tmp_path / "textures_index.json"
481 index.write_text('{"files": []}', encoding="utf-8")
482 out = tmp_path / "out"
483 _argv(monkeypatch, index, tmp_path, out)
484 assert T.main() == 2
485 err = capsys.readouterr().err
486 assert err.startswith("ERROR: cannot read "), err
487 assert len(err.strip().splitlines()) == 1, err
488 assert not out.exists()
489
490
491def test_main_reports_an_index_row_without_keys(tmp_path, monkeypatch, capsys):
492 index = tmp_path / "textures_index.json"
493 index.write_text('[{"gpu": 0}]', encoding="utf-8")
494 _argv(monkeypatch, index, tmp_path, tmp_path / "out")
495 assert T.main() == 2
496 err = capsys.readouterr().err
497 assert "ERROR: cannot read " in err, err
498 assert "row has no 'archive'" in err, err
499 assert "Traceback" not in err
500
501
502def test_main_rejects_an_out_that_is_a_file(tmp_path, monkeypatch, capsys):
503 index = tmp_path / "textures_index.json"
504 index.write_text("[]", encoding="utf-8")
505 out = tmp_path / "existing.txt"
506 out.write_text("x", encoding="utf-8")
507 _argv(monkeypatch, index, tmp_path, out)
508 assert T.main() == 2
509 err = capsys.readouterr().err
510 assert "is a file, not a folder" in err, err
511 assert out.read_text(encoding="utf-8") == "x"
512
513
514def test_main_reports_an_out_under_an_existing_file(tmp_path, monkeypatch, capsys):
515 index = tmp_path / "textures_index.json"
516 index.write_text("[]", encoding="utf-8")
517 blocker = tmp_path / "file.txt"
518 blocker.write_text("x", encoding="utf-8")
519 _argv(monkeypatch, index, tmp_path, blocker / "sub")
520 assert T.main() == 2
521 err = capsys.readouterr().err
522 assert "ERROR: cannot create " in err, err
523 assert "Traceback" not in err
524
525
526def test_main_reports_a_dangling_symlink_out(tmp_path, monkeypatch, capsys):
527 index = tmp_path / "textures_index.json"
528 index.write_text("[]", encoding="utf-8")
529 link = tmp_path / "dangling-out"
530 try:
531 os.symlink(str(tmp_path / "missing-target"), str(link))
532 except (OSError, NotImplementedError):
533 pytest.skip("symlinks are not available")
534 _argv(monkeypatch, index, tmp_path, link)
535 assert T.main() == 2
536 err = capsys.readouterr().err
537 assert "ERROR: cannot create " in err, err
538 assert "Traceback" not in err
539
540
541def test_main_still_accepts_an_empty_list(tmp_path, monkeypatch, capsys):
542 index = tmp_path / "textures_index.json"
543 index.write_text("[]", encoding="utf-8")
544 out = tmp_path / "out"
545 _argv(monkeypatch, index, tmp_path, out)
546 assert T.main() in (None, 0) # main() has no explicit return; sys.exit(None) is exit 0
547 assert (out / "export_log.json").is_file() \ No newline at end of file
diff --git a/tests/test_text_tables.py b/tests/test_text_tables.py
index 670b92df6..2714d2b90 100644
--- a/tests/test_text_tables.py
+++ b/tests/test_text_tables.py
@@ -178,6 +178,62 @@ class TestCli(unittest.TestCase):
178 with open(outs["strings"], encoding="utf-8", newline="") as fh: 178 with open(outs["strings"], encoding="utf-8", newline="") as fh:
179 strings = list(csv.DictReader(fh)) 179 strings = list(csv.DictReader(fh))
180 self.assertIn(("ZZ_MENU_TITLE", "das Menü"), {(s["label"], s["text"]) for s in strings}) 180 self.assertIn(("ZZ_MENU_TITLE", "das Menü"), {(s["label"], s["text"]) for s in strings})
181 self.assertFalse([f for f in os.listdir(tmp) if f.startswith(".text_tables-")],
182 "staging files must not be left behind")
183
184 def test_failed_later_write_leaves_earlier_reports_intact(self):
185 with tempfile.TemporaryDirectory() as tmp:
186 src = os.path.join(tmp, "src")
187 os.mkdir(src)
188 write(os.path.join(src, "conv.pso"), CONV)
189 dialogue = os.path.join(tmp, "dialogue.csv")
190 old = "OLD GOOD REPORT\n"
191 with open(dialogue, "w", encoding="utf-8") as fh:
192 fh.write(old)
193 tables = os.path.join(tmp, "tables.csv")
194 os.mkdir(tables) # a later output that cannot be written
195 with contextlib.redirect_stderr(io.StringIO()) as err:
196 self.assertEqual(T.main([src, "--dialogue", dialogue, "--tables", tables]), 2)
197 self.assertIn("cannot write", err.getvalue())
198 with open(dialogue, encoding="utf-8") as fh:
199 self.assertEqual(fh.read(), old)
200 self.assertFalse([f for f in os.listdir(tmp) if f.startswith(".text_tables-")])
201
202 @unittest.skipUnless(os.name == "nt", "Windows denies os.replace on a file held open by a reader")
203 def test_reader_holding_a_later_report_keeps_all_reports(self):
204 with tempfile.TemporaryDirectory() as tmp:
205 src = os.path.join(tmp, "src")
206 os.mkdir(src)
207 write(os.path.join(src, "conv.pso"), CONV)
208 dialogue = os.path.join(tmp, "dialogue.csv")
209 tables = os.path.join(tmp, "tables.csv")
210 old_dialogue, old_tables = "OLD DIALOGUE\n", "OLD TABLES\n"
211 for path, text in ((dialogue, old_dialogue), (tables, old_tables)):
212 with open(path, "w", encoding="utf-8") as fh:
213 fh.write(text)
214 with open(tables, "rb"): # a reader keeps the second output open
215 with contextlib.redirect_stderr(io.StringIO()) as err:
216 self.assertEqual(T.main([src, "--dialogue", dialogue, "--tables", tables]), 2)
217 self.assertIn("cannot write", err.getvalue())
218 with open(dialogue, encoding="utf-8") as fh:
219 self.assertEqual(fh.read(), old_dialogue)
220 with open(tables, encoding="utf-8") as fh:
221 self.assertEqual(fh.read(), old_tables)
222 self.assertFalse([f for f in os.listdir(tmp) if f.startswith(".text_tables-")],
223 "staging and backup files must not be left behind")
224
225 def test_two_outputs_naming_one_file_are_refused(self):
226 with tempfile.TemporaryDirectory() as tmp:
227 src = os.path.join(tmp, "src")
228 os.mkdir(src)
229 write(os.path.join(src, "conv.pso"), CONV)
230 out = os.path.join(tmp, "same.csv")
231 with contextlib.redirect_stderr(io.StringIO()) as err:
232 with self.assertRaises(SystemExit) as cm:
233 T.main([src, "--dialogue", out, "--tables", out])
234 self.assertEqual(cm.exception.code, 2)
235 self.assertIn("distinct", err.getvalue())
236 self.assertFalse(os.path.exists(out), "no report may be written before the check")
181 237
182 def test_missing_input(self): 238 def test_missing_input(self):
183 with contextlib.redirect_stderr(io.StringIO()): 239 with contextlib.redirect_stderr(io.StringIO()):
diff --git a/tests/test_values.py b/tests/test_values.py
index 012122ab3..7bfbe77e9 100644
--- a/tests/test_values.py
+++ b/tests/test_values.py
@@ -87,6 +87,10 @@ CASES = {
87 "v_pack_b32_f16_neg_lo": ("v_pack_b32_f16 v3, neg(v1), v2", 0xAAAA3C00, 0xBBBB4000, 0, 0x4000BC00), 87 "v_pack_b32_f16_neg_lo": ("v_pack_b32_f16 v3, neg(v1), v2", 0xAAAA3C00, 0xBBBB4000, 0, 0x4000BC00),
88 "v_pack_b32_f16_neg_hi_sel": ("v_pack_b32_f16 v3, v1, neg(v2) op_sel:[0,1,0]", 0xAAAA3C00, 0x4000BBBB, 0, 88 "v_pack_b32_f16_neg_hi_sel": ("v_pack_b32_f16 v3, v1, neg(v2) op_sel:[0,1,0]", 0xAAAA3C00, 0x4000BBBB, 0,
89 0xC0003C00), 89 0xC0003C00),
90 # `abs` is the ISA's sign clear (|S|), applied before `neg`; it has no hardware run of this instruction yet.
91 "v_pack_b32_f16_abs_lo": ("v_pack_b32_f16 v3, abs(v1), v2", 0xAAAABC00, 0xBBBB4000, 0, 0x40003C00),
92 "v_pack_b32_f16_abs_snan": ("v_pack_b32_f16 v3, abs(v1), v2", 0xAAAAFC01, 0xBBBB4000, 0, 0x40007C01),
93 "v_pack_b32_f16_neg_abs": ("v_pack_b32_f16 v3, -abs(v1), v2", 0xAAAA3C00, 0xBBBB4000, 0, 0x4000BC00),
90 # 16-bit float add keeps the other half of the destination (GFX10 partial write; see docs/design.md). 94 # 16-bit float add keeps the other half of the destination (GFX10 partial write; see docs/design.md).
91 # These pin the translator's keep; they do not reproduce the AMD driver quirk in valu_fuzz f16 95 # These pin the translator's keep; they do not reproduce the AMD driver quirk in valu_fuzz f16
92 # seed 3 programme 38, where the same keep is lost on the GPU (driver 26.11.1, RX 9070). 96 # seed 3 programme 38, where the same keep is lost on the GPU (driver 26.11.1, RX 9070).
diff --git a/tests/test_vk_subgroup_info.py b/tests/test_vk_subgroup_info.py
index 45f90e0b9..d8ca4ed0f 100644
--- a/tests/test_vk_subgroup_info.py
+++ b/tests/test_vk_subgroup_info.py
@@ -66,6 +66,8 @@ class FakeDevice:
66 ) 66 )
67 fragment_shader_barycentric: bool = True 67 fragment_shader_barycentric: bool = True
68 driver_id: int = 1 # VK_DRIVER_ID_AMD_PROPRIETARY 68 driver_id: int = 1 # VK_DRIVER_ID_AMD_PROPRIETARY
69 vendor_id: int = 0
70 device_id: int = 0
69 71
70 72
71class FakeVulkan: 73class FakeVulkan:
@@ -159,6 +161,8 @@ class FakeVulkan:
159 base = addr + 16 161 base = addr + 16
160 ctypes.c_uint32.from_address(base + vk_info.PROPS_API_VERSION).value = dev.api_version 162 ctypes.c_uint32.from_address(base + vk_info.PROPS_API_VERSION).value = dev.api_version
161 ctypes.c_uint32.from_address(base + vk_info.PROPS_DEVICE_TYPE).value = dev.device_type 163 ctypes.c_uint32.from_address(base + vk_info.PROPS_DEVICE_TYPE).value = dev.device_type
164 ctypes.c_uint32.from_address(base + vk_info.PROPS_VENDOR_ID).value = dev.vendor_id
165 ctypes.c_uint32.from_address(base + vk_info.PROPS_DEVICE_ID).value = dev.device_id
162 raw_name = dev.name.encode("utf-8") if isinstance(dev.name, str) else dev.name 166 raw_name = dev.name.encode("utf-8") if isinstance(dev.name, str) else dev.name
163 name_bytes = raw_name[:256].ljust(256, b"\x00") 167 name_bytes = raw_name[:256].ljust(256, b"\x00")
164 ctypes.memmove(base + vk_info.PROPS_DEVICE_NAME, name_bytes, 256) 168 ctypes.memmove(base + vk_info.PROPS_DEVICE_NAME, name_bytes, 256)
@@ -521,6 +525,67 @@ class QueryTest(unittest.TestCase):
521 self.assertEqual(res["device"], expected_name) 525 self.assertEqual(res["device"], expected_name)
522 self.assertEqual(vk.destroyed_instances, [FakeVulkan.INSTANCE_HANDLE]) 526 self.assertEqual(vk.destroyed_instances, [FakeVulkan.INSTANCE_HANDLE])
523 527
528 def test_leonida_vk_device_filters_case_insensitively_and_fails_on_no_match(self):
529 igpu = FakeDevice(
530 name="AMD Radeon(TM) 780M Graphics",
531 device_type=1,
532 subgroup_size=64,
533 min_subgroup_size=32,
534 max_subgroup_size=64,
535 )
536 dgpu = FakeDevice(
537 name="NVIDIA GeForce RTX 4070",
538 device_type=vk_info.VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU,
539 subgroup_size=32,
540 min_subgroup_size=32,
541 max_subgroup_size=32,
542 )
543 other_dgpu = FakeDevice(
544 name="AMD Radeon RX 7900 XTX",
545 device_type=vk_info.VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU,
546 subgroup_size=64,
547 min_subgroup_size=32,
548 max_subgroup_size=64,
549 )
550 old_match = FakeDevice(
551 name="Legacy Radeon 1.2",
552 api_version=(1 << 22) | (2 << 12),
553 )
554
555 # Unset or empty selects the last discrete GPU as usual.
556 for empty in ("",):
557 with mock.patch.dict(vk_info.os.environ, {"LEONIDA_VK_DEVICE": empty}):
558 res, _ = self._run_query(igpu, dgpu)
559 self.assertEqual(res["device"], "NVIDIA GeForce RTX 4070")
560 self.assertFalse(res["native64"])
561
562 # Case-insensitive substring can select the integrated GPU over a later discrete GPU.
563 for filt in ("780m", "RADEON(tm) 780M", "amd radeon"):
564 with self.subTest(filter=filt), mock.patch.dict(vk_info.os.environ, {"LEONIDA_VK_DEVICE": filt}):
565 res, vk = self._run_query(igpu, dgpu)
566 self.assertEqual(res["device"], "AMD Radeon(TM) 780M Graphics")
567 self.assertTrue(res["native64"])
568 # Non-matching discrete GPU was skipped before feature/queue queries.
569 self.assertEqual(vk.features_calls, [vk._device_handles[0]])
570 self.assertEqual(vk.queue_calls, [vk._device_handles[0], vk._device_handles[0]])
571
572 # Among multiple matching devices, the runtime's discrete/last-discrete rule still applies.
573 with mock.patch.dict(vk_info.os.environ, {"LEONIDA_VK_DEVICE": "radeon"}):
574 res, _ = self._run_query(igpu, dgpu, other_dgpu)
575 self.assertEqual(res["device"], "AMD Radeon RX 7900 XTX")
576 with mock.patch.dict(vk_info.os.environ, {"LEONIDA_VK_DEVICE": "geforce"}):
577 res, _ = self._run_query(igpu, dgpu, other_dgpu)
578 self.assertEqual(res["device"], "NVIDIA GeForce RTX 4070")
579
580 # A filter that matches no device (or only an unsuitable device) raises RuntimeError and destroys the instance.
581 for filt, devs in (("nomatch", (igpu, dgpu)), ("legacy", (old_match, dgpu))):
582 with self.subTest(no_match=filt), mock.patch.dict(vk_info.os.environ, {"LEONIDA_VK_DEVICE": filt}):
583 vk = FakeVulkan(devices=devs)
584 with mock.patch.object(vk_info, "load_vulkan", return_value=vk):
585 with self.assertRaisesRegex(RuntimeError, rf"LEONIDA_VK_DEVICE={filt}"):
586 vk_info.query()
587 self.assertEqual(vk.destroyed_instances, [FakeVulkan.INSTANCE_HANDLE])
588
524 def test_native64_conditions_and_boundaries(self): 589 def test_native64_conditions_and_boundaries(self):
525 both = vk_info.VK_SHADER_STAGE_COMPUTE_BIT | vk_info.VK_SHADER_STAGE_MESH_BIT_EXT 590 both = vk_info.VK_SHADER_STAGE_COMPUTE_BIT | vk_info.VK_SHADER_STAGE_MESH_BIT_EXT
526 cases = [ 591 cases = [
@@ -559,6 +624,10 @@ class QueryTest(unittest.TestCase):
559 "mesh_in_supported_stages": True, 624 "mesh_in_supported_stages": True,
560 "native64": want_native64, 625 "native64": want_native64,
561 "per_vertex_inputs": True, 626 "per_vertex_inputs": True,
627 "vendor_id": 0,
628 "device_id": 0,
629 "driver_id": 1,
630 "rdna2_amd_windows": False,
562 }) 631 })
563 632
564 def test_per_vertex_inputs(self): 633 def test_per_vertex_inputs(self):
@@ -569,6 +638,33 @@ class QueryTest(unittest.TestCase):
569 res, _vk = self._run_query(FakeDevice(fragment_shader_barycentric=bary, driver_id=driver)) 638 res, _vk = self._run_query(FakeDevice(fragment_shader_barycentric=bary, driver_id=driver))
570 self.assertIs(res["per_vertex_inputs"], want) 639 self.assertIs(res["per_vertex_inputs"], want)
571 640
641 def test_rdna2_amd_windows(self):
642 """#857: RDNA2 by PCI device ID, and only under AMD's proprietary driver (RADV takes the same modules)."""
643 amd, radv = vk_info.VK_DRIVER_ID_AMD_PROPRIETARY, 3
644 cases = (("rx6700", 0x1002, 0x73DF, amd, True), ("rx6800", 0x1002, 0x73BF, amd, True),
645 ("navi24", 0x1002, 0x743F, amd, True), ("granite_ridge_igpu", 0x1002, 0x13C0, amd, True),
646 ("raphael_igpu", 0x1002, 0x164E, amd, True), ("rx6700_radv", 0x1002, 0x73DF, radv, False),
647 ("rdna3_7900xtx", 0x1002, 0x744C, amd, False), ("rdna4_9070xt", 0x1002, 0x7550, amd, False),
648 ("rdna3_780m", 0x1002, 0x15BF, amd, False), ("nvidia_same_id", 0x10DE, 0x73DF, 4, False))
649 for label, vendor, device, driver, want in cases:
650 with self.subTest(case=label):
651 self.assertIs(vk_info.rdna2_amd_windows(vendor, device, driver), want)
652 res, _vk = self._run_query(FakeDevice(vendor_id=vendor, device_id=device, driver_id=driver))
653 self.assertEqual((res["vendor_id"], res["device_id"], res["driver_id"]), (vendor, device, driver))
654 self.assertIs(res["rdna2_amd_windows"], want)
655
656 def test_rdna2_answer_is_for_the_runtime_gpu(self):
657 """An Intel iGPU next to an RX 6700: the runtime takes the discrete card, and so does the answer."""
658 intel = FakeDevice(name="Intel iGPU", device_type=1, vendor_id=0x8086, device_id=0xA780, driver_id=5,
659 min_subgroup_size=8, max_subgroup_size=32)
660 rx = FakeDevice(name="AMD Radeon RX 6700", vendor_id=0x1002, device_id=0x73DF)
661 for devs in ((intel, rx), (rx, intel)):
662 with self.subTest(order=[d.name for d in devs]):
663 res, _vk = self._run_query(*devs)
664 self.assertEqual(res["device"], "AMD Radeon RX 6700")
665 self.assertTrue(res["rdna2_amd_windows"])
666 self.assertTrue(res["native64"])
667
572 def test_native64_uses_default_size_without_required_mesh_stage(self): 668 def test_native64_uses_default_size_without_required_mesh_stage(self):
573 dev = FakeDevice( 669 dev = FakeDevice(
574 subgroup_size=64, 670 subgroup_size=64,
diff --git a/tests/test_world_index.py b/tests/test_world_index.py
index a5e873857..93ca58e68 100644
--- a/tests/test_world_index.py
+++ b/tests/test_world_index.py
@@ -4,6 +4,7 @@
4""" 4"""
5import contextlib 5import contextlib
6import csv 6import csv
7import errno
7import importlib.util 8import importlib.util
8import io 9import io
9import json 10import json
@@ -13,6 +14,7 @@ import sys
13import tempfile 14import tempfile
14import unittest 15import unittest
15import zlib 16import zlib
17from unittest import mock
16 18
17ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) 19ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
18 20
@@ -351,9 +353,20 @@ class WorldIndexTest(unittest.TestCase):
351 self.assert_report_collision([source, "--out", upper, "--csv", lower], 353 self.assert_report_collision([source, "--out", upper, "--csv", lower],
352 "--out and --csv must use different paths") 354 "--out and --csv must use different paths")
353 self.assertEqual(os.listdir(folder), []) 355 self.assertEqual(os.listdir(folder), [])
354 accent = os.path.join(folder, "café.json") # composed é 356 # Case folding and Unicode normalization are separate filesystem behaviors.
355 self.assert_report_collision([source, "--out", accent, "--csv", os.path.join(folder, "CAFÉ.json")], 357 composed = os.path.join(folder, "caf\u00e9.json")
356 "--out and --csv must use different paths") 358 decomposed = os.path.join(folder, "cafe\u0301.json")
359 with open(composed, "wb"):
360 pass
361 aliases = os.path.exists(decomposed)
362 os.unlink(composed)
363 reports = [source, "--out", composed, "--csv", decomposed]
364 if aliases:
365 self.assert_report_collision(reports, "--out and --csv must use different paths")
366 self.assertEqual(os.listdir(folder), [])
367 else:
368 self.assertEqual(WI.main(reports), 0)
369 self.assertFalse(os.path.samefile(composed, decomposed))
357 else: 370 else:
358 self.assertEqual(WI.main([source, "--out", upper, "--csv", lower]), 0) 371 self.assertEqual(WI.main([source, "--out", upper, "--csv", lower]), 0)
359 with open(upper, encoding="utf-8") as f: 372 with open(upper, encoding="utf-8") as f:
@@ -436,6 +449,34 @@ class WorldIndexTest(unittest.TestCase):
436 with open(entities, "rb") as f: 449 with open(entities, "rb") as f:
437 self.assertEqual(f.read(), previous) 450 self.assertEqual(f.read(), previous)
438 451
452 def test_failed_directory_walk_keeps_existing_reports(self):
453 carve = os.path.join(self.dir, "carve")
454 blocked = os.path.join(carve, "unreadable")
455 os.makedirs(blocked)
456 with open(os.path.join(carve, "resource.bin"), "wb") as f:
457 f.write(make_resource())
458 summary = os.path.join(self.dir, "summary.json")
459 entities = os.path.join(self.dir, "entities.jsonl")
460 previous = b'{"previous":true}\n'
461 for report in (summary, entities):
462 with open(report, "wb") as f:
463 f.write(previous)
464
465 scandir = os.scandir
466
467 def scan(path):
468 if path == blocked:
469 raise PermissionError(errno.EACCES, "permission denied", blocked)
470 return scandir(path)
471
472 err = io.StringIO()
473 with mock.patch.object(WI.os, "scandir", side_effect=scan), contextlib.redirect_stderr(err):
474 self.assertEqual(WI.main([carve, "--out", summary, "--entities-out", entities]), 2)
475 self.assertIn("unreadable", err.getvalue())
476 for report in (summary, entities):
477 with open(report, "rb") as f:
478 self.assertEqual(f.read(), previous)
479
439 def test_summary_write_failure_keeps_existing_placement_report(self): 480 def test_summary_write_failure_keeps_existing_placement_report(self):
440 source = os.path.join(self.dir, "resource.bin") 481 source = os.path.join(self.dir, "resource.bin")
441 with open(source, "wb") as f: 482 with open(source, "wb") as f:
@@ -568,6 +609,22 @@ class WorldIndexTest(unittest.TestCase):
568 rows, _ = WI.scan_path(self.carve([blob[:0x150], blob[0x150:]], gap=0x10)) 609 rows, _ = WI.scan_path(self.carve([blob[:0x150], blob[0x150:]], gap=0x10))
569 self.assertEqual(rows, []) 610 self.assertEqual(rows, [])
570 611
612 def test_carved_file_inflate_cap_matches_directory_scan(self):
613 resource = make_resource()
614 path = os.path.join(self.dir, "sample.bin")
615 with open(path, "wb") as f:
616 f.write(resource)
617
618 for source in (path, self.dir):
619 for cap, expected in ((len(resource) - 1, 0), (len(resource), 1)):
620 with self.subTest(source=source, cap=cap):
621 entities = []
622 rows, stats = WI.scan_path(source, max_inflate=cap, collect=entities)
623 self.assertEqual(len(rows), expected)
624 self.assertEqual(len(entities), expected)
625 self.assertEqual(stats["files"], expected)
626 self.assertEqual(stats["scanned_bytes"], expected * len(resource))
627
571 def test_directory_inflate_cap_does_not_exclude_large_archives(self): 628 def test_directory_inflate_cap_does_not_exclude_large_archives(self):
572 resource = make_resource() 629 resource = make_resource()
573 cap = len(resource) 630 cap = len(resource)
diff --git a/tools/anim_index.py b/tools/anim_index.py
index e950c0461..29d590685 100644
--- a/tools/anim_index.py
+++ b/tools/anim_index.py
@@ -458,7 +458,7 @@ def write_output(path, rows, summary):
458 json.dump({"summary": summary, "files": rows}, f, indent=1) 458 json.dump({"summary": summary, "files": rows}, f, indent=1)
459 return 459 return
460 with open(path, "w", encoding="utf-8", newline="") as f: 460 with open(path, "w", encoding="utf-8", newline="") as f:
461 w = csv.writer(f) 461 w = csv.writer(f, lineterminator="\n")
462 w.writerow(COLUMNS) 462 w.writerow(COLUMNS)
463 for r in rows: 463 for r in rows:
464 w.writerow([f"0x{r['offset']:x}" if i == 0 else ("" if r[c] is None else r[c]) 464 w.writerow([f"0x{r['offset']:x}" if i == 0 else ("" if r[c] is None else r[c])
diff --git a/tools/anim_rigs.py b/tools/anim_rigs.py
new file mode 100644
index 000000000..40afdc437
--- /dev/null
+++ b/tools/anim_rigs.py
@@ -0,0 +1,172 @@
1"""Read the rig dictionaries in anim.rpf and join the RBF0 rig-set manager's entries to them (ASSET-20).
2
3 python -I tools/anim_rigs.py <package>\\anim.rpf <work>\\anim-rigs.json [--rigs <work>\\rigs.json]
4
5A rig dictionary has the clip dictionary's root layout (docs/animation.md, "Clip dictionaries are RAGE
6resources") with `RIG` + a version byte at +0x70 instead of the pack array. Its map is keyed by `joaat32` of a rig
7path. Each value points at +0x20 to a `RIG` block, which holds tables of 8-byte `(hash, word)` items. `--rigs`
8takes the JSON `anim_index.py --rigs` writes and resolves every rig-set entry (source = rig dictionary name,
9rig = key). The output holds counts and one row per rig dictionary, no item values.
10"""
11import argparse
12import collections
13import json
14import mmap
15import os
16import struct
17import sys
18import zlib
19
20sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
21import anim_clips # noqa: E402
22import anim_index # noqa: E402
23
24SYSTEM = anim_clips.SYSTEM
25MAGIC = b"RIG"
26
27
28def is_rig_dictionary(data):
29 return len(data) >= 0x78 and data[0x70:0x73] == MAGIC
30
31
32def block_tables(s, at):
33 """Tables of a `RIG` block at page offset `at`: `RIG` + u8 version, u32 length of what follows, then tables
34 `{u32 kind hash; u32 size = 0xC + 8 * count; u32 count; u32 word}` + count × `{u32 hash; u32 word}`, with other
35 bytes between them. Returns (version, length, [(kind, count)])."""
36 if s.d[at:at + 3] != MAGIC:
37 raise anim_clips.DecodeError(f"no RIG block at 0x{at:x}")
38 version, length = s.d[at + 3], s.u32(at + 4)
39 end = min(len(s.d), at + 8 + length)
40 o, tables = at + 8, []
41 while o + 16 <= end:
42 kind, size, count, _word = struct.unpack_from("<4I", s.d, o)
43 if 0 < count < 4096 and size == 0xC + 8 * count and o + 16 + 8 * count <= end:
44 tables.append((kind, count))
45 o += 16 + 8 * count
46 else:
47 o += 4
48 return version, length, tables
49
50
51def parse_rig_dictionary(s):
52 """Root: +0x38 name, +0x48 map (key = joaat32(rig path), high half 0), +0x68 joaat32(name), +0x70 `RIG`."""
53 d = {"name": s.string(0x38), "hash": s.u32(0x68), "version": s.d[0x73], "entries": []}
54 for key, value in s.atmap(0x48):
55 if value is None:
56 continue
57 block = s.ptr(value + 0x20)
58 e = {"key": key & 0xFFFFFFFF, "key_high": key >> 32, "block": block}
59 if block is not None:
60 e["block_version"], e["block_length"], e["tables"] = block_tables(s, block)
61 d["entries"].append(e)
62 return d
63
64
65def _read(path, segments):
66 with open(path, "rb") as fh:
67 data = b""
68 for off, stored, raw in segments:
69 fh.seek(off)
70 data += fh.read(stored) if raw else zlib.decompressobj().decompress(fh.read(stored))
71 return data
72
73
74def scan(path, start=None, limit=None):
75 rows, walk = anim_index.scan_rpf(path, start, limit)
76 with open(path, "rb") as fh, mmap.mmap(fh.fileno(), 0, access=mmap.ACCESS_READ) as m:
77 groups, _unresolved, _gaps = anim_clips.group(m, rows)
78 stats, dicts = collections.Counter(), []
79 for _i, parts in groups:
80 segments = [anim_clips.segment(rows, k) for k in parts]
81 with open(path, "rb") as fh:
82 fh.seek(segments[0][0])
83 head = fh.read(segments[0][1])
84 first = head if segments[0][2] else zlib.decompressobj().decompress(head, 0x80)
85 if not is_rig_dictionary(first):
86 continue
87 s = anim_clips.System(_read(path, segments))
88 try:
89 d = parse_rig_dictionary(s)
90 except (anim_clips.DecodeError, struct.error) as e:
91 stats["rig_dictionaries_unparsed"] += 1
92 dicts.append({"offset": segments[0][0], "error": str(e)[:120]})
93 continue
94 d["offset"], d["streams"], d["system_bytes"] = segments[0][0], len(segments), len(s.d)
95 dicts.append(d)
96 stats["rig_dictionaries"] += 1
97 stats["rig_dictionary_hash_matches_name"] += d["name"] is not None and anim_index.joaat32(d["name"]) == d["hash"]
98 stats[f"rig_dictionary_version:{d['version']}"] += 1
99 for e in d["entries"]:
100 stats["entries"] += 1
101 stats["entries_key_high_zero"] += e["key_high"] == 0
102 if e["block"] is None:
103 stats["entries_without_block"] += 1
104 continue
105 stats["entries_with_block"] += 1
106 stats[f"block_version:{e['block_version']}"] += 1
107 stats["tables"] += len(e["tables"])
108 for kind, count in e["tables"]:
109 stats[f"table_kind:0x{kind:08x}"] += 1
110 stats[f"table_items:0x{kind:08x}"] += count
111 return dicts, {"streams": walk["files"], "dictionary_roots": len(groups), "counts": dict(sorted(stats.items()))}
112
113
114def join_rbf0(dicts, rigs):
115 """Resolve the rig-set manager's entries: source = rig dictionary name, joaat32(rig) = a key there."""
116 keys = {d["name"]: {e["key"] for e in d.get("entries", ())} for d in dicts if d.get("name")}
117 entries = [e for rs in rigs["rbf0"]["rigsets"] for e in rs["entries"]]
118 c = collections.Counter()
119 for e in entries:
120 h = anim_index.joaat32(e["rig"].lower())
121 if h in keys.get(e["source"], ()):
122 c["resolved"] += 1
123 elif any(h in k for k in keys.values()):
124 c["in_another_dictionary"] += 1
125 elif e["source"] not in keys:
126 c["no_dictionary_named_source"] += 1
127 else:
128 c["key_missing"] += 1
129 distinct = {(e["source"], e["rig"].lower()) for e in entries}
130 used = {(src, anim_index.joaat32(r)) for src, r in distinct}
131 c["distinct_rigs"] = len(distinct)
132 c["keys"] = sum(len(k) for k in keys.values())
133 c["keys_named_by_an_entry"] = sum(1 for name, k in keys.items() for h in k if (name, h) in used)
134 return dict(sorted(c.items()))
135
136
137def main():
138 ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])
139 ap.add_argument("archive", help="anim.rpf")
140 ap.add_argument("out", help="output .json (counts and one row per rig dictionary)")
141 ap.add_argument("--rigs", help="the JSON anim_index.py --rigs wrote, to resolve the RBF0 entries")
142 ap.add_argument("--start", type=anim_index.offset, help="first byte to scan (default: the RPF data start)")
143 ap.add_argument("--limit", type=anim_index.byte_count, help="number of bytes to scan")
144 a = ap.parse_args()
145 try:
146 dicts, summary = scan(a.archive, a.start, a.limit)
147 if a.rigs:
148 with open(a.rigs, encoding="utf-8") as f:
149 summary["rbf0_join"] = join_rbf0(dicts, json.load(f))
150 except ValueError as e:
151 sys.exit(f"{a.archive}: {e}")
152 except OSError as e:
153 sys.exit(f"{e.filename or a.archive}: {e.strerror or e}")
154 rows = [{k: v for k, v in d.items() if k != "entries"} | {"entries": len(d.get("entries", ()))} for d in dicts]
155 try:
156 with open(a.out, "w", encoding="utf-8") as f:
157 json.dump({"summary": summary, "rig_dictionaries": rows}, f, indent=1)
158 except OSError as e:
159 sys.exit(f"{a.out}: cannot write: {e.strerror or e}")
160 c = summary["counts"]
161 print(json.dumps({k: c.get(k, 0) for k in ("rig_dictionaries", "entries", "entries_with_block", "tables")}))
162 if "rbf0_join" in summary:
163 print(json.dumps(summary["rbf0_join"]))
164 return 0
165
166
167if __name__ == "__main__":
168 try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode
169 sys.stdout.reconfigure(errors="replace")
170 except (AttributeError, ValueError, OSError):
171 pass
172 sys.exit(main())
diff --git a/tools/awc_names.py b/tools/awc_names.py
index d3bc22135..ae8b345fe 100644
--- a/tools/awc_names.py
+++ b/tools/awc_names.py
@@ -321,7 +321,8 @@ def main(argv=None) -> int:
321 json.dump({"summary": summary, "streams": rows}, fh, indent=1) 321 json.dump({"summary": summary, "streams": rows}, fh, indent=1)
322 else: 322 else:
323 with open(a.out, "w", encoding="utf-8", newline="") as fh: 323 with open(a.out, "w", encoding="utf-8", newline="") as fh:
324 w = csv.DictWriter(fh, fieldnames=["source", "bank", "stream_id", "name", "rule"]) 324 w = csv.DictWriter(fh, fieldnames=["source", "bank", "stream_id", "name", "rule"],
325 lineterminator="\n")
325 w.writeheader() 326 w.writeheader()
326 w.writerows(rows) 327 w.writerows(rows)
327 except OSError as error: 328 except OSError as error:
diff --git a/tools/awc_opus.py b/tools/awc_opus.py
index cb96c55a9..5bad0dfbb 100644
--- a/tools/awc_opus.py
+++ b/tools/awc_opus.py
@@ -95,25 +95,47 @@ OPUS_PRE_SKIP = 312
95 95
96def write_ogg_opus(path: str, packets: list, channels: int, serial: int, length: int = 0, 96def write_ogg_opus(path: str, packets: list, channels: int, serial: int, length: int = 0,
97 pre_skip: int = OPUS_PRE_SKIP) -> int: 97 pre_skip: int = OPUS_PRE_SKIP) -> int:
98 """length: the stream's declared per-channel sample count at 48 kHz; the last page's granule position is 98 """length: the stream's declared per-channel sample count at 48 kHz; the EOS page's granule position is
99 trimmed to pre_skip + length (Ogg Opus granules count the pre-skip too), so decoders drop the encoder priming 99 trimmed to pre_skip + length (Ogg Opus granules count the pre-skip too), so decoders drop the encoder priming
100 at the start and stop at the exact end instead of the padded last frame.""" 100 at the start and stop at the exact end instead of the padded last frame.
101
102 The EOS page is emitted at the packet that first reaches pre_skip + length; any later packets are encoder
103 padding and are dropped. Clamping only the final page would make its granule smaller than the previous page's
104 when the trim point falls before that page starts, which is invalid Ogg and makes decoders keep the excess.
105 """
106 if not 0 <= pre_skip <= 0xFFFF:
107 raise ValueError(f"pre-skip must be 0..65535, got {pre_skip}")
108 if length < 0:
109 raise ValueError(f"length must be non-negative, got {length}")
110 total = sum(opus_samples(p) for p in packets)
111 if pre_skip > total:
112 pre_skip = total # a granule below the pre-skip makes the stream undecodable
101 head = b"OpusHead" + struct.pack("<BBHIhB", 1, channels, pre_skip, 48000, 0, 0) 113 head = b"OpusHead" + struct.pack("<BBHIhB", 1, channels, pre_skip, 48000, 0, 0)
102 tags = b"OpusTags" + struct.pack("<I", 8) + b"leonida " + struct.pack("<I", 0) 114 tags = b"OpusTags" + struct.pack("<I", 8) + b"leonida " + struct.pack("<I", 0)
103 out = [ogg_page(serial, 0, 0, [head], 0x02), ogg_page(serial, 1, 0, [tags], 0x00)] 115 out = [ogg_page(serial, 0, 0, [head], 0x02), ogg_page(serial, 1, 0, [tags], 0x00)]
104 seq, granule, pending, size = 2, 0, [], 0 116 seq, granule, pending, size = 2, 0, [], 0
117 target = pre_skip + length if length > 0 else None
118 written = 0
119 if not packets:
120 out.append(ogg_page(serial, 2, pre_skip, [], 0x04))
121 write_file(path, b"".join(out))
122 return pre_skip
105 for i, p in enumerate(packets): 123 for i, p in enumerate(packets):
106 pending.append(p) 124 pending.append(p)
107 granule += opus_samples(p) 125 granule += opus_samples(p)
108 size += len(p) 126 size += len(p)
127 reach = target is not None and granule >= target
109 last = i == len(packets) - 1 128 last = i == len(packets) - 1
110 if size > 4000 or len(pending) >= 50 or last: 129 if reach or size > 4000 or len(pending) >= 50 or last:
111 g = min(granule, pre_skip + length) if (last and 0 < length) else granule 130 g = target if reach else granule
112 out.append(ogg_page(serial, seq, g, pending, 0x04 if last else 0x00)) 131 out.append(ogg_page(serial, seq, g, pending, 0x04 if (reach or last) else 0x00))
132 written = g
113 seq += 1 133 seq += 1
114 pending, size = [], 0 134 pending, size = [], 0
135 if reach or last:
136 break
115 write_file(path, b"".join(out)) 137 write_file(path, b"".join(out))
116 return granule 138 return written
117 139
118 140
119def write_file(path: str, data: bytes) -> None: 141def write_file(path: str, data: bytes) -> None:
@@ -293,9 +315,12 @@ def export_bank(path: str, out_dir: str, pre_skip: int = OPUS_PRE_SKIP):
293 pk = opus_packets(d, at, size) 315 pk = opus_packets(d, at, size)
294 if pk: 316 if pk:
295 # +0x0C is the per-channel Opus frame count: equal to the +0 count for mono and 317 # +0x0C is the per-channel Opus frame count: equal to the +0 count for mono and
296 # half of it for stereo in all 7,451 measured streams. Fall back to dividing the 318 # half of it for stereo in all 7,451 measured streams. Use it only when it agrees
297 # interleaved count when a synthetic or malformed block leaves the field zero. 319 # with the interleaved +0 count; a synthetic or malformed block that disagrees
298 frames = s["frames"] or s["samples"] // max(1, s["channels"]) 320 # must not silently truncate the real audio.
321 frames = s["frames"]
322 if not frames or frames * s["channels"] != s["samples"]:
323 frames = s["samples"] // max(1, s["channels"])
299 write_ogg_opus(os.path.join(od, stem + ".ogg"), pk, s["channels"], s["id"], frames, 324 write_ogg_opus(os.path.join(od, stem + ".ogg"), pk, s["channels"], s["id"], frames,
300 pre_skip=pre_skip) 325 pre_skip=pre_skip)
301 counts["opus"] += 1 326 counts["opus"] += 1
diff --git a/tools/bink_index.py b/tools/bink_index.py
index 5b04ec769..2b8232834 100644
--- a/tools/bink_index.py
+++ b/tools/bink_index.py
@@ -276,7 +276,7 @@ def _flat(row, fields):
276def write_csv(path, rows, probe): 276def write_csv(path, rows, probe):
277 fields = BASE_FIELDS + (PROBE_FIELDS if probe else []) 277 fields = BASE_FIELDS + (PROBE_FIELDS if probe else [])
278 with open(path, "w", encoding="utf-8", newline="") as fh: 278 with open(path, "w", encoding="utf-8", newline="") as fh:
279 writer = csv.DictWriter(fh, fieldnames=fields) 279 writer = csv.DictWriter(fh, fieldnames=fields, lineterminator="\n")
280 writer.writeheader() 280 writer.writeheader()
281 for row in rows: 281 for row in rows:
282 writer.writerow(_flat(row, fields)) 282 writer.writerow(_flat(row, fields))
diff --git a/tools/bink_names.py b/tools/bink_names.py
index c8b2e763d..13bc9b12a 100644
--- a/tools/bink_names.py
+++ b/tools/bink_names.py
@@ -303,7 +303,7 @@ def write(out, rows, unmatched, summary):
303 json.dump({"summary": summary, "streams": rows, "unmatched_list_entries": unmatched}, fh, indent=1) 303 json.dump({"summary": summary, "streams": rows, "unmatched_list_entries": unmatched}, fh, indent=1)
304 else: 304 else:
305 with open(out, "w", encoding="utf-8", newline="") as fh: 305 with open(out, "w", encoding="utf-8", newline="") as fh:
306 w = csv.DictWriter(fh, fieldnames=FIELDS) 306 w = csv.DictWriter(fh, fieldnames=FIELDS, lineterminator="\n")
307 w.writeheader() 307 w.writeheader()
308 w.writerows(rows) 308 w.writerows(rows)
309 309
diff --git a/tools/bvh_index.py b/tools/bvh_index.py
index 94acc06ab..90bcd3bbc 100644
--- a/tools/bvh_index.py
+++ b/tools/bvh_index.py
@@ -363,7 +363,7 @@ def write_outputs(rows, summaries, out, csv_path):
363 "compression_params", "dehydrated", "chunked", "bounds_min", "bounds_max", 363 "compression_params", "dehydrated", "chunked", "bounds_min", "bounds_max",
364 "hash", "off_a0", "hi16", "lo16", "desc_word", "fragment"] 364 "hash", "off_a0", "hi16", "lo16", "desc_word", "fragment"]
365 with open(csv_path, "w", newline="", encoding="utf-8") as f: 365 with open(csv_path, "w", newline="", encoding="utf-8") as f:
366 w = csv.DictWriter(f, fieldnames=cols, extrasaction="ignore") 366 w = csv.DictWriter(f, fieldnames=cols, extrasaction="ignore", lineterminator="\n")
367 w.writeheader() 367 w.writeheader()
368 for r in rows: 368 for r in rows:
369 r = dict(r) 369 r = dict(r)
diff --git a/tools/cf_ref.py b/tools/cf_ref.py
index 6ceaac292..e8aa45565 100644
--- a/tools/cf_ref.py
+++ b/tools/cf_ref.py
@@ -101,10 +101,14 @@ class WaveMachine(cpu_ref.Machine):
101 return self.vcc & self.wmask 101 return self.vcc & self.wmask
102 if t == "vcc_lo": 102 if t == "vcc_lo":
103 return self.vcc & MASK32 103 return self.vcc & MASK32
104 if t == "vcc_hi":
105 return (self.vcc >> 32) & MASK32
104 if t == "exec": 106 if t == "exec":
105 return self.exec & self.wmask 107 return self.exec & self.wmask
106 if t == "exec_lo": 108 if t == "exec_lo":
107 return self.exec & MASK32 109 return self.exec & MASK32
110 if t == "exec_hi":
111 return 0 if self.wave == 32 else (self.exec >> 32) & MASK32
108 if t == "null": 112 if t == "null":
109 return 0 113 return 0
110 if k == "imm": 114 if k == "imm":
@@ -126,12 +130,19 @@ class WaveMachine(cpu_ref.Machine):
126 if t == "vcc_lo": 130 if t == "vcc_lo":
127 self.vcc = (self.vcc & ~MASK32 & MASK64) | (value & MASK32) 131 self.vcc = (self.vcc & ~MASK32 & MASK64) | (value & MASK32)
128 return 132 return
133 if t == "vcc_hi":
134 self.vcc = (self.vcc & MASK32) | ((value & MASK32) << 32)
135 return
129 if t == "exec": 136 if t == "exec":
130 self.exec = value & MASK64 137 self.exec = value & MASK64
131 return 138 return
132 if t == "exec_lo": 139 if t == "exec_lo":
133 self.exec = (self.exec & ~MASK32 & MASK64) | (value & MASK32) 140 self.exec = (self.exec & ~MASK32 & MASK64) | (value & MASK32)
134 return 141 return
142 if t == "exec_hi":
143 if self.wave == 64:
144 self.exec = (self.exec & MASK32) | ((value & MASK32) << 32)
145 return
135 if t == "null": 146 if t == "null":
136 return 147 return
137 raise Unsupported(dst.get("t", k), self.pc, "mask destination is not modelled") 148 raise Unsupported(dst.get("t", k), self.pc, "mask destination is not modelled")
@@ -201,12 +212,12 @@ class WaveMachine(cpu_ref.Machine):
201 return self._vcmp(ins, base) 212 return self._vcmp(ins, base)
202 if base.startswith("s_cmp_"): 213 if base.startswith("s_cmp_"):
203 self._expect(ins, 2) 214 self._expect(ins, 2)
204 _, cc, ty = base.split("_")[1:] 215 cc, _, ty = base[len("s_cmp_"):].partition("_")
216 if cc not in _CMP or ty not in ("u32", "i32"):
217 raise Unsupported(op, self.pc, "compare is not modelled")
205 x, y = self._int_src(a[0], 0, scalar=True), self._int_src(a[1], 0, scalar=True) 218 x, y = self._int_src(a[0], 0, scalar=True), self._int_src(a[1], 0, scalar=True)
206 if ty == "i32": 219 if ty == "i32":
207 x, y = _signed(x), _signed(y) 220 x, y = _signed(x), _signed(y)
208 elif ty != "u32":
209 raise Unsupported(op, self.pc, "compare type is not modelled")
210 self.scc = 1 if _CMP[cc](x, y) else 0 221 self.scc = 1 if _CMP[cc](x, y) else 0
211 return None 222 return None
212 if base.endswith("_saveexec_b32") or base.endswith("_saveexec_b64"): 223 if base.endswith("_saveexec_b32") or base.endswith("_saveexec_b64"):
@@ -227,9 +238,11 @@ class WaveMachine(cpu_ref.Machine):
227 self._expect(ins, 3) 238 self._expect(ins, 3)
228 mask_op = self._touches_mask(a) 239 mask_op = self._touches_mask(a)
229 if parts[2] == "b64" or mask_op: 240 if parts[2] == "b64" or mask_op:
230 self._check_width(base, op) 241 if parts[2] == "b64" or any(x["k"] == "special" and x["t"] in ("exec", "vcc") for x in a):
231 x, y = self._read_mask(a[1]), self._read_mask(a[2]) 242 self._check_width(base, op)
232 r = _SOP2_LOGIC[parts[1]](x, y, self.wmask) & self.wmask 243 mask = MASK64 if parts[2] == "b64" else MASK32
244 x, y = self._read_mask(a[1]) & mask, self._read_mask(a[2]) & mask
245 r = _SOP2_LOGIC[parts[1]](x, y, mask) & mask
233 self._write_mask(a[0], r) 246 self._write_mask(a[0], r)
234 else: 247 else:
235 x, y = self._int_src(a[1], 0, scalar=True), self._int_src(a[2], 0, scalar=True) 248 x, y = self._int_src(a[1], 0, scalar=True), self._int_src(a[2], 0, scalar=True)
diff --git a/tools/f32_fuzz.py b/tools/f32_fuzz.py
index 96f2f317a..7c23a58fd 100644
--- a/tools/f32_fuzz.py
+++ b/tools/f32_fuzz.py
@@ -465,6 +465,9 @@ ALL_OPS = {
465 "v_trunc_f32": _op("f", lambda x: rounding(x, "trunc")), 465 "v_trunc_f32": _op("f", lambda x: rounding(x, "trunc")),
466 "v_rndne_f32": _op("f", lambda x: rounding(x, "rne")), 466 "v_rndne_f32": _op("f", lambda x: rounding(x, "rne")),
467 "v_rcp_f32": _op("t", lambda x: transcendental("v_rcp_f32", x)), 467 "v_rcp_f32": _op("t", lambda x: transcendental("v_rcp_f32", x)),
468 # v_rcp_iflag_f32 is v_rcp_f32 without the FP exception flags: bit-identical on gfx1030 (design.md, "Denormal
469 # flush and special results"), so it shares the model; clamp and omod are what is new here (SHADER-136).
470 "v_rcp_iflag_f32": _op("t", lambda x: transcendental("v_rcp_f32", x)),
468 "v_rsq_f32": _op("t", lambda x: transcendental("v_rsq_f32", x)), 471 "v_rsq_f32": _op("t", lambda x: transcendental("v_rsq_f32", x)),
469 "v_sqrt_f32": _op("t", lambda x: transcendental("v_sqrt_f32", x)), 472 "v_sqrt_f32": _op("t", lambda x: transcendental("v_sqrt_f32", x)),
470 "v_exp_f32": _op("e", lambda x: transcendental("v_exp_f32", x)), 473 "v_exp_f32": _op("e", lambda x: transcendental("v_exp_f32", x)),
@@ -822,8 +825,8 @@ HW_PRIMARY = "flush"
822 825
823# Ops whose omod does not depend on the f32 denormal mode: the transcendental unit and the cube ops flush or select 826# Ops whose omod does not depend on the f32 denormal mode: the transcendental unit and the cube ops flush or select
824# whatever MODE says, and gfx1150 applies their omod with denormals kept (measured, 'omod' table). 827# whatever MODE says, and gfx1150 applies their omod with denormals kept (measured, 'omod' table).
825OMOD_IGNORES_DENORM_MODE = ("v_rcp_f32", "v_rsq_f32", "v_sqrt_f32", "v_exp_f32", "v_log_f32", "v_cubeid_f32", 828OMOD_IGNORES_DENORM_MODE = ("v_rcp_f32", "v_rcp_iflag_f32", "v_rsq_f32", "v_sqrt_f32", "v_exp_f32", "v_log_f32",
826 "v_cubesc_f32", "v_cubetc_f32", "v_cubema_f32") 829 "v_cubeid_f32", "v_cubesc_f32", "v_cubetc_f32", "v_cubema_f32")
827 830
828 831
829def omod_active(mode, op=None): 832def omod_active(mode, op=None):
@@ -1140,8 +1143,8 @@ FAMILIES = [
1140 ("f16 convert", ("v_cvt_f32_f16", "v_cvt_f16_f32", "v_cvt_pkrtz_f16_f32")), 1143 ("f16 convert", ("v_cvt_f32_f16", "v_cvt_f16_f32", "v_cvt_pkrtz_f16_f32")),
1141 ("v_cvt_pk_u8_f32", ("v_cvt_pk_u8_f32",)), 1144 ("v_cvt_pk_u8_f32", ("v_cvt_pk_u8_f32",)),
1142 ("floor / ceil / trunc / rndne", ("v_floor_f32", "v_ceil_f32", "v_trunc_f32", "v_rndne_f32")), 1145 ("floor / ceil / trunc / rndne", ("v_floor_f32", "v_ceil_f32", "v_trunc_f32", "v_rndne_f32")),
1143 ("rcp / rsq / sqrt / exp / log (exact inputs)", ("v_rcp_f32", "v_rsq_f32", "v_sqrt_f32", "v_exp_f32", 1146 ("rcp / rsq / sqrt / exp / log (exact inputs)", ("v_rcp_f32", "v_rcp_iflag_f32", "v_rsq_f32", "v_sqrt_f32",
1144 "v_log_f32")), 1147 "v_exp_f32", "v_log_f32")),
1145 ("cube", ("v_cubeid_f32", "v_cubesc_f32", "v_cubetc_f32", "v_cubema_f32")), 1148 ("cube", ("v_cubeid_f32", "v_cubesc_f32", "v_cubetc_f32", "v_cubema_f32")),
1146 ("v_cmp_class_f32", ("v_cmp_class_f32",)), 1149 ("v_cmp_class_f32", ("v_cmp_class_f32",)),
1147 ("min / max / med3 (hardware only)", HW_ONLY_OPS), 1150 ("min / max / med3 (hardware only)", HW_ONLY_OPS),
diff --git a/tools/fspx_unpack.py b/tools/fspx_unpack.py
index ea79e8001..6c18bb7b7 100644
--- a/tools/fspx_unpack.py
+++ b/tools/fspx_unpack.py
@@ -201,7 +201,11 @@ def main(argv=None) -> int:
201 stage = psv_stage(dxbc_parts(container)) if container else None 201 stage = psv_stage(dxbc_parts(container)) if container else None
202 meta["source"] = {"file": os.path.basename(path), "offset": off} 202 meta["source"] = {"file": os.path.basename(path), "offset": off}
203 entry = {"file": name + ".dxbc", "stage": "cs" if stage in (None, STAGE_COMPUTE) else f"psv{stage}", 203 entry = {"file": name + ".dxbc", "stage": "cs" if stage in (None, STAGE_COMPUTE) else f"psv{stage}",
204 "source_offset": off, "threads": meta["threads"], "wave32": meta["wave32"]} 204 "source_offset": off}
205 if "threads" in meta:
206 entry["threads"] = meta["threads"]
207 if "wave32" in meta:
208 entry["wave32"] = meta["wave32"]
205 if container: 209 if container:
206 with open(os.path.join(a.out, name + ".dxbc"), "wb") as f: 210 with open(os.path.join(a.out, name + ".dxbc"), "wb") as f:
207 f.write(container) 211 f.write(container)
diff --git a/tools/gamedata_index.py b/tools/gamedata_index.py
index f82413171..85f4f7023 100644
--- a/tools/gamedata_index.py
+++ b/tools/gamedata_index.py
@@ -41,6 +41,10 @@ XML_CLOSE_TAIL = re.compile(rb"</([A-Za-z_][\w.:-]*)>\s*$")
41# Tag-like text inside these cannot open or close an element. 41# Tag-like text inside these cannot open or close an element.
42XML_NON_TAG = re.compile(rb"<!--.*?-->|<!\[CDATA\[.*?\]\]>|<\?.*?\?>", re.S) 42XML_NON_TAG = re.compile(rb"<!--.*?-->|<!\[CDATA\[.*?\]\]>|<\?.*?\?>", re.S)
43MAGIC = {b"MHIU": "MHIU", b"PAMH": "PAMH", b"SPS1Z": "SPS1Z", b"RBF0": "RBF0", b"PSIN": "PSIN"} 43MAGIC = {b"MHIU": "MHIU", b"PAMH": "PAMH", b"SPS1Z": "SPS1Z", b"RBF0": "RBF0", b"PSIN": "PSIN"}
44# A resource whose page directory starts the stream carries "0DRP" at +16 (docs/animation.md, "0DRP page marker").
45# Its first 4 KiB can be over 95% printable, so without this check such a stream reads as text, and as XML when it
46# holds a "<": data.rpf has 337 of them and no XML at all (docs/gamedata.md, "Relationship to data.rpf").
47PAGE_MARKER, PAGE_MARKER_AT = b"0DRP", 16
44 48
45 49
46def printable(data: bytes) -> float: 50def printable(data: bytes) -> float:
@@ -123,6 +127,8 @@ def stream_kind(data: bytes, row: dict) -> str:
123 for magic in MAGIC: 127 for magic in MAGIC:
124 if data.startswith(magic): 128 if data.startswith(magic):
125 return "other" 129 return "other"
130 if data[PAGE_MARKER_AT:PAGE_MARKER_AT + len(PAGE_MARKER)] == PAGE_MARKER:
131 return "other"
126 if printable(data) > 0.95: 132 if printable(data) > 0.95:
127 return "text" 133 return "text"
128 return "binary" 134 return "binary"
@@ -132,6 +138,8 @@ def magic_name(data: bytes) -> str:
132 for magic, name in MAGIC.items(): 138 for magic, name in MAGIC.items():
133 if data.startswith(magic): 139 if data.startswith(magic):
134 return name 140 return name
141 if data[PAGE_MARKER_AT:PAGE_MARKER_AT + len(PAGE_MARKER)] == PAGE_MARKER:
142 return PAGE_MARKER.decode()
135 return "" 143 return ""
136 144
137 145
@@ -344,7 +352,7 @@ def write_csv(path: str, rows: list) -> None:
344 fields = ["offset", "offset_hex", "stored", "size", "type", "root", "detail", "chunks", 352 fields = ["offset", "offset_hex", "stored", "size", "type", "root", "detail", "chunks",
345 "complete", "header"] 353 "complete", "header"]
346 with open(path, "w", newline="", encoding="utf-8") as f: 354 with open(path, "w", newline="", encoding="utf-8") as f:
347 w = csv.DictWriter(f, fieldnames=fields) 355 w = csv.DictWriter(f, fieldnames=fields, lineterminator="\n")
348 w.writeheader() 356 w.writeheader()
349 w.writerows(rows) 357 w.writerows(rows)
350 358
diff --git a/tools/gamedata_xml.py b/tools/gamedata_xml.py
index ab91ae7da..02cea8dee 100644
--- a/tools/gamedata_xml.py
+++ b/tools/gamedata_xml.py
@@ -518,7 +518,7 @@ def write_csv(path: str, rows: list) -> None:
518 "parent_path", "parent_file", "xi_include", "type_attrs", "type_values", "content_values", 518 "parent_path", "parent_file", "xi_include", "type_attrs", "type_values", "content_values",
519 "error"] 519 "error"]
520 with open(path, "w", newline="", encoding="utf-8") as f: 520 with open(path, "w", newline="", encoding="utf-8") as f:
521 writer = csv.DictWriter(f, fieldnames=fields, extrasaction="ignore") 521 writer = csv.DictWriter(f, fieldnames=fields, extrasaction="ignore", lineterminator="\n")
522 writer.writeheader() 522 writer.writeheader()
523 for row in rows: 523 for row in rows:
524 out = dict(row) 524 out = dict(row)
diff --git a/tools/hashdict.py b/tools/hashdict.py
index cc8da2ace..acf668d79 100644
--- a/tools/hashdict.py
+++ b/tools/hashdict.py
@@ -6,6 +6,7 @@ When multiple names share a hash, the dictionary keeps the lexicographically fir
6 6
7Usage: 7Usage:
8 python -I hashdict.py <carve dir> --out hashes.json [--archives a,b] [--extra f1 f2 ...] [--min 3] 8 python -I hashdict.py <carve dir> --out hashes.json [--archives a,b] [--extra f1 f2 ...] [--min 3]
9 <carve dir> holds one folder per archive (<work>/carve), or is one archive's folder (<work>/carve/common).
9 python -I hashdict.py --lookup <hashes.json> 0x28cca8df ... 10 python -I hashdict.py --lookup <hashes.json> 0x28cca8df ...
10""" 11"""
11import argparse 12import argparse
@@ -91,11 +92,17 @@ def main():
91 what = "is not a folder" if os.path.exists(a.carve) else "does not exist" 92 what = "is not a folder" if os.path.exists(a.carve) else "does not exist"
92 print(f"ERROR: the carve folder {a.carve} {what}", file=sys.stderr) 93 print(f"ERROR: the carve folder {a.carve} {what}", file=sys.stderr)
93 return 2 94 return 2
95 # A folder with its own index.json is one archive's carve (<work>\carve\common, the folder the gamedata_*
96 # tools take): harvest it as that archive. Otherwise each subfolder with an index.json is one archive.
97 if os.path.isfile(os.path.join(a.carve, "index.json")):
98 archives = [(os.path.basename(os.path.normpath(os.path.abspath(a.carve))), a.carve)]
99 else:
100 archives = [(d, os.path.join(a.carve, d)) for d in sorted(os.listdir(a.carve))]
94 # The dictionary is written after the harvest: an --out naming one of the inputs would replace it. 101 # The dictionary is written after the harvest: an --out naming one of the inputs would replace it.
95 # samefile also catches a case-only difference on Windows and macOS's default volume. 102 # samefile also catches a case-only difference on Windows and macOS's default volume.
96 if os.path.exists(a.out): 103 if os.path.exists(a.out):
97 inputs = [x for x in a.extra if os.path.isfile(x)] 104 inputs = [x for x in a.extra if os.path.isfile(x)]
98 inputs += [os.path.join(a.carve, d, "index.json") for d in os.listdir(a.carve)] 105 inputs += [os.path.join(d, "index.json") for _, d in archives]
99 for x in inputs: 106 for x in inputs:
100 try: 107 try:
101 same = os.path.isfile(x) and os.path.samefile(a.out, x) 108 same = os.path.isfile(x) and os.path.samefile(a.out, x)
@@ -108,8 +115,8 @@ def main():
108 strings = set() 115 strings = set()
109 full = set(a.archives.split(",")) 116 full = set(a.archives.split(","))
110 missing = [] # carved blobs an index.json lists that can't be read: skipped, reported 117 missing = [] # carved blobs an index.json lists that can't be read: skipped, reported
111 for arch in sorted(os.listdir(a.carve)): 118 for arch, arch_dir in archives:
112 p = os.path.join(a.carve, arch, "index.json") 119 p = os.path.join(arch_dir, "index.json")
113 if not os.path.isfile(p): 120 if not os.path.isfile(p):
114 continue 121 continue
115 try: 122 try:
@@ -126,7 +133,7 @@ def main():
126 continue 133 continue
127 meta = r["head"].startswith("5053494e") or r["head"].startswith("52424630") 134 meta = r["head"].startswith("5053494e") or r["head"].startswith("52424630")
128 if arch in full or meta: 135 if arch in full or meta:
129 blob = os.path.join(a.carve, arch, f"{r['off']:012x}.bin") 136 blob = os.path.join(arch_dir, f"{r['off']:012x}.bin")
130 try: 137 try:
131 with open(blob, "rb") as f: 138 with open(blob, "rb") as f:
132 data = f.read() 139 data = f.read()
diff --git a/tools/imhex/rbf0.hexpat b/tools/imhex/rbf0.hexpat
new file mode 100644
index 000000000..8d311e099
--- /dev/null
+++ b/tools/imhex/rbf0.hexpat
@@ -0,0 +1,96 @@
1// ImHex pattern for one RBF0 resource: RAGE's binary form of an XML data file.
2//
3// The grammar is the one measured in docs/rbf0.md (section 3) and parsed by tools/rbf0_index.py (parse_rbf0):
4//
5// 0x00 "RBF0"
6// 0x04 FB FF 01 00 optional prologue. With it, integers and floats are 8 bytes ("wide"); without it they are
7// 4 bytes ("narrow") and the records start at 0x04. What the four bytes mean is not established;
8// the width follows them in every measured resource (docs/rbf0.md).
9// records, each a u8 descriptor index and a u8 type:
10// FF FF close the open element
11// FD FF text for the open element: u32 length, then that many bytes
12// index == descriptors so far a new descriptor: u16 name length, then the UTF-8 name, before the payload
13// type 0x00 open an element: u16 0, u16 0, u16 attribute count
14// type 0x10 integer 0x20 true 0x30 false 0x40 float 0x50 three floats
15// type 0x60 string: u16 length, then UTF-8 bytes
16// The stream has no length field and no section table: it ends where the root element closes, and the pattern
17// stops there.
18//
19// Open an inflated, joined resource, not the archive. A resource larger than 64 KiB is split over several zlib
20// streams, with no header on the continuations (docs/rbf0.md section 2); tools/rbf0_index.py joins them.
21
22#pragma description RBF0 record stream (binary XML, docs/rbf0.md)
23#pragma endian little
24#pragma magic [ 52 42 46 30 ] @ 0x00
25// The largest measured resource has 68,398 elements and about twice as many records.
26#pragma array_limit 4194304
27#pragma pattern_limit 33554432
28
29import std.mem;
30import std.io;
31
32bool g_wide = std::mem::size() >= 8 && std::mem::read_unsigned(0x04, 4) == 0x0001FFFB;
33u32 g_descriptors = 0;
34u32 g_depth = 0;
35bool g_done = false;
36
37struct Header {
38 char magic[4];
39 if (g_wide) {
40 u8 prologue[4] [[comment("FB FF 01 00: 8-byte integers and floats follow")]];
41 }
42};
43
44struct Record {
45 u8 index;
46 u8 type;
47 if (index == 0xFF) {
48 if (g_depth > 0) g_depth -= 1;
49 if (g_depth == 0) g_done = true;
50 } else if (index == 0xFD) {
51 u32 text_length;
52 char text[text_length];
53 } else {
54 if (index == g_descriptors) {
55 u16 name_length;
56 char name[name_length] [[comment("new descriptor")]];
57 g_descriptors += 1;
58 }
59 if (type == 0x00) {
60 u16 word0;
61 u16 word1;
62 u16 attribute_count;
63 g_depth += 1;
64 } else if (type == 0x10) {
65 if (g_wide) {
66 u64 value_int;
67 } else {
68 u32 value_int;
69 }
70 } else if (type == 0x40) {
71 if (g_wide) {
72 double value_float;
73 } else {
74 float value_float;
75 }
76 } else if (type == 0x50) {
77 if (g_wide) {
78 double value_vec3[3];
79 } else {
80 float value_vec3[3];
81 }
82 } else if (type == 0x60) {
83 u16 string_length;
84 char value_string[string_length];
85 }
86 }
87} [[format("format_record")]];
88
89fn format_record(Record r) {
90 if (r.index == 0xFF) return "close";
91 if (r.index == 0xFD) return "text";
92 return std::format("descriptor {} type 0x{:02X}", r.index, r.type);
93};
94
95Header header @ 0x00;
96Record records[while(!g_done && !std::mem::eof())] @ sizeof(header);
diff --git a/tools/imhex/rpf9.hexpat b/tools/imhex/rpf9.hexpat
new file mode 100644
index 000000000..0fbc1e450
--- /dev/null
+++ b/tools/imhex/rpf9.hexpat
@@ -0,0 +1,32 @@
1// ImHex pattern for the header of an RPF9 archive.
2//
3// Only measured fields are named (docs/rpf.md "What is readable"; docs/story.md "Signatures actually observed"):
4// 0x00 "9FPR" RPF9 stored little-endian
5// 0x04 data offset u32, where the data area (zlib streams laid end to end) starts
6// 0x08 u32 present in every header; meaning not established
7// 0x0C u32 present in every header; meaning not established
8// Everything from 0x10 to the data offset is the rest of the header and the table of contents. The TOC is
9// encrypted/packed: this pattern shows that range as opaque bytes and decodes nothing in it (no keys, no decryption).
10//
11// This describes the archive's own header at offset 0. Nested RPF9 headers occur inside the data area
12// (docs/story.md); their offsets are not covered here.
13
14#pragma description RPF9 archive header, opaque TOC and data area start (docs/rpf.md)
15#pragma endian little
16#pragma magic [ 39 46 50 52 ] @ 0x00
17
18import std.mem;
19import std.sys;
20
21struct Rpf9Header {
22 char magic[4] [[comment("\"9FPR\": RPF9 stored little-endian")]];
23 u32 data_offset [[comment("start of the data area (docs/rpf.md)")]];
24 u32 u32_08 [[comment("meaning not established")]];
25 u32 u32_0c [[comment("meaning not established")]];
26};
27
28Rpf9Header header @ 0x00;
29std::assert(header.data_offset >= sizeof(header) && header.data_offset <= std::mem::size(),
30 "the data offset is outside the file");
31u8 header_rest_and_toc[header.data_offset - sizeof(header)] @ sizeof(header)
32 [[comment("rest of the header and the table of contents: encrypted/packed, not decoded")]];
diff --git a/tools/int_hw_probe.py b/tools/int_hw_probe.py
new file mode 100644
index 000000000..2e94569bc
--- /dev/null
+++ b/tools/int_hw_probe.py
@@ -0,0 +1,767 @@
1r"""SHADER-137: RDNA2 hardware probe for the integer contract rows checked only on the CPU.
2
3Runs small, self-contained RDNA2 instruction sequences natively on an AMD GPU through tools/hw_oracle (wave32 and
4wave64) and compares every output word with Leonida's live translator (tools/rdna2spirv.py ->
5tests/semantic/spirv_mini_interp.py). Standard library only; no game files.
6
7Groups covered (each references its contract row in docs/design.md):
8 salu_absdiff_mulhi s_absdiff_i32, s_mul_hi_i32, s_mul_hi_u32 (SCC written vs kept)
9 salu_lshl_add s_lshl1..4_add_u32 (64-bit carry / shift-out into SCC)
10 salu_sext_flbit s_sext_i32_i8, s_sext_i32_i16, s_flbit_i32 (SCC kept)
11 salu_cmov_pack s_cmov_b32, s_cmovk_i32, s_pack_ll/lh/hh_b32_b16 (SCC kept)
12 salu_bfe_past31 s_bfe_u32, s_bfe_i32 with offset + width > 32 and width 0
13 salu_64_data s_brev_b64, s_bfe_u64/i64, s_bitset0/1_b64, s_flbit_i32_b64/i64
14 salu_quad_bitrep s_quadmask_b32/b64, s_bitreplicate_b64_b32
15 salu_64_bitwise s_and/or/xor/andn2/orn2/nand/nor/xnor/not_b64 on scalar data
16 salu_movrels s_movrels_b32, s_movrels_b64 (M0 indexing, SCC kept)
17 valu_add_nc_clamp v_add/sub/subrev_nc_u32, v_add/sub_nc_i32, v_add/sub_nc_u16 with clamp
18 valu_add_co_clamp v_add/sub/subrev_co[_ci]_u32 with clamp (saturation + carry)
19 valu_mad64 v_mad_u64_u32, v_mad_i64_i32 (sdst bit 64 and inactive EXEC lane)
20 valu_sad_lerp v_sad_u8, v_sad_hi_u8, v_sad_u16, v_sad_u32, v_msad_u8, v_lerp_u8
21 valu_qsad_mqsad v_qsad_pk_u16_u8, v_mqsad_pk_u16_u8, v_mqsad_u32_u8
22 valu_mul24_sh64 v_mul_hi_u32_u24, v_mul_hi_i32_i24, v_lshrrev_b64, v_ashrrev_i64
23 valu_mad16 v_mad_u16, v_mad_i16 (clamp, op_sel, kept half)
24 valu_cvt_16 v_cvt_f16_u16/i16, v_cvt_u16/i16_f16 (kept half, op_sel, NaN, inf)
25 valu_cvt_flr_rpi v_cvt_flr_i32_f32, v_cvt_rpi_i32_f32 (exact floor(x+0.5), signed NaN)
26 valu_cvt_pknorm v_cvt_pknorm_i16_f32, v_cvt_pknorm_u16_f32 (ties, saturation, NaN)
27
28Usage:
29 python -I tools/int_hw_probe.py # translator side only (CPU)
30 python -I tools/int_hw_probe.py --oracle hw # native AMD GPU only (wave32 + wave64)
31 python -I tools/int_hw_probe.py --oracle both # compare hardware vs translator
32 python -I tools/int_hw_probe.py --oracle both --strict # fail on known translator divergences too
33 python -I tools/int_hw_probe.py --self-test
34
35Exit codes:
36 0 all unexpected comparisons match (and wave32 == wave64 on hardware)
37 1 at least one unexpected mismatch, wave32/64 diff, or known divergence under --strict
38 2 bad CLI arguments or harness error
39 77 hardware oracle requested but unavailable on this machine
40"""
41import argparse
42import json
43import os
44import struct
45import sys
46import tempfile
47import warnings
48
49HERE = os.path.dirname(os.path.abspath(__file__))
50ROOT = os.path.dirname(HERE)
51sys.dont_write_bytecode = True
52for p in (HERE, os.path.join(ROOT, "tests", "semantic")):
53 if p not in sys.path:
54 sys.path.insert(0, p)
55
56import rdna2spirv # noqa: E402
57import spirv_mini_interp # noqa: E402
58
59STUB_DXBC = b"DXBC" + bytes(24) + struct.pack("<I", 0) + bytes(4)
60SENTINEL = 0x5A5A5A5A
61
62# Live translator divergences confirmed on AMD Radeon 680M (gfx1035, RDNA2, wave32 & wave64).
63# Each entry maps case.name -> (tag, expected_hw_words, reason).
64KNOWN_DIVERGENCES = {
65 "v_add_co_u32_clamp": (
66 "co_clamp_ignored",
67 [0xFFFFFFFF, 0x00000001, 0x00000000, 0x00000001],
68 "translator ignores VOP3 clamp on v_add_co_u32 / v_sub_co_u32",
69 ),
70 "v_subrev_co_u32_clamp": (
71 "co_clamp_ignored",
72 [0x00000000, 0x00000001, 0x00000000, 0x00000001],
73 "translator ignores VOP3 clamp on v_subrev_co_u32 / v_subrev_co_ci_u32",
74 ),
75 "v_add_co_ci_u32_clamp": (
76 "co_clamp_ignored",
77 [0xFFFFFFFF, 0x00000001, 0x00000000, 0x00000001],
78 "translator ignores VOP3 clamp on v_add_co_ci_u32 / v_sub_co_ci_u32",
79 ),
80 "v_cvt_rpi_precision": (
81 "cvt_rpi_exact_half",
82 [0x00000000, 0x00800001, 0x00FFFFFF, 0x00000000],
83 "hardware computes exact floor(x + 0.5); translator rounds x + 0.5 in binary32 first",
84 ),
85 "v_cvt_flr_rpi_nan_inf": (
86 "cvt_flr_rpi_nan_sign",
87 [0x7FFFFFFF, 0x80000000, 0x7FFFFFFF, 0x80000000],
88 "hardware saturates NaN by sign (+NaN -> 0x7fffffff, -NaN -> 0x80000000); translator gives 0",
89 ),
90}
91
92
93class Case:
94 """One self-contained 4-word probe. `body` leaves results in v8..v11 and must not clobber s[0:3] or v0.
95 For wave-size-dependent mask instructions, `{vcc}`, `{exec}`, `{smov}`, `{stmp}` expand to wave32/wave64 forms."""
96
97 __slots__ = ("group", "name", "body", "note")
98
99 def __init__(self, group, name, body, note=""):
100 self.group = group
101 self.name = name
102 self.body = tuple(body)
103 self.note = note
104
105 def lines(self, wave=32):
106 vcc = "vcc_lo" if wave == 32 else "vcc"
107 exc = "exec_lo" if wave == 32 else "exec"
108 smov = "s_mov_b32" if wave == 32 else "s_mov_b64"
109 stmp = "s14" if wave == 32 else "s[14:15]"
110 return [ln.format(vcc=vcc, exec=exc, smov=smov, stmp=stmp) for ln in self.body]
111
112
113def _scc_seed(val):
114 return "s_cmp_eq_u32 0, 0" if val else "s_cmp_eq_u32 0, 1"
115
116
117def _salu32_pair(group, name, setup, op_line, note=""):
118 """Run one 32-bit scalar op twice: once with SCC preset to 0 (v8=D, v9=SCC) and once with SCC preset to 1
119 (v10=D, v11=SCC), so 'SCC kept' and 'SCC written' are both directly observed."""
120 body = [
121 *setup, _scc_seed(0), op_line,
122 "s_cselect_b32 s30, 1, 0", "v_mov_b32 v8, s6", "v_mov_b32 v9, s30",
123 *setup, _scc_seed(1), op_line,
124 "s_cselect_b32 s30, 1, 0", "v_mov_b32 v10, s6", "v_mov_b32 v11, s30",
125 ]
126 return Case(group, name, body, note)
127
128
129def _salu64_case(group, name, setup, op_line, scc_in, note=""):
130 """Run one 64-bit scalar op with SCC preset to scc_in; output v8=s6 (lo), v9=s7 (hi), v10=SCC, v11=0."""
131 body = [
132 *setup, _scc_seed(scc_in), op_line,
133 "s_cselect_b32 s30, 1, 0",
134 "v_mov_b32 v8, s6", "v_mov_b32 v9, s7", "v_mov_b32 v10, s30", "v_mov_b32 v11, 0",
135 ]
136 return Case(group, name, body, note)
137
138
139def _valu4_case(group, name, body, note=""):
140 return Case(group, name, body, note)
141
142
143def build_cases():
144 cases = []
145
146 # 1. s_absdiff_i32, s_mul_hi_i32, s_mul_hi_u32 (docs/design.md)
147 cases += [
148 _salu32_pair("salu_absdiff_mulhi", "s_absdiff_basic",
149 ["s_mov_b32 s4, 10", "s_mov_b32 s5, 25"],
150 "s_absdiff_i32 s6, s4, s5", "|10 - 25| = 15, SCC=1"),
151 _salu32_pair("salu_absdiff_mulhi", "s_absdiff_equal",
152 ["s_mov_b32 s4, 0x80000000", "s_mov_b32 s5, 0x80000000"],
153 "s_absdiff_i32 s6, s4, s5", "equal -> 0, SCC=0"),
154 _salu32_pair("salu_absdiff_mulhi", "s_absdiff_wrap_max_min",
155 ["s_mov_b32 s4, 0x7fffffff", "s_mov_b32 s5, 0x80000000"],
156 "s_absdiff_i32 s6, s4, s5", "0x7fffffff - 0x80000000 wraps to -1 -> abs 1, SCC=1"),
157 _salu32_pair("salu_absdiff_mulhi", "s_absdiff_int_min",
158 ["s_mov_b32 s4, 0x80000000", "s_mov_b32 s5, 0"],
159 "s_absdiff_i32 s6, s4, s5", "diff = INT_MIN stays 0x80000000, SCC=1"),
160 _salu32_pair("salu_absdiff_mulhi", "s_mul_hi_i32_min_min",
161 ["s_mov_b32 s4, 0x80000000", "s_mov_b32 s5, 0x80000000"],
162 "s_mul_hi_i32 s6, s4, s5", "(-2^31)*(-2^31) >> 32 = 0x40000000, SCC kept"),
163 _salu32_pair("salu_absdiff_mulhi", "s_mul_hi_i32_neg_pos",
164 ["s_mov_b32 s4, 0xffffffff", "s_mov_b32 s5, 2"],
165 "s_mul_hi_i32 s6, s4, s5", "(-1)*2 >> 32 = 0xffffffff, SCC kept"),
166 _salu32_pair("salu_absdiff_mulhi", "s_mul_hi_u32_max_max",
167 ["s_mov_b32 s4, 0xffffffff", "s_mov_b32 s5, 0xffffffff"],
168 "s_mul_hi_u32 s6, s4, s5", "(2^32-1)^2 >> 32 = 0xfffffffe, SCC kept"),
169 ]
170
171 # 2. s_lshl1..4_add_u32 (64-bit shift-out + add carry into SCC)
172 for shift in (1, 2, 3, 4):
173 op = f"s_lshl{shift}_add_u32"
174 high_bit = 1 << (32 - shift)
175 cases += [
176 _salu32_pair("salu_lshl_add", f"{op}_no_carry",
177 ["s_mov_b32 s4, 0x00010000", "s_mov_b32 s5, 5"],
178 f"{op} s6, s4, s5", "no shift-out, no add carry -> SCC=0"),
179 _salu32_pair("salu_lshl_add", f"{op}_shift_out_only",
180 [f"s_mov_b32 s4, 0x{high_bit:08x}", "s_mov_b32 s5, 0"],
181 f"{op} s6, s4, s5", "bit shifted out of S0 with S1=0 -> D=0, SCC=1"),
182 _salu32_pair("salu_lshl_add", f"{op}_add_carry_only",
183 ["s_mov_b32 s4, 1", "s_mov_b32 s5, 0xffffffff"],
184 f"{op} s6, s4, s5", "add carry without shift-out -> SCC=1"),
185 ]
186
187 # 3. s_sext_i32_i8, s_sext_i32_i16, s_flbit_i32
188 cases += [
189 _salu32_pair("salu_sext_flbit", "s_sext_i8_neg",
190 ["s_mov_b32 s4, 0x12345680"], "s_sext_i32_i8 s6, s4", "0x80 -> 0xffffff80, SCC kept"),
191 _salu32_pair("salu_sext_flbit", "s_sext_i8_pos",
192 ["s_mov_b32 s4, 0xffffff7f"], "s_sext_i32_i8 s6, s4", "0x7f -> 0x0000007f, SCC kept"),
193 _salu32_pair("salu_sext_flbit", "s_sext_i16_neg",
194 ["s_mov_b32 s4, 0x00008001"], "s_sext_i32_i16 s6, s4", "0x8001 -> 0xffff8001, SCC kept"),
195 _salu32_pair("salu_sext_flbit", "s_sext_i16_pos",
196 ["s_mov_b32 s4, 0xffff7fff"], "s_sext_i32_i16 s6, s4", "0x7fff -> 0x00007fff, SCC kept"),
197 _salu32_pair("salu_sext_flbit", "s_flbit_i32_zero",
198 ["s_mov_b32 s4, 0"], "s_flbit_i32 s6, s4", "0 -> 0xffffffff, SCC kept"),
199 _salu32_pair("salu_sext_flbit", "s_flbit_i32_neg1",
200 ["s_mov_b32 s4, 0xffffffff"], "s_flbit_i32 s6, s4", "-1 -> 0xffffffff, SCC kept"),
201 _salu32_pair("salu_sext_flbit", "s_flbit_i32_pos1",
202 ["s_mov_b32 s4, 1"], "s_flbit_i32 s6, s4", "1 -> 30, SCC kept"),
203 _salu32_pair("salu_sext_flbit", "s_flbit_i32_neg16",
204 ["s_mov_b32 s4, 0xfffffff0"], "s_flbit_i32 s6, s4", "-16 -> 27, SCC kept"),
205 _salu32_pair("salu_sext_flbit", "s_flbit_i32_int_min",
206 ["s_mov_b32 s4, 0x80000000"], "s_flbit_i32 s6, s4", "INT_MIN -> 0, SCC kept"),
207 ]
208
209 # 4. s_cmov_b32, s_cmovk_i32, s_pack_ll/lh/hh_b32_b16
210 cases += [
211 _salu32_pair("salu_cmov_pack", "s_cmov_b32",
212 ["s_mov_b32 s4, 0x11223344", "s_mov_b32 s6, 0xaabbccdd"],
213 "s_cmov_b32 s6, s4", "SCC=0 keeps D, SCC=1 takes S0, SCC kept"),
214 _salu32_pair("salu_cmov_pack", "s_cmovk_i32_neg",
215 ["s_mov_b32 s6, 0x12345678"],
216 "s_cmovk_i32 s6, -300", "SCC=0 keeps D, SCC=1 sign-extends imm16, SCC kept"),
217 _salu32_pair("salu_cmov_pack", "s_pack_ll",
218 ["s_mov_b32 s4, 0x11112222", "s_mov_b32 s5, 0x33334444"],
219 "s_pack_ll_b32_b16 s6, s4, s5", "{S1.lo, S0.lo} = 0x44442222, SCC kept"),
220 _salu32_pair("salu_cmov_pack", "s_pack_lh",
221 ["s_mov_b32 s4, 0x11112222", "s_mov_b32 s5, 0x33334444"],
222 "s_pack_lh_b32_b16 s6, s4, s5", "{S1.hi, S0.lo} = 0x33332222, SCC kept"),
223 _salu32_pair("salu_cmov_pack", "s_pack_hh",
224 ["s_mov_b32 s4, 0x11112222", "s_mov_b32 s5, 0x33334444"],
225 "s_pack_hh_b32_b16 s6, s4, s5", "{S1.hi, S0.hi} = 0x33331111, SCC kept"),
226 ]
227
228 # 5. s_bfe_u32 / s_bfe_i32 past bit 31
229 cases += [
230 _salu32_pair("salu_bfe_past31", "s_bfe_i32_past31",
231 ["s_mov_b32 s4, 0xd2f90159", "s_mov_b32 s5, 0x7f001c"],
232 "s_bfe_i32 s6, s4, s5", "off=28 width=127 stops at bit 31 -> 0xfffffffd, SCC=1"),
233 _salu32_pair("salu_bfe_past31", "s_bfe_u32_past31",
234 ["s_mov_b32 s4, 0xd2f90159", "s_mov_b32 s5, 0xff7f001c"],
235 "s_bfe_u32 s6, s4, s5", "upper bits ignored, stops at bit 31 -> 0x0000000d, SCC=1"),
236 _salu32_pair("salu_bfe_past31", "s_bfe_i32_width0",
237 ["s_mov_b32 s4, 0xffffffff", "s_mov_b32 s5, 0x00000005"],
238 "s_bfe_i32 s6, s4, s5", "width=0 -> 0, SCC=0"),
239 ]
240
241 # 6. 64-bit scalar data ops (s_brev_b64, s_bfe_u64/i64, s_bitset0/1_b64, s_flbit_i32_b64/i64)
242 cases += [
243 _salu64_case("salu_64_data", "s_brev_b64_scc1",
244 ["s_mov_b32 s4, 0x80000001", "s_mov_b32 s5, 0x12345678"],
245 "s_brev_b64 s[6:7], s[4:5]", 1, "bit-reverse 64-bit pair, SCC kept"),
246 _salu64_case("salu_64_data", "s_bfe_u64_cross_past63",
247 ["s_mov_b32 s4, 0x12345678", "s_mov_b32 s5, 0xd2f90159", "s_mov_b32 s8, 0x7f003c"],
248 "s_bfe_u64 s[6:7], s[4:5], s8", 0, "off=60 width=127 stops at bit 63 -> 0xd, SCC=1"),
249 _salu64_case("salu_64_data", "s_bfe_i64_past63",
250 ["s_mov_b32 s4, 0x12345678", "s_mov_b32 s5, 0xd2f90159", "s_mov_b32 s8, 0x7f003c"],
251 "s_bfe_i64 s[6:7], s[4:5], s8", 0, "off=60 width=127 sign-extends 0xd -> -3, SCC=1"),
252 _salu64_case("salu_64_data", "s_bfe_u64_width0",
253 ["s_mov_b32 s4, 0xffffffff", "s_mov_b32 s5, 0xffffffff", "s_mov_b32 s8, 0x00000010"],
254 "s_bfe_u64 s[6:7], s[4:5], s8", 1, "width=0 -> 0, SCC=0"),
255 _salu64_case("salu_64_data", "s_bitset0_b64_hi",
256 ["s_mov_b32 s6, 0xffffffff", "s_mov_b32 s7, 0xffffffff", "s_mov_b32 s8, 63"],
257 "s_bitset0_b64 s[6:7], s8", 1, "clear bit 63, SCC kept"),
258 _salu64_case("salu_64_data", "s_bitset1_b64_mod64",
259 ["s_mov_b32 s6, 0", "s_mov_b32 s7, 0", "s_mov_b32 s8, 97"],
260 "s_bitset1_b64 s[6:7], s8", 0, "set bit 97 & 63 = 33 (hi bit 1), SCC kept"),
261 _salu32_pair("salu_64_data", "s_flbit_i32_b64_zero",
262 ["s_mov_b32 s4, 0", "s_mov_b32 s5, 0"],
263 "s_flbit_i32_b64 s6, s[4:5]", "0 -> -1, SCC kept"),
264 _salu32_pair("salu_64_data", "s_flbit_i32_b64_lo",
265 ["s_mov_b32 s4, 0x00010000", "s_mov_b32 s5, 0"],
266 "s_flbit_i32_b64 s6, s[4:5]", "bit 16 -> 47 leading zeros, SCC kept"),
267 _salu32_pair("salu_64_data", "s_flbit_i32_i64_neg",
268 ["s_mov_b32 s4, 0xfffffff0", "s_mov_b32 s5, 0xffffffff"],
269 "s_flbit_i32_i64 s6, s[4:5]", "-16 -> 59 sign bits, SCC kept"),
270 _salu32_pair("salu_64_data", "s_flbit_i32_i64_neg1",
271 ["s_mov_b32 s4, 0xffffffff", "s_mov_b32 s5, 0xffffffff"],
272 "s_flbit_i32_i64 s6, s[4:5]", "-1 -> -1, SCC kept"),
273 ]
274
275 # 7. s_quadmask_b32/b64, s_bitreplicate_b64_b32
276 cases += [
277 _salu32_pair("salu_quad_bitrep", "s_quadmask_b32_nz",
278 ["s_mov_b32 s4, 0x10080041"],
279 "s_quadmask_b32 s6, s4", "quads 0,1,4,7 set -> 0x93, SCC=1"),
280 _salu32_pair("salu_quad_bitrep", "s_quadmask_b32_zero",
281 ["s_mov_b32 s4, 0"],
282 "s_quadmask_b32 s6, s4", "0 -> 0, SCC=0"),
283 _salu64_case("salu_quad_bitrep", "s_quadmask_b64_hi",
284 ["s_mov_b32 s4, 0x00000000", "s_mov_b32 s5, 0x80000001"],
285 "s_quadmask_b64 s[6:7], s[4:5]", 0, "quads 8,15 -> lo=0x8100 hi=0, SCC=1"),
286 _salu64_case("salu_quad_bitrep", "s_bitreplicate_b64_b32",
287 ["s_mov_b32 s4, 0x80010005"],
288 "s_bitreplicate_b64_b32 s[6:7], s4", 1, "each bit doubled, SCC kept"),
289 ]
290
291 # 8. 64-bit scalar bitwise ops on scalar data
292 for op in ("s_and_b64", "s_or_b64", "s_xor_b64", "s_andn2_b64", "s_orn2_b64",
293 "s_nand_b64", "s_nor_b64", "s_xnor_b64"):
294 cases.append(_salu64_case(
295 "salu_64_bitwise", f"{op}_data",
296 ["s_mov_b32 s4, 0xf0f000ff", "s_mov_b32 s5, 0x12345678",
297 "s_mov_b32 s8, 0x0ff0ff00", "s_mov_b32 s9, 0x87654321"],
298 f"{op} s[6:7], s[4:5], s[8:9]", 0, f"{op} on 64-bit scalar data + SCC",
299 ))
300 cases.append(_salu64_case(
301 "salu_64_bitwise", "s_not_b64_all_ones",
302 ["s_mov_b32 s4, 0xffffffff", "s_mov_b32 s5, 0xffffffff"],
303 "s_not_b64 s[6:7], s[4:5]", 1, "~(-1) = 0, SCC=0",
304 ))
305
306 # 9. s_movrels_b32 / s_movrels_b64
307 cases += [
308 _salu32_pair("salu_movrels", "s_movrels_b32_m0_2",
309 ["s_mov_b32 s10, 0x11111111", "s_mov_b32 s11, 0x22222222",
310 "s_mov_b32 s12, 0x33333333", "s_mov_b32 m0, 2"],
311 "s_movrels_b32 s6, s10", "SGPR[10+2] = 0x33333333, SCC kept"),
312 _salu64_case("salu_movrels", "s_movrels_b64_m0_2",
313 ["s_mov_b32 s10, 0x11111111", "s_mov_b32 s11, 0x22222222",
314 "s_mov_b32 s12, 0x33333333", "s_mov_b32 s13, 0x44444444", "s_mov_b32 m0, 2"],
315 "s_movrels_b64 s[6:7], s[10:11]", 1, "SGPR[12:13], SCC kept"),
316 ]
317
318 # 10. Integer clamp on v_add/sub/subrev_nc_u32, v_add/sub_nc_i32, v_add/sub_nc_u16
319 cases += [
320 _valu4_case("valu_add_nc_clamp", "v_add_sub_nc_u32_clamp", [
321 "v_mov_b32 v1, 0xfffffff0", "v_mov_b32 v2, 0x30",
322 "v_add_nc_u32_e64 v8, v1, v2 clamp", # saturates to 0xffffffff
323 "v_sub_nc_u32_e64 v9, v2, v1 clamp", # saturates to 0
324 "v_subrev_nc_u32_e64 v10, v1, v2 clamp", # v2 - v1 -> saturates to 0
325 "v_subrev_nc_u32_e64 v11, v2, v1 clamp", # v1 - v2 = 0xffffffc0
326 ], "u32 nc add/sub/subrev with clamp"),
327 _valu4_case("valu_add_nc_clamp", "v_add_sub_nc_i32_clamp", [
328 "v_mov_b32 v1, 0x7ffffff0", "v_mov_b32 v2, 0x30",
329 "v_mov_b32 v3, 0x80000010", "v_mov_b32 v4, 0x30",
330 "v_add_nc_i32_e64 v8, v1, v2 clamp", # +overflow -> 0x7fffffff
331 "v_sub_nc_i32_e64 v9, v3, v4 clamp", # -overflow -> 0x80000000
332 "v_add_nc_i32_e64 v10, v3, v3 clamp", # neg+neg overflow -> 0x80000000
333 "v_sub_nc_i32_e64 v11, v1, v3 clamp", # pos-neg overflow -> 0x7fffffff
334 ], "i32 nc add/sub with clamp"),
335 _valu4_case("valu_add_nc_clamp", "v_add_sub_nc_u16_clamp", [
336 "v_mov_b32 v1, 0x1234fff0", "v_mov_b32 v2, 0x56780030",
337 f"v_mov_b32 v8, 0x{SENTINEL:08x}",
338 f"v_mov_b32 v9, 0x{SENTINEL:08x}",
339 f"v_mov_b32 v10, 0x{SENTINEL:08x}",
340 f"v_mov_b32 v11, 0x{SENTINEL:08x}",
341 "v_add_nc_u16_e64 v8, v1, v2 clamp", # lo saturates 0xffff, hi kept
342 "v_sub_nc_u16_e64 v9, v2, v1 clamp", # lo saturates 0x0000, hi kept
343 "v_add_nc_u16_e64 v10, v1, v2 op_sel:[0,0,1] clamp", # write hi saturates 0xffff, lo kept
344 "v_sub_nc_u16_e64 v11, v1, v2 op_sel:[1,1,0] clamp", # 0x1234 - 0x5678 -> 0x0000, hi kept
345 ], "u16 nc add/sub with clamp and op_sel (untouched half kept)"),
346 ]
347
348 # 11. v_add/sub/subrev_co[_ci]_u32 with clamp (known divergence: translator ignores clamp)
349 cases += [
350 _valu4_case("valu_add_co_clamp", "v_add_co_u32_clamp", [
351 "v_mov_b32 v1, 0xffffffff", "v_mov_b32 v2, 0xffffffff",
352 "v_add_co_u32 v8, {vcc}, v1, v2 clamp",
353 "v_cndmask_b32_e64 v9, 0, 1, {vcc}",
354 "v_mov_b32 v3, 5", "v_mov_b32 v4, 10",
355 "v_sub_co_u32 v10, {vcc}, v3, v4 clamp",
356 "v_cndmask_b32_e64 v11, 0, 1, {vcc}",
357 ], "v_add_co_u32 / v_sub_co_u32 clamp: hardware saturates D and reports real carry/borrow"),
358 _valu4_case("valu_add_co_clamp", "v_subrev_co_u32_clamp", [
359 "v_mov_b32 v1, 10", "v_mov_b32 v2, 5",
360 "v_subrev_co_u32 v8, {vcc}, v1, v2 clamp",
361 "v_cndmask_b32_e64 v9, 0, 1, {vcc}",
362 "v_mov_b32 v3, 0", "v_mov_b32 v4, 0",
363 "{smov} {vcc}, -1",
364 "v_subrev_co_ci_u32_e64 v10, {vcc}, v3, v4, {vcc} clamp",
365 "v_cndmask_b32_e64 v11, 0, 1, {vcc}",
366 ], "v_subrev_co_u32 / v_subrev_co_ci_u32 clamp: hardware saturates D to 0 and reports borrow=1"),
367 _valu4_case("valu_add_co_clamp", "v_add_co_ci_u32_clamp", [
368 "v_mov_b32 v1, 0xffffffff", "v_mov_b32 v2, 0",
369 "{smov} {vcc}, -1",
370 "v_add_co_ci_u32_e64 v8, {vcc}, v1, v2, {vcc} clamp",
371 "v_cndmask_b32_e64 v9, 0, 1, {vcc}",
372 "v_mov_b32 v3, 0", "v_mov_b32 v4, 0",
373 "{smov} {vcc}, -1",
374 "v_sub_co_ci_u32_e64 v10, {vcc}, v3, v4, {vcc} clamp",
375 "v_cndmask_b32_e64 v11, 0, 1, {vcc}",
376 ], "v_add_co_ci_u32 / v_sub_co_ci_u32 clamp: carry-in overflow saturates D and sets carry-out"),
377 ]
378
379 # 12. v_mad_u64_u32, v_mad_i64_i32 (sdst bit 64 and EXEC masking)
380 cases += [
381 _valu4_case("valu_mad64", "v_mad_u64_u32_carry", [
382 "v_mov_b32 v1, 0xffffffff", "v_mov_b32 v2, 0xffffffff",
383 "v_mov_b32 v4, 0xffffffff", "v_mov_b32 v5, 0xffffffff",
384 "v_mad_u64_u32 v[8:9], {vcc}, v1, v2, v[4:5]",
385 "v_cndmask_b32_e64 v10, 0, 1, {vcc}",
386 "v_mov_b32 v11, 0",
387 ], "u64 max*max + max64 -> carry=1"),
388 _valu4_case("valu_mad64", "v_mad_i64_i32_pos_overflow", [
389 "v_mov_b32 v1, 0x80000000", "v_mov_b32 v2, 0x80000000",
390 "v_mov_b32 v4, 0xffffffff", "v_mov_b32 v5, 0x7fffffff",
391 "v_mad_i64_i32 v[8:9], {vcc}, v1, v2, v[4:5]",
392 "v_cndmask_b32_e64 v10, 0, 1, {vcc}",
393 "v_mov_b32 v11, 0",
394 ], "(-2^31)^2 + INT64_MAX > 0 (signed overflow, positive exact sum -> sdst=0)"),
395 _valu4_case("valu_mad64", "v_mad_i64_i32_neg_sum", [
396 "v_mov_b32 v1, 0xfffffffe", "v_mov_b32 v2, 3",
397 "v_mov_b32 v4, 0", "v_mov_b32 v5, 0",
398 "v_mad_i64_i32 v[8:9], {vcc}, v1, v2, v[4:5]",
399 "v_cndmask_b32_e64 v10, 0, 1, {vcc}",
400 "v_mov_b32 v11, 0",
401 ], "(-2)*3 + 0 = -6 -> sdst=1 (bit 64 sign of exact 65-bit sum)"),
402 _valu4_case("valu_mad64", "v_mad_u64_u32_inactive_lane", [
403 "v_mov_b32 v1, 0xffffffff", "v_mov_b32 v2, 0xffffffff",
404 "v_mov_b32 v4, 0xffffffff", "v_mov_b32 v5, 0xffffffff",
405 "v_mov_b32 v8, 0x11111111", "v_mov_b32 v9, 0x22222222",
406 "{smov} {vcc}, -1",
407 "{smov} {stmp}, {exec}",
408 "{smov} {exec}, 0",
409 "v_mad_u64_u32 v[8:9], {vcc}, v1, v2, v[4:5]",
410 "{smov} {exec}, {stmp}",
411 "v_cndmask_b32_e64 v10, 0, 1, {vcc}",
412 "v_mov_b32 v11, 0",
413 ], "inactive EXEC lane: D untouched and sdst bit cleared to 0"),
414 ]
415
416 # 13. v_sad_u8, v_sad_hi_u8, v_sad_u16, v_sad_u32, v_msad_u8, v_lerp_u8
417 cases += [
418 _valu4_case("valu_sad_lerp", "v_sad_ops", [
419 "v_mov_b32 v1, 0xff801001", "v_mov_b32 v2, 0x0080f002", "v_mov_b32 v3, 0xffffff00",
420 "v_sad_u8 v8, v1, v2, v3", # wraps 32-bit
421 "v_sad_hi_u8 v9, v1, v2, v3", # (byte_sad << 16) + S2
422 "v_sad_u16 v10, v1, v2, v3", # 2x16-bit SAD + S2
423 "v_sad_u32 v11, v1, v2, v3", # |v1 - v2| + S2
424 ], "v_sad_u8 / v_sad_hi_u8 / v_sad_u16 / v_sad_u32 with 32-bit wrap"),
425 _valu4_case("valu_sad_lerp", "v_msad_and_lerp", [
426 "v_mov_b32 v1, 0xff801001", "v_mov_b32 v2, 0x00800005", "v_mov_b32 v3, 100",
427 "v_msad_u8 v8, v1, v2, v3", # skips bytes 1 and 3 where S1 byte == 0
428 "v_mov_b32 v4, 0xff030200", "v_mov_b32 v5, 0xff040301", "v_mov_b32 v6, 0x01000100",
429 "v_lerp_u8 v9, v4, v5, v6", # per-byte (a+b+(c&1))>>1
430 "v_mov_b32 v7, 0x00feffff",
431 "v_lerp_u8 v10, v4, v5, v7", # upper bits of S2 bytes ignored
432 "v_mov_b32 v11, 0",
433 ], "v_msad_u8 zero-byte mask and v_lerp_u8 rounding/no-carry"),
434 ]
435
436 # 14. v_qsad_pk_u16_u8, v_mqsad_pk_u16_u8, v_mqsad_u32_u8
437 cases += [
438 _valu4_case("valu_qsad_mqsad", "v_qsad_mqsad_pk_u16", [
439 "v_mov_b32 v2, 0x40302010", "v_mov_b32 v3, 0x80706050",
440 "v_mov_b32 v4, 0x00150025", # S1 has two zero bytes for mqsad
441 "v_mov_b32 v6, 0xfffe0005", "v_mov_b32 v7, 0xfff00100",
442 "v_qsad_pk_u16_u8 v[8:9], v[2:3], v4, v[6:7]",
443 "v_mqsad_pk_u16_u8 v[10:11], v[2:3], v4, v[6:7]",
444 ], "v_qsad_pk_u16_u8 and v_mqsad_pk_u16_u8 with 16-bit wrap and zero S1 bytes"),
445 _valu4_case("valu_qsad_mqsad", "v_mqsad_u32_u8", [
446 "v_mov_b32 v2, 0x40302010", "v_mov_b32 v3, 0x80706050",
447 "v_mov_b32 v4, 0x00150025",
448 "v_mov_b32 v12, 0xfffffffe", "v_mov_b32 v13, 10",
449 "v_mov_b32 v14, 20", "v_mov_b32 v15, 0xffffffff",
450 "v_mqsad_u32_u8 v[8:11], v[2:3], v4, v[12:15]",
451 ], "v_mqsad_u32_u8 four 32-bit accumulators with wrap"),
452 ]
453
454 # 15. v_mul_hi_u32_u24, v_mul_hi_i32_i24, v_lshrrev_b64, v_ashrrev_i64
455 cases += [
456 _valu4_case("valu_mul24_sh64", "v_mul_hi_24", [
457 "v_mov_b32 v1, 0xabffffff", "v_mov_b32 v2, 0xcdffffff",
458 "v_mul_hi_u32_u24 v8, v1, v2", # upper 8 bits ignored
459 "v_mul_hi_i32_i24 v9, v1, v2", # (-1)*(-1) >> 32 = 0
460 "v_mov_b32 v3, 0x12800000", "v_mov_b32 v4, 0x347fffff",
461 "v_mul_hi_i32_i24 v10, v3, v4", # (-2^23)*(2^23-1) >> 32
462 "v_mul_hi_u32_u24 v11, v3, v4",
463 ], "v_mul_hi_u32_u24 and v_mul_hi_i32_i24 (upper 8 bits ignored)"),
464 _valu4_case("valu_mul24_sh64", "v_lshr_ashr_64", [
465 "v_mov_b32 v2, 0x12345678", "v_mov_b32 v3, 0x87654321",
466 "v_mov_b32 v1, 36",
467 "v_lshrrev_b64 v[8:9], v1, v[2:3]",
468 "v_ashrrev_i64 v[10:11], v1, v[2:3]",
469 ], "v_lshrrev_b64 and v_ashrrev_i64 shift=36"),
470 _valu4_case("valu_mul24_sh64", "v_lshr_ashr_64_mod64", [
471 "v_mov_b32 v2, 0x12345678", "v_mov_b32 v3, 0x87654321",
472 "v_mov_b32 v1, 68", # 68 & 63 = 4
473 "v_lshrrev_b64 v[8:9], v1, v[2:3]",
474 "v_ashrrev_i64 v[10:11], v1, v[2:3]",
475 ], "v_lshrrev_b64 and v_ashrrev_i64 shift masked to 6 bits"),
476 ]
477
478 # 16. v_mad_u16 / v_mad_i16 (clamp, op_sel, kept half)
479 cases += [
480 _valu4_case("valu_mad16", "v_mad_u16_i16_clamp_opsel", [
481 "v_mov_b32 v1, 0x80000300", "v_mov_b32 v2, 0x00020200", "v_mov_b32 v3, 0x00010010",
482 f"v_mov_b32 v8, 0x{SENTINEL:08x}",
483 f"v_mov_b32 v9, 0x{SENTINEL:08x}",
484 f"v_mov_b32 v10, 0x{SENTINEL:08x}",
485 f"v_mov_b32 v11, 0x{SENTINEL:08x}",
486 "v_mad_u16 v8, v1, v2, v3 clamp", # 0x300*0x200+0x10 = 0x60010 -> 0xffff
487 "v_mad_u16 v9, v1, v2, v3", # wraps to 0x0010, hi kept
488 "v_mad_i16 v10, v1, v2, v3 op_sel:[1,1,1,0] clamp", # (-32768)*2 + 1 = -65535 -> 0x8000
489 "v_mad_i16 v11, v1, v2, v3 op_sel:[0,0,0,1] clamp", # 0x300*0x200+0x10 -> 0x7fff in hi, lo kept
490 ], "v_mad_u16 / v_mad_i16 clamp, op_sel and untouched destination half"),
491 ]
492
493 # 17. v_cvt_f16_u16 / v_cvt_f16_i16 / v_cvt_u16_f16 / v_cvt_i16_f16 (kept half, NaN, inf)
494 cases += [
495 _valu4_case("valu_cvt_16", "v_cvt_u16_i16_f16_e64_nan_inf", [
496 "v_mov_b32 v1, 0x00007e00", # +qNaN
497 "v_mov_b32 v2, 0x0000fe00", # -qNaN
498 "v_mov_b32 v3, 0x00007c00", # +inf
499 "v_mov_b32 v4, 0x0000fc00", # -inf
500 f"v_mov_b32 v8, 0x{SENTINEL:08x}",
501 f"v_mov_b32 v9, 0x{SENTINEL:08x}",
502 f"v_mov_b32 v10, 0x{SENTINEL:08x}",
503 f"v_mov_b32 v11, 0x{SENTINEL:08x}",
504 "v_cvt_u16_f16_e64 v8, v1", # +qNaN -> 0, check high half
505 "v_cvt_i16_f16_e64 v9, v2", # -qNaN -> 0, check high half
506 "v_cvt_u16_f16_e64 v10, v3", # +inf -> 0xffff, check high half
507 "v_cvt_i16_f16_e64 v11, v4", # -inf -> 0x8000, check high half
508 ], "v_cvt_u16/i16_f16_e64 on +-qNaN and +-inf (high half behavior)"),
509 _valu4_case("valu_cvt_16", "v_cvt_f16_u16_i16_e64_keep", [
510 "v_mov_b32 v1, 0x0000fff0", # 65520 -> +inf (0x7c00)
511 "v_mov_b32 v2, 0x00008000", # -32768 -> -32768.0 (0xf800)
512 "v_mov_b32 v3, 0x0000002a", # 42 -> 42.0 (0x5140)
513 "v_mov_b32 v4, 0x00007fff", # 32767 -> 32768.0 (0x7800)
514 f"v_mov_b32 v8, 0x{SENTINEL:08x}",
515 f"v_mov_b32 v9, 0x{SENTINEL:08x}",
516 f"v_mov_b32 v10, 0x{SENTINEL:08x}",
517 f"v_mov_b32 v11, 0x{SENTINEL:08x}",
518 "v_cvt_f16_u16_e64 v8, v1",
519 "v_cvt_f16_i16_e64 v9, v2",
520 "v_cvt_f16_u16_e64 v10, v3",
521 "v_cvt_f16_i16_e64 v11, v4",
522 ], "v_cvt_f16_u16/i16_e64 overflow to +inf and high half behavior"),
523 ]
524
525 # 18. v_cvt_flr_i32_f32 / v_cvt_rpi_i32_f32 (exact floor(x+0.5) + signed NaN; v_cvt_i32_f32 control)
526 cases += [
527 _valu4_case("valu_cvt_flr_rpi", "v_cvt_rpi_precision", [
528 "v_mov_b32 v1, 0x3effffff", # 0.49999997 (f32(x+0.5)==1.0, exact floor(x+0.5)==0)
529 "v_mov_b32 v2, 0x4b000001", # 8388609.0 (f32(x+0.5)==8388610.0, exact==8388609)
530 "v_mov_b32 v3, 0x4b7fffff", # 16777215.0 (f32(x+0.5)==16777216.0, exact==16777215)
531 "v_mov_b32 v4, 0xbf000000", # -0.5 -> floor(-0.5 + 0.5) = 0
532 "v_cvt_rpi_i32_f32 v8, v1",
533 "v_cvt_rpi_i32_f32 v9, v2",
534 "v_cvt_rpi_i32_f32 v10, v3",
535 "v_cvt_rpi_i32_f32 v11, v4",
536 ], "v_cvt_rpi_i32_f32 exact floor(x+0.5) vs binary32 x+0.5"),
537 _valu4_case("valu_cvt_flr_rpi", "v_cvt_flr_rpi_nan_inf", [
538 "v_mov_b32 v1, 0x7fc00000", # +qNaN
539 "v_mov_b32 v2, 0xffc00000", # -qNaN
540 "v_cvt_flr_i32_f32 v8, v1",
541 "v_cvt_flr_i32_f32 v9, v2",
542 "v_cvt_rpi_i32_f32 v10, v1",
543 "v_cvt_rpi_i32_f32 v11, v2",
544 ], "v_cvt_flr_i32_f32 / v_cvt_rpi_i32_f32 on +qNaN and -qNaN"),
545 _valu4_case("valu_cvt_flr_rpi", "v_cvt_i32_f32_nan_control", [
546 "v_mov_b32 v1, 0x7fc00000", # +qNaN
547 "v_mov_b32 v2, 0xffc00000", # -qNaN
548 "v_mov_b32 v3, 0x7f800001", # +sNaN
549 "v_mov_b32 v4, 0xff800001", # -sNaN
550 "v_cvt_i32_f32 v8, v1",
551 "v_cvt_i32_f32 v9, v2",
552 "v_cvt_i32_f32 v10, v3",
553 "v_cvt_i32_f32 v11, v4",
554 ], "control: v_cvt_i32_f32 returns 0 for every NaN"),
555 _valu4_case("valu_cvt_flr_rpi", "v_cvt_flr_edges", [
556 "v_mov_b32 v1, 0xbf800001", # -1.0000001 -> -2
557 "v_mov_b32 v2, 0x7f800000", # +inf -> INT_MAX
558 "v_mov_b32 v3, 0xff800000", # -inf -> INT_MIN
559 "v_mov_b32 v4, 0x4f000000", # +2^31 -> INT_MAX
560 "v_cvt_flr_i32_f32 v8, v1",
561 "v_cvt_flr_i32_f32 v9, v2",
562 "v_cvt_flr_i32_f32 v10, v3",
563 "v_cvt_flr_i32_f32 v11, v4",
564 ], "v_cvt_flr_i32_f32 negative fraction, infinities and 2^31 saturation"),
565 ]
566
567 # 19. v_cvt_pknorm_i16_f32 / v_cvt_pknorm_u16_f32 (NaN, inf, out-of-range, ties)
568 cases += [
569 _valu4_case("valu_cvt_pknorm", "v_cvt_pknorm_nan_inf", [
570 "v_mov_b32 v1, 0x7fc00000", # +qNaN
571 "v_mov_b32 v2, 0xffc00000", # -qNaN
572 "v_mov_b32 v3, 0x7f800000", # +inf
573 "v_mov_b32 v4, 0xff800000", # -inf
574 "v_cvt_pknorm_i16_f32 v8, v1, v2",
575 "v_cvt_pknorm_u16_f32 v9, v1, v2",
576 "v_cvt_pknorm_i16_f32 v10, v3, v4",
577 "v_cvt_pknorm_u16_f32 v11, v3, v4",
578 ], "v_cvt_pknorm_i16/u16_f32 on +-qNaN and +-inf"),
579 _valu4_case("valu_cvt_pknorm", "v_cvt_pknorm_ties", [
580 "v_mov_b32 v1, 0x3f000000", # 0.5 -> 0.5*32767 = 16383.5 (RNE=16384), 0.5*65535 = 32767.5 (RNE=32768)
581 "v_mov_b32 v2, 0xbf000000", # -0.5 -> -16383.5 (RNE=-16384), u16 -> 0
582 "v_mov_b32 v3, 0x3f800000", # 1.0 -> 32767 / 65535
583 "v_mov_b32 v4, 0xbf800000", # -1.0 -> -32767 (0x8001) / 0
584 "v_cvt_pknorm_i16_f32 v8, v1, v2",
585 "v_cvt_pknorm_u16_f32 v9, v1, v2",
586 "v_cvt_pknorm_i16_f32 v10, v3, v4",
587 "v_cvt_pknorm_u16_f32 v11, v3, v4",
588 ], "v_cvt_pknorm_i16/u16_f32 ties at +-0.5 and +-1.0 endpoints"),
589 ]
590
591 return cases
592
593
594def _translate_case(work, case):
595 os.makedirs(os.path.join(work, "disasm"), exist_ok=True)
596 name = f"ps_int_hw_{case.name}"
597 src = os.path.join(work, "disasm", name + ".s")
598 body = case.lines(wave=32) + ["exp mrt0 v8, v9, v10, v11 done vm", "s_endpgm"]
599 with open(src, "w", encoding="utf-8", newline="\n") as f:
600 f.write(f"; {name}\n" + "".join(f"\t{ln}\n" for ln in body))
601 with open(os.path.join(work, name + ".dxbc"), "wb") as f:
602 f.write(STUB_DXBC)
603 with warnings.catch_warnings():
604 warnings.simplefilter("ignore", ResourceWarning)
605 spv = rdna2spirv.translate(src)
606 return list(spirv_mini_interp.run_fragment(spv)["%out_mrt0"])
607
608
609def run_translator(cases):
610 out = {}
611 with tempfile.TemporaryDirectory(prefix="int_hw_probe_") as work:
612 for case in cases:
613 try:
614 out[case.name] = _translate_case(work, case)
615 except Exception as e:
616 out[case.name] = f"error: {type(e).__name__}: {e}"
617 return out
618
619
620def run_hw(cases, arch=None, waves=(32, 64)):
621 from hw_oracle import asm, runner # noqa: E402
622 oracle = runner.open_oracle(arch=arch)
623 try:
624 device = oracle.device
625 per_wave = {}
626 for wave in waves:
627 kernels = [asm.Kernel(case.lines(wave=wave), wave=wave, threads=1, words=4) for case in cases]
628 res = oracle.run(kernels, words=4)
629 per_wave[wave] = {case.name: r for case, r in zip(cases, res)}
630 return device, per_wave
631 finally:
632 oracle.close()
633
634
635def _fmt_words(w):
636 if isinstance(w, list):
637 return " ".join(f"0x{x:08x}" for x in w)
638 return str(w)
639
640
641def self_test():
642 cases = build_cases()
643 names = [c.name for c in cases]
644 assert len(names) == len(set(names)), "duplicate case names"
645 for name in KNOWN_DIVERGENCES:
646 assert name in names, f"unknown KNOWN_DIVERGENCES key: {name}"
647 res = run_translator(cases)
648 errors = {k: v for k, v in res.items() if not isinstance(v, list)}
649 assert not errors, f"translator errors: {errors}"
650 print(f"self-test: {len(cases)} cases across {len({c.group for c in cases})} groups translated and ran on CPU OK")
651 return 0
652
653
654def main(argv=None):
655 ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])
656 ap.add_argument("--oracle", choices=("translator", "hw", "both"), default="translator")
657 ap.add_argument("--wave", choices=("32", "64", "both"), default="both")
658 ap.add_argument("--group", action="append", default=[], help="run only named group(s)")
659 ap.add_argument("--hw-arch", default=None, help="override GPU architecture for hw_oracle")
660 ap.add_argument("--list-groups", action="store_true")
661 ap.add_argument("--strict", action="store_true", help="treat known translator divergences as failures")
662 ap.add_argument("--json", dest="json_out", default=None, help="write raw results to a JSON file")
663 ap.add_argument("--self-test", action="store_true")
664 args = ap.parse_args(argv)
665
666 if args.self_test:
667 return self_test()
668
669 cases = build_cases()
670 groups = []
671 for c in cases:
672 if c.group not in groups:
673 groups.append(c.group)
674 if args.list_groups:
675 for g in groups:
676 n = sum(1 for c in cases if c.group == g)
677 print(f"{g:<22} ({n} cases)")
678 return 0
679
680 if args.group:
681 unknown = [g for g in args.group if g not in groups]
682 if unknown:
683 print(f"unknown group(s): {', '.join(unknown)}", file=sys.stderr)
684 return 2
685 want = set(args.group)
686 cases = [c for c in cases if c.group in want]
687
688 waves = (32, 64) if args.wave == "both" else (int(args.wave),)
689 tr_res = run_translator(cases) if args.oracle in ("translator", "both") else None
690 hw_device, hw_res = None, None
691 if args.oracle in ("hw", "both"):
692 from hw_oracle import runner # noqa: E402
693 try:
694 hw_device, hw_res = run_hw(cases, arch=args.hw_arch, waves=waves)
695 except runner.Unavailable as e:
696 print(f"hardware oracle unavailable: {e}", file=sys.stderr)
697 return 77
698 print(f"hardware oracle: {hw_device} (waves: {','.join(str(w) for w in waves)})")
699
700 mismatches = 0
701 known_diffs = 0
702 wave_diffs = 0
703 records = []
704 for c in cases:
705 tr = tr_res[c.name] if tr_res is not None else None
706 h32 = hw_res[32][c.name] if hw_res and 32 in hw_res else None
707 h64 = hw_res[64][c.name] if hw_res and 64 in hw_res else None
708 hw_ref = h32 if h32 is not None else h64
709 status = "OK"
710 tag = None
711 if h32 is not None and h64 is not None and h32 != h64:
712 status = "WAVE_DIFF"
713 wave_diffs += 1
714 elif (tr is not None and not isinstance(tr, list)) or (hw_ref is not None and not isinstance(hw_ref, list)):
715 status = "ERROR"
716 mismatches += 1
717 elif tr is not None and hw_ref is not None and tr != hw_ref:
718 known = KNOWN_DIVERGENCES.get(c.name)
719 if known and hw_ref == known[1]:
720 status = "KNOWN_DIFF"
721 tag = known[0]
722 known_diffs += 1
723 else:
724 status = "MISMATCH"
725 mismatches += 1
726 records.append({
727 "group": c.group, "name": c.name, "note": c.note, "status": status, "known_tag": tag,
728 "translator": tr, "hw_w32": h32, "hw_w64": h64,
729 })
730 if status != "OK" or args.oracle != "both":
731 label = f"{status}:{tag}" if tag else status
732 print(f"[{label:<22}] {c.group}/{c.name}: {c.note}")
733 if h32 is not None:
734 print(f" hw_w32: {_fmt_words(h32)}")
735 if h64 is not None and h64 != h32:
736 print(f" hw_w64: {_fmt_words(h64)}")
737 if tr is not None:
738 print(f" transl: {_fmt_words(tr)}")
739
740 total = len(cases)
741 matched = total - mismatches - known_diffs - wave_diffs
742 print(f"summary: {total} cases: {matched} match, {known_diffs} known divergence, "
743 f"{mismatches} unexpected mismatch, {wave_diffs} wave32/64 diff")
744
745 if args.json_out:
746 out_path = os.path.abspath(args.json_out)
747 if os.path.isdir(out_path):
748 print(f"ERROR: --json path is a directory: {out_path}", file=sys.stderr)
749 return 2
750 parent = os.path.dirname(out_path)
751 if parent:
752 os.makedirs(parent, exist_ok=True)
753 with open(out_path, "w", encoding="utf-8", newline="\n") as f:
754 json.dump({"device": hw_device, "waves": list(waves), "cases": records}, f, indent=2)
755 f.write("\n")
756
757 if mismatches or wave_diffs or (args.strict and known_diffs):
758 return 1
759 return 0
760
761
762if __name__ == "__main__":
763 try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode
764 sys.stdout.reconfigure(errors="replace")
765 except (AttributeError, ValueError, OSError):
766 pass
767 sys.exit(main())
diff --git a/tools/manifest.py b/tools/manifest.py
index 9c39d9030..d1ac69ba4 100644
--- a/tools/manifest.py
+++ b/tools/manifest.py
@@ -22,7 +22,7 @@ DEFAULT = os.path.join(os.path.dirname(__file__), "..", "reports", "manifest.jso
22 22
23 23
24class ManifestError(Exception): 24class ManifestError(Exception):
25 """A manifest that isn't valid JSON or doesn't have the layout create() writes.""" 25 """An input or manifest error that the CLI reports without a traceback."""
26 26
27 27
28def default_jobs() -> int: 28def default_jobs() -> int:
@@ -52,12 +52,32 @@ def below_normal() -> None:
52 k32.SetPriorityClass(k32.GetCurrentProcess(), 0x00004000) # BELOW_NORMAL_PRIORITY_CLASS 52 k32.SetPriorityClass(k32.GetCurrentProcess(), 0x00004000) # BELOW_NORMAL_PRIORITY_CLASS
53 53
54 54
55def sha256(path: str) -> str: 55def _file_stamp(st: os.stat_result) -> tuple[int, int, int]:
56 return st.st_size, st.st_mtime_ns, st.st_ctime_ns
57
58
59def _hash_file(path: str, *, expected_size: int | None = None) -> tuple[int, str]:
60 """Return the size and digest of the same open file, or fail if it changes."""
56 h = hashlib.sha256() 61 h = hashlib.sha256()
57 with open(path, "rb", buffering=0) as f: 62 with open(path, "rb", buffering=0) as f:
58 while chunk := f.read(CHUNK): 63 before = os.fstat(f.fileno())
64 size = before.st_size
65 if expected_size is not None and size != expected_size:
66 raise ManifestError(f"{path}: file size changed before hashing")
67 remaining = size
68 while remaining and (chunk := f.read(min(CHUNK, remaining))):
59 h.update(chunk) 69 h.update(chunk)
60 return h.hexdigest() 70 remaining -= len(chunk)
71 # Compare timestamps from the same handle. Windows can report different times by path.
72 # Compare the path by identity so a replacement of the open file is detected too.
73 if (remaining or _file_stamp(os.fstat(f.fileno())) != _file_stamp(before)
74 or not os.path.samestat(before, os.stat(path))):
75 raise ManifestError(f"{path}: file changed while hashing")
76 return size, h.hexdigest()
77
78
79def sha256(path: str) -> str:
80 return _hash_file(path)[1]
61 81
62 82
63def same_output_path(first: str, second: str) -> bool: 83def same_output_path(first: str, second: str) -> bool:
@@ -114,7 +134,8 @@ def create(game_dir: str, out: str, jobs: int = 1) -> int:
114 if same_output_path(out, path): 134 if same_output_path(out, path):
115 raise ManifestError(f"--out would overwrite the input {path}; " 135 raise ManifestError(f"--out would overwrite the input {path}; "
116 "choose a manifest path that is not one of the hashed files") 136 "choose a manifest path that is not one of the hashed files")
117 total = sum(os.path.getsize(p) for _, p in files) 137 sizes = {path: os.path.getsize(path) for _, path in files}
138 total = sum(sizes.values())
118 entries = {} 139 entries = {}
119 done = count = 0 140 done = count = 0
120 t0 = time.time() 141 t0 = time.time()
@@ -131,7 +152,8 @@ def create(game_dir: str, out: str, jobs: int = 1) -> int:
131 print(f"[{pct:6.1%}] {count}/{len(files)} files {rate:7.0f} MiB/s", flush=True) 152 print(f"[{pct:6.1%}] {count}/{len(files)} files {rate:7.0f} MiB/s", flush=True)
132 153
133 def work(rel: str, path: str) -> tuple[str, int, str]: 154 def work(rel: str, path: str) -> tuple[str, int, str]:
134 return rel, os.path.getsize(path), sha256(path) 155 size, digest = _hash_file(path, expected_size=sizes[path])
156 return rel, size, digest
135 157
136 if jobs == 1: 158 if jobs == 1:
137 for rel, p in files: 159 for rel, p in files:
diff --git a/tools/navmesh_decode.py b/tools/navmesh_decode.py
index 3832a8590..7571c2ae9 100644
--- a/tools/navmesh_decode.py
+++ b/tools/navmesh_decode.py
@@ -927,7 +927,7 @@ def _make_parent(path):
927def write_csv(path, rows): 927def write_csv(path, rows):
928 _make_parent(path) 928 _make_parent(path)
929 with open(path, "w", newline="", encoding="utf-8") as f: 929 with open(path, "w", newline="", encoding="utf-8") as f:
930 w = csv.DictWriter(f, fieldnames=COLUMNS, extrasaction="ignore") 930 w = csv.DictWriter(f, fieldnames=COLUMNS, extrasaction="ignore", lineterminator="\n")
931 w.writeheader() 931 w.writeheader()
932 for r in rows: 932 for r in rows:
933 w.writerow({k: ("" if r.get(k) is None else r.get(k)) for k in COLUMNS}) 933 w.writerow({k: ("" if r.get(k) is None else r.get(k)) for k in COLUMNS})
diff --git a/tools/navmesh_index.py b/tools/navmesh_index.py
index 4867f7c84..0fa6c7f83 100644
--- a/tools/navmesh_index.py
+++ b/tools/navmesh_index.py
@@ -204,7 +204,7 @@ def write_outputs(rows, summary, out_path, csv_path):
204 if csv_path: 204 if csv_path:
205 _make_parent(csv_path) 205 _make_parent(csv_path)
206 with open(csv_path, "w", newline="", encoding="utf-8") as f: 206 with open(csv_path, "w", newline="", encoding="utf-8") as f:
207 w = csv.DictWriter(f, fieldnames=FIELDS, extrasaction="ignore") 207 w = csv.DictWriter(f, fieldnames=FIELDS, extrasaction="ignore", lineterminator="\n")
208 w.writeheader() 208 w.writeheader()
209 w.writerows(rows) 209 w.writerows(rows)
210 written.append(csv_path) 210 written.append(csv_path)
@@ -258,8 +258,14 @@ def is_scanned_input(path, input_path, pattern):
258 return False 258 return False
259 root = parent 259 root = parent
260 pattern = pattern or "*.bin" 260 pattern = pattern or "*.bin"
261 return (fnmatch.fnmatch(os.path.relpath(target, root), pattern) 261 if (fnmatch.fnmatch(os.path.relpath(target, root), pattern)
262 or fnmatch.fnmatch(os.path.basename(target), pattern)) 262 or fnmatch.fnmatch(os.path.basename(target), pattern)):
263 return True
264 # The spelling may not match while the file is still one the scan reads: fnmatch folds case only on Windows,
265 # so CARVE/PAGE.BIN on a case-insensitive macOS or Linux volume, or a hard link, slips past the pattern. Ask
266 # the scan's own glob whether any file it reads is this one.
267 return any(same_report_path(target, scanned)
268 for scanned in glob.iglob(os.path.join(input_path, "**", pattern), recursive=True))
263 269
264 270
265def main() -> int: 271def main() -> int:
diff --git a/tools/opus_tags.py b/tools/opus_tags.py
index a1395e6ef..51986d3a0 100644
--- a/tools/opus_tags.py
+++ b/tools/opus_tags.py
@@ -4,7 +4,7 @@ awc_opus.py writes <out>/<bank>/<stream id>.ogg with an empty OpusTags header. T
4from two local work products: 4from two local work products:
5 5
6``--names`` awc_names.py CSV (source, bank, stream_id, name, rule). A file is matched by its stream id (the file 6``--names`` awc_names.py CSV (source, bank, stream_id, name, rule). A file is matched by its stream id (the file
7 name) and its bank (the folder path below the Opus folder; if that has no match, the path with its 7 name; awc_opus.py's ``<id>~2.ogg`` for a second stream with the same id gets the same name) and its bank (the folder path below the Opus folder; if that has no match, the path with its
8 leading folders removed one at a time, so the Opus folder may hold several archives' outputs). 8 leading folders removed one at a time, so the Opus folder may hold several archives' outputs).
9``--dialogue`` text_tables.py dialogue CSV (wave, key, label, speaker, text_<lang> ...). A named stream whose name is 9``--dialogue`` text_tables.py dialogue CSV (wave, key, label, speaker, text_<lang> ...). A named stream whose name is
10 a dialogue wave gets that line's label, speaker and subtitles. 10 a dialogue wave gets that line's label, speaker and subtitles.
@@ -40,7 +40,7 @@ from awc_opus import ogg_page, write_file # noqa: E402
40VENDOR = b"leonida " 40VENDOR = b"leonida "
41MARKUP = re.compile(r"~[^~]*~") 41MARKUP = re.compile(r"~[^~]*~")
42SPACES = re.compile(r"\s+") 42SPACES = re.compile(r"\s+")
43STREAM_FILE = re.compile(r"^([0-9A-Fa-f]{8})\.ogg$") 43STREAM_FILE = re.compile(r"^([0-9A-Fa-f]{8})(?:~\d+)?\.ogg$") # <id>~2 ...: a later stream with the same id
44MAX_PACKET = 255 * 255 - 1 # lacing values of one page: 254 full segments and a final short one 44MAX_PACKET = 255 * 255 - 1 # lacing values of one page: 254 full segments and a final short one
45 45
46 46
diff --git a/tools/page_index.py b/tools/page_index.py
index fac172670..41d9f3783 100644
--- a/tools/page_index.py
+++ b/tools/page_index.py
@@ -322,7 +322,7 @@ def write_json(path, pages, summary):
322 322
323def write_csv(path, pages): 323def write_csv(path, pages):
324 with open(path, "w", newline="", encoding="utf-8") as f: 324 with open(path, "w", newline="", encoding="utf-8") as f:
325 w = csv.DictWriter(f, fieldnames=COLUMNS) 325 w = csv.DictWriter(f, fieldnames=COLUMNS, lineterminator="\n")
326 w.writeheader() 326 w.writeheader()
327 for page in pages: 327 for page in pages:
328 records = page["q38_records"] 328 records = page["q38_records"]
diff --git a/tools/pe_inspect.py b/tools/pe_inspect.py
index 148318c15..dbe8f75a8 100644
--- a/tools/pe_inspect.py
+++ b/tools/pe_inspect.py
@@ -78,7 +78,9 @@ class PeImage:
78 magic = struct.unpack_from("<H", data, opt)[0] 78 magic = struct.unpack_from("<H", data, opt)[0]
79 if magic not in (0x10B, 0x20B): 79 if magic not in (0x10B, 0x20B):
80 raise PeFormatError(f"unknown optional header magic 0x{magic:x}") 80 raise PeFormatError(f"unknown optional header magic 0x{magic:x}")
81 if opt + 72 > len(data): # the fixed fields read below end with DllCharacteristics at +70 81 # The declared optional header must contain every fixed field we read,
82 # and the complete declared header must fit inside the file.
83 if opt_size < 72 or opt + opt_size > len(data):
82 raise PeFormatError("truncated optional header") 84 raise PeFormatError("truncated optional header")
83 self.is64 = magic == 0x20B 85 self.is64 = magic == 0x20B
84 self.entry_rva = struct.unpack_from("<I", data, opt + 16)[0] 86 self.entry_rva = struct.unpack_from("<I", data, opt + 16)[0]
diff --git a/tools/rbf0_index.py b/tools/rbf0_index.py
index f257963eb..c13122afa 100644
--- a/tools/rbf0_index.py
+++ b/tools/rbf0_index.py
@@ -468,7 +468,7 @@ def write_output(path, records, summary, all_strings=False):
468 json.dump({"summary": summary, "files": docs}, f, indent=1) 468 json.dump({"summary": summary, "files": docs}, f, indent=1)
469 return 469 return
470 with open(path, "w", encoding="utf-8", newline="") as f: 470 with open(path, "w", encoding="utf-8", newline="") as f:
471 writer = csv.writer(f) 471 writer = csv.writer(f, lineterminator="\n")
472 writer.writerow(COLUMNS) 472 writer.writerow(COLUMNS)
473 for r in records: 473 for r in records:
474 sample = "; ".join(r["sample"]) 474 sample = "; ".join(r["sample"])
diff --git a/tools/rbf0_tree.py b/tools/rbf0_tree.py
index 44a6b37db..f4533009a 100644
--- a/tools/rbf0_tree.py
+++ b/tools/rbf0_tree.py
@@ -600,7 +600,7 @@ def write_csv(path, docs):
600 The rows carry names and payloads, so the file is game data and must stay local. 600 The rows carry names and payloads, so the file is game data and must stay local.
601 """ 601 """
602 with open(path, "w", encoding="utf-8", newline="") as f: 602 with open(path, "w", encoding="utf-8", newline="") as f:
603 writer = csv.writer(f) 603 writer = csv.writer(f, lineterminator="\n")
604 writer.writerow(CSV_COLUMNS) 604 writer.writerow(CSV_COLUMNS)
605 for doc in docs: 605 for doc in docs:
606 root = doc["tree"] 606 root = doc["tree"]
diff --git a/tools/rdna2spirv.py b/tools/rdna2spirv.py
index 26d8ff9d1..6806a4b1b 100644
--- a/tools/rdna2spirv.py
+++ b/tools/rdna2spirv.py
@@ -64,11 +64,14 @@ MESH_COMPUTE = False
64# `exp paramN` also exports the channel's two f16 halves decoded to f32, low halves at f16_half_location(N, 0) and high 64# `exp paramN` also exports the channel's two f16 halves decoded to f32, low halves at f16_half_location(N, 0) and high
65# halves at f16_half_location(N, 1), and a PS *_f16 read of attrN.c takes component c of that smooth input. The 65# halves at f16_half_location(N, 1), and a PS *_f16 read of attrN.c takes component c of that smooth input. The
66# interpolation is linear, so this is the same P0 + i(P1 - P0) + j(P2 - P0) of the decoded halves, rounded by the 66# interpolation is linear, so this is the same P0 + i(P1 - P0) + j(P2 - P0) of the decoded halves, rounded by the
67# device's interpolator instead of by explicit arithmetic. The halves sit below location F16_HALF_TOP (30: 31 67# device's interpolator instead of by explicit arithmetic. The halves count down from location F16_HALF_TOP (param 0's
68# locations is MoltenVK's limit, 124 components), counting down from param 0, so a producer with params 0..P-1 has 68# high halves, its low halves one below), so a producer with params 0..P-1 has room for the halves of params
69# room for the halves of params 0..(29 - P) / 2; Gen.export skips the ones that would land on its own params. 69# 0..(28 - P) / 2; Gen.export skips the ones that would land on its own params. The top is 29, not 30 (SHADER-291):
70# MoltenVK's maxVertexOutputComponents is 124 because Metal counts gl_Position in its 128 vertex-output scalars, and
71# the validation layer counts it too (VUID-RuntimeSpirv-Location-06272), so (29 + 1) * 4 + 4 = 124 is the most a VS
72# can use there.
70F16_HALVES = False 73F16_HALVES = False
71F16_HALF_TOP = 30 74F16_HALF_TOP = 29
72 75
73 76
74def f16_half_location(n, half): 77def f16_half_location(n, half):
@@ -182,6 +185,7 @@ class Gen:
182 self.uses_wave_bits = False # a whole lane mask gathered from the wave (OpGroupNonUniformBitwiseOr) 185 self.uses_wave_bits = False # a whole lane mask gathered from the wave (OpGroupNonUniformBitwiseOr)
183 self.uses_quad = False # s_wqm on a lane mask (OpGroupNonUniformQuadSwap) 186 self.uses_quad = False # s_wqm on a lane mask (OpGroupNonUniformQuadSwap)
184 self.lane_masks = {} # id(instruction) -> registers holding a lane mask there (lane_masks.py) 187 self.lane_masks = {} # id(instruction) -> registers holding a lane mask there (lane_masks.py)
188 self.ever_mask = set() # SGPRs that held a lane mask anywhere in the shader (conservative)
185 self.cur_masks = {} 189 self.cur_masks = {}
186 self.mask_writes = set() # id(instruction) of the ones that write a lane mask to a VGPR 190 self.mask_writes = set() # id(instruction) of the ones that write a lane mask to a VGPR
187 self.write_all_lanes = False 191 self.write_all_lanes = False
@@ -278,6 +282,19 @@ class Gen:
278 self.emit(f"{p} = OpAccessChain %_ptr_Function_uint {arr} {self.cu(r)}") 282 self.emit(f"{p} = OpAccessChain %_ptr_Function_uint {arr} {self.cu(r)}")
279 self.emit(f"OpStore {p} {val}") 283 self.emit(f"OpStore {p} {val}")
280 284
285 def imm_val(self, a):
286 """Integer literal value if 'a' is an immediate or known SGPR constant, else None."""
287 if a.get("abs") or a.get("neg"):
288 return None
289 k = a.get("k")
290 if k == "imm":
291 return a["v"] & 0xFFFFFFFF
292 if k == "sgpr" and a.get("n", 1) == 1 and a.get("r") in self.sgpr_imm:
293 return self.sgpr_imm[a["r"]] & 0xFFFFFFFF
294 if k == "special" and a.get("t") == "null":
295 return 0
296 return None
297
281 def src_u(self, a): 298 def src_u(self, a):
282 k = a["k"] 299 k = a["k"]
283 if k in ("vgpr", "sgpr"): 300 if k in ("vgpr", "sgpr"):
@@ -414,7 +431,10 @@ class Gen:
414 selhi = next((m for m in mods if m.startswith("op_sel_hi:")), "op_sel_hi:[0,0,0]") 431 selhi = next((m for m in mods if m.startswith("op_sel_hi:")), "op_sel_hi:[0,0,0]")
415 sb = [int(x) for x in sel.split("[")[1].rstrip("]").split(",")] 432 sb = [int(x) for x in sel.split("[")[1].rstrip("]").split(",")]
416 hb = [int(x) for x in selhi.split("[")[1].rstrip("]").split(",")] 433 hb = [int(x) for x in selhi.split("[")[1].rstrip("]").split(",")]
417 return [self.f16_in(src, sb[i]) if hb[i] else self.src_f(src) for i, src in enumerate(a[1:4])] 434 # An f32 operand reads as a zero of its sign when it is denormal: the game's MODE flushes f32 denormals
435 # (denorm_mode_32 = 0), measured on gfx1036 for 0x00000001, 0x807fffff and the integer inline constants 1 and
436 # 64 used as f32 operands (@Sanonymous01, SHADER-298). The f16 operands widen to normal f32 values.
437 return [self.f16_in(src, sb[i]) if hb[i] else self.flush_f32(self.src_f(src)) for i, src in enumerate(a[1:4])]
418 438
419 def f16_bits(self, f, rtz=False): 439 def f16_bits(self, f, rtz=False):
420 """f32 ``f`` -> f16 bits in the low 16 bits of a %uint, computed with integer ops only (SHADER-56). 440 """f32 ``f`` -> f16 bits in the low 16 bits of a %uint, computed with integer ops only (SHADER-56).
@@ -931,15 +951,20 @@ class Gen:
931 return 951 return
932 if d["k"] != "sgpr" or d.get("n") != 2: 952 if d["k"] != "sgpr" or d.get("n") != 2:
933 raise Unsupported("s_mov_b64 destination") 953 raise Unsupported("s_mov_b64 destination")
954 lit_lo = lit_hi = None
934 if s["k"] == "special" and s["t"] == "exec": 955 if s["k"] == "special" and s["t"] == "exec":
935 lo = hi = self.exec_value() 956 lo = hi = self.exec_value()
936 elif s["k"] == "sgpr" and s.get("n") == 2: 957 elif s["k"] == "sgpr" and s.get("n") == 2:
958 lit_lo = self.sgpr_imm.get(s["r"])
959 lit_hi = self.sgpr_imm.get(s["r"] + 1)
937 lo, hi = self.load_reg("sgpr", s["r"]), self.load_reg("sgpr", s["r"] + 1) 960 lo, hi = self.load_reg("sgpr", s["r"]), self.load_reg("sgpr", s["r"] + 1)
938 elif s["k"] == "imm": 961 elif s["k"] == "imm":
939 v = s["v"] & 0xFFFFFFFFFFFFFFFF 962 v = s["v"] & 0xFFFFFFFFFFFFFFFF
940 if s["v"] < 0: 963 if s["v"] < 0:
941 v = s["v"] & 0xFFFFFFFFFFFFFFFF 964 v = s["v"] & 0xFFFFFFFFFFFFFFFF
942 lo, hi = self.cu(v & 0xFFFFFFFF), self.cu(v >> 32) 965 lit_lo = v & 0xFFFFFFFF
966 lit_hi = (v >> 32) & 0xFFFFFFFF
967 lo, hi = self.cu(lit_lo), self.cu(lit_hi)
943 elif s["k"] == "special" and s["t"] == "vcc": 968 elif s["k"] == "special" and s["t"] == "vcc":
944 lo = hi = self.tmp() # this lane's bit in both halves, as for EXEC 969 lo = hi = self.tmp() # this lane's bit in both halves, as for EXEC
945 self.emit(f"{lo} = OpLoad %uint %vcc") 970 self.emit(f"{lo} = OpLoad %uint %vcc")
@@ -947,6 +972,11 @@ class Gen:
947 raise Unsupported("s_mov_b64 source") 972 raise Unsupported("s_mov_b64 source")
948 self.store_reg("sgpr", d["r"], lo) 973 self.store_reg("sgpr", d["r"], lo)
949 self.store_reg("sgpr", d["r"] + 1, hi) 974 self.store_reg("sgpr", d["r"] + 1, hi)
975 if self.desc_cache_ok():
976 if lit_lo is not None:
977 self.sgpr_imm[d["r"]] = lit_lo
978 if lit_hi is not None:
979 self.sgpr_imm[d["r"] + 1] = lit_hi
950 980
951 def compare(self, op, a, scalar, exec_only=False, mods=()): 981 def compare(self, op, a, scalar, exec_only=False, mods=()):
952 """v_cmp_* / s_cmp_*: lane result into VCC/SGPR mask (vector), SCC (scalar), or EXEC (v_cmpx).""" 982 """v_cmp_* / s_cmp_*: lane result into VCC/SGPR mask (vector), SCC (scalar), or EXEC (v_cmpx)."""
@@ -1235,13 +1265,12 @@ class Gen:
1235 # GFX10 buffer formats (from Mesa src/amd/registers/gfx10-rsrc.json, GFX10_FORMAT): 1265 # GFX10 buffer formats (from Mesa src/amd/registers/gfx10-rsrc.json, GFX10_FORMAT):
1236 # code: (bytes, kind, component bit widths from bit 0) 1266 # code: (bytes, kind, component bit widths from bit 0)
1237 # The names list the widths from the top bit down, so 2_10_10_10 (50) is R10G10B10A2. 1267 # The names list the widths from the top bit down, so 2_10_10_10 (50) is R10G10B10A2.
1238 # A 32-bit SINT component holds the same bits as UINT (no conversion, nothing to clamp at full width), so the 1268 # Full-width SINT and UINT preserve the same raw dwords. Keep separate kinds for signed D16 conversion.
1239 # *_SINT codes 21/63/73/76 share the raw-dword "u32" path with their UINT twins 20/62/72/75.
1240 FORMATS = {22: (4, "f32", (32,)), 64: (8, "f32", (32, 32)), 74: (12, "f32", (32, 32, 32)), 1269 FORMATS = {22: (4, "f32", (32,)), 64: (8, "f32", (32, 32)), 74: (12, "f32", (32, 32, 32)),
1241 77: (16, "f32", (32, 32, 32, 32)), 20: (4, "u32", (32,)), 62: (8, "u32", (32, 32)), 1270 77: (16, "f32", (32, 32, 32, 32)), 20: (4, "u32", (32,)), 62: (8, "u32", (32, 32)),
1242 72: (12, "u32", (32, 32, 32)), 75: (16, "u32", (32, 32, 32, 32)), 1271 72: (12, "u32", (32, 32, 32)), 75: (16, "u32", (32, 32, 32, 32)),
1243 21: (4, "u32", (32,)), 63: (8, "u32", (32, 32)), 73: (12, "u32", (32, 32, 32)), 1272 21: (4, "i32", (32,)), 63: (8, "i32", (32, 32)), 73: (12, "i32", (32, 32, 32)),
1244 76: (16, "u32", (32, 32, 32, 32)), 13: (2, "f16", (16,)), 29: (4, "f16", (16, 16)), 1273 76: (16, "i32", (32, 32, 32, 32)), 13: (2, "f16", (16,)), 29: (4, "f16", (16, 16)),
1245 71: (8, "f16", (16, 16, 16, 16)), 1: (1, "unorm", (8,)), 14: (2, "unorm", (8, 8)), 1274 71: (8, "f16", (16, 16, 16, 16)), 1: (1, "unorm", (8,)), 14: (2, "unorm", (8, 8)),
1246 56: (4, "unorm", (8, 8, 8, 8)), 57: (4, "snorm", (8, 8, 8, 8)), 60: (4, "uint", (8, 8, 8, 8)), 1275 56: (4, "unorm", (8, 8, 8, 8)), 57: (4, "snorm", (8, 8, 8, 8)), 60: (4, "uint", (8, 8, 8, 8)),
1247 7: (2, "unorm", (16,)), 23: (4, "unorm", (16, 16)), 24: (4, "snorm", (16, 16)), 1276 7: (2, "unorm", (16,)), 23: (4, "unorm", (16, 16)), 24: (4, "snorm", (16, 16)),
@@ -1252,14 +1281,14 @@ class Gen:
1252 1281
1253 def encode_format(self, fcomps, icomps, code): 1282 def encode_format(self, fcomps, icomps, code):
1254 """Encode one element of format `code` -> list of uint ids (whole dwords; elements under 4 bytes return one 1283 """Encode one element of format `code` -> list of uint ids (whole dwords; elements under 4 bytes return one
1255 value in the low bits). fcomps are f32 bit patterns (float/normalized kinds), icomps integers (u32/uint).""" 1284 value in the low bits). fcomps are f32 bit patterns (float/normalized kinds), icomps integer bit patterns (u32/i32/uint)."""
1256 try: 1285 try:
1257 size, kind, widths = self.FORMATS[code] 1286 size, kind, widths = self.FORMATS[code]
1258 except KeyError: 1287 except KeyError:
1259 raise Unsupported(f"format {code} (not in FORMATS)") 1288 raise Unsupported(f"format {code} (not in FORMATS)")
1260 if kind == "f32": 1289 if kind == "f32":
1261 return list(fcomps[:len(widths)]) 1290 return list(fcomps[:len(widths)])
1262 if kind == "u32": 1291 if kind in ("u32", "i32"):
1263 return list(icomps[:len(widths)]) 1292 return list(icomps[:len(widths)])
1264 words = [self.cu(0)] * max(1, (size + 3) // 4) 1293 words = [self.cu(0)] * max(1, (size + 3) // 4)
1265 bit = 0 1294 bit = 0
@@ -1348,7 +1377,7 @@ class Gen:
1348 return result 1377 return result
1349 1378
1350 def decode_format(self, words, code, *, fixed: bool = False): 1379 def decode_format(self, words, code, *, fixed: bool = False):
1351 """Decode one element of format `code` from raw dwords -> 4 uint ids holding f32 bits (or uint for *_UINT/uint). 1380 """Decode one element of format `code` from raw dwords -> 4 uint ids holding f32 or integer bits.
1352 1381
1353 Missing channels repeat the format's own (component c = c mod n): measured on RX 6700 for SHADER-86. 1382 Missing channels repeat the format's own (component c = c mod n): measured on RX 6700 for SHADER-86.
1354 UNORM/SNORM give the correctly rounded quotient, as the RX 6700 does, built with integer ops (norm_bits): 1383 UNORM/SNORM give the correctly rounded quotient, as the RX 6700 does, built with integer ops (norm_bits):
@@ -1357,7 +1386,7 @@ class Gen:
1357 size, kind, widths = self.FORMATS[code] 1386 size, kind, widths = self.FORMATS[code]
1358 except KeyError: 1387 except KeyError:
1359 raise Unsupported(f"format {code} (not in FORMATS)") 1388 raise Unsupported(f"format {code} (not in FORMATS)")
1360 if kind in ("f32", "u32"): 1389 if kind in ("f32", "u32", "i32"):
1361 n = len(widths) 1390 n = len(widths)
1362 vals = list(words[:n]) 1391 vals = list(words[:n])
1363 while len(vals) < 4: 1392 while len(vals) < 4:
@@ -1429,8 +1458,9 @@ class Gen:
1429 old_d = self.load_reg("vgpr", vdst["r"]) if vdst is not None else self.cu(0) 1458 old_d = self.load_reg("vgpr", vdst["r"]) if vdst is not None else self.cu(0)
1430 lbl_do, lbl_end, res, old = self.tmp() + "_do", self.tmp() + "_end", self.tmp(), self.tmp() 1459 lbl_do, lbl_end, res, old = self.tmp() + "_do", self.tmp() + "_end", self.tmp(), self.tmp()
1431 pre = self.current_label_placeholder() 1460 pre = self.current_label_placeholder()
1461 act = self.active_b() # loaded before the merge: OpSelectionMerge must directly precede the branch
1432 self.emit(f"OpSelectionMerge {lbl_end} None") 1462 self.emit(f"OpSelectionMerge {lbl_end} None")
1433 self.emit(f"OpBranchConditional {self.active_b()} {lbl_do} {lbl_end}") 1463 self.emit(f"OpBranchConditional {act} {lbl_do} {lbl_end}")
1434 self.emit(f"{lbl_do} = OpLabel") 1464 self.emit(f"{lbl_do} = OpLabel")
1435 ptr, p = self.tmp(), self.tmp() 1465 ptr, p = self.tmp(), self.tmp()
1436 self.emit(f"{ptr} = OpConvertUToPtr %_ptr_PSB_arr {self.host_addr(full)}") 1466 self.emit(f"{ptr} = OpConvertUToPtr %_ptr_PSB_arr {self.host_addr(full)}")
@@ -1462,8 +1492,9 @@ class Gen:
1462 spv = self.BUF_ATOMICS[kind][0] 1492 spv = self.BUF_ATOMICS[kind][0]
1463 lbl_do, lbl_end = self.tmp() + "_do", self.tmp() + "_end" 1493 lbl_do, lbl_end = self.tmp() + "_do", self.tmp() + "_end"
1464 pre = self.current_label_placeholder() 1494 pre = self.current_label_placeholder()
1495 act = self.active_b() # loaded before the merge: OpSelectionMerge must directly precede the branch
1465 self.emit(f"OpSelectionMerge {lbl_end} None") 1496 self.emit(f"OpSelectionMerge {lbl_end} None")
1466 self.emit(f"OpBranchConditional {self.active_b()} {lbl_do} {lbl_end}") 1497 self.emit(f"OpBranchConditional {act} {lbl_do} {lbl_end}")
1467 self.emit(f"{lbl_do} = OpLabel") 1498 self.emit(f"{lbl_do} = OpLabel")
1468 ptr = self.tmp() 1499 ptr = self.tmp()
1469 self.emit(f"{ptr} = OpConvertUToPtr %_ptr_PSB_arr {self.host_addr(full)}") 1500 self.emit(f"{ptr} = OpConvertUToPtr %_ptr_PSB_arr {self.host_addr(full)}")
@@ -1736,13 +1767,17 @@ class Gen:
1736 else: 1767 else:
1737 comps = self.format_decode_call(fmt, words) 1768 comps = self.format_decode_call(fmt, words)
1738 # DST_SEL swizzle: 0 -> 0, 1 -> 1.0 (float/norm) or integer 1 (UINT/SINT; SHADER-86), 4..7 -> X..W. 1769 # DST_SEL swizzle: 0 -> 0, 1 -> 1.0 (float/norm) or integer 1 (UINT/SINT; SHADER-86), 4..7 -> X..W.
1739 is_int_fmt = "%false" 1770 is_int_fmt, is_signed = "%false", "%false"
1740 for code_v, (_, kind, _) in self.FORMATS.items(): 1771 for code_v, (_, kind, _) in self.FORMATS.items():
1741 if kind in ("u32", "uint"): 1772 if kind in ("u32", "i32", "uint"):
1742 e, o = self.tmp(), self.tmp() 1773 e, o = self.tmp(), self.tmp()
1743 self.emit(f"{e} = OpIEqual %bool {fmt} {self.cu(code_v)}") 1774 self.emit(f"{e} = OpIEqual %bool {fmt} {self.cu(code_v)}")
1744 self.emit(f"{o} = OpLogicalOr %bool {is_int_fmt} {e}") 1775 self.emit(f"{o} = OpLogicalOr %bool {is_int_fmt} {e}")
1745 is_int_fmt = o 1776 is_int_fmt = o
1777 if d16 and kind == "i32":
1778 signed = self.tmp()
1779 self.emit(f"{signed} = OpLogicalOr %bool {is_signed} {e}")
1780 is_signed = signed
1746 dst1 = self.tmp() 1781 dst1 = self.tmp()
1747 self.emit(f"{dst1} = OpSelect %uint {is_int_fmt} {self.cu(1)} {self.cu(0x3F800000)}") 1782 self.emit(f"{dst1} = OpSelect %uint {is_int_fmt} {self.cu(1)} {self.cu(0x3F800000)}")
1748 outs = [] 1783 outs = []
@@ -1762,33 +1797,32 @@ class Gen:
1762 else: 1797 else:
1763 self.dst({"k": "vgpr", "r": vd["r"] + c, "n": 1}, rb) 1798 self.dst({"k": "vgpr", "r": vd["r"] + c, "n": 1}, rb)
1764 if d16: 1799 if d16:
1765 # d16: two 16-bit results per register (x | y << 16, z | w << 16): f16 for float/normalized formats, 1800 # D16 packs two results per register, saturating integer formats according to signedness.
1766 # saturating unsigned conversion for integer formats (FORMATS kinds u32/uint). 1801 def int_half(word):
1767 is_int = "%false" 1802 unsigned = self.saturate_int16(word, signed=False)
1768 for code_v, (_, kind, _) in self.FORMATS.items(): 1803 signed = self.saturate_int16(word, signed=True)
1769 if kind in ("u32", "uint"): 1804 half = self.tmp()
1770 e, o = self.tmp(), self.tmp() 1805 self.emit(f"{half} = OpSelect %uint {is_signed} {signed} {unsigned}")
1771 self.emit(f"{e} = OpIEqual %bool {fmt} {self.cu(code_v)}") 1806 return half
1772 self.emit(f"{o} = OpLogicalOr %bool {is_int} {e}") 1807
1773 is_int = o
1774 for i in range(0, len(outs), 2): 1808 for i in range(0, len(outs), 2):
1775 dest = {"k": "vgpr", "r": vd["r"] + i // 2, "n": 1} 1809 dest = {"k": "vgpr", "r": vd["r"] + i // 2, "n": 1}
1776 lo = outs[i] 1810 lo = outs[i]
1777 il = self.saturate_int16(lo, signed=False) 1811 il = int_half(lo)
1778 r = self.tmp() 1812 r = self.tmp()
1779 if i + 1 == len(outs): 1813 if i + 1 == len(outs):
1780 # For d16_x and d16_xyz the unaddressed high half keeps its previous bits. 1814 # For d16_x and d16_xyz the unaddressed high half keeps its previous bits.
1781 fl = self.f16_bits(self.tof(lo)) 1815 fl = self.f16_bits(self.tof(lo))
1782 self.emit(f"{r} = OpSelect %uint {is_int} {il} {fl}") 1816 self.emit(f"{r} = OpSelect %uint {is_int_fmt} {il} {fl}")
1783 self.write_lo16(dest, r) 1817 self.write_lo16(dest, r)
1784 continue 1818 continue
1785 hi = outs[i + 1] 1819 hi = outs[i + 1]
1786 ph = self.pack_f16_pair_int(self.tof(lo), self.tof(hi)) 1820 ph = self.pack_f16_pair_int(self.tof(lo), self.tof(hi))
1787 ih, pi = self.tmp(), self.tmp() 1821 ih, pi = self.tmp(), self.tmp()
1788 high_half = self.saturate_int16(hi, signed=False) 1822 high_half = int_half(hi)
1789 self.emit(f"{ih} = OpShiftLeftLogical %uint {high_half} {self.cu(16)}") 1823 self.emit(f"{ih} = OpShiftLeftLogical %uint {high_half} {self.cu(16)}")
1790 self.emit(f"{pi} = OpBitwiseOr %uint {il} {ih}") 1824 self.emit(f"{pi} = OpBitwiseOr %uint {il} {ih}")
1791 self.emit(f"{r} = OpSelect %uint {is_int} {pi} {ph}") 1825 self.emit(f"{r} = OpSelect %uint {is_int_fmt} {pi} {ph}")
1792 self.dst(dest, r) 1826 self.dst(dest, r)
1793 1827
1794 def global_address(self, op, vaddr, saddr, mods): 1828 def global_address(self, op, vaddr, saddr, mods):
@@ -2344,6 +2378,13 @@ class Gen:
2344 self.emit(f"{red} = OpSelect %uint {bgra} {unorm_rgba[2]} {unorm_rgba[0]}") 2378 self.emit(f"{red} = OpSelect %uint {bgra} {unorm_rgba[2]} {unorm_rgba[0]}")
2345 self.emit(f"{blue} = OpSelect %uint {bgra} {unorm_rgba[0]} {unorm_rgba[2]}") 2379 self.emit(f"{blue} = OpSelect %uint {bgra} {unorm_rgba[0]} {unorm_rgba[2]}")
2346 unorm_view = [red, unorm_rgba[1], blue, unorm_rgba[3]] 2380 unorm_view = [red, unorm_rgba[1], blue, unorm_rgba[3]]
2381 signed_ic = ic
2382 if d16:
2383 signed_ic = []
2384 for component in ic[:n]:
2385 extended = self.tmp()
2386 self.emit(f"{extended} = OpBitFieldSExtract %int {self.as_int(component)} {self.cu(0)} {self.cu(16)}")
2387 signed_ic.append(self.tou(extended))
2347 for code, (size, kind, widths) in self.FORMATS.items(): 2388 for code, (size, kind, widths) in self.FORMATS.items():
2348 e = self.tmp() 2389 e = self.tmp()
2349 self.emit(f"{e} = OpIEqual %bool {fmt} {self.cu(code)}") 2390 self.emit(f"{e} = OpIEqual %bool {fmt} {self.cu(code)}")
@@ -2356,7 +2397,8 @@ class Gen:
2356 fcs = source[:ncomp] + [self.cu(0)] * (len(widths) - ncomp) 2397 fcs = source[:ncomp] + [self.cu(0)] * (len(widths) - ncomp)
2357 if code in (50, 56): 2398 if code in (50, 56):
2358 fcs = unorm_view 2399 fcs = unorm_view
2359 ics = ic[:ncomp] + [self.cu(0)] * (len(widths) - ncomp) 2400 integer_source = signed_ic if kind == "i32" else ic
2401 ics = integer_source[:ncomp] + [self.cu(0)] * (len(widths) - ncomp)
2360 words = self.encode_format(fcs + [self.cu(0)] * 4, ics + [self.cu(0)] * 4, code) 2402 words = self.encode_format(fcs + [self.cu(0)] * 4, ics + [self.cu(0)] * 4, code)
2361 if size >= 4: 2403 if size >= 4:
2362 for k, w in enumerate(words[:size // 4]): 2404 for k, w in enumerate(words[:size // 4]):
@@ -2609,6 +2651,26 @@ class Gen:
2609 olds.append(old) 2651 olds.append(old)
2610 for k, old in enumerate(olds): # every exchange before the first write (vdst may alias) 2652 for k, old in enumerate(olds): # every exchange before the first write (vdst may alias)
2611 self.dst({"k": "vgpr", "r": d["r"] + k, "n": 1}, old) 2653 self.dst({"k": "vgpr", "r": d["r"] + k, "n": 1}, old)
2654 elif name in ("ds_and_b64", "ds_or_b64", "ds_xor_b64"):
2655 # M = M op D on a 64-bit LDS element (the dwords at ADDR and ADDR + 4, low first); the _rtn_ form returns
2656 # the old 64 bits in a VGPR pair. A bitwise op works on each bit alone, so one 32-bit atomic per dword
2657 # leaves exactly the memory a 64-bit atomic would, with no Int64 atomics on Workgroup memory (optional in
2658 # Vulkan). The returned pair is two reads, so a 64-bit op from another lane on the same element between
2659 # them could be seen half done; the memory result is exact either way.
2660 d, ad, dat = (a[0], a[1], a[2]) if rtn else (None, a[0], a[1])
2661 if dat["k"] != "vgpr" or dat.get("n") != 2 or (d is not None and (d["k"] != "vgpr" or d.get("n") != 2)):
2662 raise Unsupported(op + " operands")
2663 k = {"ds_and_b64": "OpAtomicAnd", "ds_or_b64": "OpAtomicOr", "ds_xor_b64": "OpAtomicXor"}[name]
2664 addr = self.src_u(ad)
2665 vals = [self.load_reg("vgpr", dat["r"] + w) for w in range(2)]
2666 olds = []
2667 for w in range(2):
2668 old = self.tmp()
2669 self.emit(f"{old} = {k} %uint {self.lds_ptr(addr, off + 4 * w)} {sc} {sem} {vals[w]}")
2670 olds.append(old)
2671 if d is not None:
2672 for w in range(2):
2673 self.dst({"k": "vgpr", "r": d["r"] + w, "n": 1}, olds[w])
2612 elif op in ("ds_cmpst_rtn_b32", "ds_cmpst_b32"): 2674 elif op in ("ds_cmpst_rtn_b32", "ds_cmpst_b32"):
2613 # tmp = M[A]; M[A] = (tmp == DATA) ? DATA2 : tmp; the _rtn_ form returns tmp, ds_cmpst_b32 drops it. 2675 # tmp = M[A]; M[A] = (tmp == DATA) ? DATA2 : tmp; the _rtn_ form returns tmp, ds_cmpst_b32 drops it.
2614 d, ad, cmp_, src = (a[0], a[1], a[2], a[3]) if rtn else (None, a[0], a[1], a[2]) 2676 d, ad, cmp_, src = (a[0], a[1], a[2], a[3]) if rtn else (None, a[0], a[1], a[2])
@@ -2762,13 +2824,17 @@ class Gen:
2762 """On hardware a wave's lanes run each instruction together: every lane's access of one instruction comes 2824 """On hardware a wave's lanes run each instruction together: every lane's access of one instruction comes
2763 before every lane's access of the next. Two halves of an emulated wave can be in different subgroups, so an 2825 before every lane's access of the next. Two halves of an emulated wave can be in different subgroups, so an
2764 access that conflicts with an earlier one of the same segment (read after write, write after read, write 2826 access that conflicts with an earlier one of the same segment (read after write, write after read, write
2765 after write, on the same memory) waits for the next round, whose barrier orders the memory. Not ordered: 2827 after write, on the same memory) waits for the next round, whose barrier orders the memory. A scalar load
2766 scalar loads (s_load / s_buffer_load) of memory the wave wrote, and sampling an image it wrote.""" 2828 (s_load / s_buffer_load) is a read of the same memory as the vector ops: on hardware every lane's earlier
2829 store is done before the wave issues it, but here the other half could load before this half has stored
2830 (#1587: valu_fuzz --family mem --emulate, lanes 32-63 read the fill pattern). Not ordered: sampling an
2831 image the wave wrote."""
2767 if op in ("ds_swizzle_b32", "ds_bpermute_b32", "ds_permute_b32"): 2832 if op in ("ds_swizzle_b32", "ds_bpermute_b32", "ds_permute_b32"):
2768 return 2833 return
2769 if op.startswith("ds_"): 2834 if op.startswith("ds_"):
2770 kind = "lds" 2835 kind = "lds"
2771 elif op.startswith(("buffer_", "tbuffer_", "global_", "flat_", "image_load", "image_store", "image_atomic")): 2836 elif op.startswith(("buffer_", "tbuffer_", "global_", "flat_", "image_load", "image_store", "image_atomic",
2837 "s_load_", "s_buffer_load_")):
2772 kind = "mem" 2838 kind = "mem"
2773 else: 2839 else:
2774 return 2840 return
@@ -2992,6 +3058,9 @@ class Gen:
2992 """Run the lane-mask analysis and give every VGPR lane a mask is fetched back from a slot of its own, 3058 """Run the lane-mask analysis and give every VGPR lane a mask is fetched back from a slot of its own,
2993 after the real registers in the %sgpr array (the array grows by as many).""" 3059 after the real registers in the %sgpr array (the array grows by as many)."""
2994 self.lane_masks, self.mask_writes = lane_masks.analyse(*blocks) 3060 self.lane_masks, self.mask_writes = lane_masks.analyse(*blocks)
3061 # lane_masks merges a mask on one path with plain data on another by dropping the register,
3062 # so "not in cur_masks" does not prove it is data on every path. Keep a conservative set.
3063 self.ever_mask = {r for m in self.lane_masks.values() for r in m if isinstance(r, int)}
2995 slots = lane_masks.parked(blocks[0], self.lane_masks) 3064 slots = lane_masks.parked(blocks[0], self.lane_masks)
2996 self.parked = {slot: self.SGPRS + i for i, slot in enumerate(slots)} 3065 self.parked = {slot: self.SGPRS + i for i, slot in enumerate(slots)}
2997 3066
@@ -3041,6 +3110,18 @@ class Gen:
3041 (t == "vcc_hi" and self.wave64 and "vcc" in self.cur_masks) 3110 (t == "vcc_hi" and self.wave64 and "vcc" in self.cur_masks)
3042 return a["k"] == "sgpr" and all(a["r"] + i in self.cur_masks for i in range(a.get("n", 1))) 3111 return a["k"] == "sgpr" and all(a["r"] + i in self.cur_masks for i in range(a.get("n", 1)))
3043 3112
3113 def any_mask_word(self, a):
3114 """Whether any dword of an SGPR pair is a lane mask (EITHER constants are data here).
3115
3116 holds_lane_mask() needs every dword, but a pair with one mask word and one
3117 zero/-1 word is a zero-extended mask: selecting it as data would read this lane's bit.
3118 """
3119 return a["k"] == "sgpr" and any(a["r"] + i in self.cur_masks for i in range(a.get("n", 1)))
3120
3121 def any_ever_mask_word(self, a):
3122 """Whether any dword of an SGPR pair held a lane mask on any path, even earlier in the shader."""
3123 return a["k"] == "sgpr" and any(a["r"] + i in self.ever_mask for i in range(a.get("n", 1)))
3124
3044 def wave_mask(self, a): 3125 def wave_mask(self, a):
3045 """The whole wave's lane mask in operand `a` as real bits: (lanes 0-31, lanes 32-63). A register holds 3126 """The whole wave's lane mask in operand `a` as real bits: (lanes 0-31, lanes 32-63). A register holds
3046 only this lane's bit (all ones or zero), so each lane puts its bit at its own position and the subgroup 3127 only this lane's bit (all ones or zero), so each lane puts its bit at its own position and the subgroup
@@ -3379,20 +3460,20 @@ class Gen:
3379 return v 3460 return v
3380 3461
3381 def turn_angle(self, x): 3462 def turn_angle(self, x):
3382 """Reduce a turn count to [-0.5, 0.5) before scaling by 2*pi. 3463 """Reduce a turn count to [-0.5, 0.5] before scaling by 2*pi (SHADER-88).
3383 3464
3384 RDNA's v_sin/v_cos take turns and range-reduce in turns. Scaling first loses the fractional part for large 3465 RDNA's v_sin/v_cos take turns and range-reduce in turns. Scaling first loses the fractional part for large
3385 inputs (one f32 ulp at 255 turns is ~1.2e-4 rad) and leaves Sin outside the [-pi, pi] range where Vulkan 3466 inputs (one f32 ulp at 255 turns is ~1.2e-4 rad) and leaves Sin outside the [-pi, pi] range where Vulkan
3386 guarantees its precision. Fract first; keep -0 as -0 so Sin's sign survives. NaN and infinity stay NaN 3467 guarantees its precision. x - RoundEven(x) is exact in binary32 for every finite x, unlike Fract(x) (rounds
3387 through Fract/compare/select. 3468 1 - |x| for a negative x: -2**-26 became +0, and -0.1 was ~1.7e-7 off). RoundEven rather than Round so +-0.5
3469 reduce symmetrically. A zero keeps its sign (x - RoundEven(x) would turn -0 into +0). NaN and infinity stay
3470 NaN through the subtraction.
3388 """ 3471 """
3389 frac, gt, adj, sel, zero, t, arg = (self.tmp() for _ in range(7)) 3472 rnd, d, zero, t, arg = (self.tmp() for _ in range(5))
3390 self.emit(f"{frac} = OpExtInst %float %glsl Fract {x}") 3473 self.emit(f"{rnd} = OpExtInst %float %glsl RoundEven {x}")
3391 self.emit(f"{gt} = OpFOrdGreaterThan %bool {frac} {self.fconst(0.5)}") 3474 self.emit(f"{d} = OpFSub %float {x} {rnd}")
3392 self.emit(f"{adj} = OpFSub %float {frac} {self.fconst(1.0)}")
3393 self.emit(f"{sel} = OpSelect %float {gt} {adj} {frac}")
3394 self.emit(f"{zero} = OpFOrdEqual %bool {x} {self.fconst(0.0)}") 3475 self.emit(f"{zero} = OpFOrdEqual %bool {x} {self.fconst(0.0)}")
3395 self.emit(f"{t} = OpSelect %float {zero} {x} {sel}") 3476 self.emit(f"{t} = OpSelect %float {zero} {x} {d}")
3396 self.emit(f"{arg} = OpFMul %float {t} {self.fconst(6.283185307179586)}") 3477 self.emit(f"{arg} = OpFMul %float {t} {self.fconst(6.283185307179586)}")
3397 return arg 3478 return arg
3398 3479
@@ -3800,9 +3881,15 @@ class Gen:
3800 self.exec_half_write(0 if a[0]["t"] == "exec_lo" else 1, None if const is not None else self.src_u(src), 3881 self.exec_half_write(0 if a[0]["t"] == "exec_lo" else 1, None if const is not None else self.src_u(src),
3801 const) 3882 const)
3802 elif op == "v_mov_b32" or op == "s_mov_b32": 3883 elif op == "v_mov_b32" or op == "s_mov_b32":
3884 lit_val = None
3885 if op == "s_mov_b32" and a[0]["k"] == "sgpr" and self.desc_cache_ok():
3886 if a[1]["k"] == "imm":
3887 lit_val = a[1]["v"] & 0xFFFFFFFF # a literal S# word, see gather_addr_modes
3888 elif a[1]["k"] == "sgpr":
3889 lit_val = self.sgpr_imm.get(a[1]["r"])
3803 self.dst(a[0], self.src_u(a[1])) 3890 self.dst(a[0], self.src_u(a[1]))
3804 if op == "s_mov_b32" and a[0]["k"] == "sgpr" and a[1]["k"] == "imm" and self.desc_cache_ok(): 3891 if lit_val is not None:
3805 self.sgpr_imm[a[0]["r"]] = a[1]["v"] & 0xFFFFFFFF # a literal S# word, see gather_addr_modes 3892 self.sgpr_imm[a[0]["r"]] = lit_val
3806 elif op == "s_mov_b64": 3893 elif op == "s_mov_b64":
3807 self.mov64(a[0], a[1]) 3894 self.mov64(a[0], a[1])
3808 elif op in ("v_max3_f32", "v_min3_f32"): 3895 elif op in ("v_max3_f32", "v_min3_f32"):
@@ -4105,6 +4192,10 @@ class Gen:
4105 self.dst(a[0], r) 4192 self.dst(a[0], r)
4106 elif op == "v_pack_b32_f16": 4193 elif op == "v_pack_b32_f16":
4107 # dst = f16(src0) | f16(src1) << 16, each taken from the low half (op_sel picks high halves). 4194 # dst = f16(src0) | f16(src1) << 16, each taken from the low half (op_sel picks high halves).
4195 # neg/abs act on the selected 16-bit half of each source as plain bit moves, abs (clear bit 15) first and
4196 # neg (xor bit 15) second: on a Radeon 680M (gfx1036) ``-v0`` turned 0x7c01 into 0xfc01 under IEEE 0 and
4197 # 0xfe01 under IEEE 1, in either half and with op_sel (#1548 SHADER-260). abs rests on the ISA's sign
4198 # clear, it was not measured on this instruction. Only the IEEE 1 sNaN quieting is open (SHADER-190).
4108 sel = next((m for m in mods if m.startswith("op_sel:")), "op_sel:[0,0,0]") 4199 sel = next((m for m in mods if m.startswith("op_sel:")), "op_sel:[0,0,0]")
4109 sb = [int(x) for x in sel.split("[")[1].rstrip("]").split(",")] 4200 sb = [int(x) for x in sel.split("[")[1].rstrip("]").split(",")]
4110 halves = [] 4201 halves = []
@@ -4116,6 +4207,12 @@ class Gen:
4116 u = s 4207 u = s
4117 m = self.tmp() 4208 m = self.tmp()
4118 self.emit(f"{m} = OpBitwiseAnd %uint {u} {self.cu(0xFFFF)}") 4209 self.emit(f"{m} = OpBitwiseAnd %uint {u} {self.cu(0xFFFF)}")
4210 if src.get("abs"):
4211 # The ISA defines ABS on a float operand as |S|, a clear of the sign bit, and it is applied before
4212 # neg; no hardware run of this instruction with `abs` exists yet.
4213 a_ = self.tmp()
4214 self.emit(f"{a_} = OpBitwiseAnd %uint {m} {self.cu(0x7FFF)}")
4215 m = a_
4119 if src.get("neg"): 4216 if src.get("neg"):
4120 # SHADER-260, measured on gfx1036: a `neg` on this instruction flips the sign bit of the half it 4217 # SHADER-260, measured on gfx1036: a `neg` on this instruction flips the sign bit of the half it
4121 # packs, before any quieting (0x7c01 -> 0xfc01 in IEEE mode 0, -> 0xfe01 in mode 1), in either 4218 # packs, before any quieting (0x7c01 -> 0xfc01 in IEEE mode 0, -> 0xfe01 in mode 1), in either
@@ -4124,10 +4221,6 @@ class Gen:
4124 self.emit(f"{n} = OpBitwiseXor %uint {m} {self.cu(0x8000)}") 4221 self.emit(f"{n} = OpBitwiseXor %uint {m} {self.cu(0x8000)}")
4125 m = n 4222 m = n
4126 halves.append(m) 4223 halves.append(m)
4127 if any(src.get("abs") for src in a[1:3]):
4128 # `neg` is measured; `abs` on this instruction is not (SHADER-260), so it stays a refusal rather than
4129 # a guessed sign clear.
4130 raise Unsupported("v_pack_b32_f16 abs modifier")
4131 hi, r = self.tmp(), self.tmp() 4224 hi, r = self.tmp(), self.tmp()
4132 self.emit(f"{hi} = OpShiftLeftLogical %uint {halves[1]} {self.cu(16)}") 4225 self.emit(f"{hi} = OpShiftLeftLogical %uint {halves[1]} {self.cu(16)}")
4133 self.emit(f"{r} = OpBitwiseOr %uint {halves[0]} {hi}") 4226 self.emit(f"{r} = OpBitwiseOr %uint {halves[0]} {hi}")
@@ -4744,18 +4837,33 @@ class Gen:
4744 elif op == "v_alignbyte_b32": 4837 elif op == "v_alignbyte_b32":
4745 # (({src0, src1} as 64 bits) >> (8 * (src2 & 3))) low 32 bits 4838 # (({src0, src1} as 64 bits) >> (8 * (src2 & 3))) low 32 bits
4746 # (32 - b) & 31 keeps the left shift below 32 when b == 0; that result is discarded by the OpSelect. 4839 # (32 - b) & 31 keeps the left shift below 32 when b == 0; that result is discarded by the OpSelect.
4747 hi_, lo_, sh = (self.src_u(t) for t in a[1:4]) 4840 sh_val = self.imm_val(a[3])
4748 m, b, inv0, inv, a1, b1, nz, r0, r = (self.tmp() for _ in range(9)) 4841 if sh_val is not None:
4749 self.emit(f"{m} = OpBitwiseAnd %uint {sh} {self.cu(3)}") 4842 sel = sh_val & 3
4750 self.emit(f"{b} = OpShiftLeftLogical %uint {m} {self.cu(3)}") 4843 if sel == 0:
4751 self.emit(f"{inv0} = OpISub %uint {self.cu(32)} {b}") 4844 self.dst(a[0], self.src_u(a[2]))
4752 self.emit(f"{inv} = OpBitwiseAnd %uint {inv0} {self.cu(31)}") 4845 else:
4753 self.emit(f"{a1} = OpShiftRightLogical %uint {lo_} {b}") 4846 hi_, lo_ = self.src_u(a[1]), self.src_u(a[2])
4754 self.emit(f"{b1} = OpShiftLeftLogical %uint {hi_} {inv}") 4847 b = sel * 8
4755 self.emit(f"{r0} = OpBitwiseOr %uint {a1} {b1}") 4848 inv = 32 - b
4756 self.emit(f"{nz} = OpINotEqual %bool {b} {self.cu(0)}") 4849 a1, b1, r = self.tmp(), self.tmp(), self.tmp()
4757 self.emit(f"{r} = OpSelect %uint {nz} {r0} {lo_}") 4850 self.emit(f"{a1} = OpShiftRightLogical %uint {lo_} {self.cu(b)}")
4758 self.dst(a[0], r) 4851 self.emit(f"{b1} = OpShiftLeftLogical %uint {hi_} {self.cu(inv)}")
4852 self.emit(f"{r} = OpBitwiseOr %uint {a1} {b1}")
4853 self.dst(a[0], r)
4854 else:
4855 hi_, lo_, sh = (self.src_u(t) for t in a[1:4])
4856 m, b, inv0, inv, a1, b1, nz, r0, r = (self.tmp() for _ in range(9))
4857 self.emit(f"{m} = OpBitwiseAnd %uint {sh} {self.cu(3)}")
4858 self.emit(f"{b} = OpShiftLeftLogical %uint {m} {self.cu(3)}")
4859 self.emit(f"{inv0} = OpISub %uint {self.cu(32)} {b}")
4860 self.emit(f"{inv} = OpBitwiseAnd %uint {inv0} {self.cu(31)}")
4861 self.emit(f"{a1} = OpShiftRightLogical %uint {lo_} {b}")
4862 self.emit(f"{b1} = OpShiftLeftLogical %uint {hi_} {inv}")
4863 self.emit(f"{r0} = OpBitwiseOr %uint {a1} {b1}")
4864 self.emit(f"{nz} = OpINotEqual %bool {b} {self.cu(0)}")
4865 self.emit(f"{r} = OpSelect %uint {nz} {r0} {lo_}")
4866 self.dst(a[0], r)
4759 elif op == "v_swap_b32": 4867 elif op == "v_swap_b32":
4760 # exchange two VGPRs (active lanes only, through dst) 4868 # exchange two VGPRs (active lanes only, through dst)
4761 x, y = self.src_u(a[0]), self.src_u(a[1]) 4869 x, y = self.src_u(a[0]), self.src_u(a[1])
@@ -4830,17 +4938,31 @@ class Gen:
4830 elif op == "v_alignbit_b32": 4938 elif op == "v_alignbit_b32":
4831 # (({src0, src1} as 64 bits) >> (src2 & 31)) low 32 bits 4939 # (({src0, src1} as 64 bits) >> (src2 & 31)) low 32 bits
4832 # (32 - m) & 31 keeps the left shift below 32 when m == 0; that result is discarded by the OpSelect. 4940 # (32 - m) & 31 keeps the left shift below 32 when m == 0; that result is discarded by the OpSelect.
4833 hi_, lo_, sh = (self.src_u(t) for t in a[1:4]) 4941 sh_val = self.imm_val(a[3])
4834 m, inv0, inv, a1, b1, nz, r0, r = (self.tmp() for _ in range(8)) 4942 if sh_val is not None:
4835 self.emit(f"{m} = OpBitwiseAnd %uint {sh} {self.cu(31)}") 4943 m_val = sh_val & 31
4836 self.emit(f"{inv0} = OpISub %uint {self.cu(32)} {m}") 4944 if m_val == 0:
4837 self.emit(f"{inv} = OpBitwiseAnd %uint {inv0} {self.cu(31)}") 4945 self.dst(a[0], self.src_u(a[2]))
4838 self.emit(f"{a1} = OpShiftRightLogical %uint {lo_} {m}") 4946 else:
4839 self.emit(f"{b1} = OpShiftLeftLogical %uint {hi_} {inv}") 4947 hi_, lo_ = self.src_u(a[1]), self.src_u(a[2])
4840 self.emit(f"{r0} = OpBitwiseOr %uint {a1} {b1}") 4948 inv_val = 32 - m_val
4841 self.emit(f"{nz} = OpINotEqual %bool {m} {self.cu(0)}") 4949 a1, b1, r = self.tmp(), self.tmp(), self.tmp()
4842 self.emit(f"{r} = OpSelect %uint {nz} {r0} {lo_}") 4950 self.emit(f"{a1} = OpShiftRightLogical %uint {lo_} {self.cu(m_val)}")
4843 self.dst(a[0], r) 4951 self.emit(f"{b1} = OpShiftLeftLogical %uint {hi_} {self.cu(inv_val)}")
4952 self.emit(f"{r} = OpBitwiseOr %uint {a1} {b1}")
4953 self.dst(a[0], r)
4954 else:
4955 hi_, lo_, sh = (self.src_u(t) for t in a[1:4])
4956 m, inv0, inv, a1, b1, nz, r0, r = (self.tmp() for _ in range(8))
4957 self.emit(f"{m} = OpBitwiseAnd %uint {sh} {self.cu(31)}")
4958 self.emit(f"{inv0} = OpISub %uint {self.cu(32)} {m}")
4959 self.emit(f"{inv} = OpBitwiseAnd %uint {inv0} {self.cu(31)}")
4960 self.emit(f"{a1} = OpShiftRightLogical %uint {lo_} {m}")
4961 self.emit(f"{b1} = OpShiftLeftLogical %uint {hi_} {inv}")
4962 self.emit(f"{r0} = OpBitwiseOr %uint {a1} {b1}")
4963 self.emit(f"{nz} = OpINotEqual %bool {m} {self.cu(0)}")
4964 self.emit(f"{r} = OpSelect %uint {nz} {r0} {lo_}")
4965 self.dst(a[0], r)
4844 elif op in ("v_lshlrev_b64", "v_lshrrev_b64", "v_ashrrev_i64"): 4966 elif op in ("v_lshlrev_b64", "v_lshrrev_b64", "v_ashrrev_i64"):
4845 # v[d:d+1] = v[s:s+1] << / >> (src0 & 63): logical left, logical right, or arithmetic right (the sign 4967 # v[d:d+1] = v[s:s+1] << / >> (src0 & 63): logical left, logical right, or arithmetic right (the sign
4846 # bit 63 is copied in). 4968 # bit 63 is copied in).
@@ -5007,6 +5129,57 @@ class Gen:
5007 self.dst(a[0], v) 5129 self.dst(a[0], v)
5008 else: 5130 else:
5009 self.write_lo16(a[0], lo) 5131 self.write_lo16(a[0], lo)
5132 elif op in ("v_min3_i16", "v_min3_u16", "v_max3_i16", "v_max3_u16", "v_med3_i16", "v_med3_u16"):
5133 # Three-operand 16-bit integer min/max/median on the low halves (op_sel bits 0..2 pick the high half of
5134 # S0..S2, bit 3 writes the high half of D); VOP3-only, so the other half of D is kept (RDNA2 ISA; Mesa
5135 # ACO can_use_opsel). clamp is not modelled on integer min/max/med3.
5136 if "clamp" in mods:
5137 raise Unsupported(op + " clamp")
5138 sb, dhi = self.opsel_bits(mods, 3)
5139 if dhi and a[0]["k"] != "vgpr":
5140 raise Unsupported("op_sel destination")
5141 signed = op.endswith("_i16")
5142 vals = []
5143 for k, s_ in enumerate(a[1:4]):
5144 u = self.src_u(s_)
5145 if sb[k]:
5146 t = self.tmp()
5147 self.emit(f"{t} = OpShiftRightLogical %uint {u} {self.cu(16)}")
5148 u = t
5149 h = self.tmp()
5150 if signed:
5151 self.emit(f"{h} = OpBitFieldSExtract %int {self.as_int(u)} {self.cu(0)} {self.cu(16)}")
5152 else:
5153 self.emit(f"{h} = OpBitwiseAnd %uint {u} {self.cu(0xFFFF)}")
5154 vals.append(h)
5155 x, y, z = vals
5156 ty, pfx = ("%int", "S") if signed else ("%uint", "U")
5157 if "med3" in op:
5158 lo_, hi_, m = self.tmp(), self.tmp(), self.tmp()
5159 self.emit(f"{lo_} = OpExtInst {ty} %glsl {pfx}Min {x} {y}")
5160 self.emit(f"{hi_} = OpExtInst {ty} %glsl {pfx}Max {x} {y}")
5161 self.emit(f"{m} = OpExtInst {ty} %glsl {pfx}Clamp {z} {lo_} {hi_}")
5162 else:
5163 m0, m = self.tmp(), self.tmp()
5164 fn = pfx + ("Min" if "min3" in op else "Max")
5165 self.emit(f"{m0} = OpExtInst {ty} %glsl {fn} {x} {y}")
5166 self.emit(f"{m} = OpExtInst {ty} %glsl {fn} {m0} {z}")
5167 if signed:
5168 r = self.tmp()
5169 self.emit(f"{r} = OpBitcast %uint {m}")
5170 else:
5171 r = m
5172 lo = self.tmp()
5173 self.emit(f"{lo} = OpBitwiseAnd %uint {r} {self.cu(0xFFFF)}")
5174 if dhi:
5175 old, keep, sh16, v = (self.tmp() for _ in range(4))
5176 self.emit(f"{old} = OpCopyObject %uint {self.load_reg('vgpr', a[0]['r'])}")
5177 self.emit(f"{keep} = OpBitwiseAnd %uint {old} {self.cu(0xFFFF)}")
5178 self.emit(f"{sh16} = OpShiftLeftLogical %uint {lo} {self.cu(16)}")
5179 self.emit(f"{v} = OpBitwiseOr %uint {keep} {sh16}")
5180 self.dst(a[0], v)
5181 else:
5182 self.write_lo16(a[0], lo)
5010 elif op == "v_bcnt_u32_b32": 5183 elif op == "v_bcnt_u32_b32":
5011 x, acc = self.src_u(a[1]), self.src_u(a[2]) 5184 x, acc = self.src_u(a[1]), self.src_u(a[2])
5012 c, r = self.tmp(), self.tmp() 5185 c, r = self.tmp(), self.tmp()
@@ -5100,7 +5273,8 @@ class Gen:
5100 elif op in ("s_movrels_b32", "s_movrels_b64"): 5273 elif op in ("s_movrels_b32", "s_movrels_b64"):
5101 # Relative SGPR read through M0 (RDNA2 ISA SOP1): D = SGPR[S0 + M0] (the b64 form reads the pair at 5274 # Relative SGPR read through M0 (RDNA2 ISA SOP1): D = SGPR[S0 + M0] (the b64 form reads the pair at
5102 # S0 + M0 and S0 + M0 + 1). The SGPR file is an array, so this is a dynamic load, as v_movrels is for 5275 # S0 + M0 and S0 + M0 + 1). The SGPR file is an array, so this is a dynamic load, as v_movrels is for
5103 # VGPRs. The index wraps to the 128 array slots, so it can't reach the lane-mask parking slots past them; 5276 # VGPRs. The index wraps to the 128 array slots, so it can't reach the lane-mask parking slots past them
5277 # (an SGPR that holds a lane mask is handled below);
5104 # the hardware's own range check (and reads past s105 landing on VCC and the other specials) is not 5278 # the hardware's own range check (and reads past s105 landing on VCC and the other specials) is not
5105 # modelled. SCC is not written. s_movreld (a dynamic SGPR write) stays Unsupported: the translator keeps 5279 # modelled. SCC is not written. s_movreld (a dynamic SGPR write) stays Unsupported: the translator keeps
5106 # translate-time knowledge of SGPR values (literal S# words, descriptor caches) a dynamic write would 5280 # translate-time knowledge of SGPR values (literal S# words, descriptor caches) a dynamic write would
@@ -5109,6 +5283,17 @@ class Gen:
5109 d, src = a[0], a[1] 5283 d, src = a[0], a[1]
5110 if d["k"] != "sgpr" or src["k"] != "sgpr" or d.get("n", 1) != n or src.get("n", 1) != n: 5284 if d["k"] != "sgpr" or src["k"] != "sgpr" or d.get("n", 1) != n or src.get("n", 1) != n:
5111 raise Unsupported(op + " operands") 5285 raise Unsupported(op + " operands")
5286 # An SGPR that lane_masks.py marks as a lane mask holds only this lane's bit, so a plain load would copy
5287 # that bit as data (a saved EXEC of 5 read back as 0xffffffff in lanes 0 and 2, 0 elsewhere). For each
5288 # such SGPR the whole wave's mask word is collected first (wave_mask, as for s_bcnt1) and replaces the
5289 # load when the index lands on it. D then holds the mask as data, which is what lane_masks.py assumes
5290 # for an s_movrels destination. The index is dynamic, so every mask SGPR here is a candidate (#1548,
5291 # SHADER-284).
5292 mask_words = []
5293 for r in sorted(k for k in self.cur_masks if isinstance(k, int) and k < self.SGPRS):
5294 reg = {"k": "sgpr", "r": r, "n": 1}
5295 lo, hi = self.wave_mask(reg)
5296 mask_words.append((r, hi if self.mask_half(reg) == "hi" else lo))
5112 m0 = self.tmp() 5297 m0 = self.tmp()
5113 self.emit(f"{m0} = OpLoad %uint %m0") 5298 self.emit(f"{m0} = OpLoad %uint %m0")
5114 vals = [] 5299 vals = []
@@ -5118,9 +5303,42 @@ class Gen:
5118 self.emit(f"{j} = OpBitwiseAnd %uint {i} {self.cu(self.SGPRS - 1)}") 5303 self.emit(f"{j} = OpBitwiseAnd %uint {i} {self.cu(self.SGPRS - 1)}")
5119 self.emit(f"{ptr} = OpAccessChain %_ptr_Function_uint %sgpr {j}") 5304 self.emit(f"{ptr} = OpAccessChain %_ptr_Function_uint %sgpr {j}")
5120 self.emit(f"{v} = OpLoad %uint {ptr}") 5305 self.emit(f"{v} = OpLoad %uint {ptr}")
5306 for r, word in mask_words:
5307 hit, sel = self.tmp(), self.tmp()
5308 self.emit(f"{hit} = OpIEqual %bool {j} {self.cu(r)}")
5309 self.emit(f"{sel} = OpSelect %uint {hit} {word} {v}")
5310 v = sel
5121 vals.append(v) 5311 vals.append(v)
5122 for w, v in enumerate(vals): # every read before the first write (D may overlap the source) 5312 for w, v in enumerate(vals): # every read before the first write (D may overlap the source)
5123 self.store_reg("sgpr", d["r"] + w, v) 5313 self.store_reg("sgpr", d["r"] + w, v)
5314 elif op == "v_swaprel_b32":
5315 # GFX10 VOP1 (opcode 104): swap VGPR[D + M0[25:16]] and VGPR[S0 + M0[9:0]], the fields v_movrelsd_2_b32
5316 # uses (RDNA2 ISA: tmp = VGPR[D + M0[25:16]]; VGPR[D + M0[25:16]] = VGPR[S0 + M0[9:0]];
5317 # VGPR[S0 + M0[9:0]] = tmp). Both registers are read before either is written; inactive lanes keep both.
5318 # As for v_movrel*, the hardware's range check against the VGPR allocation is not modelled.
5319 d, s0 = a[0], a[1]
5320 if d["k"] != "vgpr" or s0["k"] != "vgpr":
5321 raise Unsupported(op + " operands")
5322 m0, lo, hi, md = (self.tmp() for _ in range(4))
5323 self.emit(f"{m0} = OpLoad %uint %m0")
5324 self.emit(f"{lo} = OpBitwiseAnd %uint {m0} {self.cu(0x3FF)}")
5325 self.emit(f"{hi} = OpShiftRightLogical %uint {m0} {self.cu(16)}")
5326 self.emit(f"{md} = OpBitwiseAnd %uint {hi} {self.cu(0x3FF)}")
5327 ptrs, vals = [], []
5328 for reg, off in ((d["r"], md), (s0["r"], lo)):
5329 i, p_, v = self.tmp(), self.tmp(), self.tmp()
5330 self.emit(f"{i} = OpIAdd %uint {self.cu(reg)} {off}")
5331 self.emit(f"{p_} = OpAccessChain %_ptr_Function_uint %vgpr {i}")
5332 self.emit(f"{v} = OpLoad %uint {p_}")
5333 ptrs.append(p_)
5334 vals.append(v)
5335 act = self.active_b()
5336 # D's slot gets S0's value, then S0's slot gets D's old value: when both name one register the second
5337 # store writes back its own value, so the register is unchanged, as a swap with itself is.
5338 for p_, new, old in ((ptrs[0], vals[1], vals[0]), (ptrs[1], vals[0], vals[1])):
5339 sel = self.tmp()
5340 self.emit(f"{sel} = OpSelect %uint {act} {new} {old}")
5341 self.emit(f"OpStore {p_} {sel}")
5124 elif op in ("v_movrels_b32", "v_movreld_b32", "v_movrelsd_b32", "v_movrelsd_2_b32"): 5342 elif op in ("v_movrels_b32", "v_movreld_b32", "v_movrelsd_b32", "v_movrelsd_2_b32"):
5125 # Relative VGPR indexing through M0: movrels reads VGPR[src + M0], movreld writes VGPR[dst + M0], 5343 # Relative VGPR indexing through M0: movrels reads VGPR[src + M0], movreld writes VGPR[dst + M0],
5126 # movrelsd does both. The register file is an array, so these become dynamic array accesses. 5344 # movrelsd does both. The register file is an array, so these become dynamic array accesses.
@@ -5153,10 +5371,16 @@ class Gen:
5153 self.emit(f"OpStore {dp} {sel}") 5371 self.emit(f"OpStore {dp} {sel}")
5154 else: 5372 else:
5155 self.dst(d, v) 5373 self.dst(d, v)
5156 elif op == "v_med3_f16": 5374 elif op in ("v_med3_f16", "v_min3_f16", "v_max3_f16"):
5157 sel, dhi = self.opsel_bits(mods, 3) # op_sel:[src0,src1,src2,dst] 5375 sel, dhi = self.opsel_bits(mods, 3) # op_sel:[src0,src1,src2,dst]
5158 vals = [self.f16_in(s, sel[i]) for i, s in enumerate(a[1:4])] 5376 vals = [self.f16_in(s, sel[i]) for i, s in enumerate(a[1:4])]
5159 r = self.med3_f(vals, a[1:4], sel) 5377 if op == "v_med3_f16":
5378 r = self.med3_f(vals, a[1:4], sel)
5379 else:
5380 f = "NMax" if "max" in op else "NMin" # a NaN operand gives the other one (docs/design.md)
5381 m, r = self.tmp(), self.tmp()
5382 self.emit(f"{m} = OpExtInst %float %glsl {f} {vals[0]} {vals[1]}")
5383 self.emit(f"{r} = OpExtInst %float %glsl {f} {m} {vals[2]}")
5160 r = self.clamp_mods(r, mods) 5384 r = self.clamp_mods(r, mods)
5161 self.f16_out(a[0], r, dhi) # opsel-capable VOP3: keeps the other half (Mesa ACO can_use_opsel) 5385 self.f16_out(a[0], r, dhi) # opsel-capable VOP3: keeps the other half (Mesa ACO can_use_opsel)
5162 elif op in ("v_qsad_pk_u16_u8", "v_mqsad_pk_u16_u8"): 5386 elif op in ("v_qsad_pk_u16_u8", "v_mqsad_pk_u16_u8"):
@@ -5411,13 +5635,20 @@ class Gen:
5411 else: 5635 else:
5412 self.mask_dst(d, r) 5636 self.mask_dst(d, r)
5413 elif op == "s_not_b32": 5637 elif op == "s_not_b32":
5414 x = self.src_u(a[1]) 5638 x_val = self.imm_val(a[1])
5415 r = self.tmp() 5639 if x_val is not None:
5416 self.emit(f"{r} = OpNot %uint {x}") 5640 val = (~x_val) & 0xFFFFFFFF
5417 self.dst(a[0], r) 5641 r = self.cu(val)
5418 z = self.tmp() 5642 self.dst(a[0], r)
5419 self.emit(f"{z} = OpSelect %uint {self.tmp_bool_nz(r)} {self.cu(1)} {self.cu(0)}") 5643 self.emit(f"OpStore %scc {self.cu(1 if val != 0 else 0)}")
5420 self.emit(f"OpStore %scc {z}") 5644 else:
5645 x = self.src_u(a[1])
5646 r = self.tmp()
5647 self.emit(f"{r} = OpNot %uint {x}")
5648 self.dst(a[0], r)
5649 z = self.tmp()
5650 self.emit(f"{z} = OpSelect %uint {self.tmp_bool_nz(r)} {self.cu(1)} {self.cu(0)}")
5651 self.emit(f"OpStore %scc {z}")
5421 elif op in ("s_cmp_eq_u64", "s_cmp_lg_u64"): 5652 elif op in ("s_cmp_eq_u64", "s_cmp_lg_u64"):
5422 # 64-bit compare of masks/pointers: equal iff both halves are equal. 5653 # 64-bit compare of masks/pointers: equal iff both halves are equal.
5423 m0, m1 = self.holds_lane_mask(a[0]), self.holds_lane_mask(a[1]) 5654 m0, m1 = self.holds_lane_mask(a[0]), self.holds_lane_mask(a[1])
@@ -5661,6 +5892,16 @@ class Gen:
5661 self.cu(3), self.cu(4) 5892 self.cu(3), self.cu(4)
5662 elif op in ("s_add_i32", "s_sub_i32", "s_min_u32", "s_max_u32", "s_xor_b32", "s_andn2_b32", 5893 elif op in ("s_add_i32", "s_sub_i32", "s_min_u32", "s_max_u32", "s_xor_b32", "s_andn2_b32",
5663 "s_cselect_b32", "s_orn2_b32", "s_nand_b32", "s_nor_b32", "s_xnor_b32"): 5894 "s_cselect_b32", "s_orn2_b32", "s_nand_b32", "s_nor_b32", "s_xnor_b32"):
5895 if op == "s_xor_b32":
5896 x_val, y_val = self.imm_val(a[1]), self.imm_val(a[2])
5897 writes_exec = a[0]["k"] == "special" and a[0].get("t", "").startswith("exec")
5898 is_mask = not self.wave64 and (writes_exec or self.holds_lane_mask(a[1]) or self.holds_lane_mask(a[2]))
5899 if x_val is not None and y_val is not None and not is_mask:
5900 val = (x_val ^ y_val) & 0xFFFFFFFF
5901 r = self.cu(val)
5902 self.dst(a[0], r)
5903 self.emit(f"OpStore %scc {self.cu(1 if val != 0 else 0)}")
5904 return
5664 x, y = self.src_u(a[1]), self.src_u(a[2]) 5905 x, y = self.src_u(a[1]), self.src_u(a[2])
5665 r = self.tmp() 5906 r = self.tmp()
5666 if op == "s_cselect_b32": 5907 if op == "s_cselect_b32":
@@ -5889,7 +6130,10 @@ class Gen:
5889 self.dst(a[0], self.tou(f)) 6130 self.dst(a[0], self.tou(f))
5890 elif op == "s_movk_i32": 6131 elif op == "s_movk_i32":
5891 v = a[1]["v"] & 0xFFFF 6132 v = a[1]["v"] & 0xFFFF
5892 self.dst(a[0], self.cu(v - 0x10000 if v & 0x8000 else v)) 6133 val = (v - 0x10000 if v & 0x8000 else v) & 0xFFFFFFFF
6134 self.dst(a[0], self.cu(val))
6135 if a[0]["k"] == "sgpr" and self.desc_cache_ok():
6136 self.sgpr_imm[a[0]["r"]] = val
5893 elif op in ("s_cmov_b32", "s_cmovk_i32"): 6137 elif op in ("s_cmov_b32", "s_cmovk_i32"):
5894 # D = SCC ? S0 : D (s_cmovk_i32: S0 is the 16-bit immediate, sign-extended). SCC is read, not written. 6138 # D = SCC ? S0 : D (s_cmovk_i32: S0 is the 16-bit immediate, sign-extended). SCC is read, not written.
5895 if a[0]["k"] != "sgpr": 6139 if a[0]["k"] != "sgpr":
@@ -5904,6 +6148,26 @@ class Gen:
5904 self.emit(f"{c} = OpLoad %uint %scc") 6148 self.emit(f"{c} = OpLoad %uint %scc")
5905 self.emit(f"{r} = OpSelect %uint {self.tmp_bool_nz(c)} {x} {old}") 6149 self.emit(f"{r} = OpSelect %uint {self.tmp_bool_nz(c)} {x} {old}")
5906 self.dst(a[0], r) 6150 self.dst(a[0], r)
6151 elif op == "s_cmov_b64":
6152 # RDNA2 ISA SOP1: D = SCC ? S0 : D, SCC read and not written (LLVM AMDGPU SOPInstructions.td:
6153 # S_CMOV_B64 : SOP1_64 under Uses = [SCC]). Plain 64-bit data only: a lane-mask pair holds one
6154 # lane's bit here, so selecting it as data would silently read a bool instead of the wave's mask
6155 # (issue #210). Those operands keep failing loudly.
6156 if self.is_mask_op(a[1]) or self.any_mask_word(a[1]) or self.any_ever_mask_word(a[1]):
6157 raise Unsupported("s_cmov_b64 lane-mask source")
6158 if a[0]["k"] != "sgpr" or a[0].get("n") != 2:
6159 raise Unsupported("s_cmov_b64 destination")
6160 if self.holds_lane_mask(a[0]) or self.any_mask_word(a[0]) or self.any_ever_mask_word(a[0]):
6161 raise Unsupported("s_cmov_b64 lane-mask destination")
6162 (xlo, xhi) = self.src64_data(a[1], op)
6163 # Read both old dwords before any store, so D overlapping S0 stays exact.
6164 oldlo, oldhi = self.load_reg("sgpr", a[0]["r"]), self.load_reg("sgpr", a[0]["r"] + 1)
6165 c, rlo, rhi = self.tmp(), self.tmp(), self.tmp()
6166 self.emit(f"{c} = OpLoad %uint %scc")
6167 b = self.tmp_bool_nz(c)
6168 self.emit(f"{rlo} = OpSelect %uint {b} {xlo} {oldlo}")
6169 self.emit(f"{rhi} = OpSelect %uint {b} {xhi} {oldhi}")
6170 self.dst64_data(a[0], rlo, rhi, op)
5907 elif op.startswith("v_cmp_") and not op.startswith("v_cmp_class") and not op.endswith(("_u64", "_i64")): 6171 elif op.startswith("v_cmp_") and not op.startswith("v_cmp_class") and not op.endswith(("_u64", "_i64")):
5908 self.compare(op, a, scalar=False, mods=mods) 6172 self.compare(op, a, scalar=False, mods=mods)
5909 elif op.startswith("v_cmpx_") and not op.startswith("v_cmpx_class") and not op.endswith(("_u64", "_i64")): 6173 elif op.startswith("v_cmpx_") and not op.startswith("v_cmpx_class") and not op.endswith(("_u64", "_i64")):
@@ -6159,16 +6423,7 @@ class Gen:
6159 self.scc_nonzero(r) 6423 self.scc_nonzero(r)
6160 elif op in ("v_fma_mixlo_f16", "v_fma_mixhi_f16"): 6424 elif op in ("v_fma_mixlo_f16", "v_fma_mixhi_f16"):
6161 vals = self.fma_mix_srcs(a, mods) 6425 vals = self.fma_mix_srcs(a, mods)
6162 r = self.tmp() 6426 r = self.fma_mix_odd(*vals)
6163 self.emit_fma(r, vals[0], vals[1], vals[2])
6164 if self.round_mode:
6165 # Toward zero the hardware rounds the exact fma once, to f16; round-to-odd at f32 narrows exactly.
6166 # Nearest even keeps the f32 Fma then narrow (unchanged).
6167 ro, m, isz, rs = self.fma_mix_odd(*vals), self.tmp(), self.tmp(), self.tmp()
6168 self.emit(f"{m} = OpLoad %uint %mode_r16")
6169 self.emit(f"{isz} = OpIEqual %bool {m} {self.cu(3)}")
6170 self.emit(f"{rs} = OpSelect %float {isz} {ro} {r}")
6171 r = rs
6172 r = self.clamp_mods(r, mods) 6427 r = self.clamp_mods(r, mods)
6173 self.f16_out(a[0], r, hi=(op == "v_fma_mixhi_f16")) 6428 self.f16_out(a[0], r, hi=(op == "v_fma_mixhi_f16"))
6174 elif op == "v_cvt_pk_u8_f32": 6429 elif op == "v_cvt_pk_u8_f32":
@@ -6423,19 +6678,49 @@ class Gen:
6423 self.emit(f"{result} = OpSelect %uint {in_range} {converted} {saturated}") 6678 self.emit(f"{result} = OpSelect %uint {in_range} {converted} {saturated}")
6424 self.dst(a[0], result) 6679 self.dst(a[0], result)
6425 elif op in U2 or op in S2: 6680 elif op in U2 or op in S2:
6426 x, y = self.src_u(a[1]), self.src_u(a[2]) 6681 if op in S2:
6682 x_val, y_val = self.imm_val(a[1]), self.imm_val(a[2])
6683 writes_exec = a[0]["k"] == "special" and a[0].get("t", "").startswith("exec")
6684 is_mask = not self.wave64 and (writes_exec or self.holds_lane_mask(a[1]) or self.holds_lane_mask(a[2]))
6685 if x_val is not None and y_val is not None and not is_mask:
6686 folded = None
6687 if op == "s_and_b32":
6688 folded = (x_val & y_val) & 0xFFFFFFFF
6689 elif op == "s_or_b32":
6690 folded = (x_val | y_val) & 0xFFFFFFFF
6691 elif op == "s_lshl_b32":
6692 folded = (x_val << (y_val & 31)) & 0xFFFFFFFF
6693 elif op == "s_lshr_b32":
6694 folded = (x_val >> (y_val & 31)) & 0xFFFFFFFF
6695 elif op == "s_mul_i32":
6696 folded = (x_val * y_val) & 0xFFFFFFFF
6697 if folded is not None:
6698 r = self.cu(folded)
6699 self.dst(a[0], r)
6700 if op in ("s_and_b32", "s_or_b32", "s_lshl_b32", "s_lshr_b32"):
6701 self.emit(f"OpStore %scc {self.cu(1 if folded != 0 else 0)}")
6702 return
6427 r = self.tmp() 6703 r = self.tmp()
6428 kind = U2.get(op) or S2.get(op) 6704 kind = U2.get(op) or S2.get(op)
6429 if kind == "mul24": 6705 if kind == "mul24":
6706 x, y = self.src_u(a[1]), self.src_u(a[2])
6430 xm, ym = self.tmp(), self.tmp() 6707 xm, ym = self.tmp(), self.tmp()
6431 self.emit(f"{xm} = OpBitwiseAnd %uint {x} {self.cu(0xFFFFFF)}") 6708 self.emit(f"{xm} = OpBitwiseAnd %uint {x} {self.cu(0xFFFFFF)}")
6432 self.emit(f"{ym} = OpBitwiseAnd %uint {y} {self.cu(0xFFFFFF)}") 6709 self.emit(f"{ym} = OpBitwiseAnd %uint {y} {self.cu(0xFFFFFF)}")
6433 self.emit(f"{r} = OpIMul %uint {xm} {ym}") 6710 self.emit(f"{r} = OpIMul %uint {xm} {ym}")
6434 else: 6711 else:
6435 if op in ("s_lshl_b32", "s_lshr_b32"): 6712 if op in ("s_lshl_b32", "s_lshr_b32"):
6436 m = self.tmp() 6713 y_val = self.imm_val(a[2])
6437 self.emit(f"{m} = OpBitwiseAnd %uint {y} {self.cu(31)}") 6714 if y_val is not None:
6438 y = m 6715 y = self.cu(y_val & 31)
6716 else:
6717 y_raw = self.src_u(a[2])
6718 m = self.tmp()
6719 self.emit(f"{m} = OpBitwiseAnd %uint {y_raw} {self.cu(31)}")
6720 y = m
6721 else:
6722 y = self.src_u(a[2])
6723 x = self.src_u(a[1])
6439 self.emit(f"{r} = {kind} %uint {x} {y}") 6724 self.emit(f"{r} = {kind} %uint {x} {y}")
6440 self.dst(a[0], r) 6725 self.dst(a[0], r)
6441 if op in ("s_and_b32", "s_or_b32"): 6726 if op in ("s_and_b32", "s_or_b32"):
@@ -6443,18 +6728,41 @@ class Gen:
6443 elif op in ("s_lshl_b32", "s_lshr_b32"): 6728 elif op in ("s_lshl_b32", "s_lshr_b32"):
6444 self.scc_nonzero(r) 6729 self.scc_nonzero(r)
6445 elif op in SHIFT_REV: 6730 elif op in SHIFT_REV:
6446 sh, x = self.src_u(a[1]), self.src_u(a[2]) 6731 sh_val = self.imm_val(a[1])
6447 m, r = self.tmp(), self.tmp() 6732 if sh_val is not None:
6448 self.emit(f"{m} = OpBitwiseAnd %uint {sh} {self.cu(31)}") 6733 m = self.cu(sh_val & 31)
6734 else:
6735 sh = self.src_u(a[1])
6736 m = self.tmp()
6737 self.emit(f"{m} = OpBitwiseAnd %uint {sh} {self.cu(31)}")
6738 x = self.src_u(a[2])
6739 r = self.tmp()
6449 self.emit(f"{r} = {SHIFT_REV[op]} %uint {x} {m}") 6740 self.emit(f"{r} = {SHIFT_REV[op]} %uint {x} {m}")
6450 self.dst(a[0], r) 6741 self.dst(a[0], r)
6451 elif op in ("v_bfe_u32", "v_bfe_i32"): 6742 elif op in ("v_bfe_u32", "v_bfe_i32"):
6452 # offset and width are taken mod 32 (a width of 0 gives 0) 6743 # offset and width are taken mod 32 (a width of 0 gives 0)
6453 x, o, w = (self.src_u(t) for t in a[1:4]) 6744 o_val, w_val = self.imm_val(a[2]), self.imm_val(a[3])
6454 om, wm, r = self.tmp(), self.tmp(), self.tmp() 6745 if o_val is not None and w_val is not None:
6455 self.emit(f"{om} = OpBitwiseAnd %uint {o} {self.cu(31)}") 6746 off = o_val & 31
6456 self.emit(f"{wm} = OpBitwiseAnd %uint {w} {self.cu(31)}") 6747 wid = min(w_val & 31, 32 - off)
6457 wc = self.bfe_width(om, wm) 6748 om = self.cu(off)
6749 wc = self.cu(wid)
6750 else:
6751 if o_val is not None:
6752 om = self.cu(o_val & 31)
6753 else:
6754 o = self.src_u(a[2])
6755 om = self.tmp()
6756 self.emit(f"{om} = OpBitwiseAnd %uint {o} {self.cu(31)}")
6757 if w_val is not None:
6758 wm = self.cu(w_val & 31)
6759 else:
6760 w = self.src_u(a[3])
6761 wm = self.tmp()
6762 self.emit(f"{wm} = OpBitwiseAnd %uint {w} {self.cu(31)}")
6763 wc = self.bfe_width(om, wm)
6764 x = self.src_u(a[1])
6765 r = self.tmp()
6458 f = "OpBitFieldSExtract" if op.endswith("i32") else "OpBitFieldUExtract" 6766 f = "OpBitFieldSExtract" if op.endswith("i32") else "OpBitFieldUExtract"
6459 self.emit(f"{r} = {f} %uint {x} {om} {wc}") 6767 self.emit(f"{r} = {f} %uint {x} {om} {wc}")
6460 self.dst(a[0], r) 6768 self.dst(a[0], r)
@@ -6534,6 +6842,24 @@ class Gen:
6534 self.emit(f"{m} = OpIMul %uint {hs[0]} {hs[1]}") 6842 self.emit(f"{m} = OpIMul %uint {hs[0]} {hs[1]}")
6535 self.emit(f"{r} = OpIAdd %uint {m} {self.src_u(a[3])}") 6843 self.emit(f"{r} = OpIAdd %uint {m} {self.src_u(a[3])}")
6536 self.dst(a[0], r) 6844 self.dst(a[0], r)
6845 elif op in ("v_dot4_i32_i8", "v_dot4c_i32_i8"):
6846 # The four products of the signed bytes of two dwords, summed, plus an addend: the third source for
6847 # v_dot4_i32_i8 (VOP3P), the destination's old value for v_dot4c_i32_i8 (VOP2). The sum wraps at 32 bits.
6848 # Measured on RDNA2 hardware (docs/design.md, "Signed-byte dot products"), where clamp saturates
6849 # v_dot4_i32_i8 to a signed 32-bit value and op_sel picks the 16-bit half of a source each half of the
6850 # product reads. llvm-mc prints neither for the programs measured, so both forms are refused, not guessed.
6851 if "clamp" in mods or any(m.startswith("op_sel") for m in mods):
6852 raise Unsupported(op + (" clamp" if "clamp" in mods else " op_sel"))
6853 x, y = self.src_u(a[1]), self.src_u(a[2])
6854 acc = self.src_u(a[3]) if op == "v_dot4_i32_i8" else self.src_u(a[0])
6855 for i in range(4):
6856 xb, yb, prod, total = (self.tmp() for _ in range(4))
6857 self.emit(f"{xb} = OpBitFieldSExtract %uint {x} {self.cu(8 * i)} {self.cu(8)}")
6858 self.emit(f"{yb} = OpBitFieldSExtract %uint {y} {self.cu(8 * i)} {self.cu(8)}")
6859 self.emit(f"{prod} = OpIMul %uint {xb} {yb}")
6860 self.emit(f"{total} = OpIAdd %uint {acc} {prod}")
6861 acc = total
6862 self.dst(a[0], acc)
6537 elif op == "v_mad_u32_u24": 6863 elif op == "v_mad_u32_u24":
6538 x, y, z = (self.src_u(t) for t in a[1:4]) 6864 x, y, z = (self.src_u(t) for t in a[1:4])
6539 xm, ym, p, r = self.tmp(), self.tmp(), self.tmp(), self.tmp() 6865 xm, ym, p, r = self.tmp(), self.tmp(), self.tmp(), self.tmp()
@@ -6602,8 +6928,12 @@ class Gen:
6602 except ValueError: 6928 except ValueError:
6603 raise Unsupported(f"{op} offset:{inst[0]}") from None 6929 raise Unsupported(f"{op} offset:{inst[0]}") from None
6604 reg = None 6930 reg = None
6931 off_val = self.imm_val(off)
6605 if off["k"] == "imm": 6932 if off["k"] == "imm":
6606 imm = off["v"] # immediate-only form 6933 imm = off["v"] # immediate-only form
6934 elif off_val is not None:
6935 off_trunc = off_val & ~3
6936 imm = (imm & ~3) + off_trunc
6607 else: 6937 else:
6608 reg = self.src_u(off) 6938 reg = self.src_u(off)
6609 if sbuf: 6939 if sbuf:
@@ -6634,21 +6964,36 @@ class Gen:
6634 self.emit(f"{ptr} = OpConvertUToPtr %_ptr_PSB_arr {self.host_addr(full)}") 6964 self.emit(f"{ptr} = OpConvertUToPtr %_ptr_PSB_arr {self.host_addr(full)}")
6635 self.uses_psb = True 6965 self.uses_psb = True
6636 lim = None 6966 lim = None
6967 lim_val = None
6637 if sbuf: 6968 if sbuf:
6638 # limit = NUM_RECORDS * stride, or NUM_RECORDS when stride is 0 (bytes, 64-bit so the product can't wrap) 6969 # limit = NUM_RECORDS * stride, or NUM_RECORDS when stride is 0 (bytes, 64-bit so the product can't wrap)
6639 stride, nr64, st64, prod, raw, lim = (self.tmp() for _ in range(6)) 6970 lit1 = self.sgpr_imm.get(base["r"] + 1)
6640 nr = self.load_reg("sgpr", base["r"] + 2) 6971 lit2 = self.sgpr_imm.get(base["r"] + 2)
6641 self.emit(f"{stride} = OpBitFieldUExtract %uint {word1} {self.cu(16)} {self.cu(14)}") 6972 if lit1 is not None and lit2 is not None:
6642 self.emit(f"{nr64} = OpUConvert %ulong {nr}") 6973 stride = (lit1 >> 16) & 0x3FFF
6643 self.emit(f"{st64} = OpUConvert %ulong {stride}") 6974 lim_val = lit2 if stride == 0 else lit2 * stride
6644 self.emit(f"{prod} = OpIMul %ulong {nr64} {st64}") 6975 lim = self.cl(lim_val)
6645 self.emit(f"{raw} = OpIEqual %bool {stride} {self.cu(0)}") 6976 else:
6646 self.emit(f"{lim} = OpSelect %ulong {raw} {nr64} {prod}") 6977 stride, nr64, st64, prod, raw, lim = (self.tmp() for _ in range(6))
6978 nr = self.load_reg("sgpr", base["r"] + 2)
6979 self.emit(f"{stride} = OpBitFieldUExtract %uint {word1} {self.cu(16)} {self.cu(14)}")
6980 self.emit(f"{nr64} = OpUConvert %ulong {nr}")
6981 self.emit(f"{st64} = OpUConvert %ulong {stride}")
6982 self.emit(f"{prod} = OpIMul %ulong {nr64} {st64}")
6983 self.emit(f"{raw} = OpIEqual %bool {stride} {self.cu(0)}")
6984 self.emit(f"{lim} = OpSelect %ulong {raw} {nr64} {prod}")
6647 for i in range(n): 6985 for i in range(n):
6648 p, v = self.tmp(), self.tmp() 6986 p, v = self.tmp(), self.tmp()
6649 if lim is None: 6987 if lim is None:
6650 self.emit(f"{p} = OpAccessChain %_ptr_PSB_uint {ptr} {self.cu(i)}") 6988 self.emit(f"{p} = OpAccessChain %_ptr_PSB_uint {ptr} {self.cu(i)}")
6651 self.emit(f"{v} = OpLoad %uint {p} Aligned 4") 6989 self.emit(f"{v} = OpLoad %uint {p} Aligned 4")
6990 elif lim_val is not None and reg is None:
6991 end_val = imm + 4 * i + 4
6992 if lim_val >= end_val:
6993 self.emit(f"{p} = OpAccessChain %_ptr_PSB_uint {ptr} {self.cu(i)}")
6994 self.emit(f"{v} = OpLoad %uint {p} Aligned 4")
6995 else:
6996 v = self.cu(0)
6652 else: 6997 else:
6653 # dword i is in range when off + 4*i + 4 <= limit; outside it memory is not read and the result is 0 6998 # dword i is in range when off + 4*i + 4 <= limit; outside it memory is not read and the result is 0
6654 end, ok, got = self.tmp(), self.tmp(), self.tmp() 6999 end, ok, got = self.tmp(), self.tmp(), self.tmp()
@@ -8489,7 +8834,11 @@ def dedupe_types(text):
8489 (%v4uint for r32ui storage, %v4uint_st for typed stores, %v4uint_in for vertex inputs): keep the first 8834 (%v4uint for r32ui storage, %v4uint_st for typed stores, %v4uint_in for vertex inputs): keep the first
8490 declaration of each OpTypeVector / OpTypePointer and rename the others everywhere.""" 8835 declaration of each OpTypeVector / OpTypePointer and rename the others everywhere."""
8491 alias, seen, out = {}, {}, [] 8836 alias, seen, out = {}, {}, []
8492 for line in text.split("\n"): 8837 lines = text.split("\n")
8838 for i, line in enumerate(lines):
8839 if " = OpFunction " in line:
8840 out.extend(lines[i:])
8841 break
8493 m = _TYPE_DECL.match(line) 8842 m = _TYPE_DECL.match(line)
8494 if m: 8843 if m:
8495 name, opc, rest = m.groups() 8844 name, opc, rest = m.groups()
@@ -8501,7 +8850,8 @@ def dedupe_types(text):
8501 out.append(line) 8850 out.append(line)
8502 if not alias: 8851 if not alias:
8503 return text 8852 return text
8504 return "\n".join(_ID_REF.sub(lambda t: alias.get(t.group(0), t.group(0)), l) for l in out) 8853 pattern = re.compile(r"(?:" + "|".join(re.escape(k) for k in sorted(alias, key=len, reverse=True)) + r")\b")
8854 return pattern.sub(lambda m: alias[m.group(0)], "\n".join(out))
8505 8855
8506 8856
8507def mesh_compute_epilogue(gen): 8857def mesh_compute_epilogue(gen):
@@ -8683,6 +9033,11 @@ def assemble(gen):
8683 used = set(gen.inputs.values()) 9033 used = set(gen.inputs.values())
8684 if len(used) != len(gen.inputs): # --f16-interp-fallback: a decoded-half location is also an attribute 9034 if len(used) != len(gen.inputs): # --f16-interp-fallback: a decoded-half location is also an attribute
8685 raise Unsupported("--f16-interp-fallback: a decoded-half location is also read as an attribute") 9035 raise Unsupported("--f16-interp-fallback: a decoded-half location is also read as an attribute")
9036 # The producer fills both halves of every attribute in f16_halves (the index's f16_halves lists the pair), so a
9037 # raw attribute at the location of a half this shader doesn't read is overwritten all the same.
9038 reserved = {f16_half_location(n, h) for n in gen.f16_halves for h in (0, 1)}
9039 if any(not k.startswith("%in_f16h") and v in reserved for k, v in gen.inputs.items()):
9040 raise Unsupported("--f16-interp-fallback: a decoded-half location is also read as an attribute")
8686 gen.bary_location = next(n for n in range(len(used) + 1) if n not in used) if bary and BARY_FALLBACK else None 9041 gen.bary_location = next(n for n in range(len(used) + 1) if n not in used) if bary and BARY_FALLBACK else None
8687 bary_builtin = bary and gen.bary_location is None 9042 bary_builtin = bary and gen.bary_location is None
8688 if gen.frag_inputs or bary: 9043 if gen.frag_inputs or bary:
@@ -9636,7 +9991,7 @@ def read_before_write_vgprs(insns):
9636 regs += range(x["r"], x["r"] + x.get("n", 1)) 9991 regs += range(x["r"], x["r"] + x.get("n", 1))
9637 elif x["k"] == "vlist": 9992 elif x["k"] == "vlist":
9638 regs += x["r"] 9993 regs += x["r"]
9639 if (base_op(op) in ("v_fmac_f32", "v_mac_f32", "v_mac_legacy_f32", "v_fmac_f16") or 9994 if (base_op(op) in ("v_fmac_f32", "v_mac_f32", "v_mac_legacy_f32", "v_fmac_f16", "v_dot4c_i32_i8") or
9640 (op.startswith("global_load_") and "_d16" in op)) and a[0]["k"] == "vgpr": # d16 keeps a half 9995 (op.startswith("global_load_") and "_d16" in op)) and a[0]["k"] == "vgpr": # d16 keeps a half
9641 regs.append(a[0]["r"]) 9996 regs.append(a[0]["r"])
9642 for r in regs: 9997 for r in regs:
@@ -9864,7 +10219,7 @@ def reg_reads_writes(insns):
9864 regs += range(x["r"], x["r"] + x.get("n", 1)) 10219 regs += range(x["r"], x["r"] + x.get("n", 1))
9865 elif x["k"] == "vlist": 10220 elif x["k"] == "vlist":
9866 regs += x["r"] 10221 regs += x["r"]
9867 if base_op(op) in ("v_fmac_f32", "v_mac_f32", "v_fmac_f16") and a[0]["k"] == "vgpr": 10222 if base_op(op) in ("v_fmac_f32", "v_mac_f32", "v_fmac_f16", "v_dot4c_i32_i8") and a[0]["k"] == "vgpr":
9868 regs.append(a[0]["r"]) 10223 regs.append(a[0]["r"])
9869 rr.update(regs) 10224 rr.update(regs)
9870 if not reads_all and a[0]["k"] == "vgpr": 10225 if not reads_all and a[0]["k"] == "vgpr":
@@ -10091,6 +10446,10 @@ def translate(path):
10091 if stage not in ("vs", "ps", "cs", "ms", "gs"): 10446 if stage not in ("vs", "ps", "cs", "ms", "gs"):
10092 raise Unsupported(f"stage {stage}") 10447 raise Unsupported(f"stage {stage}")
10093 insns = info["insns"] 10448 insns = info["insns"]
10449 if not insns:
10450 # parse_file only reads tab-indented instructions, so a hand-written or re-indented .s parses to nothing
10451 # and used to translate to a module that passes spirv-val and does no work at all. Refuse it instead.
10452 raise Unsupported("no instructions (nothing tab-indented?)")
10094 if info["invalid"]: 10453 if info["invalid"]:
10095 # Undecodable words are constant tables embedded in the code range (147/155 such VS/PS use s_getpc_b64 to 10454 # Undecodable words are constant tables embedded in the code range (147/155 such VS/PS use s_getpc_b64 to
10096 # read them). LLVM skips them, so re-anchor every instruction to its true offset in the FSSM blob, then 10455 # read them). LLVM skips them, so re-anchor every instruction to its true offset in the FSSM blob, then
@@ -10814,8 +11173,12 @@ def shader_meta(g, asm, src_path=None, fssm_path=None):
10814 "features": sorted({feats[c] for c in caps if c in feats and not feats[c].startswith(("core", "shaderImage1D"))}), 11173 "features": sorted({feats[c] for c in caps if c in feats and not feats[c].startswith(("core", "shaderImage1D"))}),
10815 "bindings": binds, "push_constant_bytes": 4 * USER_SGPRS + 16, 11174 "bindings": binds, "push_constant_bytes": 4 * USER_SGPRS + 16,
10816 "subgroup_size": 64 if g.wave64 else 32, 11175 "subgroup_size": 64 if g.wave64 else 32,
10817 # 64-wide subgroups can only be requested for compute/mesh on RADV and NVIDIA; VS/PS/GS wave64 11176 # Which stages can ask for a 64-wide subgroup is the driver's requiredSubgroupSizeStages, not a fixed rule:
10818 # shaders must be treated as emulated (per-32-lane halves) until cross-half ops go through LDS. 11177 # the AMD Windows driver (FRAGMENT | COMPUTE | TASK | MESH) and Mesa RADV on GFX10+ (COMPUTE | FRAGMENT |
11178 # task/mesh) allow a wave64 PS to request 64, so it is exact there; NVIDIA has no 64 at all, and no driver
11179 # lists VERTEX or GEOMETRY. The runtime decides per device (runtime/src/subgroup_size.h) from `wave64`,
11180 # `subgroup_size` and `wave64_exchange`. This field stays true for VS/PS/GS wave64 (consumers rely on it):
11181 # it says the shader has no cross-half exchange, so it is per-subgroup, not that it must run 2x32.
10819 "wave64_emulated": bool(g.wave64 and (g.stage in ("vs", "ps", "gs") or g.emulate))} 11182 "wave64_emulated": bool(g.wave64 and (g.stage in ("vs", "ps", "gs") or g.emulate))}
10820 if g.w64g: 11183 if g.w64g:
10821 # SHADER-10: partition invariance on 32-wide subgroups. A and B are exact there (B: aggregated atomics up to 11184 # SHADER-10: partition invariance on 32-wide subgroups. A and B are exact there (B: aggregated atomics up to
@@ -11051,15 +11414,25 @@ def main():
11051 why, ok, valid = Counter(), 0, 0 11414 why, ok, valid = Counter(), 0, 0
11052 meta = {} 11415 meta = {}
11053 invalid = set() 11416 invalid = set()
11417
11418 def drop_stale(name):
11419 # A shader that no longer translates must not stay published from an earlier run: remove its old
11420 # module, and the index merge below drops its entry, exactly like a spirv-as/val rejection. The
11421 # .spvasm text stays for diagnosis, as it does on a rejection.
11422 Path(os.path.join(a.out, name + ".spv")).unlink(missing_ok=True)
11423 invalid.add(name)
11424
11054 for p in files: 11425 for p in files:
11055 name = os.path.splitext(os.path.basename(p))[0] 11426 name = os.path.splitext(os.path.basename(p))[0]
11056 try: 11427 try:
11057 asm = translate(p) 11428 asm = translate(p)
11058 except Unsupported as e: 11429 except Unsupported as e:
11059 why[str(e)] += 1 11430 why[str(e)] += 1
11431 drop_stale(name)
11060 continue 11432 continue
11061 except (IndexError, KeyError, ValueError) as e: 11433 except (IndexError, KeyError, ValueError) as e:
11062 why[f"translator error {type(e).__name__}"] += 1 11434 why[f"translator error {type(e).__name__}"] += 1
11435 drop_stale(name)
11063 continue 11436 continue
11064 ok += 1 11437 ok += 1
11065 sa = os.path.join(a.out, name + ".spvasm") 11438 sa = os.path.join(a.out, name + ".spvasm")
@@ -11075,7 +11448,7 @@ def main():
11075 except Exception as e: # noqa: BLE001 - metadata must never cost a translation 11448 except Exception as e: # noqa: BLE001 - metadata must never cost a translation
11076 meta[name] = {"error": f"{type(e).__name__}: {e}"} 11449 meta[name] = {"error": f"{type(e).__name__}: {e}"}
11077 else: 11450 else:
11078 invalid.add(name) 11451 drop_stale(name)
11079 why["INVALID: " + (r.stderr.strip().splitlines() or ["?"])[0][:90]] += 1 11452 why["INVALID: " + (r.stderr.strip().splitlines() or ["?"])[0][:90]] += 1
11080 if a.no_asm and os.path.exists(sa): 11453 if a.no_asm and os.path.exists(sa):
11081 os.remove(sa) 11454 os.remove(sa)
diff --git a/tools/restofworld_index.py b/tools/restofworld_index.py
index a784e4281..c890cf65b 100644
--- a/tools/restofworld_index.py
+++ b/tools/restofworld_index.py
@@ -326,7 +326,7 @@ def write_output(path, rows, summary):
326 json.dump({"summary": summary, "files": rows}, f, indent=1) 326 json.dump({"summary": summary, "files": rows}, f, indent=1)
327 return 327 return
328 with open(path, "w", encoding="utf-8", newline="") as f: 328 with open(path, "w", encoding="utf-8", newline="") as f:
329 writer = csv.writer(f) 329 writer = csv.writer(f, lineterminator="\n")
330 writer.writerow(COLUMNS) 330 writer.writerow(COLUMNS)
331 for row in rows: 331 for row in rows:
332 writer.writerow([f"0x{row['offset']:x}" if i == 0 else ("" if row[c] is None else row[c]) 332 writer.writerow([f"0x{row['offset']:x}" if i == 0 else ("" if row[c] is None else row[c])
diff --git a/tools/rsc8_audio.py b/tools/rsc8_audio.py
index 0998f29db..28f9c6709 100644
--- a/tools/rsc8_audio.py
+++ b/tools/rsc8_audio.py
@@ -1498,7 +1498,7 @@ def write_report(path, records, summary):
1498 ext = os.path.splitext(path)[1].lower() 1498 ext = os.path.splitext(path)[1].lower()
1499 if ext == ".csv": 1499 if ext == ".csv":
1500 def _write_csv(f): 1500 def _write_csv(f):
1501 w = csv.writer(f) 1501 w = csv.writer(f, lineterminator="\n")
1502 w.writerow(CSV_COLUMNS) 1502 w.writerow(CSV_COLUMNS)
1503 for r in records: 1503 for r in records:
1504 row = [] 1504 row = []
diff --git a/tools/salu_diff.py b/tools/salu_diff.py
index 244bee384..e34c5c96f 100644
--- a/tools/salu_diff.py
+++ b/tools/salu_diff.py
@@ -71,7 +71,8 @@ OUT_SCC = 30 # s_cselect_b32 s30, 1, 0 observes SCC at the end
71BFE_ANY = False # any s_bfe_* control word (--bfe-any), not only offset + width <= 32 71BFE_ANY = False # any s_bfe_* control word (--bfe-any), not only offset + width <= 32
72INLINE64 = False # inline constants in 64-bit positions (--inline64); the translator reads those as lane masks 72INLINE64 = False # inline constants in 64-bit positions (--inline64); the translator reads those as lane masks
73 73
74LANE_MASK_OPS = ("s_and_b64", "s_or_b64", "s_xor_b64", "s_andn2_b64", "s_orn2_b64", "s_not_b64", "s_wqm_b64", 74LANE_MASK_OPS = ("s_and_b64", "s_or_b64", "s_xor_b64", "s_andn2_b64", "s_orn2_b64", "s_nand_b64", "s_nor_b64",
75 "s_xnor_b64", "s_not_b64", "s_wqm_b64",
75 "s_wqm_b32", "s_cselect_b64", "s_bfm_b64") 76 "s_wqm_b32", "s_cselect_b64", "s_bfm_b64")
76 77
77INTERESTING = (0, 1, 2, 3, 31, 32, 33, 63, 64, 0x7FFFFFFF, 0x80000000, 0x80000001, 0xFFFFFFFF, 0xFFFFFFFE, 78INTERESTING = (0, 1, 2, 3, 31, 32, 33, 63, 64, 0x7FFFFFFF, 0x80000000, 0x80000001, 0xFFFFFFFF, 0xFFFFFFFE,
@@ -172,7 +173,9 @@ def _sop2():
172def _sop2_64(): 173def _sop2_64():
173 ops = {} 174 ops = {}
174 for name, f in (("and", lambda a, b: a & b), ("or", lambda a, b: a | b), ("xor", lambda a, b: a ^ b), 175 for name, f in (("and", lambda a, b: a & b), ("or", lambda a, b: a | b), ("xor", lambda a, b: a ^ b),
175 ("andn2", lambda a, b: a & ~b), ("orn2", lambda a, b: a | ~b)): 176 ("andn2", lambda a, b: a & ~b), ("orn2", lambda a, b: a | ~b),
177 ("nand", lambda a, b: ~(a & b)), ("nor", lambda a, b: ~(a | b)),
178 ("xnor", lambda a, b: ~(a ^ b))):
176 ops[f"s_{name}_b64"] = ("sop2_64", lambda a, b, c, f=f: (f(a, b) & M64, int(f(a, b) & M64 != 0))) 179 ops[f"s_{name}_b64"] = ("sop2_64", lambda a, b, c, f=f: (f(a, b) & M64, int(f(a, b) & M64 != 0)))
177 ops["s_cselect_b64"] = ("sop2_64", lambda a, b, c: (a if c else b, None)) 180 ops["s_cselect_b64"] = ("sop2_64", lambda a, b, c: (a if c else b, None))
178 ops["s_lshl_b64"] = ("sop2_64s", lambda a, b, c: ((a << (b & 63)) & M64, int((a << (b & 63)) & M64 != 0))) 181 ops["s_lshl_b64"] = ("sop2_64s", lambda a, b, c: ((a << (b & 63)) & M64, int((a << (b & 63)) & M64 != 0)))
diff --git a/tools/shader_link_check.py b/tools/shader_link_check.py
new file mode 100644
index 000000000..901fb2949
--- /dev/null
+++ b/tools/shader_link_check.py
@@ -0,0 +1,313 @@
1"""Check user-defined varying interfaces between translated graphics stages.
2
3Run `python -I tools/shader_link_check.py --help` for standalone pairs, batch checks,
4and reflection of a single SPIR-V module.
5"""
6from __future__ import annotations
7
8import argparse
9from dataclasses import asdict, dataclass
10import json
11import os
12from pathlib import Path
13import re
14import sys
15import tempfile
16
17sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
18from file_mode import published_mode # noqa: E402
19from spirv_interface import (Address, Declaration, InterfaceError, NumericType, # noqa: E402
20 StageInterface, reflect_module)
21
22
23STAGES = ("vs", "gs", "ms", "ps")
24CHAINS = {("vs", "ps"), ("vs", "gs", "ps"), ("ms", "ps"), ("vs", "gs")}
25STEM = re.compile(r"[a-zA-Z0-9_][a-zA-Z0-9_.-]*\Z")
26
27
28@dataclass(frozen=True)
29class ModulePath:
30 path: Path
31 stage: str
32 entry: str = "main"
33
34
35@dataclass(frozen=True)
36class Pipeline:
37 name: str
38 modules: tuple[ModulePath, ...]
39
40
41@dataclass(frozen=True)
42class Problem:
43 kind: str
44 consumer: str
45 message: str
46 producer: str | None = None
47 location: Address | None = None
48
49 def display(self):
50 stages = f"{self.producer} -> {self.consumer}" if self.producer else self.consumer
51 where = f" at {self.location.describe()}" if self.location is not None else ""
52 return f"{stages}{where} [{self.kind}] {self.message}"
53
54
55@dataclass
56class PipelineResult:
57 name: str
58 status: str
59 links_checked: int
60 problems: list[Problem]
61
62
63def wider_vector_compatible(producer, consumer, allow):
64 if not allow or producer.structure or consumer.structure:
65 return False
66 if producer.indexed_by_vertex_or_primitive or consumer.indexed_by_vertex_or_primitive:
67 return False
68 p, c = producer.varyings[0].type, consumer.varyings[0].type
69 # maintenance4 relaxes the length of vector variables. Scalar vs vector, nested types,
70 # and arrays which were unwrapped for a stage's invocation index still need exact types.
71 return (isinstance(p, NumericType) and isinstance(c, NumericType)
72 and p.kind == c.kind and p.width == c.width and p.components > c.components >= 2)
73
74
75def compare_stages(producer: StageInterface, consumer: StageInterface, maintenance4=False):
76 """Check consumer declarations against the preceding stage's output declarations."""
77 output_slots = {slot: declaration
78 for declaration in producer.outputs
79 for varying in declaration.varyings
80 for slot in varying.occupied()}
81 problems = []
82 for expected in consumer.inputs:
83 anchor = expected.varyings[0].address
84 actual = output_slots.get(anchor)
85
86 def problem(kind, message):
87 return Problem(kind, consumer.stage, message, producer.stage, anchor)
88
89 if actual is None:
90 problems.append(problem("missing-output", f"consumer expects {expected.describe()}"))
91 continue
92 if actual.structure != expected.structure or actual.block != expected.block:
93 problems.append(problem("structure-mismatch", f"{actual.describe()} cannot match {expected.describe()}"))
94 continue
95 if tuple(v.address for v in actual.varyings) != tuple(v.address for v in expected.varyings):
96 problems.append(problem("location-mismatch",
97 f"{actual.describe()} starts or places its members differently from "
98 f"{expected.describe()}"))
99 continue
100 if tuple(v.per_primitive for v in actual.varyings) != tuple(v.per_primitive for v in expected.varyings):
101 problems.append(problem("per-primitive-mismatch",
102 f"producer declares {actual.describe()}, consumer expects {expected.describe()}"))
103 continue
104 if tuple(v.type for v in actual.varyings) != tuple(v.type for v in expected.varyings):
105 if wider_vector_compatible(actual, expected, maintenance4):
106 continue
107 hint = (" (a wider output vector requires maintenance4)"
108 if wider_vector_compatible(actual, expected, True) else "")
109 problems.append(problem("type-mismatch",
110 f"producer declares {actual.describe()}, consumer expects {expected.describe()}"
111 f"{hint}"))
112 return problems
113
114
115def stage_chain(refs):
116 stages = tuple(stage for stage in STAGES if stage in refs)
117 if stages not in CHAINS:
118 raise ValueError("expected vs+ps, vs+gs, vs+gs+ps, or ms+ps")
119 return stages
120
121
122def load_pipeline_manifest(path: Path, shader_dir: Path):
123 try:
124 with path.open(encoding="utf-8") as source:
125 doc = json.load(source)
126 except (OSError, ValueError) as exc:
127 raise ValueError(f"{path}: {exc}") from exc
128 if (not isinstance(doc, dict) or set(doc) - {"pipelines", "version"}
129 or type(doc.get("version", 1)) is not int or doc.get("version", 1) != 1):
130 raise ValueError("expected a version 1 object with a pipelines list")
131 if not isinstance(doc.get("pipelines"), list) or not doc["pipelines"]:
132 raise ValueError("pipelines must be a nonempty list")
133 names = set()
134 pipelines = []
135 for number, row in enumerate(doc["pipelines"], 1):
136 try:
137 if not isinstance(row, dict) or set(row) - {"name", *STAGES}:
138 raise ValueError("unexpected pipeline field")
139 name = row.get("name")
140 if not isinstance(name, str) or not name.strip() or any(ord(ch) < 32 for ch in name):
141 raise ValueError("expected one printable, nonempty pipeline name")
142 if name in names:
143 raise ValueError(f"duplicate pipeline name {name!r}")
144 stages = stage_chain(row)
145 modules = tuple(manifest_module(row[stage], shader_dir, stage) for stage in stages)
146 names.add(name)
147 pipelines.append(Pipeline(name, modules))
148 except ValueError as exc:
149 raise ValueError(f"pipelines[{number - 1}]: {exc}") from exc
150 return pipelines
151
152
153def manifest_module(reference, shader_dir, stage):
154 entry = "main"
155 if isinstance(reference, dict):
156 if set(reference) - {"shader", "entry"}:
157 raise ValueError(f"{stage}: unexpected shader reference field")
158 entry, reference = reference.get("entry", entry), reference.get("shader")
159 if not isinstance(reference, str) or not STEM.fullmatch(reference):
160 raise ValueError(f"{stage}: expected a shader name without directories")
161 if not isinstance(entry, str) or not entry or "\x00" in entry:
162 raise ValueError(f"{stage}: expected a nonempty entry-point name")
163 return ModulePath(shader_dir / (reference + ".spv"), stage, entry)
164
165
166class InterfaceCache:
167 def __init__(self):
168 self.modules = {}
169
170 def load(self, module):
171 if module not in self.modules:
172 try:
173 self.modules[module] = reflect_module(module.path.read_bytes(), module.stage, module.entry)
174 except (OSError, InterfaceError) as exc:
175 self.modules[module] = InterfaceError(f"{module.path}: {exc}")
176 result = self.modules[module]
177 if isinstance(result, InterfaceError):
178 raise result
179 return result
180
181
182def check_pipeline(pipeline, cache, maintenance4=False):
183 interfaces = {}
184 problems = []
185 for module in pipeline.modules:
186 try:
187 interfaces[module.stage] = cache.load(module)
188 except (OSError, InterfaceError) as exc:
189 problems.append(Problem("module-error", module.stage, str(exc)))
190 links = 0
191 invalid = bool(problems)
192 for producer, consumer in zip(pipeline.modules, pipeline.modules[1:]):
193 if producer.stage in interfaces and consumer.stage in interfaces:
194 links += 1
195 problems.extend(compare_stages(interfaces[producer.stage], interfaces[consumer.stage], maintenance4))
196 status = "invalid" if invalid else ("incompatible" if problems else "compatible")
197 return PipelineResult(pipeline.name, status, links, problems)
198
199
200def write_report(path: Path, doc):
201 path = path.absolute()
202 temporary = None
203 try:
204 with tempfile.NamedTemporaryFile(mode="w", encoding="utf-8", newline="\n", delete=False,
205 dir=path.parent, prefix=".shader-link-", suffix=".tmp") as target:
206 temporary = Path(target.name)
207 json.dump(doc, target, indent=2, ensure_ascii=False)
208 target.write("\n")
209 os.chmod(temporary, published_mode(path))
210 os.replace(temporary, path)
211 finally:
212 if temporary is not None:
213 temporary.unlink(missing_ok=True)
214
215
216def ensure_report_is_separate(output, inputs):
217 if output is None:
218 return
219 out = output.resolve()
220 for source in dict.fromkeys(inputs):
221 if out == source.resolve() or (out.exists() and source.exists() and out.samefile(source)):
222 raise ValueError(f"report would overwrite an input file: {source}")
223
224
225def inspect(args):
226 ensure_report_is_separate(args.report, [args.module])
227 interface = reflect_module(args.module.read_bytes(), args.stage, args.entry)
228 doc = {
229 "stage": interface.stage,
230 "entry": interface.entry,
231 "inputs": [declaration_row(item) for item in interface.inputs],
232 "outputs": [declaration_row(item) for item in interface.outputs],
233 }
234 if args.report:
235 write_report(args.report, doc)
236 else:
237 print(json.dumps(doc, indent=2))
238 return 0
239
240
241def declaration_row(declaration):
242 return {
243 "id": declaration.symbol,
244 "structure": declaration.structure,
245 "block": declaration.block,
246 "indexed_by_vertex_or_primitive": declaration.indexed_by_vertex_or_primitive,
247 "varyings": [{**asdict(varying.address), "type": varying.type.describe(),
248 "per_primitive": varying.per_primitive} for varying in declaration.varyings],
249 }
250
251
252def run_checks(args):
253 extra_inputs = []
254 if args.command == "batch":
255 pipelines = load_pipeline_manifest(args.manifest, args.shader_dir)
256 extra_inputs = [args.manifest]
257 else:
258 refs = {stage: getattr(args, stage) for stage in STAGES if getattr(args, stage) is not None}
259 pipelines = [Pipeline("pipeline", tuple(ModulePath(refs[stage], stage, args.entry)
260 for stage in stage_chain(refs)))]
261 ensure_report_is_separate(args.report, [*extra_inputs,
262 *(module.path for pipeline in pipelines for module in pipeline.modules)])
263 cache = InterfaceCache()
264 results = [check_pipeline(pipeline, cache, args.maintenance4) for pipeline in pipelines]
265 summary = {state: sum(result.status == state for result in results)
266 for state in ("compatible", "incompatible", "invalid")}
267 if args.report:
268 write_report(args.report, {"version": 1, "maintenance4": args.maintenance4, "summary": summary,
269 "pipelines": [asdict(result) for result in results]})
270 for result in results:
271 if args.quiet and not result.problems:
272 continue
273 print(f"{result.name}: {result.status} ({result.links_checked} links checked)")
274 for problem in result.problems:
275 print(f" {problem.display()}")
276 print(", ".join(f"{count} {state}" for state, count in summary.items()))
277 if summary["invalid"]:
278 return 2
279 return int(bool(summary["incompatible"]))
280
281
282def main(argv=None):
283 parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
284 commands = parser.add_subparsers(dest="command", required=True)
285 direct = commands.add_parser("check", help="check one graphics pipeline from SPIR-V file paths")
286 for stage in STAGES:
287 direct.add_argument("--" + stage, type=Path, metavar="SPV")
288 direct.add_argument("--entry", default="main", help="entry-point name used by all direct paths")
289 batch = commands.add_parser("batch", help="check a JSON list of pipelines sharing a shader directory")
290 batch.add_argument("manifest", type=Path)
291 batch.add_argument("--shader-dir", type=Path, required=True, help="directory holding the named .spv files")
292 for command in (direct, batch):
293 command.add_argument("--maintenance4", action="store_true",
294 help="allow wider output vectors when the pipeline enables maintenance4")
295 command.add_argument("--quiet", action="store_true", help="display diagnostics and the summary")
296 command.add_argument("--report", type=Path, help="write structured results to JSON")
297 single = commands.add_parser("inspect", help="show the reflected user inputs and outputs of one entry point")
298 single.add_argument("module", type=Path)
299 single.add_argument("--stage", choices=STAGES, help="select a stage when multiple entry points share a name")
300 single.add_argument("--entry", default="main")
301 single.add_argument("--report", type=Path, help="write the reflection to JSON")
302 args = parser.parse_args(argv)
303 try:
304 return inspect(args) if args.command == "inspect" else run_checks(args)
305 except (OSError, ValueError) as exc:
306 print(f"shader_link_check: error: {exc}", file=sys.stderr)
307 return 2
308
309
310if __name__ == "__main__":
311 if hasattr(sys.stdout, "reconfigure"):
312 sys.stdout.reconfigure(errors="replace")
313 sys.exit(main())
diff --git a/tools/spirv_gs_to_compute.py b/tools/spirv_gs_to_compute.py
index 3caaa15a7..afb9edba6 100644
--- a/tools/spirv_gs_to_compute.py
+++ b/tools/spirv_gs_to_compute.py
@@ -297,15 +297,21 @@ def rewrite(text):
297 return "\n".join(out) + "\n", public 297 return "\n".join(out) + "\n", public
298 298
299 299
300USAGE = "\n".join(__doc__.strip().splitlines()[-2:])
301
302
300def main(argv): 303def main(argv):
301 args = argv[1:] 304 args = argv[1:]
305 if args and args[0] in ("-h", "--help"):
306 print(USAGE)
307 return 0
302 lay_path = None 308 lay_path = None
303 if "--layout" in args: 309 if "--layout" in args:
304 i = args.index("--layout") 310 i = args.index("--layout")
305 lay_path = args[i + 1] 311 lay_path = args[i + 1]
306 del args[i:i + 2] 312 del args[i:i + 2]
307 if len(args) != 2: 313 if len(args) != 2:
308 print("usage: spirv_gs_to_compute.py in.spv out.spv [--layout out.json]", file=sys.stderr) 314 print(USAGE, file=sys.stderr)
309 return 2 315 return 2
310 dis = os.environ.get("SPIRV_DIS", "spirv-dis") 316 dis = os.environ.get("SPIRV_DIS", "spirv-dis")
311 asm = os.environ.get("SPIRV_AS", "spirv-as") 317 asm = os.environ.get("SPIRV_AS", "spirv-as")
diff --git a/tools/spirv_interface.py b/tools/spirv_interface.py
new file mode 100644
index 000000000..a9ecfa397
--- /dev/null
+++ b/tools/spirv_interface.py
@@ -0,0 +1,522 @@
1"""Reflect the user-defined graphics interfaces in a binary SPIR-V module.
2
3This reader is deliberately limited to declarations used for Vulkan stage linking. It does not
4validate shader instructions, device features, or resource bindings. IDs and debug names are local
5to each module; the result uses normalized types and Location/Component decorations instead.
6"""
7from __future__ import annotations
8
9from array import array
10from collections import defaultdict
11from dataclasses import dataclass
12import struct
13
14
15class InterfaceError(ValueError):
16 """The module's requested interface could not be reflected."""
17
18
19SPIRV_MAGIC = 0x07230203
20SPIRV_MAGIC_SWAPPED = 0x03022307
21
22# SPIR-V core grammar. The NV/EXT spelling of PerPrimitive uses the same enumerant.
23OP_ENTRY_POINT = 15
24OP_TYPE_INT = 21
25OP_TYPE_FLOAT = 22
26OP_TYPE_VECTOR = 23
27OP_TYPE_MATRIX = 24
28OP_TYPE_ARRAY = 28
29OP_TYPE_STRUCT = 30
30OP_TYPE_POINTER = 32
31OP_CONSTANT = 43
32OP_VARIABLE = 59
33OP_DECORATE = 71
34OP_MEMBER_DECORATE = 72
35OP_DECORATION_GROUP = 73
36OP_GROUP_DECORATE = 74
37OP_GROUP_MEMBER_DECORATE = 75
38
39TYPE_OPS = {OP_TYPE_INT, OP_TYPE_FLOAT, OP_TYPE_VECTOR, OP_TYPE_MATRIX,
40 OP_TYPE_ARRAY, OP_TYPE_STRUCT, OP_TYPE_POINTER}
41DECLARATION_OPS = TYPE_OPS | {OP_ENTRY_POINT, OP_CONSTANT, OP_VARIABLE, OP_DECORATE,
42 OP_MEMBER_DECORATE, OP_DECORATION_GROUP, OP_GROUP_DECORATE,
43 OP_GROUP_MEMBER_DECORATE}
44TYPE_OPERANDS = {OP_TYPE_INT: 3, OP_TYPE_FLOAT: 2, OP_TYPE_VECTOR: 3, OP_TYPE_MATRIX: 3,
45 OP_TYPE_ARRAY: 3, OP_TYPE_POINTER: 3}
46EXECUTION_STAGES = {0: "vs", 3: "gs", 4: "ps", 5365: "ms"}
47STORAGE_INPUT = 1
48STORAGE_OUTPUT = 3
49DEC_BLOCK = 2
50DEC_BUILTIN = 11
51DEC_PATCH = 15
52DEC_LOCATION = 30
53DEC_COMPONENT = 31
54DEC_INDEX = 32
55DEC_PASSTHROUGH_NV = 5250
56DEC_PER_PRIMITIVE = 5271
57DEC_PER_VERTEX = 5285
58DECORATION_NAMES = {DEC_BLOCK: "Block", DEC_BUILTIN: "BuiltIn", DEC_PATCH: "Patch",
59 DEC_LOCATION: "Location", DEC_COMPONENT: "Component", DEC_INDEX: "Index",
60 DEC_PASSTHROUGH_NV: "PassthroughNV", DEC_PER_PRIMITIVE: "PerPrimitiveEXT",
61 DEC_PER_VERTEX: "PerVertexKHR"}
62VALUE_DECORATIONS = {DEC_BUILTIN, DEC_LOCATION, DEC_COMPONENT, DEC_INDEX}
63
64# Bound expansion of arrays from malformed modules. This is far beyond the varying space of the
65# graphics stages on current Vulkan drivers. Type and layout recursion has a separate depth limit.
66MAX_EXPANDED_LOCATIONS = 16384
67MAX_TYPE_DEPTH = 64
68
69
70@dataclass(frozen=True)
71class NumericType:
72 kind: str
73 width: int
74 components: int = 1
75
76 def describe(self):
77 scalar = f"{self.kind}{self.width}"
78 return scalar if self.components == 1 else f"vec{self.components}<{scalar}>"
79
80 def location_masks(self, component):
81 slots = self.components * (self.width // 32 if self.width >= 32 else 1)
82 if self.width == 64 and component % 2:
83 raise InterfaceError("a 64-bit varying starts on an odd Component")
84 if self.width != 64 and component + slots > 4:
85 raise InterfaceError("a 16-bit or 32-bit varying extends beyond its Location")
86 if self.width == 64 and slots > 4 and component:
87 raise InterfaceError("a 64-bit vector spanning two locations needs Component 0")
88 mask = ((1 << slots) - 1) << component
89 if mask <= 0xf:
90 return (mask,)
91 return (mask & 0xf, mask >> 4)
92
93
94@dataclass(frozen=True)
95class AggregateType:
96 kind: str
97 items: tuple[NumericType | "AggregateType", ...]
98 count: int = 1
99
100 def describe(self):
101 if self.kind == "struct":
102 return "struct{" + ", ".join(item.describe() for item in self.items) + "}"
103 return f"{self.kind}[{self.count}]<{self.items[0].describe()}>"
104
105 def location_masks(self, component):
106 if self.kind == "struct":
107 if component:
108 raise InterfaceError("a structure cannot start at a nonzero Component")
109 masks = []
110 for member in self.items:
111 member_masks = member.location_masks(0)
112 if len(masks) + len(member_masks) > MAX_EXPANDED_LOCATIONS:
113 raise InterfaceError("structure uses too many interface locations to inspect")
114 masks.extend(member_masks)
115 return tuple(masks)
116 element = self.items[0].location_masks(component)
117 if len(element) * self.count > MAX_EXPANDED_LOCATIONS:
118 raise InterfaceError("aggregate uses too many interface locations to inspect")
119 return element * self.count
120
121
122@dataclass(frozen=True, order=True)
123class Address:
124 location: int
125 component: int = 0
126 index: int = 0
127
128 def describe(self):
129 suffix = f", index {self.index}" if self.index else ""
130 return f"location {self.location}, component {self.component}{suffix}"
131
132
133@dataclass(frozen=True)
134class Varying:
135 address: Address
136 type: NumericType | AggregateType
137 per_primitive: bool = False
138
139 def occupied(self):
140 for offset, mask in enumerate(self.type.location_masks(self.address.component)):
141 for component in range(4):
142 if mask & (1 << component):
143 yield Address(self.address.location + offset, component, self.address.index)
144
145 def describe(self):
146 mode = " per-primitive" if self.per_primitive else ""
147 return f"{self.type.describe()}{mode} at {self.address.describe()}"
148
149
150@dataclass(frozen=True)
151class Declaration:
152 """One standalone varying or an entire structure. Preserve member order when linking."""
153
154 varyings: tuple[Varying, ...]
155 symbol: int
156 structure: bool = False
157 block: bool = False
158 indexed_by_vertex_or_primitive: bool = False
159
160 def describe(self):
161 parts = ", ".join(varying.describe() for varying in self.varyings)
162 if self.structure:
163 kind = "block" if self.block else "struct"
164 return f"{kind} %{self.symbol} ({parts})"
165 return f"%{self.symbol} ({parts})"
166
167
168@dataclass(frozen=True)
169class StageInterface:
170 stage: str
171 entry: str
172 inputs: tuple[Declaration, ...]
173 outputs: tuple[Declaration, ...]
174
175
176@dataclass(frozen=True)
177class EntryPoint:
178 model: int
179 name: str
180 interface_ids: tuple[int, ...]
181
182
183def parse_words(data):
184 if len(data) < 20 or len(data) % 4:
185 raise InterfaceError("SPIR-V must contain a five-word header and complete 32-bit words")
186 words = array("I")
187 words.frombytes(data)
188 if words[0] == SPIRV_MAGIC_SWAPPED:
189 words.byteswap()
190 if words[0] != SPIRV_MAGIC:
191 raise InterfaceError("invalid SPIR-V magic")
192 if not 0x00010000 <= words[1] <= 0x00010600 or words[1] & 0xff:
193 raise InterfaceError(f"unsupported SPIR-V version word 0x{words[1]:08x}")
194 if not words[3] or words[4]:
195 raise InterfaceError("invalid SPIR-V ID bound or reserved header word")
196 return words
197
198
199def instructions(words):
200 start = 5
201 while start < len(words):
202 first = words[start]
203 length, opcode = first >> 16, first & 0xffff
204 end = start + length
205 if not length or end > len(words):
206 raise InterfaceError(f"invalid instruction length at word {start}")
207 if opcode in DECLARATION_OPS:
208 yield opcode, tuple(words[start + 1:end]), start
209 start = end
210
211
212def decode_literal_string(words):
213 for i, word in enumerate(words):
214 if b"\x00" in struct.pack("<I", word):
215 raw = struct.pack(f"<{i + 1}I", *words[:i + 1])
216 name, _, padding = raw.partition(b"\x00")
217 if any(padding):
218 raise InterfaceError("nonzero padding in OpEntryPoint name")
219 try:
220 return name.decode("utf-8"), i + 1
221 except UnicodeDecodeError as exc:
222 raise InterfaceError("OpEntryPoint name is not UTF-8") from exc
223 raise InterfaceError("unterminated OpEntryPoint name")
224
225
226class Module:
227 def __init__(self, data):
228 words = parse_words(data)
229 self.bound = words[3]
230 self.types = {}
231 self.constants = {}
232 self.variables = {}
233 self.entry_points = []
234 self.decorations = defaultdict(dict)
235 self.member_decorations = defaultdict(dict)
236 self.groups = set()
237 self.group_uses = []
238 self.definition_ids = set()
239 self.shape_cache = {}
240 for opcode, operands, at in instructions(words):
241 self.read_instruction(opcode, operands, at)
242 self.apply_decoration_groups()
243
244 def require_id(self, identifier):
245 if not 0 < identifier < self.bound:
246 raise InterfaceError(f"ID %{identifier} is outside the SPIR-V bound")
247
248 def define(self, identifier):
249 self.require_id(identifier)
250 if identifier in self.definition_ids:
251 raise InterfaceError(f"duplicate definition of ID %{identifier}")
252 self.definition_ids.add(identifier)
253
254 @staticmethod
255 def require_operands(operands, at, minimum, maximum=None):
256 if len(operands) < minimum or (maximum is not None and len(operands) > maximum):
257 raise InterfaceError(f"invalid operands at word {at}")
258
259 def read_instruction(self, opcode, operands, at):
260 if opcode in TYPE_OPS:
261 exact = TYPE_OPERANDS.get(opcode)
262 self.require_operands(operands, at, exact or 1, exact)
263 identifier, *args = operands
264 self.define(identifier)
265 self.types[identifier] = (opcode, tuple(args))
266 elif opcode == OP_CONSTANT:
267 self.require_operands(operands, at, 3)
268 type_id, identifier, *literal = operands
269 self.require_id(type_id)
270 self.define(identifier)
271 self.constants[identifier] = (type_id, tuple(literal))
272 elif opcode == OP_VARIABLE:
273 self.require_operands(operands, at, 3, 4)
274 pointer, identifier, storage = operands[:3]
275 self.require_id(pointer)
276 self.define(identifier)
277 self.variables[identifier] = (pointer, storage)
278 elif opcode == OP_ENTRY_POINT:
279 self.require_operands(operands, at, 3)
280 model, function, *rest = operands
281 self.require_id(function)
282 name, words_used = decode_literal_string(rest)
283 ids = tuple(rest[words_used:])
284 for identifier in ids:
285 self.require_id(identifier)
286 if len(set(ids)) != len(ids):
287 raise InterfaceError(f"duplicate entry-point interface ID in {name!r}")
288 self.entry_points.append(EntryPoint(model, name, ids))
289 elif opcode in (OP_DECORATE, OP_MEMBER_DECORATE):
290 split = 1 if opcode == OP_DECORATE else 2
291 self.require_operands(operands, at, split + 1)
292 identifier = operands[0]
293 self.require_id(identifier)
294 decoration, *extra = operands[split:]
295 if decoration not in DECORATION_NAMES:
296 return
297 expected = int(decoration in VALUE_DECORATIONS)
298 if len(extra) != expected:
299 raise InterfaceError(f"invalid {DECORATION_NAMES[decoration]} decoration at word {at}")
300 target = (self.decorations[identifier] if split == 1
301 else self.member_decorations[(identifier, operands[1])])
302 self.add_decoration(target, decoration, extra[0] if extra else True)
303 elif opcode == OP_DECORATION_GROUP:
304 self.require_operands(operands, at, 1, 1)
305 self.define(operands[0])
306 self.groups.add(operands[0])
307 else:
308 self.require_operands(operands, at, 2 if opcode == OP_GROUP_DECORATE else 3)
309 if opcode == OP_GROUP_MEMBER_DECORATE and len(operands) % 2 != 1:
310 raise InterfaceError(f"unpaired group member decoration at word {at}")
311 self.group_uses.append((opcode, operands))
312
313 @staticmethod
314 def add_decoration(target, decoration, value):
315 if decoration in target and target[decoration] != value:
316 raise InterfaceError(f"conflicting {DECORATION_NAMES[decoration]} decorations")
317 target[decoration] = value
318
319 def apply_decoration_groups(self):
320 for opcode, operands in self.group_uses:
321 group, *targets = operands
322 if group not in self.groups:
323 raise InterfaceError(f"undefined decoration group %{group}")
324 source = self.decorations.get(group, {})
325 if opcode == OP_GROUP_DECORATE:
326 destinations = ((identifier, None) for identifier in targets)
327 else:
328 destinations = zip(targets[::2], targets[1::2])
329 for identifier, member in destinations:
330 self.require_id(identifier)
331 if identifier in self.groups:
332 raise InterfaceError("decoration groups cannot decorate each other")
333 target = (self.decorations[identifier] if member is None
334 else self.member_decorations[(identifier, member)])
335 for decoration, value in source.items():
336 self.add_decoration(target, decoration, value)
337
338 def type_declaration(self, identifier):
339 try:
340 return self.types[identifier]
341 except KeyError:
342 raise InterfaceError(f"missing or unsupported varying type %{identifier}") from None
343
344 def array_count(self, identifier):
345 try:
346 type_id, literal = self.constants[identifier]
347 except KeyError:
348 raise InterfaceError(f"varying array length %{identifier} is not a literal OpConstant") from None
349 opcode, args = self.type_declaration(type_id)
350 if opcode != OP_TYPE_INT or args[0] not in (16, 32, 64) or args[1] not in (0, 1):
351 raise InterfaceError("varying array length must be an integer")
352 width, signed = args
353 if len(literal) != (width + 31) // 32:
354 raise InterfaceError("invalid literal width for varying array length")
355 count = sum(word << (32 * i) for i, word in enumerate(literal)) & ((1 << width) - 1)
356 if not count or (signed and count >> (width - 1)):
357 raise InterfaceError("varying array length must be positive")
358 return count
359
360 def shape(self, identifier, path=()):
361 if identifier in self.shape_cache:
362 return self.shape_cache[identifier]
363 if identifier in path or len(path) == MAX_TYPE_DEPTH:
364 raise InterfaceError("cyclic or excessively deep varying type")
365 opcode, args = self.type_declaration(identifier)
366 nested = (*path, identifier)
367 if opcode in (OP_TYPE_INT, OP_TYPE_FLOAT):
368 width = args[0]
369 if width not in (16, 32, 64) or (opcode == OP_TYPE_INT and args[1] not in (0, 1)):
370 raise InterfaceError("unsupported numeric type in graphics interface")
371 kind = "f" if opcode == OP_TYPE_FLOAT else ("i" if args[1] else "u")
372 result = NumericType(kind, width)
373 elif opcode == OP_TYPE_VECTOR:
374 element = self.shape(args[0], nested)
375 if not isinstance(element, NumericType) or element.components != 1 or not 2 <= args[1] <= 4:
376 raise InterfaceError("invalid varying vector type")
377 result = NumericType(element.kind, element.width, args[1])
378 elif opcode in (OP_TYPE_ARRAY, OP_TYPE_MATRIX):
379 element = self.shape(args[0], nested)
380 if opcode == OP_TYPE_ARRAY:
381 result = AggregateType("array", (element,), self.array_count(args[1]))
382 else:
383 if (not isinstance(element, NumericType) or element.kind != "f" or element.components < 2
384 or not 2 <= args[1] <= 4):
385 raise InterfaceError("invalid varying matrix type")
386 result = AggregateType("matrix", (element,), args[1])
387 elif opcode == OP_TYPE_STRUCT:
388 if not args:
389 raise InterfaceError("empty structure in graphics interface")
390 for i in range(len(args)):
391 if self.member_decorations.get((identifier, i)):
392 raise InterfaceError("decorated nested interface structure members are unsupported")
393 result = AggregateType("struct", tuple(self.shape(member, nested) for member in args))
394 else:
395 raise InterfaceError("unsupported pointer in graphics interface")
396 self.shape_cache[identifier] = result
397 return result
398
399 def pick_entry(self, stage, entry):
400 named = [candidate for candidate in self.entry_points if candidate.name == entry]
401 matches = [candidate for candidate in named if stage is None or EXECUTION_STAGES.get(candidate.model) == stage]
402 if not matches:
403 found = ", ".join(EXECUTION_STAGES.get(candidate.model, str(candidate.model)) for candidate in named)
404 if found:
405 raise InterfaceError(f"entry point {entry!r} is {found}, expected {stage}")
406 raise InterfaceError(f"entry point {entry!r} not found")
407 if len(matches) > 1:
408 raise InterfaceError(f"entry point {entry!r} is ambiguous without a stage")
409 selected = matches[0]
410 if selected.model not in EXECUTION_STAGES:
411 raise InterfaceError(f"unsupported execution model {selected.model} for entry point {entry!r}")
412 return selected
413
414 def varying_type(self, pointer, storage, stage, decorations):
415 opcode, args = self.type_declaration(pointer)
416 if opcode != OP_TYPE_POINTER or args[0] != storage:
417 raise InterfaceError("variable pointer type does not match its storage class")
418 pointee = args[1]
419 per_vertex = DEC_PER_VERTEX in decorations
420 if per_vertex and (stage, storage) != ("ps", STORAGE_INPUT):
421 raise InterfaceError("PerVertexKHR is only supported on fragment inputs")
422 primitive_array = (stage, storage) in (("gs", STORAGE_INPUT), ("ms", STORAGE_OUTPUT))
423 indexed = per_vertex or primitive_array
424 if indexed:
425 # The array indexes vertices or primitives. It is outside the linked payload shape
426 # and does not consume locations. Its length does not need to match the other stage.
427 opcode, args = self.type_declaration(pointee)
428 if opcode != OP_TYPE_ARRAY:
429 raise InterfaceError(f"{stage} requires an outer per-vertex or per-primitive array")
430 pointee = args[0]
431 return pointee, indexed
432
433 @staticmethod
434 def address(decorations, location=None):
435 location = decorations.get(DEC_LOCATION, location)
436 component = decorations.get(DEC_COMPONENT, 0)
437 index = decorations.get(DEC_INDEX, 0)
438 if location is None:
439 raise InterfaceError("user varying is missing a Location decoration")
440 if component > 3 or index > 1:
441 raise InterfaceError("invalid Component or Index decoration")
442 return Address(location, component, index)
443
444 @staticmethod
445 def check_modes(decorations):
446 if DEC_PASSTHROUGH_NV in decorations:
447 raise InterfaceError("geometry passthrough interfaces require different matching rules")
448 if DEC_PATCH in decorations:
449 raise InterfaceError("tessellation patch interfaces are unsupported")
450
451 def declaration(self, symbol, pointer, storage, stage):
452 decorations = self.decorations.get(symbol, {})
453 self.check_modes(decorations)
454 if DEC_BUILTIN in decorations:
455 return None
456 type_id, indexed = self.varying_type(pointer, storage, stage, decorations)
457 opcode, args = self.type_declaration(type_id)
458 per_primitive = DEC_PER_PRIMITIVE in decorations
459 if opcode != OP_TYPE_STRUCT:
460 varying = Varying(self.address(decorations), self.shape(type_id), per_primitive)
461 return Declaration((varying,), symbol, indexed_by_vertex_or_primitive=indexed)
462
463 member_decs = [self.member_decorations.get((type_id, i), {}) for i in range(len(args))]
464 if member_decs and all(DEC_BUILTIN in member for member in member_decs):
465 return None
466 if any(DEC_BUILTIN in member for member in member_decs):
467 raise InterfaceError("mixed built-in and user-defined structure members")
468 is_block = DEC_BLOCK in self.decorations.get(type_id, {})
469 base_location = decorations.get(DEC_LOCATION)
470 if base_location is None and not is_block:
471 raise InterfaceError("a non-block structure needs a Location")
472 if DEC_COMPONENT in decorations or DEC_INDEX in decorations:
473 raise InterfaceError("Component or Index on an entire varying structure is unsupported")
474 if base_location is not None and any(DEC_LOCATION in member for member in member_decs):
475 raise InterfaceError("both the structure and its members declare Locations")
476 if not args:
477 raise InterfaceError("empty structure in graphics interface")
478 members = []
479 next_location = base_location
480 for child, member in zip(args, member_decs):
481 self.check_modes(member)
482 address = self.address(member, next_location)
483 shape = self.shape(child, (type_id,))
484 members.append(Varying(address, shape, per_primitive or DEC_PER_PRIMITIVE in member))
485 if base_location is not None:
486 next_location += len(shape.location_masks(address.component))
487 return Declaration(tuple(members), symbol, structure=True, block=is_block,
488 indexed_by_vertex_or_primitive=indexed)
489
490 def reflect(self, stage=None, entry="main"):
491 selected = self.pick_entry(stage, entry)
492 stage = EXECUTION_STAGES[selected.model]
493 directions = {STORAGE_INPUT: [], STORAGE_OUTPUT: []}
494 slots = {STORAGE_INPUT: {}, STORAGE_OUTPUT: {}}
495 for symbol in selected.interface_ids:
496 if symbol not in self.variables:
497 raise InterfaceError(f"entry point references missing variable %{symbol}")
498 pointer, storage = self.variables[symbol]
499 if storage not in directions:
500 continue
501 try:
502 declaration = self.declaration(symbol, pointer, storage, stage)
503 if declaration is None:
504 continue
505 for varying in declaration.varyings:
506 for address in varying.occupied():
507 before = slots[storage].get(address)
508 if before is not None:
509 raise InterfaceError(
510 f"overlap with %{before} at {address.describe()}")
511 slots[storage][address] = symbol
512 except InterfaceError as exc:
513 direction = "input" if storage == STORAGE_INPUT else "output"
514 raise InterfaceError(f"{stage} {direction} variable %{symbol}: {exc}") from exc
515 directions[storage].append(declaration)
516 key = lambda declaration: declaration.varyings[0].address
517 return StageInterface(stage, entry, tuple(sorted(directions[STORAGE_INPUT], key=key)),
518 tuple(sorted(directions[STORAGE_OUTPUT], key=key)))
519
520
521def reflect_module(data, stage=None, entry="main"):
522 return Module(data).reflect(stage, entry)
diff --git a/tools/spirv_metal_set0.py b/tools/spirv_metal_set0.py
index 767e93ff9..cbd2792f5 100644
--- a/tools/spirv_metal_set0.py
+++ b/tools/spirv_metal_set0.py
@@ -107,6 +107,11 @@ def rewrite(text, counts):
107 107
108 108
109def main(argv): 109def main(argv):
110 rest = argv[1:]
111 if rest and rest[0] in ("-h", "--help"):
112 for line in __doc__.strip().splitlines()[-2:]:
113 print(line)
114 return 0
110 counts = capacities() 115 counts = capacities()
111 if argv[1:] == ["--print-layout"]: 116 if argv[1:] == ["--print-layout"]:
112 for b, (c, i) in enumerate(zip(counts, metal_ids(counts))): 117 for b, (c, i) in enumerate(zip(counts, metal_ids(counts))):
diff --git a/tools/story_index.py b/tools/story_index.py
index 731185a02..7a7c7a837 100644
--- a/tools/story_index.py
+++ b/tools/story_index.py
@@ -303,7 +303,7 @@ def write_output(path, rows, summary):
303 json.dump({"summary": summary, "files": rows}, f, indent=1) 303 json.dump({"summary": summary, "files": rows}, f, indent=1)
304 else: 304 else:
305 with open(staged, "w", encoding="utf-8", newline="") as f: 305 with open(staged, "w", encoding="utf-8", newline="") as f:
306 w = csv.writer(f) 306 w = csv.writer(f, lineterminator="\n")
307 w.writerow(COLUMNS) 307 w.writerow(COLUMNS)
308 for r in rows: 308 for r in rows:
309 w.writerow([f"0x{r['offset']:x}" if i == 0 else ("" if r[c] is None else r[c]) 309 w.writerow([f"0x{r['offset']:x}" if i == 0 else ("" if r[c] is None else r[c])
diff --git a/tools/tex_export.py b/tools/tex_export.py
index df5157b27..f7de7dd28 100644
--- a/tools/tex_export.py
+++ b/tools/tex_export.py
@@ -187,12 +187,33 @@ def main():
187 ap.add_argument("--limit", type=positive_int, help="export only the first N textures (N >= 1)") 187 ap.add_argument("--limit", type=positive_int, help="export only the first N textures (N >= 1)")
188 ap.add_argument("--png", action="store_true", help="also write a PNG beside each DDS dds_png.py can decode") 188 ap.add_argument("--png", action="store_true", help="also write a PNG beside each DDS dds_png.py can decode")
189 a = ap.parse_args() 189 a = ap.parse_args()
190 with open(a.index, encoding="utf-8") as f: 190 try:
191 texs = json.load(f) 191 with open(a.index, encoding="utf-8") as f:
192 texs.sort(key=lambda t: (t["archive"], t["gpu"])) 192 texs = json.load(f)
193 except (OSError, ValueError) as e:
194 print(f"ERROR: cannot read {a.index}: {e}", file=sys.stderr)
195 return 2
196 if not isinstance(texs, list):
197 print(f"ERROR: cannot read {a.index}: expected a texture list, got {type(texs).__name__}", file=sys.stderr)
198 return 2
199 try:
200 texs.sort(key=lambda t: (t["archive"], t["gpu"]))
201 except KeyError as e:
202 print(f"ERROR: cannot read {a.index}: row has no {e.args[0]!r}", file=sys.stderr)
203 return 2
204 except TypeError as e:
205 print(f"ERROR: cannot read {a.index}: {e}", file=sys.stderr)
206 return 2
193 if a.limit is not None: # 0 used to read as "no limit", and a negative N dropped the last N 207 if a.limit is not None: # 0 used to read as "no limit", and a negative N dropped the last N
194 texs = texs[: a.limit] 208 texs = texs[: a.limit]
195 os.makedirs(a.out, exist_ok=True) 209 if os.path.exists(a.out) and not os.path.isdir(a.out):
210 print(f"ERROR: {a.out} is a file, not a folder", file=sys.stderr)
211 return 2
212 try:
213 os.makedirs(a.out, exist_ok=True)
214 except OSError as e: # a report path under an existing file, or a dangling symlink
215 print(f"ERROR: cannot create {a.out}: {e.strerror or e}", file=sys.stderr)
216 return 2
196 res, cache, pngs = Counter(), {}, Counter() 217 res, cache, pngs = Counter(), {}, Counter()
197 for i, t in enumerate(texs, 1): 218 for i, t in enumerate(texs, 1):
198 try: 219 try:
diff --git a/tools/text_tables.py b/tools/text_tables.py
index deee48822..60c4e9dce 100644
--- a/tools/text_tables.py
+++ b/tools/text_tables.py
@@ -40,10 +40,12 @@ import os
40import re 40import re
41import struct 41import struct
42import sys 42import sys
43import tempfile
43 44
44ROOT = os.path.dirname(os.path.abspath(__file__)) 45ROOT = os.path.dirname(os.path.abspath(__file__))
45if ROOT not in sys.path: 46if ROOT not in sys.path:
46 sys.path.insert(0, ROOT) 47 sys.path.insert(0, ROOT)
48from file_mode import published_mode # noqa: E402
47from hashdict import joaat # noqa: E402 49from hashdict import joaat # noqa: E402
48 50
49RESOURCE_MAGIC = b"0DRP" 51RESOURCE_MAGIC = b"0DRP"
@@ -270,7 +272,7 @@ def _clean(s: str) -> str:
270 272
271def _write_csv(path, fields, rows): 273def _write_csv(path, fields, rows):
272 with open(path, "w", encoding="utf-8", newline="") as fh: 274 with open(path, "w", encoding="utf-8", newline="") as fh:
273 w = csv.DictWriter(fh, fieldnames=fields) 275 w = csv.DictWriter(fh, fieldnames=fields, lineterminator="\n")
274 w.writeheader() 276 w.writeheader()
275 n = 0 277 n = 0
276 for row in rows: 278 for row in rows:
@@ -288,6 +290,12 @@ def main(argv=None) -> int:
288 ap.add_argument("--strings", help="CSV: every string (source, offset, lang, hash, label, text)") 290 ap.add_argument("--strings", help="CSV: every string (source, offset, lang, hash, label, text)")
289 a = ap.parse_args(argv) 291 a = ap.parse_args(argv)
290 outs = [p for p in (a.dialogue, a.tables, a.strings) if p] 292 outs = [p for p in (a.dialogue, a.tables, a.strings) if p]
293 seen = set()
294 for p in outs:
295 key = os.path.normcase(os.path.realpath(p))
296 if key in seen:
297 ap.error("outputs must be distinct files")
298 seen.add(key)
291 for path in a.sources + a.labels: 299 for path in a.sources + a.labels:
292 if not os.path.exists(path): 300 if not os.path.exists(path):
293 print(f"text_tables: error: {path}: no such file or directory", file=sys.stderr) 301 print(f"text_tables: error: {path}: no such file or directory", file=sys.stderr)
@@ -308,24 +316,73 @@ def main(argv=None) -> int:
308 316
309 lines = sum(len(v) for v in scan.pairs.values()) 317 lines = sum(len(v) for v in scan.pairs.values())
310 langs = scan.languages() 318 langs = scan.languages()
319 jobs = []
320 if a.dialogue:
321 fields = ["wave", "key", "label", "speaker"] + [f"text_{x}" for x in langs]
322 jobs.append((a.dialogue, fields, scan.dialogue_rows()))
323 if a.tables:
324 jobs.append((a.tables, ["source", "offset", "lang", "group", "strings", "resolved"],
325 ({"source": s, "offset": o, "lang": lang,
326 "group": table_group(names[h] for h in t if h in names),
327 "strings": len(t), "resolved": sum(h in names for h in t)}
328 for s, o, lang, t in scan.tables)))
329 if a.strings:
330 jobs.append((a.strings, ["source", "offset", "lang", "hash", "label", "text"],
331 ({"source": s, "offset": o, "lang": lang, "hash": f"{h:08x}", "label": names.get(h, ""),
332 "text": _clean(text)}
333 for s, o, lang, t in scan.tables for h, text in t.items())))
334 # Stage every report next to its destination, then swap them all in. A write that fails part-way must
335 # leave the previous reports intact instead of truncating the ones that came before it.
336 staged = []
337 originals = {}
311 try: 338 try:
312 if a.dialogue: 339 for dest, fields, rows in jobs:
313 fields = ["wave", "key", "label", "speaker"] + [f"text_{x}" for x in langs] 340 parent = os.path.dirname(os.path.abspath(dest))
314 _write_csv(a.dialogue, fields, scan.dialogue_rows()) 341 fd, tmp = tempfile.mkstemp(dir=parent, prefix=".text_tables-", suffix=".csv")
315 if a.tables: 342 os.close(fd)
316 _write_csv(a.tables, ["source", "offset", "lang", "group", "strings", "resolved"], 343 staged.append((tmp, dest))
317 ({"source": s, "offset": o, "lang": lang, 344 _write_csv(tmp, fields, rows)
318 "group": table_group(names[h] for h in t if h in names), 345 for _tmp, dest in staged:
319 "strings": len(t), "resolved": sum(h in names for h in t)} 346 if os.path.isdir(dest):
320 for s, o, lang, t in scan.tables)) 347 raise OSError(f"{dest} is a directory")
321 if a.strings: 348 for tmp, dest in staged:
322 _write_csv(a.strings, ["source", "offset", "lang", "hash", "label", "text"], 349 os.chmod(tmp, published_mode(dest))
323 ({"source": s, "offset": o, "lang": lang, "hash": f"{h:08x}", "label": names.get(h, ""), 350 # Move every old report aside before putting any new one in place. On Windows a report held
324 "text": _clean(text)} 351 # open by a reader cannot be renamed; failing here leaves all the originals untouched.
325 for s, o, lang, t in scan.tables for h, text in t.items())) 352 for _tmp, dest in staged:
353 if os.path.lexists(dest):
354 fd, backup = tempfile.mkstemp(dir=os.path.dirname(os.path.abspath(dest)),
355 prefix=".text_tables-old-", suffix=".csv")
356 os.close(fd)
357 os.remove(backup)
358 os.replace(dest, backup)
359 originals[dest] = backup
360 else:
361 originals[dest] = None
362 for tmp, dest in staged:
363 os.replace(tmp, dest)
326 except OSError as error: 364 except OSError as error:
365 for dest, backup in originals.items():
366 try:
367 if os.path.lexists(dest):
368 os.remove(dest)
369 if backup is not None:
370 os.replace(backup, dest)
371 except OSError:
372 pass
373 for tmp, _ in staged:
374 try:
375 os.remove(tmp)
376 except OSError:
377 pass
327 print(f"text_tables: error: cannot write: {error}", file=sys.stderr) 378 print(f"text_tables: error: cannot write: {error}", file=sys.stderr)
328 return 2 379 return 2
380 for backup in originals.values():
381 if backup is not None:
382 try:
383 os.remove(backup)
384 except OSError:
385 pass
329 with_text = collections.Counter() 386 with_text = collections.Counter()
330 for row in scan.dialogue_rows(): 387 for row in scan.dialogue_rows():
331 for lang in langs: 388 for lang in langs:
diff --git a/tools/valu_fuzz.py b/tools/valu_fuzz.py
index 8e1a65a44..2b9beeb97 100644
--- a/tools/valu_fuzz.py
+++ b/tools/valu_fuzz.py
@@ -530,8 +530,8 @@ class F16Family(Family):
530 elif n == "v_pack_b32_f16": 530 elif n == "v_pack_b32_f16":
531 sel = op["opsel"] 531 sel = op["opsel"]
532 lo, hi = half(s[0], sel[0]), half(s[1], sel[1]) 532 lo, hi = half(s[0], sel[0]), half(s[1], sel[1])
533 # a signaling NaN half is uncertain (a quiet NaN stays compared): gfx1150 quiets a signaling NaN here (0x7c96 -> 0x7e96); the model moves bits, 533 # a signaling NaN half is uncertain (a quiet NaN stays compared): gfx1150 quiets a signaling NaN here (0x7c96 -> 0x7e96); the model moves
534 # and whether RDNA2 does the same is not known 534 # bits, which is what RDNA2 does under IEEE mode 0 and not under mode 1 (0x7c01 -> 0xfe01 on gfx1036, SHADER-260)
535 if "pack_swapped" in PERTURB: 535 if "pack_swapped" in PERTURB:
536 lo, hi = hi, lo 536 lo, hi = hi, lo
537 R[d] = Reg(lo | (hi << 16), unc(s[0], sel[0]) or is_f16_snan(lo), unc(s[1], sel[1]) or is_f16_snan(hi)) 537 R[d] = Reg(lo | (hi << 16), unc(s[0], sel[0]) or is_f16_snan(lo), unc(s[1], sel[1]) or is_f16_snan(hi))
diff --git a/tools/vk_subgroup_info.py b/tools/vk_subgroup_info.py
index bbac702cf..97e3880cf 100644
--- a/tools/vk_subgroup_info.py
+++ b/tools/vk_subgroup_info.py
@@ -6,17 +6,23 @@ make_game.py uses it to choose between native wave64 translation and --wave64-em
6Vulkan implementation through ctypes (standard library only), so it works before the runtime stage has built anything. 6Vulkan implementation through ctypes (standard library only), so it works before the runtime stage has built anything.
7On macOS it opens MoltenVK directly, using the same LEONIDA_VULKAN_LOADER override as the C++ test tools. 7On macOS it opens MoltenVK directly, using the same LEONIDA_VULKAN_LOADER override as the C++ test tools.
8 8
9Device choice follows the runtime (runtime/shims/d3d12_vulkan_device.cpp): Vulkan 1.3 devices with dynamicRendering, 9Device choice follows the runtime (runtime/shims/d3d12_vulkan_device.cpp, runtime/src/vulkan_device_filter.h):
10synchronization2, timelineSemaphore and separateDepthStencilLayouts and a graphics queue family; a discrete GPU wins 10LEONIDA_VK_DEVICE filters by deviceName substring case-insensitively (failing when nothing matches), then Vulkan 1.3
11(the last one), otherwise the first. The runtime also needs the rest of its device setup (surface, extensions); 11devices with dynamicRendering, synchronization2, timelineSemaphore and separateDepthStencilLayouts and a graphics queue
12that is not checked here. vk_pipeline_check picks by device type only, so on a PC where the two differ the pipelines 12family; a discrete GPU wins (the last one), otherwise the first. The runtime also needs the rest of its device setup
13stage can run on another GPU than the one asked here. VK_LOADER_DRIVERS_SELECT (e.g. '*amd*') narrows which 13(surface, extensions); that is not checked here. vk_pipeline_check picks by device type only, so on a PC where the two
14drivers the loader offers. 14differ the pipelines stage can run on another GPU than the one asked here. VK_LOADER_DRIVERS_SELECT (e.g. '*amd*')
15narrows which drivers the loader offers.
15 16
16native64 matches the current translated SPIR-V 1.5 modules, which do not allow varying subgroup sizes: either 64 can 17native64 matches the current translated SPIR-V 1.5 modules, which do not allow varying subgroup sizes: either 64 can
17be required for both compute and mesh, or the default subgroupSize is 64 and subgroup operations are supported in 18be required for both compute and mesh, or the default subgroupSize is 64 and subgroup operations are supported in
18both stages. SPIR-V 1.6 modules or stages created with ALLOW_VARYING_SUBGROUP_SIZE need a different check. 19both stages. SPIR-V 1.6 modules or stages created with ALLOW_VARYING_SUBGROUP_SIZE need a different check.
19 20
21rdna2_amd_windows says whether the device is RDNA2 (gfx103x, by PCI device ID) under AMD's proprietary Windows driver.
22That driver's shader compiler crashes (an access violation in vkCreateComputePipelines) on many --wave64-emulate
23compute shaders with LDS: #857, from driver 32.0.21030 to at least 32.0.21045.29003, on iGPUs and RX 6000 cards
24alike, while RDNA3, RDNA4, RADV and NVIDIA take the same modules. make_game.py leaves emulation off for such a GPU.
25
20per_vertex_inputs says whether the device can run a pixel shader with PerVertexKHR inputs (16-bit interpolation, 26per_vertex_inputs says whether the device can run a pixel shader with PerVertexKHR inputs (16-bit interpolation,
21docs/design.md): the fragmentShaderBarycentric feature, and a driver other than MoltenVK, whose SPIR-V to MSL 27docs/design.md): the fragmentShaderBarycentric feature, and a driver other than MoltenVK, whose SPIR-V to MSL
22conversion rejects the decoration ("PerVertexKHR decoration is not supported in MSL", MoltenVK 1.4.2). Where it is 28conversion rejects the decoration ("PerVertexKHR decoration is not supported in MSL", MoltenVK 1.4.2). Where it is
@@ -38,6 +44,13 @@ VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SUBGROUP_SIZE_CONTROL_PROPERTIES = 1000225000
38VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DRIVER_PROPERTIES = 1000196000 44VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DRIVER_PROPERTIES = 1000196000
39VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FRAGMENT_SHADER_BARYCENTRIC_FEATURES_KHR = 1000203000 45VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FRAGMENT_SHADER_BARYCENTRIC_FEATURES_KHR = 1000203000
40VK_DRIVER_ID_MOLTENVK = 14 46VK_DRIVER_ID_MOLTENVK = 14
47VK_DRIVER_ID_AMD_PROPRIETARY = 1
48AMD_VENDOR_ID = 0x1002
49# PCI device IDs of RDNA2 (gfx103x) GPUs: Navi 21/22/23/24 cards, and the iGPUs of Van Gogh (Steam Deck),
50# Rembrandt (Ryzen 6000), Mendocino (Ryzen 7020) and Raphael/Granite Ridge (Ryzen 7000/9000 desktop). #857 has
51# crash reports from 0x13C0, 0x164E, 0x73BF (RX 6800) and 0x73DF (RX 6700).
52RDNA2_DEVICE_IDS = ((0x73A0, 0x73FF), (0x7420, 0x743F), (0x163F, 0x163F), (0x1435, 0x1435), (0x1681, 0x1681),
53 (0x1506, 0x1506), (0x164E, 0x164E), (0x13C0, 0x13C0))
41DRIVER_PROPS_SIZE = 536 # sizeof(VkPhysicalDeviceDriverProperties): 16 + driverID + 2 x char[256] + version, padded 54DRIVER_PROPS_SIZE = 536 # sizeof(VkPhysicalDeviceDriverProperties): 16 + driverID + 2 x char[256] + version, padded
42BARY_FEATURES_SIZE = 24 # sizeof(VkPhysicalDeviceFragmentShaderBarycentricFeaturesKHR): 16 + one VkBool32 55BARY_FEATURES_SIZE = 24 # sizeof(VkPhysicalDeviceFragmentShaderBarycentricFeaturesKHR): 16 + one VkBool32
43VK_SHADER_STAGE_COMPUTE_BIT = 0x20 56VK_SHADER_STAGE_COMPUTE_BIT = 0x20
@@ -58,6 +71,8 @@ F13_SUBGROUP_SIZE_CONTROL = 16 + 4 * 7
58F13_SYNCHRONIZATION2 = 16 + 4 * 9 71F13_SYNCHRONIZATION2 = 16 + 4 * 9
59F13_DYNAMIC_RENDERING = 16 + 4 * 12 72F13_DYNAMIC_RENDERING = 16 + 4 * 12
60PROPS_DEVICE_TYPE = 16 # offsets in VkPhysicalDeviceProperties 73PROPS_DEVICE_TYPE = 16 # offsets in VkPhysicalDeviceProperties
74PROPS_VENDOR_ID = 8
75PROPS_DEVICE_ID = 12
61PROPS_DEVICE_NAME = 20 # char[256] 76PROPS_DEVICE_NAME = 20 # char[256]
62PROPS_API_VERSION = 0 77PROPS_API_VERSION = 0
63QUEUE_FAMILY_SIZE = 24 # sizeof(VkQueueFamilyProperties) 78QUEUE_FAMILY_SIZE = 24 # sizeof(VkQueueFamilyProperties)
@@ -119,6 +134,12 @@ def load_vulkan():
119 raise RuntimeError("no Vulkan loader found (" + ", ".join(names) + ")") 134 raise RuntimeError("no Vulkan loader found (" + ", ".join(names) + ")")
120 135
121 136
137def rdna2_amd_windows(vendor_id: int, device_id: int, driver_id: int) -> bool:
138 """An RDNA2 GPU under AMD's proprietary (Windows) driver: the one whose compiler crashes on #857's modules."""
139 return (vendor_id == AMD_VENDOR_ID and driver_id == VK_DRIVER_ID_AMD_PROPRIETARY
140 and any(lo <= device_id <= hi for lo, hi in RDNA2_DEVICE_IDS))
141
142
122def physical_devices(vk, instance): 143def physical_devices(vk, instance):
123 # The list can grow between the count and fetch. Recount, with a bound for a changing driver. 144 # The list can grow between the count and fetch. Recount, with a bound for a changing driver.
124 for _ in range(3): 145 for _ in range(3):
@@ -160,6 +181,8 @@ def query() -> dict:
160 devs = physical_devices(vk, inst) 181 devs = physical_devices(vk, inst)
161 if not devs: 182 if not devs:
162 raise RuntimeError("no Vulkan device") 183 raise RuntimeError("no Vulkan device")
184 device_filter = os.environ.get("LEONIDA_VK_DEVICE", "")
185 wanted = device_filter.lower()
163 chosen = None 186 chosen = None
164 for d in devs: 187 for d in devs:
165 d = ctypes.c_void_p(d) 188 d = ctypes.c_void_p(d)
@@ -173,8 +196,11 @@ def query() -> dict:
173 set_next(props, subgroup) 196 set_next(props, subgroup)
174 vk.vkGetPhysicalDeviceProperties2(d, props) 197 vk.vkGetPhysicalDeviceProperties2(d, props)
175 raw = bytes(props)[16:] 198 raw = bytes(props)[16:]
199 dev_name = raw[PROPS_DEVICE_NAME:PROPS_DEVICE_NAME + 256].split(b"\0")[0].decode("utf-8", "replace")
176 if int.from_bytes(raw[PROPS_API_VERSION:PROPS_API_VERSION + 4], "little") < VK_API_VERSION_1_3: 200 if int.from_bytes(raw[PROPS_API_VERSION:PROPS_API_VERSION + 4], "little") < VK_API_VERSION_1_3:
177 continue 201 continue
202 if wanted and wanted not in dev_name.lower():
203 continue
178 f13 = block(F13_SIZE, VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_3_FEATURES) 204 f13 = block(F13_SIZE, VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_3_FEATURES)
179 f12 = block(F12_SIZE, VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES) 205 f12 = block(F12_SIZE, VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES)
180 set_next(f12, f13) 206 set_next(f12, f13)
@@ -195,13 +221,20 @@ def query() -> dict:
195 dtype = int.from_bytes(raw[PROPS_DEVICE_TYPE:PROPS_DEVICE_TYPE + 4], "little") 221 dtype = int.from_bytes(raw[PROPS_DEVICE_TYPE:PROPS_DEVICE_TYPE + 4], "little")
196 # the runtime's rule: the first usable device, replaced by every later discrete GPU 222 # the runtime's rule: the first usable device, replaced by every later discrete GPU
197 if chosen is None or dtype == VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU: 223 if chosen is None or dtype == VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU:
198 chosen = (raw[PROPS_DEVICE_NAME:PROPS_DEVICE_NAME + 256].split(b"\0")[0].decode("utf-8", "replace"), 224 chosen = (dev_name,
199 subgroup.subgroupSize, subgroup.supportedStages, sg.minSubgroupSize, sg.maxSubgroupSize, 225 subgroup.subgroupSize, subgroup.supportedStages, sg.minSubgroupSize, sg.maxSubgroupSize,
200 sg.requiredSubgroupSizeStages, bool(u32(f13, F13_SUBGROUP_SIZE_CONTROL)), 226 sg.requiredSubgroupSizeStages, bool(u32(f13, F13_SUBGROUP_SIZE_CONTROL)),
201 bool(u32(bary, 16)) and u32(drv, 16) != VK_DRIVER_ID_MOLTENVK) 227 bool(u32(bary, 16)) and u32(drv, 16) != VK_DRIVER_ID_MOLTENVK,
228 int.from_bytes(raw[PROPS_VENDOR_ID:PROPS_VENDOR_ID + 4], "little"),
229 int.from_bytes(raw[PROPS_DEVICE_ID:PROPS_DEVICE_ID + 4], "little"), u32(drv, 16))
202 if chosen is None: 230 if chosen is None:
231 if device_filter:
232 raise RuntimeError(
233 f"LEONIDA_VK_DEVICE={device_filter}: no Vulkan 1.3 GPU with the features and graphics queue "
234 "the runtime needs matches"
235 )
203 raise RuntimeError("no Vulkan 1.3 GPU with the features and graphics queue the runtime needs") 236 raise RuntimeError("no Vulkan 1.3 GPU with the features and graphics queue the runtime needs")
204 name, subgroup_size, supported_stages, lo, hi, required_stages, sgc, per_vertex = chosen 237 name, subgroup_size, supported_stages, lo, hi, required_stages, sgc, per_vertex, vendor, device, driver = chosen
205 compute_required = bool(required_stages & VK_SHADER_STAGE_COMPUTE_BIT) 238 compute_required = bool(required_stages & VK_SHADER_STAGE_COMPUTE_BIT)
206 mesh_required = bool(required_stages & VK_SHADER_STAGE_MESH_BIT_EXT) 239 mesh_required = bool(required_stages & VK_SHADER_STAGE_MESH_BIT_EXT)
207 compute_supported = bool(supported_stages & VK_SHADER_STAGE_COMPUTE_BIT) 240 compute_supported = bool(supported_stages & VK_SHADER_STAGE_COMPUTE_BIT)
@@ -221,6 +254,10 @@ def query() -> dict:
221 "mesh_in_supported_stages": mesh_supported, 254 "mesh_in_supported_stages": mesh_supported,
222 "native64": bool(can_require_64 or has_default_64), 255 "native64": bool(can_require_64 or has_default_64),
223 "per_vertex_inputs": per_vertex, 256 "per_vertex_inputs": per_vertex,
257 "vendor_id": vendor,
258 "device_id": device,
259 "driver_id": driver,
260 "rdna2_amd_windows": rdna2_amd_windows(vendor, device, driver),
224 } 261 }
225 finally: 262 finally:
226 vk.vkDestroyInstance(inst, None) 263 vk.vkDestroyInstance(inst, None)
diff --git a/tools/world_index.py b/tools/world_index.py
index e72f8952c..c3e6a62bf 100644
--- a/tools/world_index.py
+++ b/tools/world_index.py
@@ -396,7 +396,11 @@ def scan_rpf(path, start=None, limit=None, max_inflate=CAP, collect=None):
396 396
397 397
398def _directory_files(path): 398def _directory_files(path):
399 for root, _, files in os.walk(path): 399 def scan_failed(error: OSError) -> None:
400 raise error
401
402 # A partial walk must fail before the caller starts writing reports.
403 for root, _, files in os.walk(path, onerror=scan_failed):
400 for name in sorted(files): 404 for name in sorted(files):
401 yield os.path.join(root, name) 405 yield os.path.join(root, name)
402 406
@@ -415,6 +419,15 @@ def _carve_successors(folder):
415 for off, stored in by_off.items() if (off + stored + 15) & ~15 in by_off} 419 for off, stored in by_off.items() if (off + stored + 15) & ~15 in by_off}
416 420
417 421
422def _read_carved(path, max_inflate):
423 """Read a carved file within the cap, or return None if it is too large."""
424 with open(path, "rb") as f:
425 if os.fstat(f.fileno()).st_size > max_inflate:
426 return None
427 data = f.read(max_inflate + 1) # detect growth after fstat
428 return data if len(data) <= max_inflate else None
429
430
418def scan_path(path, start=None, limit=None, max_inflate=CAP, collect=None, *, directory_files=None): 431def scan_path(path, start=None, limit=None, max_inflate=CAP, collect=None, *, directory_files=None):
419 """Scan an RPF9 archive, or every carved file in a directory.""" 432 """Scan an RPF9 archive, or every carved file in a directory."""
420 if directory_files is not None or os.path.isdir(path): 433 if directory_files is not None or os.path.isdir(path):
@@ -436,10 +449,9 @@ def scan_path(path, start=None, limit=None, max_inflate=CAP, collect=None, *, di
436 stats["files"] += 1 449 stats["files"] += 1
437 stats["scanned_bytes"] += sub["scanned_bytes"] 450 stats["scanned_bytes"] += sub["scanned_bytes"]
438 continue 451 continue
439 if os.path.getsize(p) > max_inflate: 452 b = _read_carved(p, max_inflate)
453 if b is None:
440 continue 454 continue
441 with open(p, "rb") as f:
442 b = f.read(max_inflate + 1)
443 stats["files"] += 1 455 stats["files"] += 1
444 stats["scanned_bytes"] += len(b) 456 stats["scanned_bytes"] += len(b)
445 # As in scan_rpf: a 0DRPz resource that needs a continuation takes the next stream, when the 457 # As in scan_rpf: a 0DRPz resource that needs a continuation takes the next stream, when the
@@ -476,8 +488,9 @@ def scan_path(path, start=None, limit=None, max_inflate=CAP, collect=None, *, di
476 magic = f.read(4) 488 magic = f.read(4)
477 if magic == b"9FPR": 489 if magic == b"9FPR":
478 return scan_rpf(path, start, limit, max_inflate, collect) 490 return scan_rpf(path, start, limit, max_inflate, collect)
479 with open(path, "rb") as f: 491 b = _read_carved(path, max_inflate)
480 b = f.read(max_inflate + 1) 492 if b is None:
493 return [], {"path": os.path.abspath(path), "files": 0, "scanned_bytes": 0}
481 row = parse_resource(b, collect) 494 row = parse_resource(b, collect)
482 return ([dict(row, offset=0, size=len(b), file=os.path.basename(path))] if row else [], 495 return ([dict(row, offset=0, size=len(b), file=os.path.basename(path))] if row else [],
483 {"path": os.path.abspath(path), "files": 1, "scanned_bytes": len(b)}) 496 {"path": os.path.abspath(path), "files": 1, "scanned_bytes": len(b)})
@@ -748,7 +761,7 @@ def _write_reports(a, rows, stats, agg):
748 "position_max", "lod", "lod_dist_min", "lod_dist_max"] 761 "position_max", "lod", "lod_dist_min", "lod_dist_max"]
749 os.makedirs(os.path.dirname(os.path.abspath(a.csv)), exist_ok=True) 762 os.makedirs(os.path.dirname(os.path.abspath(a.csv)), exist_ok=True)
750 with open(a.csv, "w", newline="", encoding="utf-8") as f: 763 with open(a.csv, "w", newline="", encoding="utf-8") as f:
751 w = csv.DictWriter(f, fieldnames=cols, extrasaction="ignore") 764 w = csv.DictWriter(f, fieldnames=cols, extrasaction="ignore", lineterminator="\n")
752 w.writeheader() 765 w.writeheader()
753 for r in rows: 766 for r in rows:
754 r = dict(r) 767 r = dict(r)
diff --git a/tools/world_names.py b/tools/world_names.py
index 70e89b62f..4ffe3f01a 100644
--- a/tools/world_names.py
+++ b/tools/world_names.py
@@ -573,7 +573,7 @@ def _resolve(args) -> int:
573 for path in (args.dict, *args.maps, *args.archetypes): 573 for path in (args.dict, *args.maps, *args.archetypes):
574 if _same_report_path(args.out, path): 574 if _same_report_path(args.out, path):
575 raise ValueError( 575 raise ValueError(
576 f"resolve: --out {args.out!r} would overwrite input {path!r}") 576 f"resolve: --out {args.out} would overwrite input {path}")
577 try: 577 try:
578 dictionary = NameDictionary.from_json(_load_json(args.dict)) 578 dictionary = NameDictionary.from_json(_load_json(args.dict))
579 except ValueError as exc: 579 except ValueError as exc:
diff --git a/tools/xdxr_bvh.py b/tools/xdxr_bvh.py
index edcc79a8b..e8fcefde3 100644
--- a/tools/xdxr_bvh.py
+++ b/tools/xdxr_bvh.py
@@ -740,11 +740,15 @@ def check_build(directory, rays=300, seed=1):
740 return [f"no cases in {directory}"] 740 return [f"no cases in {directory}"]
741 problems = [] 741 problems = []
742 cases = {n: _load_case(directory, n) for n in names} 742 cases = {n: _load_case(directory, n) for n in names}
743 mem = Memory()
744 for n, (desc, data) in cases.items():
745 mem.place(desc["address"], data)
746 rng = random.Random(seed) 743 rng = random.Random(seed)
747 for n, (desc, data) in cases.items(): 744 for n, (desc, data) in cases.items():
745 # An in-place update leaves two dumps at one address (before and after): the case being checked comes first,
746 # so its own bytes answer reads there.
747 mem = Memory()
748 mem.place(desc["address"], data)
749 for other, (odesc, odata) in cases.items():
750 if other != n:
751 mem.place(odesc["address"], odata)
748 errs = validate(data, expect_bottom=desc["kind"] == "blas") 752 errs = validate(data, expect_bottom=desc["kind"] == "blas")
749 problems += [f"{n}: {e}" for e in errs] 753 problems += [f"{n}: {e}" for e in errs]
750 if desc["kind"] == "blas": 754 if desc["kind"] == "blas":