diff --git a/CMakeLists.txt b/CMakeLists.txt index ab2ae7661d..1e37bf69c8 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1043,6 +1043,15 @@ target_compile_features(startup_chad_check PRIVATE cxx_std_17) add_dependencies(startup_chad_check startup_stub_chad) add_test(NAME startup_chad_check COMMAND startup_chad_check "$") set_tests_properties(startup_chad_check PROPERTIES TIMEOUT 60) +# Activity counter of the AcpHal and XApu stand-ins (X2W_AUDIO_ACTIVITY=1): exact counts, a zero-write control, the +# same results with the counter on and off, and a caller that unloads both DLLs and must exit cleanly +# (docs/startup-runtime.md). +add_executable(startup_acphal_xma_activity tests/startup_acphal_xma_activity.cpp) +target_compile_features(startup_acphal_xma_activity PRIVATE cxx_std_17) +add_dependencies(startup_acphal_xma_activity startup_stub_acphal startup_stub_xapu) +add_test(NAME startup_acphal_xma_activity COMMAND startup_acphal_xma_activity "$" + "$") +set_tests_properties(startup_acphal_xma_activity PROPERTIES TIMEOUT 60) # BMP writer of the draw dumps (src/startup_stubs/draw_bmp.h); the mutated runs are negative controls. add_executable(startup_draw_bmp_check tests/startup_draw_bmp.cpp) @@ -1252,6 +1261,10 @@ target_compile_features(startup_debug_probe PRIVATE cxx_std_17) # The DLL the probe calls for the debugger's call-hook case (--trace-calls). add_library(startup_debug_calls SHARED tests/startup_debug_calls.cpp) add_dependencies(startup_debug_probe startup_debug_calls) +# Input for the launcher's --map-drive check (tests/startup_map_drive_check.py): the consumer opens its +# package through a mapped letter, and the launcher rewrites that open. +add_executable(startup_map_drive_consumer tests/startup_map_drive_consumer.cpp) +target_compile_features(startup_map_drive_consumer PRIVATE cxx_std_17) # A visible window that changes its picture at a known time: input for the --capture-every check (tests/startup_debug_window_check.py). add_executable(startup_window_probe tests/startup_window_probe.cpp) target_compile_features(startup_window_probe PRIVATE cxx_std_17) @@ -1958,6 +1971,22 @@ if(TARGET compile_dxil AND EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${ "${CMAKE_SOURCE_DIR}/tests/native_compute_clear_check.py" "$" "${DXC_BIN_DIR}") add_test(NAME native_compute_raw_root COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/native_compute_raw_root_check.py" "$" "${DXC_BIN_DIR}") + foreach(adapter IN ITEMS warp hardware) + add_test(NAME startup_native_graphics_draw_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_native_graphics_draw_check.py" + "$" "$" "${DXC_BIN_DIR}" ${adapter}) + set_tests_properties(startup_native_graphics_draw_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) + endforeach() + foreach(backend IN ITEMS hardware warp) + add_test(NAME native_descriptor_scc_${backend} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/native_descriptor_scc_check.py" "$" + "$" "${DXC_BIN_DIR}" ${backend}) + set_tests_properties(native_descriptor_scc_${backend} PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60) + add_test(NAME startup_compute_descriptor_scc_${backend} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/native_descriptor_scc_check.py" runtime "$" + "$" "${DXC_BIN_DIR}" ${backend}) + set_tests_properties(startup_compute_descriptor_scc_${backend} PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60) + endforeach() add_test(NAME native_direct_container COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/native_direct_container_check.py" "$" "${DXC_BIN_DIR}") @@ -1978,6 +2007,14 @@ if(TARGET compile_dxil AND EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${ add_test(NAME native_compute_pack COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/native_compute_pack_check.py" "$" "$" "${DXC_BIN_DIR}") + foreach(adapter IN ITEMS warp hardware) + foreach(case IN ITEMS r rg rgb array volume rgba sparse) + add_test(NAME native_image_store_exact_width_${adapter}_${case} + COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/native_image_store_exact_width_check.py" + "$" "${DXC_BIN_DIR}" "$" ${adapter} ${case}) + set_tests_properties(native_image_store_exact_width_${adapter}_${case} PROPERTIES TIMEOUT 90 SKIP_RETURN_CODE 77) + endforeach() + endforeach() add_test(NAME native_dpp_mirror_hardware COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/native_dpp_mirror_check.py" "$" "$" "$" "${DXC_BIN_DIR}") @@ -2571,6 +2608,8 @@ target_compile_features(startup_local_log_check PRIVATE cxx_std_17) add_test(NAME startup_local_log COMMAND startup_local_log_check) add_test(NAME startup_local_log_precheck_off COMMAND startup_local_log_check --phase precheck-off) set_tests_properties(startup_local_log_precheck_off PROPERTIES ENVIRONMENT "X2W_PROBE_PRECHECK=0") +add_test(NAME startup_local_log_precheck_off_debugger COMMAND startup_local_log_check --phase precheck-off-debugger) +set_tests_properties(startup_local_log_precheck_off_debugger PROPERTIES ENVIRONMENT "X2W_PROBE_PRECHECK=0") add_test(NAME startup_local_log_guard_drop_control COMMAND startup_local_log_check --mutate guard-drop) set_tests_properties(startup_local_log_guard_drop_control PROPERTIES WILL_FAIL TRUE) add_test(NAME startup_local_log_reopen_control COMMAND startup_local_log_check --mutate reopen) @@ -4549,7 +4588,7 @@ if(EXISTS "${INTAKE_PYTHON}") "$" ${adapter}) set_tests_properties(startup_gfx2hlsl_compute_mbcnt_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) foreach(control IN ITEMS swapped-axes dropped-store b-offset c-unpredicated f-peer f-broadcast f-second-fill g-swapped-offsets g-overlap - j-scalar-dropped h-inner-unpredicated k-block-entered m-else-unswitched n-unmasked o-mask-kept + j-scalar-dropped h-inner-unpredicated k-block-entered m-else-unswitched n-unmasked o-mask-kept o-subset-remask-dropped n-dropped-broadcast p-dropped-andn2 p-dropped-or p-block-entered q-block-entered q-not-all-ones s-min-strict s-borrow-flipped) add_test(NAME startup_gfx2hlsl_compute_${control}_${adapter} COMMAND "${INTAKE_PYTHON}" -B @@ -4834,6 +4873,21 @@ if(EXISTS "${INTAKE_PYTHON}") "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_debug_window_check.py" "$") set_tests_properties(startup_debug_window PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) + # tools/startup/debug_launch.py --map-drive: a console package on another volume is opened through + # a mapped letter, and the launcher rewrites that open in the caller's own name. + add_test(NAME startup_map_drive COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/startup_map_drive_check.py" + "$" "${CMAKE_SOURCE_DIR}/tools/startup/debug_launch.py" + "${CMAKE_CURRENT_BINARY_DIR}") + set_tests_properties(startup_map_drive PROPERTIES TIMEOUT 300 SKIP_RETURN_CODE 77) + # Two threads with their own caller-owned names in flight at once: all 64 opens are rewritten, succeed + # and restore their caller strings while the debugger holds the other threads for each step; the + # control without holding them (--suspend-others 0) must lose opens. Needs the step window (#1281). + add_test(NAME startup_map_drive_overlap COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_map_drive_check.py" + "$" "${CMAKE_SOURCE_DIR}/tools/startup/debug_launch.py" + "${CMAKE_CURRENT_BINARY_DIR}" overlap) + set_tests_properties(startup_map_drive_overlap PROPERTIES TIMEOUT 300 SKIP_RETURN_CODE 77) + add_test(NAME startup_stream_request_warp COMMAND "${CMAKE_COMMAND}" -E env "X2W_FXC=${STARTUP_FXC}" "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_stream_check.py" "$") # Device slot 67 compute pipelines publish req_.{desc,sa,sb,data,root,c67}; the control (render mode off) must fail. diff --git a/CMakePresets.json b/CMakePresets.json index ff53cb8bf9..8fff29df28 100644 --- a/CMakePresets.json +++ b/CMakePresets.json @@ -33,7 +33,8 @@ "xmem_shim_test_controls", "startup_stub_xcrdapi", "startup_stub_xcrdapi_break_window_control", "xmem_run_break_readers_check", "xmem_run_break_readers_control", "xmem_cross_call_merge_check", "xmem_placeholder_split_check", "xmem_map_split_first_check", "startup_dstorage_break_window_check", - "xmem_page_runs_device_check", "linear_buffer_backing_check" + "xmem_page_runs_device_check", "linear_buffer_backing_check", + "bcpack_formats_check", "startup_stub_consumer" ] }, { "name": "release", "configurePreset": "release" }, @@ -47,7 +48,7 @@ "displayName": "Windows pull request smoke tests", "filter": { "include": { - "name": "^(desktop_root_signature|era_heap_(allocation|failure)|xmem_shim_mapped_pages|cpu_aot_fuzz_smoke|cpu_archive_texture_gpu_warp|dual_uav_warp|spirv_.*_warp|static_exe_intake|descriptor_heap_paging(_swapped)?_warp|startup_launch|startup_tools_lint|startup_gfx2hlsl_cvt_off_f32_i4_controls|startup_gfx2hlsl_sad_hi_msad_controls|startup_indirect_(dispatch|count_split|draw(_indexed)?|mesh(_xmem_arguments(_skip_wait)?)?|counts_control)_warp|startup_indirect_mesh_lease_warp_dual(-trace(-disabled)?)?|startup_shader_cache_key|startup_present_readback|xmem_(run_break_readers|cross_call_merge|placeholder_split|map_split_first)(_[a-z_]+)?|startup_dstorage_break_window(_[a-z_]+)?|xmem_page_runs_device(_join)?_warp|linear_buffer_backing_share_warp)$" + "name": "^(bcpack_all_formats(_golden_control)?|startup_bcpack_storage|desktop_root_signature|era_heap_(allocation|failure)|xmem_shim_mapped_pages|cpu_aot_fuzz_smoke|cpu_archive_texture_gpu_warp|dual_uav_warp|spirv_.*_warp|static_exe_intake|descriptor_heap_paging(_swapped)?_warp|startup_launch|startup_tools_lint|startup_gfx2hlsl_cvt_off_f32_i4_controls|startup_gfx2hlsl_sad_hi_msad_controls|startup_indirect_(dispatch|count_split|draw(_indexed)?|mesh(_xmem_arguments(_skip_wait)?)?|counts_control)_warp|startup_indirect_mesh_lease_warp_dual(-trace(-disabled)?)?|startup_shader_cache_key|startup_present_readback|xmem_(run_break_readers|cross_call_merge|placeholder_split|map_split_first)(_[a-z_]+)?|startup_dstorage_break_window(_[a-z_]+)?|xmem_page_runs_device(_join)?_warp|linear_buffer_backing_share_warp|startup_stage_package)$" } } }, diff --git a/README.md b/README.md index 1c26df1061..bd6b59850d 100644 --- a/README.md +++ b/README.md @@ -124,7 +124,7 @@ The control-flow CPU translator supports [source-built string memory transfers]( | CPU differential fuzz | Generate 20 deterministic leaf functions from seed `0xA902`, translate them, and compare native, default and `/O2` builds over 313 inputs each. | `ctest --preset dev --no-tests=error -R '^cpu_aot_fuzz_smoke$' -V` | | Script states | Reproduce a parent/child lookup, an ambiguous selection or a damaged sibling link with a synthetic tree. | `ctest --preset dev --no-tests=error -R '^script_(state_literals\|path_links)$' -V` | | Resource metadata | Check a [relocated resource root](docs/experiments.md#relocated-resource-root) against its block directory and type schema. | `ctest --preset dev --no-tests=error -R '^resource_relocated_root$' -V` | -| Texture recovery | [Decode MDU rANS symbols](docs/experiments.md#decoding-mdu-rans-symbol-streams) using [bcpack-rs by Ahmet Dedeler](https://github.com/Ahmet-Dedeler/bcpack-rs), or check a packed mip tail, a first refill byte, the fields of a generated BC7 block, or a resident mip drawn on the software adapter. [Look up a texture key across archives and inspect a matching descriptor](docs/experiments.md#reading-logical-ranges-and-probing-structured-resources). [Batch export TTPF textures with optional Rust kernels](docs/experiments.md#batch-export-ttpf-textures-to-dds). | `ctest --preset dev --no-tests=error -R '^(bcpack_prefix_and_mip_tail\|bcpack_rans_symbols\|bc7_block_reference\|bc7_draw_warp\|resource_range_controls)$' -V` | +| Texture recovery | [Check standalone BCPack BC1–BC7 reconstruction](docs/experiments/bcpack-standalone.md) or [decode MDU rANS symbols](docs/experiments.md#decoding-mdu-rans-symbol-streams) using [bcpack-rs by Ahmet Dedeler](https://github.com/Ahmet-Dedeler/bcpack-rs), or check a packed mip tail, a first refill byte, the fields of a generated BC7 block, or a resident mip drawn on the software adapter. [Look up a texture key across archives and inspect a matching descriptor](docs/experiments.md#reading-logical-ranges-and-probing-structured-resources). [Batch export TTPF textures with optional Rust kernels](docs/experiments.md#batch-export-ttpf-textures-to-dds). | `ctest --preset dev --no-tests=error -R '^(bcpack_all_formats\|startup_bcpack_storage\|bcpack_prefix_and_mip_tail\|bcpack_rans_symbols\|bc7_block_reference\|bc7_draw_warp\|resource_range_controls)$' -V` | | Audio metadata | Inventory stream counts, codec IDs and sample rates in a bounded [AWC sound-effect or music bank](docs/experiments.md#awc-sound-effect-format-metadata) with flag word `0xff000001` or `0xff020001`. | `ctest --preset dev --no-tests=error -R '^audio_awc_metadata$' -V` | | Compute shader recompilation | Translate fixed, indexed and row-pitch raw UAV stores for 1D, 2D and 3D thread groups, including an optional runtime constant buffer, and compare the complete buffer on D3D12. [Bindings and commands](docs/experiments.md#compute-uav-stores-from-a-native-container) · [Bounded gfx1030 DS lane routing](docs/experiments.md#bounded-gfx1030-ds-lane-routing) · [Private gfx1030 LDS access and updates, including 64-bit min/max and xor](docs/experiments.md#private-gfx1030-lds-word-access) | `ctest --preset dev --no-tests=error -R '^compute_store_aot_'` | | gfx1013 compute DPP16 | Lower `v_or_b32_dpp` with `quad_perm`, and `v_or_b32_dpp`/`v_add_nc_u32_dpp` with `row_shr:1`–`15` with or without `bound_ctrl`, under full row/bank masks; compare source-built fixtures with logical-thread references. Scope and limits: [quad_perm](docs/experiments.md#gfx1013-compute-dpp16-quad-permutation), [row_shr](docs/experiments.md#gfx1013-compute-dpp16-row-shift-right) | `ctest --preset dev --no-tests=error -R '^compute_store_aot_dpp_' -V` | diff --git a/docs/experiments.md b/docs/experiments.md index 6c30d84af6..75d3674ea3 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -2,6 +2,28 @@ New notes go in `docs/experiments/.md` (see [the folder guide](experiments/README.md)); this file keeps the older notes. +## First native graphics draw through the stand-in + +Set `X2W_NATIVE_SHADERS` to the desktop DXC directory and `X2W_SHADER_CACHE` to a writable cache. +The stand-in reads the published graphics request, links the pair, and uses the compiler's persistent +frontend and bytecode caches. The runtime consumes the same supported binding manifest as the offline +compiler. The source-built triangle fixture uses one RGBA8 target and checks all 32 pixels in each +of two processes. A third process supplies an unsupported pixel stage and checks the untouched clear. + +```powershell +cmake --build --preset dev --target startup_stream_consumer d3d12_xs_shim compile_dxil +ctest --preset dev --no-tests=error -V -R '^startup_native_graphics_draw_(hardware|warp)$' +``` + +## Implicit derivatives in direct compute + +[Group shapes, lane mapping and readback fixtures](experiments/native-compute-implicit-derivatives.md) + +## Slot 67 wave size in direct compute + +State block A bit 20 of dword 4 selects the guest wave size. +[Capture inference and hardware fixture](experiments/native-slot67-wave-size.md) + ## Plain binary16 arithmetic in direct compute VOP2 and VOP3 add, sub, subrev and mul use binary32 arithmetic and an integer nearest-even conversion back @@ -70,6 +92,8 @@ local second operand. A sparse EXEC mask distinguishes fetching an inactive source, supplying zero and retaining the destination. The test checks both workgroups and the surrounding buffer guards. +Wave32 direct compute lowers `s_or_saveexec_b32`. As with `s_mov_b32 exec_lo`, EXEC keeps bits past the group; a lane runs only if its own bit is set. + The pixel fixture opens EXEC to all lanes, seeds a guest register with scalar lane writes and reads back lanes in each half of a guest wave64. The compiler can track those words independently of the desktop rasterizer's choice of @@ -296,6 +320,16 @@ The source is a same-device desktop resource with no title shadow, a unique alia or an already covered range. Later overlapping copies invalidate earlier coverage. The recording discards this proof at Close, so another recording needs its own writer. +`X2W_TRANSLATED_TITLE_INPUT_SNAPSHOT=1` lets a translated compute Dispatch read an input that lies in a placed buffer which does +not alias title memory. That buffer's desktop copy is a committed default buffer that holds zeros, so the bytes the title wrote +exist only in title memory. The input resolves in this order: a validated GPU copy of the current recording (the proof above, +which needs `X2W_TRANSLATED_INDIRECT_COPY_RANGES=1`), else a snapshot of the range (at most 16 MiB) taken from title memory +into the snapshot pool when the Dispatch is recorded, else the refusal `an input is in a placed buffer that does not alias title +memory`. A guest write after the recording is not seen, and data a GPU pass wrote into such a buffer is not either. The first +use per pipeline key logs `x2w-draw compute input (...) comes from a GPU copy this list made|a snapshot of title +memory`, and the render totals line counts both paths. Off by default. To turn it on for a run, set `$env:X2W_TRANSLATED_TITLE_INPUT_SNAPSHOT = "1"` in the PowerShell session before +starting `tools/startup/run.ps1`, which passes the session's environment on to the run. The snapshots have a pool of their own (128 MiB, chunks of 16 MiB, built like the shared upload ring: a chunk is reused once no recording can submit its bytes and every queue that used it has finished), so draw and texture uploads cannot starve them and a long run is not stopped by a full pool; a reservation it cannot serve logs `x2w-draw snapshot pool reservation refused: no unused capacity`. `startup_compute_dispatch_input` covers it with the `dispatch-input-snapshot` case and, for the recycling, `dispatch-input-snapshot-long` (48 frames of an 8 MiB snapshot, 384 MiB in all). + The source-built fixture reproduces a 68-byte request shape with source offset `0xbfffa0`. Its compute writer fills the source with contrasting colours. The consumer reads red from the second DWORD in the destination while the title-side green sentinel stays @@ -631,7 +665,7 @@ python3 -B tests/startup_buffer_address_check.py controls ## Startup translator: SMEM combined register and immediate offsets -Direct C++ wave32 compute accepts numeric `vcc_lo` and `vcc_hi` as SMEM offsets and scalar load destinations through s107. +Direct C++ compute, in wave32 and wave64, accepts numeric `vcc_lo` and `vcc_hi` as SMEM offsets and scalar load destinations through s107. In RDNA 2 SMEM instructions (`s_load_dword*` and `s_buffer_load_dword*`), a scalar register `SOFFSET` (`s0`..`s105` or `m0`) and a non-zero 21-bit signed immediate `OFFSET` (`w1[20:0]`) can be active at the same time: [`tools/disasm_rdna2.py`](../tools/disasm_rdna2.py) prints the register in `ops[2]` and the signed immediate in `mods` (`offset:0x...` or `offset:-0x...`). Previously, `Stage.op_s_buffer_load_dword()` and `Stage.op_s_load_dwordx4()` in [`tools/startup/gfx2hlsl.py`](../tools/startup/gfx2hlsl.py) ignored `mods`, silently dropping `offset:0x...` on register-addressed buffer and dynamic sampler-heap loads, accepting unknown modifiers, reading negative 21-bit signed encodings (`0x100000`..`0x1fffff`) as `+1`..`2` MiB, and overwriting a runtime SGPR `soffset` mid-load when a multi-dword `s_buffer_load_dwordx*` wrote into that register first. @@ -9017,7 +9051,7 @@ The exact conversions `v_cvt_f64_i32` and `v_cvt_f64_u32` lower as the binary64 `v_cvt_f32_f64` lowers for a binary64 VGPR pair `v[d:d+1]` only in a mode-independent slice (the slice the maintainer approved in #1606), with the semantics of LLVM 15 `VOP1Instructions.td` (VOP1, 64-bit source, 32-bit result), not checked against the ISA document here and not measured on a console. It reuses the origin tracking above: the pair must be the pair of a `v_cvt_f64_f32` of a statically known source, carried as the record `("static", low, high)` on both words (a copy of both words, in either order, keeps it; one overwritten word, words of different pairs, the high word read as the low word and a join of different records end it). The narrowing is computed in Python at translation time and emitted as a constant; no HLSL `double` is used. It is accepted only when the binary64 value is exactly a normal binary32 or a signed zero, that is, when narrowing it with `struct` and widening the result again with `cvt_f64_f32_words` returns the same two words bit for bit; the result is then the binary32 word that went in (`0x80000000` for `-0.0`, `0x00800000` and `0x7f7fffff` and their negatives, `0x3f800000` and `0x3f800001`). Because the conversion is exact it does not read a rounding mode or a denorm mode, and this slice does not decide which MODE field governs binary64: the choice between MODE[1:0]/[5:4] and MODE[3:2]/[7:6] stays open until independent native evidence distinguishes the two fields, and the accepted forms do not depend on it. The existing refusal of binary16 and binary64 forms under a non-default rounding mode is unchanged. Refused with a diagnostic: both infinities (accepted by the widening, "is not finite" here), a NaN and a subnormal (refused already by the widening, so no pair exists), a pair of unknown provenance (raw constants, SGPR or VGPR words, interpolants), a pair of integer origin (`v_cvt_f64_i32` or `v_cvt_f64_u32`, also where the integer is exact in binary32), a pair of which either word was overwritten after the conversion, an unequal join of the two words, any use inside a masked region, the `_e64` spelling and every modifier (clamp, omod, `-v[..]`, `|v[..]|`). LLVM 15 prints the unmodified form as `v_cvt_f32_f64_e32` (`141f1a7e` for `v13, v[20:21]`) whether or not the source spelled the suffix, and both spellings are lowered; DPP and SDWA do not assemble for this opcode in LLVM 15. No path of this translator leads a pair that needs rounding to the origin check: the only static records come from the exact widening, an integer pair is refused by origin, and every join keeps a record only if all paths carry the same one. The rounding refusal is therefore checked on two levels: the translator helper `cvt_f32_f64_exact_bits` rejects binary64 values that do not fit binary32 exactly (`1 + 2^-24`, `2^24 + 1`, `0.1`, values beyond or just above the largest binary32, values below the smallest normal) with "requires rounding", and the translator refuses the pair of `v_cvt_f64_i32` of `0x01000001` (2^24 + 1, which is exact in binary64 and would need rounding in binary32) as an integer-origin pair. The test (`tests/pixel_aot_check.py draw-cvt-f32-f64`) draws each of `+0`, `-0`, `0x00800000`, `0x80800000`, `0x7f7fffff`, `0xff7fffff`, `1.0`, `-1.0`, `0x3f800001` and `0xbf800001` as its own program (the pair of a literal, the narrowing of the pair and of a copy of it) through the `R32G32B32A32_UINT` readback target as `result ^ M`, against the original binary32 bit pattern as an independent reference. The wrong references must report `pixel_mismatch`: the sign lost (including that of `-0`), a flipped mantissa bit, the high or the low pair word in place of the result, one result slot off by one bit and a sentinel replaced by a pair word; the test requires that each kind is drawn. The refusal controls run in the pure-Python checks and the LLVM 15 round trip covers the spellings. One lowering check that asserted `v_cvt_f32_f64` of a pair of `1.0` was refused (`check_cvt_f64_f32_lowering`) now asserts the supported case instead and moved here; the integer-pair `v_cvt_f32_f64` refusal in the `v_cvt_f64_i32` check stays, and so does the refusal under a non-default rounding mode. Runtime values, integer-origin pairs, rounding narrowings, infinities, NaN, subnormals, modifiers and the binary64 arithmetic remain unsupported and are left for separately measured behavior. The tests are `pixel_aot_cvt_f32_f64_hardware` and `pixel_aot_cvt_f32_f64_warp`, with their own coverage record. They passed on the NVIDIA GeForce RTX 3080 (driver 32.0.16.2124) and on WARP (Microsoft Basic Render Driver 10.0.26100.9818), Windows 11 (build 26200). They show that the translated shader computes the stated operation on desktop GPUs, not that the console does. Run `ctest --preset dev --no-tests=error -R '^pixel_aot_cvt_f32_f64_' -V`. -`v_cvt_pk_u16_u32` and `v_cvt_pk_i16_i32` lower through the integer table as two-source operations that exist in the VOP3 encoding only on gfx10. The AMD RDNA 2 ISA reference (30 November 2020, VOP3 opcodes 874 and 875) gives the layout: `D.u16_lo = u32_to_u16(S0.u32); D.u16_hi = u32_to_u16(S1.u32)` and `D.i16_lo = i32_to_i16(S0.i32); D.i16_hi = i32_to_i16(S1.i32)`, so src0 is the low half and src1 the high half. Neither that document nor the RDNA 3.5 reference defines `u32_to_u16` or `i32_to_i16`, and LLVM 15 gives the instructions no meaning beyond their types (`VOP_V2I16_I32_I32`, selected only from the `llvm.amdgcn.cvt.pk.u16` and `llvm.amdgcn.cvt.pk.i16` intrinsics). The saturation used here is the one Mesa states: its NIR operations `pack_uint_2x16` and `pack_sint_2x16` are documented as "Convert two unsigned integers into a packed unsigned short (clamp is applied)" and the signed counterpart, their constant folding clamps each source to 0..65535 or to -32768..32767, and the ACO backend selects exactly these two instructions for them with no clamp of its own. That is a statement by the open source driver for this hardware family, not by the ISA document, and it is not measured on the console. The lowering is `min(S0, 65535) | (min(S1, 65535) << 16)` on unsigned words, and the signed form clamps each source as a signed word and keeps its low 16 bits. The e32 spelling (gfx10 has none), ` clamp`, a float modifier, a wrong operand count, an unwritten register, a literal wider than 32 bits and the SDWA spelling are refused. The float packs `v_cvt_pknorm_i16_f32`, `v_cvt_pknorm_u16_f32`, `v_cvt_pknorm_i16_f16`, `v_cvt_pknorm_u16_f16` and `v_cvt_pk_u8_f32` stay unsupported: no public source found here states their rounding, their bounds or their NaN result. Two programs export through the `R32G32B32A32_UINT` readback target and are compared bit for bit, with A and B taken from constants s44 and s45. A normal binary32 word is outside both 16-bit ranges, so each program first derives `B >> 16`, `B >> 12` and the arithmetic `B >> 16` in the shader and packs those with A, a literal 0x12345 and an inline -16. A word whose high half saturates is not a normal binary32, so those channels are exported through an xor with 0x40000000. Each program runs on two rows. In the first row A is positive and B negative: the unsigned pack must turn the literal, `B >> 12`, A and the negative arithmetic shift into 0xffff, and the signed pack must turn A and the zero-extended `B >> 16` into 0x7fff and keep the inline -16 as 0xfff0. In the second row A is negative, which the signed pack turns into 0x8000, and `B >> 12` is 0xfff, which both packs keep. Every input and every expected result is a normal binary32 or zero, which the test asserts. Fifteen wrong references, each replacing one channel on the first row, must report `pixel_mismatch`: truncation instead of saturation in either half, swapped halves, the signed bound on the unsigned pack and the reverse, a negative source clamped to zero or kept, a value above 32767 kept, and the inline constant read as unsigned. That is 19 draws from 2 compiles and 2 renderer launches. They run as their own tests, `pixel_aot_pack_int16_hardware` and `pixel_aot_pack_int16_warp` (`tests/pixel_aot_check.py draw-pack-int16`), with their own coverage record, and the LLVM 15 round trip covers both programs; LLVM 15 prints the two instructions without an encoding suffix. They passed on the NVIDIA GeForce RTX 3060 (driver 32.0.15.9636) and on WARP (Microsoft Basic Render Driver 10.0.19041.5794), Windows 10 (10.0.19045.6466). They show that the translated shader computes the stated operations on desktop GPUs, not that the console does. +`v_cvt_pk_u16_u32` and `v_cvt_pk_i16_i32` lower through the integer table as two-source operations that exist in the VOP3 encoding only on gfx10. The AMD RDNA 2 ISA reference (30 November 2020, VOP3 opcodes 874 and 875) gives the layout: `D.u16_lo = u32_to_u16(S0.u32); D.u16_hi = u32_to_u16(S1.u32)` and `D.i16_lo = i32_to_i16(S0.i32); D.i16_hi = i32_to_i16(S1.i32)`, so src0 is the low half and src1 the high half. Neither that document nor the RDNA 3.5 reference defines `u32_to_u16` or `i32_to_i16`, and LLVM 15 gives the instructions no meaning beyond their types (`VOP_V2I16_I32_I32`, selected only from the `llvm.amdgcn.cvt.pk.u16` and `llvm.amdgcn.cvt.pk.i16` intrinsics). The saturation used here is the one Mesa states: its NIR operations `pack_uint_2x16` and `pack_sint_2x16` are documented as "Convert two unsigned integers into a packed unsigned short (clamp is applied)" and the signed counterpart, their constant folding clamps each source to 0..65535 or to -32768..32767, and the ACO backend selects exactly these two instructions for them with no clamp of its own. That is a statement by the open source driver for this hardware family, not by the ISA document, and it is not measured on the console. The lowering is `min(S0, 65535) | (min(S1, 65535) << 16)` on unsigned words, and the signed form clamps each source as a signed word and keeps its low 16 bits. The e32 spelling (gfx10 has none), ` clamp`, a float modifier, a wrong operand count, an unwritten register, a literal wider than 32 bits and the SDWA spelling are refused. The float packs `v_cvt_pknorm_i16_f32`, `v_cvt_pknorm_u16_f32`, `v_cvt_pknorm_i16_f16`, `v_cvt_pknorm_u16_f16` and `v_cvt_pk_u8_f32` stay unsupported in `pixel_aot`; for direct DXIL, `v_cvt_pknorm_i16_f32` and `v_cvt_pknorm_u16_f32` lower under an unmeasured single-rounding RNE model (`clamp(x) * 32767` / `* 65535`, `NaN -> 0`; see [native-cvt-pknorm-f32.md](experiments/native-cvt-pknorm-f32.md)), while RDNA 2 silicon probing remains open. Two programs export through the `R32G32B32A32_UINT` readback target and are compared bit for bit, with A and B taken from constants s44 and s45. A normal binary32 word is outside both 16-bit ranges, so each program first derives `B >> 16`, `B >> 12` and the arithmetic `B >> 16` in the shader and packs those with A, a literal 0x12345 and an inline -16. A word whose high half saturates is not a normal binary32, so those channels are exported through an xor with 0x40000000. Each program runs on two rows. In the first row A is positive and B negative: the unsigned pack must turn the literal, `B >> 12`, A and the negative arithmetic shift into 0xffff, and the signed pack must turn A and the zero-extended `B >> 16` into 0x7fff and keep the inline -16 as 0xfff0. In the second row A is negative, which the signed pack turns into 0x8000, and `B >> 12` is 0xfff, which both packs keep. Every input and every expected result is a normal binary32 or zero, which the test asserts. Fifteen wrong references, each replacing one channel on the first row, must report `pixel_mismatch`: truncation instead of saturation in either half, swapped halves, the signed bound on the unsigned pack and the reverse, a negative source clamped to zero or kept, a value above 32767 kept, and the inline constant read as unsigned. That is 19 draws from 2 compiles and 2 renderer launches. They run as their own tests, `pixel_aot_pack_int16_hardware` and `pixel_aot_pack_int16_warp` (`tests/pixel_aot_check.py draw-pack-int16`), with their own coverage record, and the LLVM 15 round trip covers both programs; LLVM 15 prints the two instructions without an encoding suffix. They passed on the NVIDIA GeForce RTX 3060 (driver 32.0.15.9636) and on WARP (Microsoft Basic Render Driver 10.0.19041.5794), Windows 10 (10.0.19045.6466). They show that the translated shader computes the stated operations on desktop GPUs, not that the console does. `v_pack_b32_f16` lowers through the integer table as a two-source operation that exists in the VOP3OpSel encoding only on gfx10. The AMD RDNA ISA reference gives `D[15:0].f16 = S0.f16; D[31:16].f16 = S1.f16`: each source's low binary16 encoding is copied into its half of the destination with no conversion, rounding or NaN handling, so the lowering is `(S0 & 0xffff) | ((S1 & 0xffff) << 16)` on the raw words. LLVM 15 prints the gfx1013 form without a suffix, and `tools/ffx_dispatch_aot.py` already lowers the same mnemonic with this expression. The e32 spelling (gfx10 has none), ` clamp`, ` op_sel` (only the default `[0,0]` shape is modelled), a float modifier, a wrong operand count, an unwritten or out-of-range register, a literal wider than 32 bits and the SDWA spelling are refused; sources go through the existing integer operand rules, so an outstanding sample is refused as well. An inline float constant is the exception: `llvm-mc` types these sources as binary16 and prints the constant as a decimal float, and its binary16 encoding is used (`1.0` is `0x3c00`), as for the packed `VOP3P` forms (not measured on the console); any other decimal float is refused. One program exports through the `R32G32B32A32_UINT` readback target and is compared bit for bit, with A and B taken from constants s44 and s45, copied to v18 and v19 and carrying the distinct noisy upper halves 0xa5a5 and 0x5a5a. Three packs read A and B as register/register, SGPR/register and register/SGPR; a fourth writes back to v18, its own src0, so a lowering that writes the destination before reading src0 differs. Five rows vary the low halves: an asymmetric pair for the controls, a quiet NaN half, a signed-zero half, a NaN half in src1 (which lands in bits 31:16 but still yields a normal binary32 word) and two zero halves, which must give zero. Every input and every expected word is a normal binary32 or zero, which the test asserts; the NaN and signed-zero half patterns are copied as bits with no quieting or conversion and stay in the low halves of the packed words. Five wrong references, each replacing one channel of the first row, must report `pixel_mismatch`: swapped halves, src0's high half leaked into the low half, src0 taken from bits 31:16, src1 placed in the low half, and src0 read after the in-place destination write. The tests run as `pixel_aot_pack_b32_hardware` and `pixel_aot_pack_b32_warp` (`tests/pixel_aot_check.py draw-pack-b32`), with their own coverage record, and the LLVM 15 round trip covers the program. They passed on the NVIDIA GeForce RTX 3060 (driver 32.0.15.9636) and on WARP (Microsoft Basic Render Driver 10.0.19041.5794), Windows 10 (10.0.19045.6466). They show that the translated shader computes the stated operation on desktop GPUs, not that the console does. The inline-constant variant also goes through the LLVM 15 round trip. Its integer render target compares 0xc0003c00 with the old binary32-low-half result 0xc0000000, which must report a mismatch on each desktop backend. @@ -9224,19 +9258,19 @@ On Windows build 26200, the pre-executable inventory covered 16 package DLLs and ## Heap and process memory -`src/era_heap.cpp` is a desktop handler. It splits the attribute word using SlimEra's Xbox One ERA layout: object type in bits 0–13, page size in bits 14–15, allocator ID in bits 16–23, log2 alignment in bits 24–28, memory type in bits 29–32 and reserved bits 33–63. Object type and allocator ID are carried as tags and do not affect placement, as in SlimEra's default heap. +`src/era_heap.cpp` now decodes the GDK 261000 XALLOC_ATTRIBUTES layout: object type in bits 0–13, page size in bits 14–15, allocator ID in bits 16–23, log2 alignment in bits 24–28, memory type in bits 29–32, an address-below-4-GiB bit at 33 and 30 reserved bits at 34–63. Object type and allocator ID are carried as tags and do not affect placement. The earlier desktop experiments compared the handler with SlimEra's Xbox One ERA layout, which treated bits 33–63 as reserved; those observations stay scoped to that historical layout. The desktop handling is: - **Heap (memory type 0):** served from the CRT heap at the requested alignment, minimum 16 bytes, and zero-filled. The page size does not affect these requests. SlimEra passes every heap request to `_aligned_malloc`, which commits the alignment padding as heap memory, so a 257-byte request with exponent 31 would commit more than 2 GiB. The desktop handler instead gives alignments above the page size their own reservation and commits only the pages that hold the payload; `VirtualAlloc` returns them zeroed. - **Graphics (memory types 1–6):** committed as a separate `VirtualAlloc` region. `release_with_attributes` frees it with `VirtualFree`. The region starts on the desktop allocation granularity, which covers 4 KB and 64 KB pages. This is ordinary CPU-visible memory; no GPU mapping or caching behavior is modeled. -- **Rejected:** physical memory types 7–9, undefined types 10–15, the undefined page-size value 3, reserved bits, and graphics requests whose page size or alignment exceeds the allocation granularity all return a null pointer. +- **Rejected:** physical memory types 7–9, undefined types 10–15, the undefined page-size value 3, the 30 reserved bits (34–63), the address-below-4-GiB bit (33), and graphics requests whose page size or alignment exceeds the allocation granularity all return a null pointer. A below-4-GiB request stays refused until the allocator can provide such an address. `release` frees heap allocations. It frees a page-backed block with `VirtualFree` when `VirtualQuery` reports it as the base of its own allocation; a CRT block never is, because `_aligned_malloc` stores its base pointer below the returned address. `release_with_attributes` takes the allocation's attribute word, as `XMemFree` callers do. -What is measured is the desktop behavior above. Under the ERA layout, the two recorded words give alignments that match their callers' own arithmetic: 32 bytes for Bink and 256 bytes for AMD. The following remain unconfirmed on Scarlett: +What is measured is the desktop behavior above. Under the 261000 layout, the two recorded words give alignments that match their callers' own arithmetic: 32 bytes for Bink and 256 bytes for AMD. The recorded words leave bit 33 and the 30 reserved bits at zero, so they do not by themselves distinguish the 261000 layout from the older SlimEra interpretation. The following remain unconfirmed on Scarlett: -- that Scarlett uses the ERA layout at all; +- whether the title's attribute words use the 261000 contract beyond the zero bits observed here; - what allocator ID `0xe5` means; - the GPU visibility and caching of memory type 5 and the other graphics types; - the console's error conventions. @@ -9246,14 +9280,14 @@ What is measured is the desktop behavior above. Under the ERA layout, the two re | CTest case | Inputs and checks | |---|---| | `era_heap_allocation` | Allocate 257 bytes using six alignment exponents. Check alignment of at least 16 bytes and the requested alignment, initial zeroing, writes and release. Debug builds also compare CRT heap snapshots. | -| `era_heap_failure` | Each reserved bit, combined with a heap alignment and with the AMD graphics word, returns a null pointer. So do memory types 7–15, page-size value 3, graphics memory with 4 MB pages or a 128 KiB alignment, zero size and excessive size. | +| `era_heap_failure` | Each of the 30 reserved bits (34–63) and the address-below-4-GiB bit at 33, combined with a heap alignment and with the AMD graphics word, return a null pointer. So do memory types 7–15, page-size value 3, graphics memory with 2 MB pages or a 128 KiB alignment, zero size and excessive size. | | `era_heap_reuse` | For three alignment exponents and three sizes, fill a block with `0xa5` and release it. Then hold up to 32 new blocks of the same shape until the released address returns. Every new block must read as zero. The output reports `recycled_address`, the number of the nine cases in which the CRT returned the dirty address. glibc returned all nine in a Linux build with a `posix_memalign` stand-in. Windows 11 build 26200.9974 with MSVC 14.44.35207 returned the dirty address in all nine cases in both Debug and Release. Low-fragmentation heap randomization can lower it. | -| `era_heap_observed_words` | Desktop handling of the two recorded words. Under the ERA layout, the Bink word `0x05e50000` splits into heap memory, 4 KB pages, allocator field `0xe5` and 32-byte alignment. The AMD word `0xa8004000` splits into memory type 5, 64 KB pages, allocator field 0 and 256-byte alignment. Bink-style 97- and 193-byte blocks are 32-byte aligned and zeroed, and each wrapper recovers its base. AMD-rounded requests of 256 to 65,792 bytes start a committed read-write region on a 64 KiB boundary and are zeroed and writable. After release, `VirtualQuery` reports the region as free. Nonzero object-type and allocator tags leave heap placement unchanged. | +| `era_heap_observed_words` | Desktop handling of the two recorded words. The words were measured under the older SlimEra interpretation and leave bit 33 and the 30 reserved bits at 0, so they do not distinguish the two layouts. The Bink word `0x05e50000` splits into heap memory, 4 KB pages, allocator field `0xe5` and 32-byte alignment. The AMD word `0xa8004000` splits into memory type 5, 64 KB pages, allocator field 0 and 256-byte alignment. Bink-style 97- and 193-byte blocks are 32-byte aligned and zeroed, and each wrapper recovers its base. AMD-rounded requests of 256 to 65,792 bytes start a committed read-write region on a 64 KiB boundary and are zeroed and writable. After release, `VirtualQuery` reports the region as free. Nonzero object-type and allocator tags leave heap placement unchanged. | | `era_heap_large_alignment` | Exponents 13, 16, 17, 20 and 31 with sizes of 1 and 257 bytes, one page, one page plus one byte and three pages minus one byte. Each block must be aligned and zeroed. `VirtualQuery` must report the block as the base of its own private read/write allocation, with a committed region equal to the payload rounded up to whole pages. After release the address must be `MEM_FREE`. The output reports the 25 cases, the committed bytes and the summed alignments. With the previous `_aligned_malloc` path, the first case already fails because the block lies inside a CRT heap allocation. | -| `era_heap_graphics_types` | Each graphics memory type 1–6 with 4 KB and 64 KB pages and alignment exponents 0, 4, 8 and 16, at 1 byte and one allocation granularity plus one byte. Exponent 16 is the 64 KiB granularity boundary itself. Each block must start on the granularity, be zeroed and writable, and be reported by `VirtualQuery` as the base of its own committed private read/write allocation. After release with the same attributes the address must be `MEM_FREE`. For every type, 4 MB pages, exponent 17 and page-size value 3 return a null pointer. The output reports 96 served and 18 rejected cases at granularity 65,536 on Windows 11 build 26200. Changing the granularity comparison from `>` to `>=` fails exponent 16 with 4 KB pages, and narrowing the graphics range to types 1–5 fails type 6; `era_heap_observed_words` catches only the first change. These are desktop policy checks; the console semantics of the six graphics types remain unconfirmed. | +| `era_heap_graphics_types` | Each graphics memory type 1–6 with 4 KB and 64 KB pages and alignment exponents 0, 4, 8 and 16, at 1 byte and one allocation granularity plus one byte. Exponent 16 is the 64 KiB granularity boundary itself. Each block must start on the granularity, be zeroed and writable, and be reported by `VirtualQuery` as the base of its own committed private read/write allocation. After release with the same attributes the address must be `MEM_FREE`. For every type, 2 MB pages, exponent 17 and page-size value 3 return a null pointer. The output reports 96 served and 18 rejected cases at granularity 65,536 on Windows 11 build 26200. Changing the granularity comparison from `>` to `>=` fails exponent 16 with 4 KB pages, and narrowing the graphics range to types 1–5 fails type 6; `era_heap_observed_words` catches only the first change. These are desktop policy checks; the console semantics of the six graphics types remain unconfirmed. | | `era_heap_concurrency` | Four threads run 100 rounds each. They hold simultaneous allocations, write distinct values, compare every byte and release the memory. | | `era_heap_caller_layout` | Owned desktop storage covers all 32 base residues at eight payload sizes. Each Bink-style wrapper recovers its original base after a payload write and preserves the surrounding guard bytes. Ten AMD-style requests check 256-byte size rounding and the unused tail. These cases establish caller-side arithmetic. The Bink-style storage uses the recorded Bink word. | -| `era_heap_decode_fields` | `decode` reads each field of the layout at its widest value with the other fields zero: object type `0x3fff`, page size 3, allocator `0xff`, alignment `0x1f`, memory type `0xf` and 31 reserved bits. It also reads an all-ones word and one word with a distinct value in every field. The recorded words leave the object type and the reserved bits at 0. So without this scenario, a 12-bit object-type mask and a reserved field taken from bit 32 both decoded them unchanged and passed every other scenario. `era_heap_decode_fields_control` expects a 13-bit object type and must fail. | +| `era_heap_decode_fields` | `decode` reads each field of the layout at its widest value with the other fields zero: object type `0x3fff`, page size 3, allocator `0xff`, alignment `0x1f`, memory type `0xf`, the address-below-4-GiB bit at 33 and the 30 reserved bits at 34–63. It also reads an all-ones word and one word with a distinct value in every field. The recorded words leave the object type, the address bit and the reserved bits at 0. Without this scenario, a 12-bit object-type mask would decode the widest object type unchanged; the all-ones word and the address-bit case also distinguish the 30-bit reserved field from one that includes bit 33. `era_heap_decode_fields_control` expects a 13-bit object type and must fail. A word with bit 33 set is still refused by the allocator because it does not provide an address below 4 GiB. | `desktop_memory_query` supplies Windows observations for `XMemVirtualQuery` and `XMemGetWorkingSetStatistics`. The test reserves memory, commits and writes 1,024 pages, checks the read-only/writable boundary, then decommits. It verifies residency of a locked page and records working set, peak working set and private commit at three points. Values vary between runs. Scarlett structure layout, units and accounting scope remain unconfirmed. [Windows working sets](https://learn.microsoft.com/en-us/windows/win32/memory/working-set) @@ -12048,11 +12082,25 @@ On success the caller exits with `0x8AC`, also with `CPU_CRC_TEST_LIVE_WORKER=1` ```powershell ctest --preset dev --no-tests=error -R '^cpu_native_acphal_hal$' -V ctest --preset release --no-tests=error -R '^cpu_native_acphal_hal$' -V +``` ### ApuFree in the AcpHal stand-in The desktop `AcpHal.dll` stand-in (not the fixture provider above) now returns `ApuAlloc` blocks on `ApuFree` through a first-fit free list with coalescing, so repeated allocate and free cycles no longer exhaust the heap. It is a stand-in contract only: the console's error codes, alignment limits and zero-size behaviour are not public, and the codes chosen are listed in [startup-runtime.md](startup-runtime.md#apu-heap-stand-in). The source-built check is `ctest --preset dev --no-tests=error -R '^startup_acphal_apu_free$' -V`. +### XMA context activity in the AcpHal stand-in + +With `X2W_AUDIO_PERMISSIVE=1` and `X2W_AUDIO_ACTIVITY=1`, the desktop `AcpHal.dll` and `xapu.dll` stand-ins count what a caller does with the audio processor. This is a first measurement for [issue #1145](https://github.com/R0Y00/Xbox2Windows/issues/1145), before any decoding. AcpHal compares the XMA context array it allocated with a copy inside the calls that count, at most once per 10 ms, and counts contexts filled (all zero to nonzero), changed and cleared, plus HAL slot2 submits by type. xapu counts `XApuEnqueueCommand` calls by command class with no cap. Neither DLL starts a thread; each logs at most a line per second, from a counted call at least a second after its previous line, when a count moved (later counts wait for a later call); the experimental exports `x2w_acphal_xma_activity` and `x2w_xapu_command_counts` return the totals. Line formats and limits are in [startup-runtime.md](startup-runtime.md#activity-counter). + +`startup_acphal_xma_activity` runs one source-built caller script in three child processes, plus an unload case. With the counter on, the caller fills 5 contexts, changes 3 and clears 2, submits 4 HAL commands of types 1, 1, 3 and 12, and enqueues 6 XApu commands of classes 1, 2 and 0x20, one null command, one command on an unknown handle and one type 3 command whose 8-byte header ends where free address space begins, sent with `X2W_XAPU_TYPED_COMPLETIONS=1` (every case sets `X2W_PROBE_PRECHECK=1`, so the free tail is refused without a fault). An `X2W_WITH_OPUS` build refuses that one with `E_POINTER` as too short to decode, and it must still count as class 3; only that build tells a counted refusal from an uncounted one. The exports and the summed log lines must give exactly those counts, and an array freed and allocated again must not be counted. The zero-write control writes only the 64 bytes after the last context and sends nothing: every count must be 0 and no line may be logged. With the counter off, the exports report nothing and no line is logged. Every result, output, last error and the final context bytes must match between the on and off runs. The unload case allocates the contexts a second time without `ApuFree`, then frees both DLLs, checks that they are unmapped, waits 1.5 s and must exit 0. + +```powershell +cmake --build --preset release --target startup_acphal_xma_activity +ctest --preset release --no-tests=error -R '^startup_acphal_xma_activity$' -V +``` + +The 64-byte context stride and the command class (the first `UINT32` of a command) are stand-in conventions, not console contracts. The counter identifies no field inside a context, such as an enable flag, decodes nothing, and does not establish which counted event starts playback. + ### XApu command-queue caller and recorder A source-built caller ([`xapu_queue_caller.asm`](../tests/cpu/xapu_queue_caller.asm)) imports the five `xapu.dll` command-queue functions by name (`XApuConnect`, `XApuEnqueueCommand`, `XApuGetResultCount`, `XApuDequeueResult`, `XApuDisconnect`), plus `finish_exe` from `cpu_exe_io.dll`, and starts through [`exe_startup.asm`](../tests/cpu/exe_startup.asm). A test-only recording provider ([`xapu_queue_provider.cpp`](../tests/cpu/xapu_queue_provider.cpp)) serves the five names. This is not a production `xapu.dll`, and this change adds no binding. @@ -12827,6 +12875,20 @@ mapping, archive stream discovery and rendered pixels remain separate work. The existing prefix probe keeps its diagnostic behavior. No local archive or texture payload is used by these checks. +### Standalone BCPack block reconstruction + +The startup DirectStorage stand-in reconstructs BC1–BC7 packed blocks without an +installed GDK or external table file. BC1's fitted endpoint window and quadrant +masks are removed; BC2 and BC6H now decode rather than report blank success. +See [the standalone implementation notes](experiments/bcpack-standalone.md) for +source provenance, synthetic golden checks, atomic storage tests, and optional +oracle reproduction commands. + +```powershell +cmake --build --preset dev --target bcpack_formats_check startup_stub_consumer startup_stub_xcrdapi +ctest --preset dev --no-tests=error -R '^(bcpack_all_formats|startup_bcpack_storage)' -V +``` + ### BCPack lane decoder paths The startup storage stand-in decodes BCPack streams with `decode_lanes` in @@ -15190,7 +15252,7 @@ For binary32 arithmetic and compare sources, the translator reads the inline int ## Startup translator: explicit-LOD image sampling -`tools/startup/gfx2hlsl.py` now lowers the gfx1013 `image_sample_l` form of a 2D or 3D texture sample to `tex.SampleLevel(smp, uv, level)`. The level is the last address register: the third for a contiguous 2D address, the fourth for 3D, and the last element of an NSA list. `tests/startup_image_sample_l_check.py` translates source-built fixtures (the words are checked against `llvm-mc`) and requires the level to come from that register; an address list `[v0, v1, v3]` must use `v3`, not the third consecutive register. Replacing the level with 0, replacing the call with implicit `Sample`, or reading the third register in every form each make the check fail. Offset (`_o`), compare (`_c_l`), gather, 1D, array, cube and multisample dimensions, an empty `dmask`, and the `unorm`, `r128`, `tfe`, `lwe`, `a16` and `d16` modifiers or any set reserved MIMG bit are refused with an `Unsupported` message; only the cache-policy bits `glc`, `slc` and `dlc` are accepted because they do not change the sampled value. The disassembler previously read `lwe` from reserved bit 14 of word 0; `llvm-mc` (19, gfx1013) encodes it in bit 17, and the check now has one `llvm-mc`-built fixture per refused modifier plus patched reserved-bit fixtures. Not measured: no draw samples a mip level on WARP or hardware through this lowering, so the level selection is checked on the generated HLSL text only. [HLSL SampleLevel](https://learn.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-to-samplelevel) +`tools/startup/gfx2hlsl.py` now lowers the gfx1013 `image_sample_l` form of a 2D or 3D texture sample to `tex.SampleLevel(smp, uv, level)`. The level is the last address register: the third for a contiguous 2D address, the fourth for 3D, and the last element of an NSA list. `tests/startup_image_sample_l_check.py` translates source-built fixtures (the words are checked against `llvm-mc`) and requires the level to come from that register; an address list `[v0, v1, v3]` must use `v3`, not the third consecutive register. Replacing the level with 0, replacing the call with implicit `Sample`, or reading the third register in every form each make the check fail. Offset (`_o`), compare (`_c_l`), gather, 1D, array and multisample dimensions (a cube lowers since #2943, see [startup-image-cube](experiments/startup-image-cube.md)), an empty `dmask`, and the `unorm`, `r128`, `tfe`, `lwe`, `a16` and `d16` modifiers or any set reserved MIMG bit are refused with an `Unsupported` message; only the cache-policy bits `glc`, `slc` and `dlc` are accepted because they do not change the sampled value. The disassembler previously read `lwe` from reserved bit 14 of word 0; `llvm-mc` (19, gfx1013) encodes it in bit 17, and the check now has one `llvm-mc`-built fixture per refused modifier plus patched reserved-bit fixtures. Not measured: no draw samples a mip level on WARP or hardware through this lowering, so the level selection is checked on the generated HLSL text only. [HLSL SampleLevel](https://learn.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-to-samplelevel) ## Startup translator: binary32 arithmetic @@ -15211,7 +15273,7 @@ Not covered: inexact products. The translation writes both `v_fma_f32`, which ro ## Startup translator: biased image sampling -`tools/startup/gfx2hlsl.py` lowers the gfx1013 `image_sample_b` form in a pixel stage to `tex.SampleBias(smp, uv, bias)` for 2D, 2D-array and 3D textures. The RDNA 2 ISA (section 8.2.4, Table 43: "_B LOD BIAS, 1: lod bias, Add this BIAS to the LOD computed"; section 8.2.5: the address is `{ offset } { bias } { z-compare } { derivative } { body }` and the bias is "One Dword float") puts the bias in the FIRST address register, so `v[0:2]` is bias, u, v and the NSA list `[v3, v1, v2]` takes the bias from `v3`. LLVM 15 agrees: `IntrinsicsAMDGPU.td` gives `AMDGPUSample_b` the extra argument `llvm_anyfloat_ty "bias"` and `MIMGInstructions.td` the gfx10 opcode `0x25`. `llvm-mc` (LLVM 15, gfx1013) assembles the contiguous 2D, 2D-array, 3D and NSA forms, and the check compares every fixture against it. HLSL `SampleBias` adds the bias to the implicit mip level and documents the range -16.0 to 15.99; the ISA text states no hardware clamp, so a bias outside that range is an unverified difference. The form needs a pixel stage whose EXEC is still the entry mask with wave-uniform control flow (implicit derivatives); a uniform (scc) join or later loop does not drop that proof, while divergent EXEC or a vcc/exec-conditioned branch before the sample does (there the plain sample is lowered to level 0, which would drop the bias). It is also refused outside a pixel stage, and so are `image_sample_b_cl`, `image_sample_c_b*`, `image_sample_b_o`, `image_gather4_b`, 1D, cube and multisample dimensions, an empty `dmask`, the `unorm`, `r128`, `tfe`, `lwe`, `a16` and `d16` modifiers, set reserved MIMG bits, and a constant sampler whose LOD bias fields (word 2 bits 19:0, s6.8 and s2.4, scaled by `T#.perf_modulation` in the ISA) are not zero or whose mip filter is 0 (mipmapping disabled), or whose MIN_LOD is above its MAX_LOD. The guest clamp is kept: MIN_LOD (word 1 bits 11:0) and MAX_LOD (bits 23:12) are unsigned 4.8 fixed point (Mesa 24.0.0 `src/amd/registers/gfx10-rsrc.json`, `SQ_IMG_SAMP_WORD1`; `radeonsi/si_state.c` lines 5169-5170 encode them with `S_FIXED(x, 8)`), and the sampler of an `image_sample_b` is written as an `smpl` manifest line that the runtime decodes to `MinLOD = MIN_LOD / 256` and `MaxLOD = MAX_LOD / 256` (`src/startup_stubs/translated_sampler_bindings.h`); `smp` and `smpc` lines still leave MinLOD at 0 and MaxLOD unbounded (the next section moves `image_sample`, `_l` and `_lz` with a constant sampler to `smpl`). A sampler read from the sampler heap, including the default-sampler shortcut for a run-time heap load, or built from a register is refused for `image_sample_b`, because its LOD limits and bias cannot be shown to be irrelevant. +`tools/startup/gfx2hlsl.py` lowers the gfx1013 `image_sample_b` form in a pixel stage to `tex.SampleBias(smp, uv, bias)` for 2D, 2D-array and 3D textures. The RDNA 2 ISA (section 8.2.4, Table 43: "_B LOD BIAS, 1: lod bias, Add this BIAS to the LOD computed"; section 8.2.5: the address is `{ offset } { bias } { z-compare } { derivative } { body }` and the bias is "One Dword float") puts the bias in the FIRST address register, so `v[0:2]` is bias, u, v and the NSA list `[v3, v1, v2]` takes the bias from `v3`. LLVM 15 agrees: `IntrinsicsAMDGPU.td` gives `AMDGPUSample_b` the extra argument `llvm_anyfloat_ty "bias"` and `MIMGInstructions.td` the gfx10 opcode `0x25`. `llvm-mc` (LLVM 15, gfx1013) assembles the contiguous 2D, 2D-array, 3D and NSA forms, and the check compares every fixture against it. HLSL `SampleBias` adds the bias to the implicit mip level and documents the range -16.0 to 15.99; the ISA text states no hardware clamp, so a bias outside that range is an unverified difference. The form needs a pixel stage whose EXEC is still the entry mask with wave-uniform control flow (implicit derivatives); a uniform (scc) join or later loop does not drop that proof, while divergent EXEC or a vcc/exec-conditioned branch before the sample does (there the plain sample is lowered to level 0, which would drop the bias). It is also refused outside a pixel stage, and so are `image_sample_b_cl`, `image_sample_c_b*`, `image_sample_b_o`, `image_gather4_b`, 1D and multisample dimensions (a cube lowers since #2943, see [startup-image-cube](experiments/startup-image-cube.md)), an empty `dmask`, the `unorm`, `r128`, `tfe`, `lwe`, `a16` and `d16` modifiers, set reserved MIMG bits, and a constant sampler whose LOD bias fields (word 2 bits 19:0, s6.8 and s2.4, scaled by `T#.perf_modulation` in the ISA) are not zero or whose mip filter is 0 (mipmapping disabled), or whose MIN_LOD is above its MAX_LOD. The guest clamp is kept: MIN_LOD (word 1 bits 11:0) and MAX_LOD (bits 23:12) are unsigned 4.8 fixed point (Mesa 24.0.0 `src/amd/registers/gfx10-rsrc.json`, `SQ_IMG_SAMP_WORD1`; `radeonsi/si_state.c` lines 5169-5170 encode them with `S_FIXED(x, 8)`), and the sampler of an `image_sample_b` is written as an `smpl` manifest line that the runtime decodes to `MinLOD = MIN_LOD / 256` and `MaxLOD = MAX_LOD / 256` (`src/startup_stubs/translated_sampler_bindings.h`); `smp` and `smpc` lines still leave MinLOD at 0 and MaxLOD unbounded (the next section moves `image_sample`, `_l` and `_lz` with a constant sampler to `smpl`). A sampler read from the sampler heap, including the default-sampler shortcut for a run-time heap load, or built from a register is refused for `image_sample_b`, because its LOD limits and bias cannot be shown to be irrelevant. `tests/startup_image_sample_b_check.py` translates source-built fixtures and, with `draw`, draws the 2D array through `offscreen_check --startup-image-2d-array-mips` (4x4, two slices, three mips whose cells all differ, point sampler with mip filter point; MAX_LOD 2 for the bias cases). Constant coordinates have no derivatives, so the draw rewrites only the `u` initialiser of the translated HLSL to `0.75 + 0.5 * (SV_Position.x - 0.5)`, an implicit LOD of 1 at the sampled pixel; the `SampleBias` call is untouched. Bias -1, 0 and +1 read mip 0, 1 and 2 on WARP with DXC and FXC. A uniform (scc) join before the sample is accepted and drawn (same mip as the plain bias -1 case); divergent EXEC or a vcc/exec-conditioned branch before the sample is refused. Negative controls: the same program with `image_sample` reads mip 1 for every case, and edited calls (bias replaced by 0, bias negated, bias and `u` exchanged, `Sample` for `SampleBias`) each read another cell. The sampler limits are discriminated by cases whose limit lies below a mip that exists: MAX_LOD 1 with bias +1 stays on mip 1 (unclamped: mip 2), MAX_LOD 0 with bias +1 stays on mip 0, MIN_LOD 2 with bias -1 reads mip 2 (unclamped: mip 0) and MIN_LOD 1 = MAX_LOD 1 with bias -1 reads mip 1; the MAX_LOD 2 bias cases cannot tell, because mip 2 is the last level. Each limit case is drawn again with an `smp` line instead of `smpl` (limits not carried) and must read the unclamped mip. `startup_sampler_comparison` checks the decoded MinLOD and MaxLOD. Replacing the bias by 0 or exchanging the bias with the first coordinate in `gfx2hlsl.py`, dropping the MaxLOD assignment in the runtime decoder, accepting a heap sampler, and the previous `gfx2hlsl.py`, each make a check fail. Not covered: a physical-adapter run (`startup_image_sample_b_hardware` is registered), a plain 2D or 3D draw (those forms are checked on the generated HLSL), fractional bias with a linear mip filter, bias outside -16 to 15.99, a fractional MIN_LOD or MAX_LOD (only whole mips are drawn; the 4.8 decode is checked without a device), a non-zero descriptor LOD bias (refused, not carried) and the limits of the other sample forms (see the next section). @@ -15987,6 +16049,8 @@ guarded block and take the latch until the counter reaches 4. The translator rep Run `python -B tests/startup_gfx2hlsl_compute_check.py` for the host controls and add `binary llvm-mc-15` to reassemble the fixture. +`subset_after` tracks pre-branch mask-subset facts (`sM <= EXEC`) across instructions and joins into `Stage.execz_refusals`, so saving `s22 <= EXEC` (or `s_mov_b32 exec_lo, s22` before `s_cbranch_execz`) proves `s_mov_b32 exec_lo, s22` inside the skipped block (#2645 T1). On the no-exit variant (`O-loop-subset`) DXC `cs_6_0` produces `[9, 1, 2, 9, 9, 9, 9, 9]` while `LOOP_BREAK_WORDS` still refuses `+0x30` with `loop exit crosses a backward s_cbranch_scc0`, and pre-branch narrowing (`s_and_saveexec_b32`, `v_cmpx_gt_u32`), mask overwrites, and unproven joins remain refused as `exec write`. + ### Scalar run before the EXEC restore at a compute exit target (#2645 T3) The 104-byte gfx1013 fixture `EXIT_RUN_*` in `tests/startup_gfx2hlsl_compute_check.py` narrows @@ -16633,6 +16697,22 @@ which then reads another mip's texels. A chain whose layout runs past the size t reports is held as before: RGBA8 33 by 9 by 18 with six mips takes 135,168 bytes in the layout against 65,536 reported. +Block-compressed volumes are read too. addrlib turns the texel sides of a BC volume into 4x4 blocks +before it lays the volume out, and does not divide the depth: the volume is the volume of its blocks, +each one depth layer deep, with every mip size counted in blocks from there. `startup_gfx10_volume` +checks that BC1 64 by 64 by 16 with five mips and BC7 48 by 20 by 9 with three mips take, element for +element, the addresses of the 8-byte and 16-byte volumes of their blocks, and adds the distinct bytes +and round trips of seven BC volumes (BC1 to BC7, with and without a chain, sides that are not powers +of two). `startup_gfx10_volume_bc_control` sizes a BC volume by its texel sides instead and must fail; +it fails four checks. `startup_gfx10_volume_addrlib`, passing each BC format to addrlib as itself, now +compares every mip count of four chains for each of BC1 to BC7 too: 501 volumes and 13,205,290 +element addresses with 0 mismatches. + +`startup_address_console_{warp,hardware}` draws three BC1 volume mips: 48 by 40 by 12 with one mip, +and mips 1 and 3 (the second in the tail) of 64 by 64 by 8 with five mips. Each block is one solid +colour, and all 65,536 pixels of each must match. A local mutation that sizes the thick layout by +texels instead of blocks, run once, fails it on the first BC volume. + ```powershell ctest --preset release --no-tests=error --output-on-failure -R '^startup_gfx10_volume' ctest --preset release --no-tests=error --output-on-failure -j 1 -R '^startup_address_console_(hardware|warp)$' diff --git a/docs/experiments/bc4-format-number.md b/docs/experiments/bc4-format-number.md new file mode 100644 index 0000000000..46b3fe7456 --- /dev/null +++ b/docs/experiments/bc4-format-number.md @@ -0,0 +1,18 @@ +# BC4 typed format number + +`texture_blocks.format_info("BC4_UNORM")` returns DXGI format 80, the public +`DXGI_FORMAT_BC4_UNORM` value. The old table returned 79, which names the typeless +parent. Both formats have eight-byte blocks, so the byte-row and volume tests +alone did not detect this metadata error. + +The two existing format-table checks now expect 80 independently of the module's +table. With the old implementation each check failed with `79 != 80`; after the +correction all 17 tests pass on Windows with Python 3.14: + +```powershell +python -B tests/texture_blocks_check.py +python -B tests/texture_bc_volume_check.py +``` + +This checks the format metadata and synthetic block rows. It does not establish +any change in rendered console textures or in the BCPack decoder. diff --git a/docs/experiments/bcpack-standalone.md b/docs/experiments/bcpack-standalone.md new file mode 100644 index 0000000000..b2a5245758 --- /dev/null +++ b/docs/experiments/bcpack-standalone.md @@ -0,0 +1,133 @@ +# Standalone BCPack BC1–BC7 reconstruction + +`src/startup_stubs/bcpack_decoder.h` reconstructs the seven BC block formats from +complete BCPack streams. BC2 uses fifteen lanes and BC6H uses sixteen. BC1 now +uses independent endpoint/index references and the full 255-entry initial +dictionary. The old fitted BC1 endpoint window and quadrant masks are removed. +BC6H supports all fourteen modes and changes of precision/subset count across +historical references. The output is packed BC blocks, not RGBA pixels. + +The DirectStorage stand-in decodes into a temporary buffer and publishes it +only after the complete request succeeds. BC2/BC6H no longer return successful +blank textures. An invalid format or malformed stream fails. Existing file, +memory, outer RFC 1950 zlib and physical-page destination handling applies. +Historical `bcpack-blank` counters remain in the log schema for compatibility; +this decoder does not produce blank-success requests. + +## Sources and constants + +The entropy decoder and existing BC3/4/5/7 code retain their bcpack-rs and +silicon-rans notices in [THIRD_PARTY_NOTICES.md](../../tools/_bcpack_rans/THIRD_PARTY_NOTICES.md). +The new BC1/2/6H routines are original C++ reconstruction code. Research used +the installed GDK interface, local implementation inspection, and comparisons +with public bcpack-rs and VIctory implementations. This is not a claim of a +strict clean-room process. No GPL implementation or binary table blob was +copied into these files. + +`bcpack_tables_extra.inl` contains fixed format dictionaries and rank mappings. +They were reconstructed by sending chosen, entirely synthetic lane streams to +the developer oracle's `BCPackDecompress` API and reading the resulting standard +BC fields. There is no sample fitting, approximation, per-asset lookup or +run-time learning. The recovery tool does not read the DLL's data section. + +The BC6H wire descriptors adapt Microsoft's MIT-licensed +[DirectXTex BC6HBC7.cpp](https://github.com/microsoft/DirectXTex/blob/a8e5dbf42909aeeb9fcf9c2ae399ae3c06737379/DirectXTex/BC6HBC7.cpp), +revision `a8e5dbf42909aeeb9fcf9c2ae399ae3c06737379`, SHA-256 +`187434fab12351df0f875ae09390981034e8479159a6f4aaaf0904f007182b8a`. +The emitted BCPack blocks use ascending high base-endpoint bits in modes 13/14; +the descriptor generator applies that ordering explicitly. Preserve the +DirectXTex MIT notice when redistributing those descriptors. + +Normal builds, tests and runtime DLLs require neither GDK nor BCPack.dll. +The optional oracle target and script below are development tools only. They +require a separately installed developer oracle, which is not redistributed. + +## Reproduce the public checks + +From an x64 Visual Studio developer PowerShell: + +```powershell +. ./tools/dev.ps1 +cmake --preset dev +cmake --build --preset dev --target bcpack_formats_check startup_stub_consumer startup_stub_xcrdapi +ctest --preset dev --no-tests=error -R '^(bcpack_all_formats|startup_bcpack_storage)' -V +python -B tests/bcpack_tables_check.py +``` + +The golden test generates 12,330 synthetic streams from source. It checks all +255 initial references plus the zero predictor, independently selected endpoint +and index references, all fourteen BC6H modes and all 32 partitions. Random +symbol streams cover all seven formats and block counts 2, 17, 255, 256, 257 +and 1024, including mode changes and history-ring wrap. BC7 selects all 285 +mapped controls. Every supported entropy path must reproduce the same bytes. + +Each group is checked against a fixed FNV-1a-64 hash of the independent oracle's +complete output. The expected hashes are not generated by the decoder under +test. A one-byte mutation must fail the golden control. Truncation, wrong output +alignment, nonzero trailing data and invalid formats must fail with zero bytes +reported. An undefined BC6H mode must fail too. The storage test checks full BC2 +and BC6H destination bytes against fixed synthetic oracle outputs across +memory/file, raw/zlib and linear/cross-page requests. Missing page grants, unsupported formats and a bad final BC6H mode after +three valid blocks must preserve the destination; a following valid request +must still succeed. + +The unchanged `synthetic_11` BC1 input in `startup_stub_consumer.cpp` had 491 +wrong bytes in its former 512-byte expected output. Its first eight expected +bytes were `85 31 64 d5 af be ff bf`; the oracle returns +`8d 73 0a 07 ea b8 fa be`. The fixture now checks the oracle's complete 512 +bytes, keeping the original input, size and malformed-input controls. + +## Optional oracle reproduction + +For the original experiment the installed BCPack library reported version +`1.2603.3.0`. Its binaries, private headers and title payloads are not part of +this repository. Supply paths to your own local installation and to the public +DirectXTex source pinned above: + +```powershell +cmake --build --preset dev --target bcpack_oracle_bridge +./out/build/dev/bcpack_formats_check.exe --oracle 'C:/path/to/BCPack.dll' +python -B tools/bcpack_recover_constants.py ` + --sdk 'C:/path/to/BCPack.dll' ` + --bridge out/build/dev/bcpack_oracle_bridge.dll ` + --bc6-reference out/DirectXTex/DirectXTex/BC6HBC7.cpp ` + --output out/bcpack_tables_extra.inl ` + --storage-goldens out/bcpack_storage_goldens.h +python -c "from pathlib import Path; assert Path('src/startup_stubs/bcpack_tables_extra.inl').read_text() == Path('out/bcpack_tables_extra.inl').read_text()" +python -c "from pathlib import Path; assert Path('tests/bcpack_storage_goldens.h').read_text() == Path('out/bcpack_storage_goldens.h').read_text()" +``` + +The recovery script queries each dictionary entry separately. BC1/2 ranks are +recovered with zero predictors. BC6H's base endpoint uses the sixteen-bit mode; +the other endpoints use modes exposing their complete stored precision. The +generated table file reproduced LF-normalized SHA-256 +`181f279bbc84a3e93aa4d44bf6f7c6e522493b3a92538b7209e4b22721a3a12e`. +An oracle change may change output; investigate differences before replacing +goldens or format constants. + +## Local comparison and limits + +A separate read-only comparison covered 105,845 chunks from 45 local archive +pools, totaling 16,356,958,208 decoded bytes. Every chunk was compared byte for +byte with the installed oracle on the AVX2 path. A distributed sample of 882 +chunks also used the reference and scalar paths. There were no byte mismatches +or guard violations. No archive bytes or extracted textures are included here. + +| Format | Local archive chunks | +|---|---:| +| BC1 | 100,020 | +| BC2 | 0 | +| BC3 | 35 | +| BC4 | 77 | +| BC5 | 325 | +| BC6H | 268 | +| BC7 | 5,120 | + +An additional 312 oracle-compressed synthetic cases across BC1–BC7 matched +byte for byte on all three paths, including random, repeated and historical +blocks and individual BC6H/BC7 modes. Inputs rejected by the oracle compressor +were excluded from that successful-compression count, not called passes. +The public synthetic golden suite supplies BC2 coverage independently of the +local archives. These are packed-block decoding checks, not GPU image or +full-application startup measurements. Finite test coverage cannot establish +correctness for every possible stream. diff --git a/docs/experiments/compute-output-buffer-reasons.md b/docs/experiments/compute-output-buffer-reasons.md new file mode 100644 index 0000000000..0ccfcba270 --- /dev/null +++ b/docs/experiments/compute-output-buffer-reasons.md @@ -0,0 +1,98 @@ +# Named reasons for a compute output buffer range + +A translated compute program's buffer output is bound only when a placed buffer aliases the title memory it +names, so the GPU writes reach the title. The single refusal `an output is not an aliased placed buffer range +with unordered access` is split into the condition that failed, in the same log and census lines, checked in +this order: + +1. `an output buffer descriptor is a view token` +2. `an output buffer descriptor has zero records` +3. `an output buffer range is over 16 MiB or not whole dwords` +4. `an output range crosses the end of a placed buffer` (also a range that two placements claim) +5. `an output is in title memory outside any placed buffer` +6. `an output is in a placed buffer that does not alias title memory` (a copied placement) +7. `an output buffer's resource was not created in the common state` (also an aliased resource with no recorded + information, which no fixture reaches) +8. `an output buffer range is not 16-byte aligned in its resource` +9. `an output buffer has no unordered access` + +Only the reason changes: what was bound is still bound and what was refused is still refused. Output view tokens +are lowered separately in #2961 (open), which binds a buffer UAV token before these checks; with it, reason 1 is +not reached. The census keeps one reason per key, the first one that key was refused with, and counts all of the +key's untranslated dispatches under it. A start-up run with this build therefore gives first-refusal buckets, not +a count per condition: a later dispatch of the same key can fail on another condition, and the per-call refusal +lines are capped. + +`tests/startup_compute_dispatch_output_check.py` dispatches case A of `startup_gfx2hlsl_compute_check.py` through +the stand-in's list on WARP and on a physical adapter (exit 77 without one). The unchanged recording matches all +320 words. Each of the nine conditions is then produced by one change to the output descriptor or its buffer, +and each dispatch refuses with its own reason in the log and the census and leaves every output word at its +sentinel. The common-state case also checks that its buffer was aliased. `dispatch-swapped` in +`startup_compute_dispatch_check.py` now expects reason 9. + +```powershell +ctest --preset dev --no-tests=error -R "^startup_compute_dispatch(_output)?_(warp|hardware)$" -V +``` + +Both tests pass on WARP (10.0.26100.9818) and on an RTX 4090 (driver 32.0.16.1088), Windows 11 build 26300, +debug layer on. With only the split reverted, the unchanged dispatch still matches and all nine cases are still +refused, each with the old reason, so all nine expectations fail: the set of refused cases is the same. + +Local observation, one 300 s start-up run with this build (`79edac55`; translator at `ad306425`, whose `gfx2hlsl.py` +is unchanged since `2e12dd8e`), counts only. A run of the parent build with the same settings refused 25 keys and +505,473 of 5,490,863 compute dispatches with the old reason as their first refusal. With the split, the same 25 +keys fall in these first-refusal buckets: + +| First refusal of the key | Keys | Untranslated dispatches of those keys | +|---|---|---| +| 1, view token | 23 | 141,224 | +| 2, zero records | 2 | 2,015 | +| 3 to 9 | 0 (no key had one of these first refusals) | 0 | + +The run made 1,490,517 compute dispatches in all, so the share in these buckets is about the same (9.2% and 9.6%). +In the first refused dispatch of each of the 23 keys, the token named a view created through device slot 19, the +form #2961 binds. In that of each of the two zero-record keys, the descriptor was all zero. No key had a copied +placement, the initial state, alignment or the unordered-access flag as its first refusal; later dispatches were +not recorded per condition. + +The same run with #2961 merged locally (`51aef000`, not pushed; reason 1 dropped, #2961's token branch first): + +| The 23 token keys | Keys | Dispatches | +|---|---|---| +| every dispatch translated, no refusal | 12 | 32,043 | +| first refusal: `an entry value reads the descriptor of an output named by a view token` | 10 | 9,372 untranslated | +| first refusal: `an output buffer view range is empty, unaligned or outside its resource` | 1 | 190,397 untranslated | + +No key had `an output view token is not a buffer UAV of a desktop resource` as its first refusal: every dispatch of +the 12 translated keys, and the first refused dispatch of each of the other 11, named a buffer unordered access view +of a desktop resource. That run made 2,453,727 compute dispatches, so dispatch counts compare only within one run. +Whether the 12 translated keys write the right values was not checked. + +## Published half-width buffer stores + +A native slot 67 request with a `half_buffer_uav` now publishes +`uav bufhalf table bytes `. The +stride selects a typed buffer view of `R16_FLOAT`, `R16G16_FLOAT` or +`R16G16B16A16_FLOAT` for 2, 4 or 8 bytes respectively. The runtime +requires the matching gfx10 buffer format, identity selects over the +written components and structured out-of-bounds mode. It binds the +descriptor's record count and element-aligned offset into an aliased +placed buffer after checking typed-store support. The typed range can +end on a halfword. Raw outputs keep their dword and 16-byte alignment +checks. Buffer UAV tokens are tracked in #2961. + +The source-built check compiles a D16 store for each width with +`compile_dxil --requests`, then runs the published translation through +slot 14. Each dispatch attempts more stores than the view has records. +The reference checks 13 records at a nonzero view offset, plus the +full prefix and suffix. Invalid formats, selectors, strides, swizzle, +out-of-bounds mode and ranges are refused before a dispatch is recorded. + +```powershell +ctest --preset release --no-tests=error -R '^startup_compute_half_buffer_uav_' -V +``` + +The descriptor checks follow the buffer resource format in the +[AMD RDNA 2 ISA](https://docs.amd.com/v/u/en-US/rdna2-shader-instruction-set-architecture). +The matching desktop view uses `FirstElement` and `NumElements` from +the [D3D12 buffer UAV contract](https://learn.microsoft.com/en-us/windows/win32/api/d3d12/ns-d3d12-d3d12_buffer_uav). diff --git a/docs/experiments/direct-compute-exact-width-image-store.md b/docs/experiments/direct-compute-exact-width-image-store.md new file mode 100644 index 0000000000..dd95da6d9a --- /dev/null +++ b/docs/experiments/direct-compute-exact-width-image-store.md @@ -0,0 +1,26 @@ +# Exact-width image stores in direct compute + +The direct gfx1013 compute translator lowers non-D16 `image_store` with +`dmask:0x1`, `0x3`, or `0x7` on 2D, 2D array, and 3D images. It consumes +one, two, or three consecutive VDATA VGPRs and declares a typed float, +float2, or float3 UAV. The DXIL store uses the full typed-store mask. +The narrower resource type determines which components reach the texture. +The `unorm` instruction modifier continues to leave the integer texel +coordinates unchanged. + +Manifest version 2 describes these outputs with +`uav float table channels <1|2|3>`. +The in-process path gets the same width from the translated binding. +The runtime requires the view and resource formats to have the specified +component count and checks adapter support for typed stores on the resource +format. It creates the UAV with that format and retains the bound subresource +range. This makes each accepted store a whole texel write. Sparse masks still +receive the translator's descriptor modifier refusal. + +The readback fixture dispatches two X groups of 4x2x1 threads into a 32x8 mip. +It explicitly sets EXEC to `0x55`, writing columns 0, 2, 4, and 6 in rows +0 and 1. The array and volume cases use relative slice 1 of a view that +starts at physical slice 1. Every other texel retains its sentinel. +The format cases use R32_FLOAT, R32G32_FLOAT, and R11G11B10_FLOAT. The +RGBA8 control leaves the complete image untouched and checks the runtime +channel-count refusal. diff --git a/docs/experiments/f16-alu-direct.md b/docs/experiments/f16-alu-direct.md index bfe744c700..0e12b27e1f 100644 --- a/docs/experiments/f16-alu-direct.md +++ b/docs/experiments/f16-alu-direct.md @@ -1,17 +1,29 @@ -# Binary16 add, sub, subrev and mul in the direct compute path +# Binary16 arithmetic in the direct compute path -Lowers VOP2 and VOP3 `v_add_f16`, `v_sub_f16`, `v_subrev_f16` and `v_mul_f16` in the direct C++ compute frontend ([`src/gfx1013_direct_compute.inl`](../../src/gfx1013_direct_compute.inl)). The handler returns without lowering when the stage is graphics, so a graphics program keeps the generic direct-lowering refusal. A graphics container was not dumped on this host. +The direct C++ compute frontend supports VOP2 and VOP3 `v_add_f16`, `v_sub_f16`, `v_subrev_f16` and `v_mul_f16`, plus VOP1 and VOP3 `v_rcp_f16`, `v_sqrt_f16`, `v_rsq_f16` and `v_exp_f16`. All eight operations support SDWA. Graphics programs keep the generic direct-lowering refusal. ## Semantics -- Each source is its low 16 bits. An inline float uses the binary16 rounding of that f32 value. An integer inline or a literal uses its low 16 bits. +- Each source is its low 16 bits by default. An inline float uses the binary16 rounding of that f32 value. An integer inline or a literal uses its low 16 bits. SDWA accepts WORD_0, WORD_1 or DWORD (low half). - abs clears bit 15 of the half, then neg toggles it. - The operation is an f32 add, sub or mul. An f32 value has a 24-bit significand, which covers a correctly rounded binary16 add, sub or mul. -- The result is rounded with the same integer round-to-nearest-even conversion `v_cvt_f16_f32` uses. The low 16 bits are written and the high half is zero. +- Reciprocal computes `1.0 / x` in f32. The other unary operations use DXIL Sqrt (24), Rsqrt (25) and Exp (21, base two). +- Reciprocal exchanges signed zeros and signed infinities. Square root preserves signed zero and produces NaN for negative nonzero inputs. Exp returns 1 for either signed zero, infinity at and above 16, positive zero at and below -25, and the canonical quiet NaN for NaN inputs. The emitter handles the exact underflow tie at -25 explicitly. +- The result is rounded with the same integer round-to-nearest-even conversion `v_cvt_f16_f32` uses. The low 16 bits are written and the high half is preserved. SDWA writes the selected half and pads or preserves the other half. +- Rsq maps +0 to +infinity, -0 to -infinity and +infinity to +0. It returns a quiet NaN for NaN and negative nonzero inputs, including -infinity. +- The emitter selects these results using the binary16 source bits after abs and neg. D3D Rsqrt does not guarantee -infinity for -0, so the rsq zero result takes its sign directly from the source. - `v_subrev_f16` subtracts the first source from the second. - DPP16 VOP2 permutes the full src0 VGPR word before selecting its low half and honors FI, BOUND_CTRL, and row and bank write masks. -The bit-exact reference is `half_op` in [`tests/f16_packed_model.py`](../../tests/f16_packed_model.py). NaN results match by class. The check is [`tests/native_f16_alu_check.py`](../../tests/native_f16_alu_check.py). +## Exp and rsq accuracy + +The Shader Model 4 assembly references specify a maximum relative error of 2^-21 for both host operations. For a normal f32 result this is less than eight f32 ULP. Every binary16 exp rounding midpoint is in the normal f32 range. [Microsoft Learn exp](https://learn.microsoft.com/en-us/windows/win32/direct3dhlsl/exp--sm4---asm-) and [Microsoft Learn rsq](https://learn.microsoft.com/en-us/windows/win32/direct3dhlsl/rsq--sm4---asm-). + +Exp targets RDNA 2's 0.5 ULP by selecting the correctly rounded half for the 70 non-tie inputs within that window and resolving the exact tie separately. The [90-digit generator](../../tests/f16_exp_midpoints.py) enumerates the binary16 inputs and the model check compares its entries with the C++ array. The IR and GPU comparisons require exact exp bits, including the canonical NaN, the tie at -25, and all 70 inputs in both VOP1 and VOP3. The table covers 0x11c4, 0x11c5 and 0x11c6. Modifier cases exercise correction after source selection and modification. + +For positive finite rsq results, a relative error of 2^-21 contributes at most 2^-10 of a binary16 ULP. Integer RNE adds at most 0.5 ULP in the rounding interval, for a total of at most 0.5 + 2^-10 < 0.51 ULP. The [reference model](../../tests/f16_packed_model.py) compares squared rational endpoints against the exact input to locate the result. It accepts either adjoining half only when the exact result is closer than eight f32 ULP to their midpoint. Both plain encodings and SDWA cover 0x3bfe, which exercises the alternate result. + +The [plain-form fixture](../../tests/native_f16_alu_check.py) covers signed zeros and infinities, quiet and signaling NaNs, negative finite values, subnormals, 1, powers of two and general values. Its IR interpreter models Rsqrt returning +infinity for -0 to exercise the sign fix. The [SDWA fixture](../../tests/native_sdwa_f16_check.py) exercises source selection and modifiers, destination padding and preservation, and negation of +0 before rsq. ## Refused forms @@ -27,7 +39,7 @@ Each of these is a named diagnostic: `s_round_mode` and `s_denorm_mode` that leave the f16 fields at that contract, and that leave the f32 fields unchanged, are accepted. A write that changes an f32 rounding or denormal field keeps the previous control-instruction refusal. A guest branch together with a MODE write makes the contract unprovable and is refused with the rounding diagnostic. -For the plain scalar-half forms, fma, fmac, fmamk, fmaak, min, max, ldexp, the min3/max3/med3 forms, div_fixup and VOP1 stay on the generic direct-lowering diagnostic. The fixture checks `v_fmac_f16` and `v_min_f16`. VOP3P arithmetic has a [separate experiment](native-packed-f16.md). +For the plain scalar-half forms, fma, fmac, fmamk, fmaak, min, max, ldexp, the min3/max3/med3 forms, div_fixup and the VOP1 ops other than rcp, sqrt, exp and rsq stay on the generic direct-lowering diagnostic. The fixture checks `v_fmac_f16`, `v_min_f16` and `v_log_f16`. The host Log absolute error allowance of 2^-21 near an input of 1 can exceed 0.51 ULP of the small binary16 result, so log needs a tighter bound or a bounded correction before lowering. [Microsoft Learn log](https://learn.microsoft.com/en-us/windows/win32/direct3dhlsl/log--sm4---asm-). ## Linux @@ -38,8 +50,8 @@ python3 -B tests/native_f16_alu_check.py model python3 -B tests/native_f16_alu_check.py ir ``` -- `model` printed `native_f16_alu model: 82 results match f32-then-round; a sub/subrev swap and a non-zero upper half are rejected`. -- `ir` printed `native_f16_alu IR: 82 results match the model; 20 refusals carry the named diagnostic`. The module calls `legacyF16ToF32`, `fadd`, `fsub` and `fmul`, and the integer round contains the constant `939524096`. +- Before unary coverage was added, `model` checked 82 results, including controls for a sub/subrev swap and a zeroed upper half. +- Before unary coverage was added, `ir` reported 82 results and 20 refusals. The module used `legacyF16ToF32`, `fadd`, `fsub` and `fmul`, and the integer round contained the constant `939524096`. `native_f16_alu_hardware` was not run. It is registered with skip code 77, the same code `native_store_replay` returns when the device cannot run a wave32 shader. WARP is expected to take that skip. diff --git a/docs/experiments/gdk-knowledge-report.md b/docs/experiments/gdk-knowledge-report.md new file mode 100644 index 0000000000..bac9dbfca5 --- /dev/null +++ b/docs/experiments/gdk-knowledge-report.md @@ -0,0 +1,97 @@ +# GDK knowledge coverage report + +tools/gdk_knowledge_report.py merges the JSON knowledge base under +D:\gdk-oracle\knowledge and writes a deterministic coverage JSON and a +Markdown summary. It uses only the Python standard library and never reads a +GDK header, library or binary. + +## Inputs + +All categories are optional. A missing directory or file is reported as a +missing category; it is not treated as an empty fact. + +| Path | Accepted shape | +| --- | --- | +| layouts/*.json | classes array with name, size and members, or a class array | +| abi/*.json | facts array with kind, name and value, or a fact array | +| exports/*.json | exports array with name, ordinal and rva, module groups, or a module map | +| exports-all.json | the same export rows, including the file and kind group form | +| behavior/*.json | observations array, or an observation array | +| platform/*.json | define, include and library lists, plus a flag list or object | +| shaders/corpus.json or shaders/corpus/corpus.json | cases array, or a case array | + +Every fact is normalised to module, kind, name, value, source, confidence and +targets. Layout classes become layout facts whose value contains size and +members; ABI sizeof and struct facts keep their kind. Exports carry their +ordinal and RVA. Runtime observations become behavior facts, and the +observation kind is retained inside the value when it adds information. +Modules are merged case-insensitively. + +A top-level source of msvc-layout, compiled-probe, dumpbin, runtime-oracle or +header-msvc-layout is treated as a method: it becomes the confidence and the +source stays the JSON path. Other source values are kept as given. + +## Conflicts + +The report emits stable value, size, ordinal, enum and type-size entries. Each +entry names the module, the fact, every distinct value with its source, and a +short message. + +- size compares all size-bearing facts for one module and type, including a + layout member list and an ABI sizeof fact. +- type-size compares a named type across modules and reports incompatible + sizes. Equal sizes in two modules are not a conflict. +- ordinal compares only ordinals that both sources report. A missing ordinal + in an import library and a present ordinal in a DLL do not conflict. +- enum compares enum facts with the same module and name. +- value covers every other fact with the same module, kind and name. +- RVAs are retained in the facts but are not compared: Debug, Release, import + library and DLL records legitimately differ. + +MSVC anonymous tags include the text unnamed-tag in their display name. Several +distinct anonymous unions or structs can share that text, so they are kept as +facts and counted as types but excluded from conflict comparisons. Their +display name is not a stable identity. + +## Coverage and shims + +The summary counts modules, unique classes/types, unique exports and raw export +rows, runtime facts, shader facts, platforms and all normalised facts. A +per-module table gives the same breakdown. + +--defs accepts the repository src directory, one .def file, or a JSON mapping. +The parser reads LIBRARY, export names, aliases and ordinals, and ignores +internal x2w_* and X2W* helpers. A shim export is associated when its name or +alias target matches any fact name. The JSON and Markdown list the remaining +exports. + +## Commands + + python -B tests/gdk_knowledge_report_check.py + + $root = 'D:\gdk-oracle\knowledge' + python -B tools/gdk_knowledge_report.py report --root $root --json "$root\coverage.json" --markdown "$root\report.md" --defs src + +Add --check to exit 1 on conflicts. Add --require layouts,abi,exports to also +exit 1 when one of those categories is missing. Bad JSON, a bad schema, an +unknown required category or an unusable path exits 2. Without --check, +missing categories and conflicts are only reported. + +## Measured run + +On 2026-11-28, the local knowledge root produced 45 modules, 11,145 unique +types, 4,714 unique exports from 8,035 export rows, 12 runtime facts, 6 shader +cases and 3 platform profiles. The 9,677 ABI sizeof facts matched their layout +sizes, so the conflict list was empty. All six categories were present. All 70 +GDK-facing shim exports matched an export fact. + +## Limits + +A header fact does not prove the runtime. A layout or ABI row only reports what +the header or compile probe describes. A runtime observation is separate +evidence. An export name proves neither a signature nor a working +implementation, and a shim name match does not prove matching behaviour. The +report intentionally does not compare RVAs, infer missing categories, or turn +an absent oracle into a pass. The generated coverage JSON can be large because +it retains every normalised fact; keep it outside the repository with the rest +of the knowledge base. diff --git a/docs/experiments/gdk-layouts.md b/docs/experiments/gdk-layouts.md new file mode 100644 index 0000000000..2aebd968d2 --- /dev/null +++ b/docs/experiments/gdk-layouts.md @@ -0,0 +1,40 @@ +# GDK layouts and ABI probes + +tools/gdk_layouts.py parses the output of MSVC /d1reportAllClassLayout and keeps +only class names, sizes, member names, offsets and flags. tools/gdk_abi_probe.py +turns that JSON into a C++ probe: static_asserts for a compile check, or a +program that prints sizeof and offsetof values for a GRDK/GXDK comparison. + +The logs are produced outside the repository. No GDK header, LIB or DLL enters +the tree. The parser is tested on a synthetic log with a base class, vftable, +bitfield, array and alignment member, so the Python check runs on Linux. + + python -B tests/gdk_layouts_check.py + python -B tools/gdk_layouts.py parse D:\gdk-oracle\fixtures\layout-xg-one.log --json out\xg.json --module xg_xs_gen8 --platform Gaming.Xbox.XboxOne.x64 --msvc 19.44.35207 + python -B tools/gdk_abi_probe.py generate --layouts out\xg.json --out out\xg-probe.cpp --include windows.h --include xg.h --prefix XG_ --print + +Measured on 28 November 2026 with MSVC 19.44.35207 and the 261000 headers: + +| Header | Platform | Classes in the log | Probe | +|---|---|---:|---| +| XboxOne/xg.h | Gaming.Xbox.XboxOne.x64 | 2,098 | 16 XG_ types; sizeof probe compiled | +| XboxOne/d3d12_x.h | Gaming.Xbox.XboxOne.x64 | 3,029 | 74 D3D12XBOX_ types; 25 anonymous skipped; compiled | +| GameInput.h | Gaming.Desktop.x64 | 3,344 | 41 GameInput types; 1 anonymous skipped; compiled | +| XGameRuntime.h | Gaming.Desktop.x64 | 3,363 | 30 selected public types; 3 anonymous skipped; compiled with windows.h first | + +The Xbox One headers use these macros: _GAMING_XBOX, _GAMING_XBOX_XBOXONE and +WINAPI_FAMILY=WINAPI_FAMILY_GAMES. The GRDK headers use _GAMING_DESKTOP and +WINAPI_FAMILY=WINAPI_FAMILY_DESKTOP_APP. XGameRuntime.h needs windows.h before +it, because XTaskQueue.h uses STDAPI. + +The parser treats a single-token member line, such as Width, as an unknown type +with a known name. MSVC prints that form for some typedefs. Anonymous nested +classes appear as NAME::; the probe generator skips them because +C++ cannot name them. + +Limits: a layout is a compile-time fact for one compiler and one macro set. It +does not prove runtime behavior, and a mismatch between a header layout and a +live library still needs an ABI probe or a runtime oracle. Private members and +non-standard-layout classes need review before offsetof is enabled; the generator +emits offsetof only for classes without bases or a vftable and for named, +non-bitfield fields. diff --git a/docs/experiments/gdk-platform-profiles.md b/docs/experiments/gdk-platform-profiles.md new file mode 100644 index 0000000000..1f25a1fb20 --- /dev/null +++ b/docs/experiments/gdk-platform-profiles.md @@ -0,0 +1,45 @@ +# GDK MSBuild platform profiles + +tools/gdk_platform_profiles.py reads the GDK platform files under +VS2022/flatDeployment/MSBuild/Microsoft/VC/v170 and writes a JSON profile per +platform. It keeps the MSBuild conditions and resolves the simple variables +defined in the same files. Variables that refer to the installed edition +(DurangoXdkInstallPath, DurangoGRDKInstallPath, XdkEdition) stay visible instead +of being guessed. + +The GDK installation and the JSON profiles stay outside the repository. + + python -B tests/gdk_platform_profiles_check.py + python -B tools/gdk_platform_profiles.py list --root D:\gdk-ref\261000\gxdk\Microsoft GDK\261000\GXDK + python -B tools/gdk_platform_profiles.py scan --root D:\gdk-ref\261000\gxdk\Microsoft GDK\261000\GXDK --platform Gaming.Xbox.Scarlett.x64 --json out\scarlett.json + +The --sdk option selects the versioned subdirectory (261000, 999999, ...). A +platform directory without that subdirectory is rejected before any output is +written, so the reported SDK, the source paths and the extracted values always +refer to the same edition. + +Measured on 28 November 2026 from the 261000 payload: + +| Platform | Sources | Defines | Includes | Libs | Dependencies | +|---|---:|---:|---:|---:|---:| +| Gaming.Desktop.x64 (GRDK) | 10 | 2 | 1 | 1 | 6 | +| Gaming.Xbox.Scarlett.x64 | 10 | 7 | 3 | 3 | 1 | +| Gaming.Xbox.XboxOne.x64 | 10 | 7 | 3 | 3 | 1 | + +The console profiles define _GAMING_XBOX, _GAMING_XBOX_SCARLETT or +_GAMING_XBOX_XBOXONE, WIN32_LEAN_AND_MEAN and +WINAPI_FAMILY=WINAPI_FAMILY_GAMES, plus the ATL/WRL strict-COM macros. The +desktop profile defines _GAMING_DESKTOP and +WINAPI_FAMILY=WINAPI_FAMILY_DESKTOP_APP. Gaming.Desktop.arm64 is not present in +this payload. + +The include and library roots are Console_EndpointIncludeRoot and +Console_EndpointLibRoot. The console dependency list in Console_Libs is +pixevt.lib, d3d12_xs.lib, gameinput.lib, xgameplatform.lib, xgameruntime.lib, +xmem.lib and xg_xs.lib. The Scarlett profile also sets +EnableEnhancedInstructionSet=AdvancedVectorExtensions, FloatingPointModel=Fast +and /favor:AMD64 for v142/v143. + +The profile is a build recipe, not a runtime fact. A fixture generated from it +still needs the matching compiler, Windows SDK and GDK edition; the unresolved +installation variables are kept exactly because their values differ per host. diff --git a/docs/experiments/gdk-runtime-oracle.md b/docs/experiments/gdk-runtime-oracle.md new file mode 100644 index 0000000000..4312dcb9f7 --- /dev/null +++ b/docs/experiments/gdk-runtime-oracle.md @@ -0,0 +1,37 @@ +# GDK runtime oracle: GRDK and shim + +tools/gdk_runtime_oracle.py compiles the same original fixture twice: once +against the GRDK import library and once against the Xbox2Windows shim. It runs +both executables, masks handles, console ids and per-user temp paths, and writes +a normalized diff and a JSON report. + + python tools/gdk_runtime_oracle.py run --gdk-root "D:\gdk-ref\261000\grdk\Microsoft GDK\261000\GRDK" --shim-dir "out\build\dev\fixture-shims" --fixture "tests\gdk\runtime_families_probe.cpp" --out "out\gdk-runtime" --vcvars "C:\Program Files (x86)\Microsoft Visual Studio\2022\BuildTools\VC\Auxiliary\Build\vcvars64.bat" + +On a host without cl.exe the command returns 77. The normalization and diff +subcommands need no SDK: + + python tools/gdk_runtime_oracle.py normalize out\gdk-runtime\candidate.txt + python tools/gdk_runtime_oracle.py diff out\gdk-runtime\reference.txt out\gdk-runtime\candidate.txt + +Measured on 28 November 2026, Windows 11 build 26200, the inbox +xgameruntime.dll 10.0.26100.9656 and the local shim: + +| Observation | GRDK reference | Xbox2Windows shim | +|---|---|---| +| XGameRuntimeInitialize | S_OK | not exported | +| XSystemGetDeviceType | 1 (Pc) | 1 (Pc) | +| XSystemGetConsoleId | S_OK, 39 bytes, all-zero id | S_OK, 39 bytes, 58325731...01 | +| XGameGetXboxTitleId | 0x80070490 (ERROR_NOT_FOUND) | S_OK, 0x58325731 | +| XPersistentLocalStorageGetPathSize | 0x80004005 | S_OK, 78 | +| XPersistentLocalStorageGetSpaceInfo | 0x80004005 | S_OK, 64 MiB total, 16 MiB used | +| XPackageMount of a missing identifier | 0x80004001 (E_NOTIMPL) | S_OK, synthetic handle and temp path | +| XTaskQueueCreate(Manual, Manual) | S_OK | S_OK | +| XTaskQueueDispatch(Completion, 0) | false | false | +| XSystemGetXboxLiveSandboxId | S_OK, RETAIL | not exported | + +The desktop runtime has no package identity on this host, so the title id and +persistent-local-storage calls fail. The shim synthesizes those values. The +oracle makes the difference explicit; it does not claim the shim matches the +console. Console-only APIs have static oracles only (headers, LIB exports and +vtables), and a successful mount of a missing identifier is an error-path +observation, not a package-format result. diff --git a/docs/experiments/gdk-shader-corpus.md b/docs/experiments/gdk-shader-corpus.md new file mode 100644 index 0000000000..b1bfb9da33 --- /dev/null +++ b/docs/experiments/gdk-shader-corpus.md @@ -0,0 +1,38 @@ +# GDK shader corpus + +tools/gdk_shader_corpus.py compiles original HLSL with the GXDK Scarlett dxc, +retargets the Xbox container with tools/dxil_retarget.py, and records the +source and container SHA-256 values. The HLSL sources are versioned; the .cso +files and the corpus manifest stay outside the repository. + + python -B tests/gdk_shader_corpus_check.py + python -B tools/gdk_shader_corpus.py build --gdk-root D:\gdk-ref\261000\gxdk\Microsoft GDK\261000 --corpus tests\gdk\shaders --out D:\gdk-oracle\knowledge\shaders\corpus + python -B tools/gdk_shader_corpus.py verify --manifest D:\gdk-oracle\knowledge\shaders\corpus\corpus.json + +Measured on 28 November 2026 with dxcompiler_xs 1.8, build +2610.2608.12522.14643: + +| Case | Profile | Xbox bytes | Desktop bytes | Triple | +|---|---|---:|---:|---| +| wave64_ballot_ps | ps_6_0 | 4,316 | 4,152 | dxil-ms-xb2 -> dxil-ms-dx | +| root_constants_vs | vs_6_0 | 3,972 | 3,804 | dxil-ms-xb2 -> dxil-ms-dx | +| image_sample_c_lz_ps | ps_6_0 | 3,912 | 3,756 | dxil-ms-xb2 -> dxil-ms-dx | +| packed_types_cs | cs_6_0 | 3,224 | 3,068 | dxil-ms-xb2 -> dxil-ms-dx | +| derivatives_ps | ps_6_0 | 3,204 | 3,048 | dxil-ms-xb2 -> dxil-ms-dx | +| mesh_ngg_ms | ms_6_5 | 3,104 | 2,944 | dxil-ms-xb2 -> dxil-ms-dx | + +All six cases compiled, retargeted and verified. The retarget removed the +xbox.compiler.options named metadata in every case. The sources cover wave +ballot and lane access, a root signature with one constant buffer, a +comparison sample at level zero, packed 16-bit fields in compute, implicit +derivatives and fwidth, and a fixed three-vertex mesh shader. + +The check runs on Linux without dxc and covers case loading, hashing, manifest +verification, triple checks and the missing-dxc skip. build returns 77 when +dxc is absent. + +Limits: a retargeted container is not a GPU execution result. The corpus does +not prove that a desktop driver accepts the mesh or pixel pipeline, and it does +not cover game shaders. It records the compiler version, the source SHA-256, +the container sizes and the metadata the retarget removed. The mesh case is a +fixed topology and does not exercise NGG culling or amplification. diff --git a/docs/experiments/native-bytewin-store.md b/docs/experiments/native-bytewin-store.md index fbe721c4aa..fc0fe5091a 100644 --- a/docs/experiments/native-bytewin-store.md +++ b/docs/experiments/native-bytewin-store.md @@ -11,6 +11,7 @@ The compiler proves that all three edits originate from the descriptor selected by word 0. The OR works on a loaded word 3 or one whose selector has already been cleared. The original table slot supplies the raw UAV. The host UAV's extent determines which writes are in range. +Direct compute raw stores accept and ignore the GLC, DLC and SLC cache-policy bits. Non-indexed dword atomics reuse the raw store UAV window, and the wave32 fixture checks add with and without GLC, unsigned min, compare-and-swap, and indexed and 64-bit refusals. ## Verification diff --git a/docs/experiments/native-compile-dxil-refusals.md b/docs/experiments/native-compile-dxil-refusals.md index 494f62a51d..090ad0bf15 100644 --- a/docs/experiments/native-compile-dxil-refusals.md +++ b/docs/experiments/native-compile-dxil-refusals.md @@ -18,13 +18,32 @@ - Strips PC offsets and normalizes hex words, byte offsets, and register indices so repeated failures across different instructions or requests aggregate into one row. +3. **Compute programs without a runtime manifest (#3224):** + - A slot-67 compute program that translates but that `format_compute_runtime_manifest` + (`src/direct_compute_cache.cpp`) cannot describe gets one fixed reason, for example + `unsupported startup runtime manifest bindings: SRV kind root_buffer_srv`. The reasons name the + exit: a zero group dimension, root constants above parameter 15 or more than 8 in one parameter, + more than 32 user data words, a resource or sampler heap view, a view above root parameter 15, + non-contiguous SRV or UAV registers, an SRV or UAV kind with no manifest line (the kind, and for + images the dimension and `array`; a texture SRV of dimension 1D, 2D, 3D or 2D array has a line, a + cube or multisampled one does not), more than 32 SRVs or 8 UAVs, a comparison sampler, and stride + words from a view that is not one raw vector SRV. No register numbers, offsets or keys. + - `--requests` still publishes `.cs.cso` and no `.txt`, still counts the request as + compiled and still removes `.fail`. It prints the reason in that job's report as + `no_manifest input=req_.c67 `. It writes no `.fail`, because `.fail` is the retry + marker of both watchers: with `X2W_SKIP_FAILED=1` / `--skip-failed` the Python watcher keeps + selecting such a key in a live cache. + - `--watch`, which refuses the key, writes the same line to `.fail` instead of the former + reasonless one. `--refusals` counts the request under it instead of under no refusal. + `triage_run.py` reports the `.fail` line as `runtime manifest: `. + ## Verification ```powershell .\tools\dev.ps1 cmake --preset release -cmake --build --preset release --target compile_dxil -ctest --preset release --no-tests=error -V -R "^native_compile_dxil_refusals$" +cmake --build --preset release --target compile_dxil native_compute_manifest_reasons +ctest --preset release --no-tests=error -V -R "^(native_compile_dxil_refusals|native_compute_manifest_reasons(_requests)?)$" .\out\pe-env\Scripts\python.exe -B tests/startup_triage_run_check.py ``` diff --git a/docs/experiments/native-compile-dxil-rekey.md b/docs/experiments/native-compile-dxil-rekey.md new file mode 100644 index 0000000000..0a886e986c --- /dev/null +++ b/docs/experiments/native-compile-dxil-rekey.md @@ -0,0 +1,44 @@ +# Native cache re-keying (`compile_dxil --rekey`) + +Added `--rekey` to `tools/startup/compile_dxil.cpp` as the native C++ equivalent of +`tools/startup/shader_cache_rekey.py` (`Refs #2935`). + +## Usage + +```powershell +compile_dxil --rekey OLD_CACHE_DIR NEW_REQUEST_DIR [--jobs N] +``` + +This mode runs without `SDK_DIRECTORY` or DXC: + +- Scans `OLD_CACHE_DIR` (non-recursively) for `req_<16-hex>` markers (`.a`, `.c67`, + `.m57`, `.rtv`), counts `.m86` markers, and ignores result/diagnostic files + (`.txt`, `.fail`, `.cso`, `.psdep`). +- Validates and recomputes keys in parallel using the current output revision + strings (`x2w-startup-shader-29`, `x2w-startup-shader-29cs`, + `x2w-startup-mesh-57-3` via shared helpers in `src/shader_compute_request.cpp`), + while the readers retain `x2w-startup-shader-28` and `x2w-startup-shader-28cs` + input compatibility. +- Rewrites `.psin` and `.rtv` payloads under their updated keys while leaving all + shader bytecode/root/layout parts intact. +- Fails with exit code `1` before creating or writing `NEW_REQUEST_DIR` if any + request is incomplete, unreadable, or malformed; exits `2` on invalid CLI usage + or when `OLD_CACHE_DIR` and `NEW_REQUEST_DIR` refer to the same directory. +- Publishes files atomically (ready markers `.a`, `.c67`, `.m57` written last) + and preserves already-present files in `NEW_REQUEST_DIR`. + +## Verification + +Build `compile_dxil` and run the native rekey parity and control check: + +```powershell +.\tools\dev.ps1 +cmake --preset release +cmake --build --preset release --target compile_dxil +ctest --preset release --no-tests=error -V -R '^native_compile_dxil_rekey$' +``` + +Expected: `native_compile_dxil_rekey` exits `0` and verifies byte-for-byte parity +with `tools/startup/shader_cache_rekey.py`, `gfx2hlsl.pending_keys` compatibility, +idempotency, read-only preservation of `OLD_CACHE_DIR`, and all incomplete-request +and CLI negative controls. diff --git a/docs/experiments/native-compute-implicit-derivatives.md b/docs/experiments/native-compute-implicit-derivatives.md new file mode 100644 index 0000000000..8e86ee0163 --- /dev/null +++ b/docs/experiments/native-compute-implicit-derivatives.md @@ -0,0 +1,41 @@ +# Implicit derivatives in direct compute + +Groups with a multiple of four threads can use implicit derivatives when +they pass the existing wave guards: a group of more than 32 threads must be +a multiple of 32, and a wave64 group a multiple of 64. The DXIL module uses +`numthreads(X*Y*Z,1,1)` and validator version 1.8 only when it emits +compute derivatives. Guest local X, Y and Z are reconstructed from the +linear guest index. + +A guest quad is four consecutive guest lanes. The emitter reconstructs +the linear guest index as host wave rank * 32 + host lane index. The +SM 6.6 derivatives spec section "1D quads" guarantees the matching position +within each quad. The full reconstruction also assumes that host lane +order follows thread order within a wave, including across quads. + +A 6-thread wave32 group has an incomplete quad and refuses with +"implicit derivatives require a pixel stage". A 36-thread wave32 group +has complete quads and fails the earlier wave guard with "partial final +wave in multi-wave group". Implicit Gather with a constant sampler requires +that sampler to be fixed to mip zero (LOD range word zero). + +```powershell +cmake --build --preset dev --target compile_dxil offscreen_check +ctest --preset dev --no-tests=error -j 1 -R '^native_compute_implicit_lod_' -V +``` + +On an NVIDIA GeForce RTX 5080 (Windows 11, Release), the hardware fixture +matches its CPU reference for 4-, 12-, 32- and 96-thread wave32 groups, +64- and 128-thread wave64 groups, and the multidimensional (8,4,1) and +(8,4,2) groups. The multidimensional fixture varies the texture coordinate +only in the quad's vertical direction. Its derivative spans 0.75 texels +for consecutive quads and three texels for spatial 2D quads. This keeps +the expected sample below the first mip transition and leaves the wrong +quad layout observable with the fixture's trilinear sampler. +The compile controls check that implicit shaders emit flattened DXIL +group dimensions and explicit-LOD shaders keep the requested dimensions. +Its other readbacks cover bias selecting mip 2, point depth +comparison at mip 1, both LOD query outputs, and the four taps of mip-zero +Gather. Bias and Gather each use the same CPU reference for their implicit +and explicit-LOD shaders. Inbox WARP reports the capability skip +"requires SM 6.6, WaveOps, and a 32-lane wave". diff --git a/docs/experiments/native-cvt-norm-f16.md b/docs/experiments/native-cvt-norm-f16.md new file mode 100644 index 0000000000..7d26f5d084 --- /dev/null +++ b/docs/experiments/native-cvt-norm-f16.md @@ -0,0 +1,57 @@ +# Normalized integer conversion from binary16 (`v_cvt_norm_i16_f16` / `v_cvt_norm_u16_f16`) in direct DXIL + +The native frontend lowers gfx1013 VOP1 (`0x63` / `0x64`) and VOP3 (`0x1e3` / +`0x1e4`) `v_cvt_norm_i16_f16` and `v_cvt_norm_u16_f16` in +`DirectCompute::float_alu()` for both Compute and Pixel shaders. + +## Exact integer lowering and semantics + +The lowering matches [pixel_aot.py](../../tools/pixel_aot.py)'s +`f16_cvt_norm_result` contract in exact 32-bit integer arithmetic instead of +widening to binary32: + +- Decodes the binary16 exponent (`mag >> 10`) and significand (normal `0x400 | + (mag & 0x3ff)` or subnormal `mag`), multiplies by `32767` (`i16`) or `65535` + (`u16`), and rounds once to nearest even with exact remainder/midpoint checks. + This avoids binary32 double-rounding mismatches (such as `0x3801` and + `0xb802`) and preserves binary16 subnormal inputs. +- `+0.0` and `-0.0` map to `0`. +- Inputs with magnitude `>= 1.0` (including `±Inf`) saturate to `+32767` / + `-32767` (`i16`) or `65535` / `0` (`u16`). +- Any negative value (`sign != 0`) maps to `0` on `v_cvt_norm_u16_f16`. +- Non-finite NaN operands (`mag > 0x7c00`) map to `0`. +- Supported VOP3 modifiers are `abs[0]`, `neg[0]`, `op_sel[0]` (VGPR high-half + source read), and `op_sel[3]` (high-half destination write), preserving the + unwritten destination half and respecting `EXEC` masking. +- Supported sources are VGPRs (`256..511`), numeric SGPRs (`0..105`), 32-bit + literals (`255`), inline binary16 float constants (`240..248`), and inline + integer words (`128..208`). + +## Refused encodings and mode gate + +The translator refuses `v_cvt_norm_i16_f16` and `v_cvt_norm_u16_f16` when any +of the following hold: + +- VOP3 `clamp != 0` or `omod != 0`. +- Unused VOP3 operand modifiers (`abs[2:1]`, `neg[2:1]`, `op_sel[2:1]`, + non-zero `src1` / `src2`). +- High-half `op_sel[0]` on a non-VGPR source (`src0 < 256`). +- DPP16, SDWA, permuted/subword encodings, or special scalar sources such as + `vcc_lo` (`106`). +- Non-default binary16 rounding/denormal mode + (`((mode_bits ^ 0xf0u) & 0x8000ccu) != 0`) or dynamic/unknown `MODE` writes. + +## Fixture coverage and reproduction + +[native_cvt_norm_f16_check.py](../../tests/native_cvt_norm_f16_check.py) checks +30 Compute cases (`<= 32` words/lane in `native_store_replay`), 11 refusal +controls, and lossless 16-bit Pixel readback across 15 draws (29 full-`EXEC` +cases padded to 30) on WARP and hardware: + +```powershell +cmake --build --preset dev --target compile_dxil native_compute_ir_dump native_store_replay offscreen_check +ctest --test-dir out/build/dev --no-tests=error --output-on-failure -j 1 -R '^native_cvt_norm_f16_' -V +``` + +Compute replay requires shader model 6.6 with wave32; adapters without wave32 +report a skip (`77`) on `native_cvt_norm_f16_compute_hardware`. diff --git a/docs/experiments/native-cvt-pknorm-f32.md b/docs/experiments/native-cvt-pknorm-f32.md new file mode 100644 index 0000000000..878f42673f --- /dev/null +++ b/docs/experiments/native-cvt-pknorm-f32.md @@ -0,0 +1,63 @@ +# Packed normalized integer conversion from binary32 (`v_cvt_pknorm_i16_f32` / `v_cvt_pknorm_u16_f32`) in direct DXIL + +The native frontend lowers gfx1013 VOP3 `v_cvt_pknorm_i16_f32` (`0x368`) and +`v_cvt_pknorm_u16_f32` (`0x369`) in `DirectCompute::float_alu()` for both Compute +and Pixel shaders, packing `cvt_norm(S0.f32)` into `D[15:0]` and +`cvt_norm(S1.f32)` into `D[31:16]`. + +## Exact 32-bit integer RNE lowering and model status + +Both lanes compute single-rounding `round_rne(clamp(x, -1, 1) * 32767)` (`i16`) +and `round_rne(clamp(x, 0, 1) * 65535)` (`u16`) in 32-bit unsigned integer +arithmetic without floating-point intermediaries or 64-bit integers. + +- **Model status:** Unlike `v_cvt_pk_u8_f32` (`tools/rdna_cvt_pk_u8.py`), + `v_cvt_pknorm_i16_f32` and `v_cvt_pknorm_u16_f32` have not yet been measured + with a silicon probe on physical RDNA 2 hardware, and the AMD RDNA 2 ISA + reference leaves rounding/bounds/NaN details of the `float32_to_snorm16` / + `float32_to_unorm16` helpers implicit. This direct DXIL lowering implements a + single RNE rounding of the exact scaled product (`clamp(x) * 32767` or `* + 65535`) with `NaN -> 0`; the fixture explicitly includes the four inputs + (`0x3F000400`, `0x38400180`, `0x3F000200`, `0x37C000C0`) that separate + single-rounding exact multiplication from a binary32 multiply followed by RNE. + +- For normal binary32 inputs with `mag in [2^-17, 1.0)` (`exp in [110, 126]`), + the 24-bit significand `m` is multiplied by `2^k - 1` (`k = 15` for `i16`, + `k = 16` for `u16`) as `(m << k) - m` split cleanly at bit `k` into `(p_hi, + p_lo)`, and rounded to nearest even using both `rem_hi` against `mid_hi` and + the nonzero carry-over `p_lo != 0` bit. +- Magnitudes `< 2^-17` (zeros and all binary32 subnormals included) round to `0`. +- Magnitudes `>= 1.0` (`±Inf` included) saturate to `±32767` (`i16`) or `65535` + / `0` (`u16`). +- Any negative value (`sign != 0`) maps to `0` on `v_cvt_pknorm_u16_f32`. +- Non-finite NaN operands (`mag > 0x7f800000`) map to `0`. +- Supported VOP3 input modifiers are `abs[1:0]` and `neg[1:0]` on `S0` and + `S1`, with `EXEC`-masked destination writes and VGPR, SGPR, 32-bit literal, + and inline `f32`/integer sources via `operand32()`. + +## Refused encodings + +The translator refuses `v_cvt_pknorm_i16_f32` and `v_cvt_pknorm_u16_f32` when +any of the following hold: + +- VOP3 `clamp != 0` or `omod != 0`. +- Any `op_sel` bits (`op_sel[3:0]`), third-operand `abs`/`neg` bits + (`abs[2]`/`neg[2]`), or non-zero `src2`. +- DPP16, SDWA, permuted/subword encodings, or unsupported operand codes (such as + `254`). + +## Fixture coverage and reproduction + +[native_cvt_pknorm_f32_check.py](../../tests/native_cvt_pknorm_f32_check.py) +checks 28 Compute cases (`<= 32` words/lane in `native_store_replay`), 8 +refusal controls, single-rounding vs binary32-multiply-then-RNE separation, and +lossless 16-bit Pixel readback across 14 draws (27 full-`EXEC` cases padded to +28) on WARP and D3D12 hardware: + +```powershell +cmake --build --preset dev --target compile_dxil native_compute_ir_dump native_store_replay offscreen_check +ctest --test-dir out/build/dev --no-tests=error --output-on-failure -j 1 -R '^native_cvt_pknorm_f32_' -V +``` + +Compute replay requires shader model 6.6 with wave32; adapters without wave32 +report a skip (`77`) on `native_cvt_pknorm_f32_compute_hardware`. diff --git a/docs/experiments/native-descriptor-stride-scc.md b/docs/experiments/native-descriptor-stride-scc.md new file mode 100644 index 0000000000..7df3ecb032 --- /dev/null +++ b/docs/experiments/native-descriptor-stride-scc.md @@ -0,0 +1,32 @@ +# Buffer-stride condition code in direct compute + +The direct DXIL frontend can carry a guest buffer descriptor symbolically +while calculating SCC from its bound stride. It recognizes a 14-bit stride +extraction from descriptor word 1 and the subsequent unsigned max with 1. The +first sets SCC when the extracted stride is nonzero. The max sets SCC when its +first operand wins strictly, so both operand orders have meaningful tests. + +This applies to fixed, unambiguous buffer SRV slots covered by a declared +descriptor-table range. The compiler adds one stride word per descriptor, +after the regular root constants. Native dispatch and the published manifest +both use the stride from the input view the runtime has already resolved. The +symbolic descriptor fields still carry their slot identity for later buffer +addressing. A dynamic heap or CBV/UAV slot, unproven stride source, and numeric +reads of other symbolic fields retain their refusals. + +The [source-built fixture](../../tests/native_descriptor_scc_check.py) checks +the layout and cache replay, then dispatches with strides of 0, 1, 4 and 16. +The runtime fixture changes guest descriptor fields between runs of the same +shader on the in-process and published paths. It compares the three status +words, the neighboring root constant, and every untouched output word. +The isolated replay also verifies 14-bit extraction and refuses to dispatch +if the stride input is missing. The fixtures use the repository's MIT license. + +```powershell +cmake --build --preset release --target compile_dxil native_store_replay startup_stream_consumer +ctest --preset release --no-tests=error -R '^(native_descriptor_scc|startup_compute_descriptor_scc)_' -V +``` + +The direct shaders require Shader Model 6.6 and 32-lane waves. An available +adapter without wave32 reports a skip. The instruction behavior follows the +[AMD RDNA 2 ISA, revision 1.0](https://docs.amd.com/v/u/en-US/rdna2-shader-instruction-set-architecture). diff --git a/docs/experiments/native-direct-fma-f16.md b/docs/experiments/native-direct-fma-f16.md index 1a6078e817..2450d2489c 100644 --- a/docs/experiments/native-direct-fma-f16.md +++ b/docs/experiments/native-direct-fma-f16.md @@ -6,16 +6,18 @@ - **Exact single-rounded FMA (`fused_half_rne()`):** Reuses the shared 32-bit integer `fused_half_rne(a, b, c)` helper (introduced in #3151 for `v_pk_fma_f16`) so `a * b + c` computes an exact product, aligns the addend with a sticky bit, and rounds once to nearest-even binary16 rather than double-rounding through binary32. -- **High-half preservation:** Every operation reads `16`-bit sources (preserving `S0..S2[15:0]` / `K[15:0]` / `D[15:0]`), +- **High-half preservation by default:** The default forms read `S0..S2[15:0]` / `K[15:0]` / `D[15:0]`, writes the result into `D[15:0]`, and keeps `D[31:16]` unchanged. - **Modifiers & MODE contract:** Supports VOP3 `abs`, `neg`, and `clamp` (`[0.0, 1.0]` saturation); refuses DPP, SDWA, - `omod`, high-half `op_sel`, third-source modifiers/`src2` on `v_fmac_f16_e64`, and non-default FP16 MODE writes + `omod`, high-half `op_sel` and third-source modifiers/`src2` on `v_fmac_f16_e64`, and non-default FP16 MODE writes (`half_binary` in `DirectCompute::lower()`). - **Test adjustment:** Updated the unlowered-instruction refusal placeholder in [`tests/native_f16_alu_check.py`](../../tests/native_f16_alu_check.py) from `v_fmac_f16` to `v_pk_fmac_f16`, and added `@dx.op.unaryBits.i32(i32 33, ...)` (`FirstbitHi`) evaluation to its IR interpreter so `native_fma_f16_ir` evaluates `fused_half_rne()` directly. +Direct compute also accepts VOP3 `v_fma_f16` with `op_sel`. Bits 0 to 2 select the high half of the respective VGPR source before abs and neg. Bit 3 selects the high destination half and preserves its low half. A clear destination selector writes the low half and preserves the high half. Selected non-VGPR sources and clamp combined with `op_sel` are refused. The [half-selection fixture](../../tests/native_fma_f16_opsel_check.py) checks six captured forms in IR and direct GPU replay. + ## Fixture [`tests/native_fma_f16_check.py`](../../tests/native_fma_f16_check.py) via diff --git a/docs/experiments/native-direct-salu-bitscan64.md b/docs/experiments/native-direct-salu-bitscan64.md index 7fa0c1d41d..896422769d 100644 --- a/docs/experiments/native-direct-salu-bitscan64.md +++ b/docs/experiments/native-direct-salu-bitscan64.md @@ -6,7 +6,7 @@ using 32-bit DXIL `unaryBits.i32` (`31` `Countbits`, `32` `FirstbitLo`, `33` `Fi `tools/startup/gfx2hlsl.py`: - **Destination:** general 32-bit SGPR (`s0..s105`), leaving `s[dst + 1]` untouched. -- **Source `S0`:** aligned SGPR pair (`s0..s104` even), inline integer (`-16..64`, sign-extended when negative), or +- **Source `S0`:** aligned SGPR pair (`s0..s104` even), EXEC (`exec_lo`/`exec_hi`, both words, in wave32 and wave64), inline integer (`-16..64`, sign-extended when negative), or 32-bit literal (sign-extended for `s_flbit_i32_i64`, zero-extended for `_b64`). - **Semantics & `SCC`:** `s_bcnt0_i32_b64` and `s_bcnt1_i32_b64` sum 32-bit `Countbits` over both halves and write `SCC = (D != 0)`. `s_ff0_i32_b64`, `s_ff1_i32_b64`, `s_flbit_i32_b64` and `s_flbit_i32_i64` preserve `SCC` and return @@ -23,8 +23,11 @@ Encodings were verified with LLVM 15.0.7 (`clang -cc1as -triple amdgcn -target-c - **Controls:** compiles all 6 ops and checks `dxc.exe -dumpbin` for `@dx.op.unaryBits.i32` opcodes `31`, `32`, `33` with no `i64` shifts; tests `s_ff1_i32_b64 s31, s[22:23]` right below `s[32:35]` to verify `s32` stays intact; - checks 6 invalid destination/source refusals (`vcc`/`exec` dst, odd/`vcc`/`exec`/float `S0`); checks 6 mutant + checks 6 invalid destination/source refusals (`vcc`/`exec` dst, odd/`vcc`/`exec_hi`/float `S0`; since EXEC became a valid `S0`, the source control uses the odd `exec_hi`); checks 6 mutant references differ. +- **EXEC as `S0`:** read back with `s_bcnt1_i32_b64` by `tests/native_wave64_exec_salu_check.py`, including masks that + span both host halves of a wave64 (`ctest --preset dev --no-tests=error -R '^native_wave64_exec_salu_hardware$' -V`). + The other five ops accept EXEC through the same source check but are not run with it. - **Hardware cases:** all 6 ops across `(0, 0)`, `(0xffffffff, 0xffffffff)`, `(0, 1)`, `(0x80000000, 0)`, `(0xfffffffe, 0xffffffff)`, `(0, 0x80000000)`, `(1, 0)`; inline `-1`; 32-bit literal `0x80000001`; explicit `SCC` preservation (`0` and `1`) across count-then-scan sequences; overlapping `s22 = ff1(s[22:23])`. diff --git a/docs/experiments/native-dot2-f32-f16.md b/docs/experiments/native-dot2-f32-f16.md new file mode 100644 index 0000000000..da380d331c --- /dev/null +++ b/docs/experiments/native-dot2-f32-f16.md @@ -0,0 +1,38 @@ +# Direct DXIL `v_dot2_f32_f16` Translation + +Experiment for direct Compute and Pixel DXIL lowering of RDNA 2 VOP3P `v_dot2_f32_f16` (`0x13`), addressing `#3238` and `#2935`. + +## What Changed + +- Lowered `v_dot2_f32_f16` in `DirectCompute::float_alu()` inside [src/gfx1013_direct_compute.inl](../../src/gfx1013_direct_compute.inl): + - Enforces the full RDNA 2 `MODE` contract (`((mode_bits ^ 0xf0u) & 0x8000ffu)` and `half_mode_known`, requiring RNE rounding and denormal preservation for both binary16 and binary32, plus `half_binary = true` in `DirectCompute::lower()`). + - Accepts `op_sel[1:0]` (`i.a >> 11`), `op_sel_hi[1:0]` (`i.b >> 27`), `neg_lo[2:0]` (`i.neg`: pair 0 binary16 signs + `src2` binary32 sign), `neg_hi[1:0]` (`i.abs`: pair 1 binary16 signs), and `clamp` (`dx.op.unary.f32` opcode `7`, saturate). Ignores unused `op_sel_hi[2]` (bit 14). + - Decodes `src0` and `src1` through `packed_f16_inline_constant()` (binary16 inline float constants `240..248` with zero high half, plus inline integers `128..208`) or `operand32()`, widens each selected half via `dx.op.legacyF16ToF32`, computes `((a0 * b0) + (a1 * b1)) + c`, and preserves binary32 subnormal accumulators `c` (`0 < |c| < 2^-126`) across desktop DXIL `fadd` / `saturate` when `(a0 * b0) + (a1 * b1) == +/-0.0` (every finite nonzero binary16 product sum has magnitude `>= 2^-48 >> 2^-126`). + - Refuses reserved `op_sel[2]` / `neg_hi[2]` bits (`i.a & 0x2400`), DPP/permuted encodings, special scalar registers on `src0`/`src1`/`src2`, and unsupported or dynamic rounding/denormal modes. +- Extended the Python DXIL IR evaluator in [tests/native_f16_alu_check.py](../../tests/native_f16_alu_check.py) to evaluate `dx.op.unary.f32(i32 7, ...)` (`Saturate`). +- Added compute/pixel test coverage in [tests/native_dot2_f32_f16_check.py](../../tests/native_dot2_f32_f16_check.py) (including `inline_int_src2_129` `0x00000001` plus VGPR-sourced binary32 subnormals `0x00000001` and `0x80400000` with and without `clamp=1`, and an `s_denorm_mode 0xC` binary32 flush refusal) and registered CTest targets in [tests/cmake/native_packed_dot2_f16.cmake](../../tests/cmake/native_packed_dot2_f16.cmake). + +## Verification + +Host: Windows 10.0.26100, `dev` and `release` (`/O2`) presets, DXC `10.0.26100.0`. + +- `cmake --build --preset dev` & `--preset release` (`compile_dxil`, `native_compute_ir_dump`, `native_store_replay`, `offscreen_check`): passed. +- `ctest --preset dev --no-tests=error --output-on-failure -j 1 -V -R '^native_(packed_dot2(_f16)?_.*|packed_f16_inline_(ir|controls|compute_hardware)|f16_alu_(ir|hardware))$'`: + - `native_packed_dot2_f16_ir`: **passed** (`30` cases matched exact binary32 model; `10` refusals matched). + - `native_packed_dot2_f16_controls`: **passed** (`30` cases compiled to DXIL; verified `10` refusals). + - `native_packed_dot2_f16_pixel_warp`: **passed** (`Microsoft Basic Render Driver` `10.0.26100.9711`, `7` quad draws matched, including `inline_int_src2_129` and all 4 VGPR subnormal cases). + - `native_packed_dot2_f16_pixel_hardware`: **passed** (`NVIDIA Quadro M1000M` `32.0.15.7371`, `7` quad draws matched; debug layer unavailable). + - `native_packed_dot2_f16_compute_hardware`: **skipped** (`77`, `Intel(R) HD Graphics 530` `31.0.101.2111` requires SM 6.6 with wave32). + - Neighbor `native_packed_dot2_controls`, `native_packed_f16_inline_ir/controls`, and `native_f16_alu_ir` passed (`*_hardware` compute tests skipped `77` on HD 530). +- `ctest --preset release --no-tests=error --output-on-failure -j 1 -V -R '^native_(packed_dot2(_f16)?_.*|packed_f16_inline_(ir|controls|compute_hardware)|f16_alu_(ir|hardware))$'`: + - Same `8` IR/controls/pixel tests **passed** and `4` SM 6.6 wave32 compute tests skipped (`77`) on HD 530. +- `ctest --preset dev --no-tests=error -R '^native_.*_(controls|ir)$' --output-on-failure`: **69/69 passed** (`0` failures, `0` skips). +- Sensitivity mutants in `src/gfx1013_direct_compute.inl`: + - `drop_subnormal_keep` (`keep_subnormal = "0"`): failed `native_packed_dot2_f16_pixel_warp` (`rc=8`, `00000001,00000001,80400000,00000001` vs `00000000,00000000,00000000,00000000`). + - `drop_hi_term`, `drop_neg_c`, `drop_clamp`, and `swap_opsel_hi`: failed `native_packed_dot2_f16_ir` (`rc=8`). +- `python -B tests/docs_links_check.py`: passed (`131` Markdown files, `631` links). + +## Limits + +- Direct Compute GPU execution (`native_packed_dot2_f16_compute_hardware`) could not run locally because `Intel(R) HD Graphics 530` lacks SM 6.6 wave32 (`77` skip). Compute IR evaluation, DXIL `controls`, and Pixel WARP + NVIDIA hardware draws (including binary32 subnormal retention on inline and VGPR `src2`) are verified. +- `signed_zero_keep`, `signed_zero_cancel_pos`, `inf_propagation`, `nan_propagation`, and `clamp_nan_to_zero` (`pixel_safe=False`) are verified in IR/controls/compute fixtures because `--startup-pixel-words` checks bitwise equality where drivers can vary on qNaN payload bits or pixel export `-0.0`. diff --git a/docs/experiments/native-dpp-quad-compute.md b/docs/experiments/native-dpp-quad-compute.md index c8f6c61598..dc160a80f9 100644 --- a/docs/experiments/native-dpp-quad-compute.md +++ b/docs/experiments/native-dpp-quad-compute.md @@ -7,6 +7,8 @@ two-bit field in the control byte. It adds that field to the base of the destination lane's quad and reads source 0 from that physical wave32 lane. Quads fit within each physical half of a split guest wave64. +Direct compute also lowers DPP8 selectors within each eight-lane group. FI reads the saved source VGPR and otherwise an inactive source supplies zero. + Without FI, the guest EXEC bit of the selected source decides whether it can be read. BOUND_CTRL supplies a zero source for a disabled lane. With BOUND_CTRL clear, the instruction preserves the old destination. FI reads the diff --git a/docs/experiments/native-fract-f16.md b/docs/experiments/native-fract-f16.md new file mode 100644 index 0000000000..0a59c712d8 --- /dev/null +++ b/docs/experiments/native-fract-f16.md @@ -0,0 +1,54 @@ +# Binary16 fractional part (`v_fract_f16`) in direct DXIL + +The native frontend lowers gfx1013 VOP1 (`0x5f`) and VOP3 (`0x1df`) +`v_fract_f16` in `DirectCompute::float_alu()` for both Compute and Pixel +shaders. + +## Semantics and supported forms + +For each active lane: + +- Finite binary16 inputs (decoded with `legacyF16ToF32`) compute + `x - floor(x)` in binary32, round to binary16 round-to-nearest-even via + `packed_half_rne()`, and clamp a result of `1.0` (`0x3c00`, produced by tiny + negative fractions such as `-2^-12` or `-2^-24`) strictly below `1.0` to + `0x3bff`, matching `min(x - floor(x), 0x3bff)`. Exact integers and `-0.0` + produce `+0.0` (`0x0000`), and positive binary16 subnormals are preserved. +- Non-finite inputs (`+Inf`, `-Inf`, and NaN) produce canonical quiet NaN + (`0x7e00`), or `+0.0` (`0x0000`) when `clamp=1`. Because finite outputs already + lie in `[+0.0, 1.0)`, `clamp=1` preserves finite results unchanged. +- Supported VOP3 modifiers are `abs[0]`, `neg[0]`, `clamp`, `op_sel[0]` + (VGPR high-half source read), and `op_sel[3]` (high-half destination write), + preserving the unwritten half of the destination VGPR under `EXEC` masking. +- Supported sources are VGPRs (`256..511`), numeric SGPRs (`0..105`), 32-bit + literals (`255`), inline binary16 float constants (`240..248`), and inline + integer words (`128..208`). + +## Refused encodings and mode gate + +The translator refuses `v_fract_f16` when any of the following hold: + +- Non-zero VOP3 output modifier (`omod != 0`). +- Unused VOP3 operand modifiers (`abs[2:1]`, `neg[2:1]`), unused `op_sel[2:1]`, + or non-zero `src1` / `src2` fields. +- High-half `op_sel[0]` on a non-VGPR source (`src0 < 256`). +- DPP16, SDWA, permuted/subword encodings, or special scalar sources such as + `vcc_lo` (`106`). +- Non-default binary16 rounding/denormal mode (`((mode_bits ^ 0xf0u) & 0x8000ccu) != 0`), + or an unknown/dynamic `MODE` state (for example a conditional `s_denorm_mode` + write). + +## Fixture coverage and reproduction + +[native_fract_f16_check.py](../../tests/native_fract_f16_check.py) checks +32 Compute cases (`<= 32` words/lane in the `native_store_replay` buffer), +10 refusal controls, and lossless 16-bit Pixel readback across 16 draws (31 +full-`EXEC` cases, padded to 32) on both WARP and D3D12 hardware: + +```powershell +cmake --build --preset dev --target compile_dxil native_compute_ir_dump native_store_replay offscreen_check +ctest --test-dir out/build/dev --no-tests=error --output-on-failure -j 1 -R '^native_fract_f16_' -V +``` + +Compute replay requires shader model 6.6 with wave32; adapters without wave32 +report a skip (`77`) on `native_fract_f16_compute_hardware`. diff --git a/docs/experiments/native-fract-f32-bound.md b/docs/experiments/native-fract-f32-bound.md new file mode 100644 index 0000000000..e55f023cb9 --- /dev/null +++ b/docs/experiments/native-fract-f32-bound.md @@ -0,0 +1,46 @@ +# Direct binary32 fract upper bound + +The direct DXIL frontend accepted `v_fract_f32` but emitted only DXIL `Frc`. +For the synthetic inputs `0xb0800000` (-2^-30) and `0xb1800000` (-2^-28), +that returned `0x3f800000` (1.0) on the tested desktop adapter. The gfx1013 +instruction keeps its result strictly below one, returning `0x3f7fffff` for +these inputs. The Python translator already applies this bound; see the +[earlier fract experiments](../experiments.md), +[#267](https://github.com/R0Y00/Xbox2Windows/pull/267) and +[#2010](https://github.com/R0Y00/Xbox2Windows/pull/2010). This is the same +boundary in the newer direct DXIL path, rather than a change to those Python +lowerings. + +The direct frontend now caps a result at or above 1.0 with an ordered comparison. +A NaN fails that comparison and passes through. The cap precedes the output +scale and clamp: `mul:2` of these tiny negative inputs must yield `0x3fffffff`, +not 2.0. Changing the direct frontend also changes its generated cache revision. + +The fixture constructs eight inputs and four instruction forms per input: +VOP1, VOP3 with input negation, VOP3 with clamp, and VOP3 with `mul:2`. +Each lane of two wave32 groups writes all 32 results. The readback compares +2,048 output words and 16 guard words, accepting NaNs by class. The controls +compile and validate DXIL and reject reference mutations that omit the cap or +replace NaN with the finite cap. + +```powershell +cmake --build --preset dev --target compile_dxil native_store_replay +ctest --preset dev --no-tests=error -V -R '^native_fract_f32_(controls|hardware)$' +``` + +At parent revision `240e0fb9c460f24d51683abe2d4cce2800b136c1`, the hardware +fixture failed on 384 of 2,064 words. With the bound, all words matched. +The adapter was an NVIDIA GeForce RTX 4070 Ti SUPER, driver 32.0.15.7270, +on Windows 10 build 19045, with DXC 1.9.2609 and Agility SDK 1.620.2. +The ordinary Windows 10 fixture executable reported the shader-model capability +skip; the measured runs relinked the same fixture objects locally with the +Agility SDK version/path exports and placed its matching runtime beside them. +The D3D12 debug layer was not enabled for those compute readbacks. +The compile controls, `native_f16_alu_ir`, `native_frexp_f32_controls` and +`native_mad32_controls` all passed. No console hardware or full program run +is claimed by these fixture results. + +After rebasing onto `aeef65b2da356b15cf1a81c5d6a73bd6cee77bcd`, the two +targets rebuilt, the compile controls passed, and the Agility-linked hardware +fixture again matched all 2,064 words. The ordinary executable still reported +the capability skip. diff --git a/docs/experiments/native-global-srv-heap-replay.md b/docs/experiments/native-global-srv-heap-replay.md index bc4787af0c..f267ca20ca 100644 --- a/docs/experiments/native-global-srv-heap-replay.md +++ b/docs/experiments/native-global-srv-heap-replay.md @@ -92,6 +92,16 @@ The check runs, in order: for selections 0 and 1 (output equals the slot's data), compiled by `compile_dxil --requests`, replayed with the same result, and replaying selection 0 against the slot 1 reference reports a mismatch. +Section 11 of the check (#3224) forms the heap descriptor address the way a waterfall loop over a lane-selected slot +does: `s_add_u32 s24, s2, s17`, `s_add_u32 s25, 0, src_scc`, `s_load_dwordx4 s[20:23], s[24:25], 0x0` instead of the +SGPR offset of the load. The compiler tracks SCC as the carry of that add and reads the pair as the same indexed heap +descriptor, under the same contract. Without `.views` it is refused with the heap text. The program is recorded, +compiled and replayed for selections 0 and 1 like PROGRAM, with the slot 1 mismatch control. The other operand order +with `s_addc_u32 s25, 0, 0` compiles. These stay refused: a constant offset (`unbound numeric SGPR s2`), `s_mov_b32 +s25, 0` or an `s_cmp` between the adds (`heap descriptor address high word is not the carry of its offset add`) and an +immediate offset on the load. `tests/native_heap_offset_add_check.py` compiles the same form from a slot 67 request with +both heap flags: it reaches the heap text like the SGPR-offset form, and the controls keep their refusals. + ## Result ``` @@ -122,6 +132,15 @@ ctest --preset dev --no-tests=error -R "^native_global_srv_heap_replay(_warp|_ha load (`buffer_load_format_*`) through the heap descriptor. After the change, the test passes with 84 assertions. The run against the earlier commit `7582c01d` fails at the `window_loop` shape (old text "heap byte window in a program with a backward branch"). The run stops there. +- Added heap address (#3224), dev build on `main` `8007a539` plus the change, NVIDIA GeForce RTX 4090 (driver + 32.0.16.1088), Windows 11 build 26300, Windows SDK 10.0.26100 DXC, D3D12 debug layer not enabled: + `native_global_srv_heap_replay_hardware` passed, 118 assertions. `native_heap_offset_add` passed, 5 of 5. `_warp` + skipped (77) as above. + - With the compiler sources of `8007a539` (before the change), the replay fails at the first section 11 assertion + (`unbound numeric SGPR s2`) and `native_heap_offset_add` fails 3 of 5 (`unbound numeric SGPR s5`). + - With the high-word check removed, both tests fail at the `mov_high` controls. + - `ctest --preset dev --no-tests=error -R "native_|startup_compute|compile_dxil" -j 8`: 415 tests, 404 passed and + 11 skipped (77, WARP). ## Limits diff --git a/docs/experiments/native-image-atomics.md b/docs/experiments/native-image-atomics.md index fffb013f57..0ded7913e9 100644 --- a/docs/experiments/native-image-atomics.md +++ b/docs/experiments/native-image-atomics.md @@ -1,9 +1,15 @@ # Direct Compute atomics on unsigned 2D textures The native Compute compiler lowers `image_atomic_add`, `image_atomic_umax`, -and `image_atomic_cmpswap` on a fixed table descriptor for a 2D `R32_UINT` -UAV. DXIL uses `RWTexture2D` with two integer coordinates and honours -the guest EXEC mask. GLC writes the pre-operation value to the data VGPR. +`image_atomic_cmpswap`, `image_atomic_swap`, `image_atomic_umin`, +`image_atomic_and`, `image_atomic_or` and `image_atomic_xor` on a fixed table +descriptor for a 2D `R32_UINT` UAV. Swap, umin, and, or and xor use DXIL +`AtomicBinOp` Exchange (8), UMin (6), And (1), Or (2) and Xor (3). Signed +`image_atomic_smin` and `_smax` are outside the verified scope and stay +refused, as do `sub`, `inc`, `dec` and the float atomics. + +DXIL uses `RWTexture2D` with two integer coordinates and honours the +guest EXEC mask. GLC writes the pre-operation value to the data VGPR. Compare-and-swap takes replacement from the first data VGPR and comparison from the next one. Atomic writes are included when translating memory waits and barriers. @@ -33,12 +39,20 @@ add with only 16 active lanes. Each returning operation also feeds its result to a second atomic. Clearing only the first operation's GLC bit changes the second readback and fails the comparison. +The [binary-operation fixture](../../tests/native_image_atomic_binops_check.py) +reuses that program for swap, umin, and, or and xor. Its controls check each +`AtomicBinOp` code, the operand refusals and the refused opcodes. Its readback +compares the same 336 words for distinct and contended texels, with GLC on and +off and 16 active lanes. + The runtime fixture publishes the native compiler's DXIL and manifest from a source-built device slot 67 request. A dispatch through the stand-in matches all 256 words, with the one target texel incremented by 32 across two groups. The same program with a float UAV is refused and leaves all 1,024 halfwords -unchanged. On Windows 11 build `26300.10075` both ran on the RTX 4070 with -driver `32.0.16.2124`. Direct DXIL requires wave32. Local WARP exposes four +unchanged. On Windows 11 build `26300.10075` the synthetic and runtime fixtures +ran on the RTX 4070 with driver `32.0.16.2124`. The binary-operation fixture +passed on an NVIDIA GeForce RTX 5080 (Windows 11, driver `32.0.16.2101`). +Direct DXIL requires wave32. Local WARP exposes four lanes, so the native execution test reports a capability skip there. ## References diff --git a/docs/experiments/native-image-cache-flags.md b/docs/experiments/native-image-cache-flags.md new file mode 100644 index 0000000000..009ee4c0d5 --- /dev/null +++ b/docs/experiments/native-image-cache-flags.md @@ -0,0 +1,36 @@ +# Direct DXIL Read-Only Image Cache Flags (`GLC` / `DLC`) + +Experiment for accepting MIMG cache-policy flags `GLC` (word 0 bit 13, `0x2000`) and `DLC` (word 0 bit 7, `0x0080`) on read-only image operations in `DirectCompute::image_io()`, addressing `#3242`, `#3224` (Rank 8), and `#2935`. + +## What Changed + +- Updated `DirectCompute::image_io()` in [src/gfx1013_direct_compute.inl](../../src/gfx1013_direct_compute.inl) so `(i.a & (store ? 0x3e0c0u : 0x3c040u))` accepts `GLC` (`0x2000`) and `DLC` (`0x0080`) on read-only image instructions (`image_load`, `image_load_mip`, `image_sample*`, `image_gather4*`, `image_getlod`, `image_getresinfo`) while keeping refusals for: + - `image_store` with `GLC` or `DLC` (`0x3e0c0u`) + - `LWE` (`0x20000`), `TFE` (`0x10000`), `R128` (`0x8000`), and reserved word 0 bits (`0x4040`) + - word 1 reserved bits (`0x3c000000u`) +- Added [tests/native_image_cache_flags_check.py](../../tests/native_image_cache_flags_check.py) and registered CTest entries in [tests/cmake/native_image_cache_flags.cmake](../../tests/cmake/native_image_cache_flags.cmake). + +## Verification + +Host: Windows 10.0.26100, `dev` preset, DXC `10.0.26100.0`. + +- `cmake --build --preset dev --target compile_dxil offscreen_check native_compute_ir_dump`: passed. +- `ctest --preset dev --no-tests=error -R '^(native_image_cache_flags_|native_gather_|native_image_atomic_|native_sample_ssamp_)' -V`: + - `native_image_cache_flags_controls`: **passed** (`48` flagged DXIL modules matched plain `flags=0` baselines across Compute and Pixel stages and `GLC`/`DLC`/`SLC`/`GLC|DLC|SLC`; `16` refusals matched across Compute and Pixel). + - `native_image_cache_flags_ps_warp`: **passed** (`12` cached-flag `image_gather4_l` cases matched on Microsoft Basic Render Driver `10.0.26100.9711`). + - `native_image_cache_flags_ps_hardware`: **passed** (`12` cached-flag `image_gather4_l` cases matched on `NVIDIA Quadro M1000M` `32.0.15.7371`; debug layer unavailable). + - `native_image_cache_flags_cs_hardware`: **passed** (`12` cached-flag `image_gather4_l` cases matched on `NVIDIA Quadro M1000M` `32.0.15.7371`; debug layer unavailable). + - `native_image_cache_flags_cs_warp`: **skipped** (`77`, Microsoft Basic Render Driver has 4-lane waves and lacks SM 6.6 wave32). + - Neighbor suites (`native_gather_compare_warp`, `native_gather_lod_controls/ps_warp/ps_hardware/cs_hardware`, `native_image_atomic_controls/hardware`, `native_sample_ssamp_hardware`): passed (with SM 6.6 wave32 WARP tests skipping `77`; `native_image_atomic_runtime_hardware` failed on this dual-GPU host because `startup_stream_consumer` runs on adapter 0 `Intel(R) HD Graphics 530` which lacks SM 6.6 wave32). +- `ctest --preset dev --no-tests=error -R '^native_.*_(controls|ir)$' --output-on-failure`: **67/67 passed** (`0` failures, `0` skips). +- Sensitivity mutants in `src/gfx1013_direct_compute.inl` tested against `native_image_cache_flags_controls`: + - `revert_ro_cache_flags` (`(i.a & 0x3e0c0u)`): failed (`rc=8`, rejected `image_load` with `GLC`). + - `drop_r128_refusal` (`(i.a & (store ? 0x3e0c0u : 0x34040u))`): failed (`rc=8`, accepted `sample_r128`). + - Clean tree restored, rebuilt, and `native_image_cache_flags_controls` passed (`48` modules, `16` refusals). +- `python -B tests/docs_links_check.py`: passed (`131` Markdown files, `631` links). + +## Limits + +- `native_image_cache_flags_cs_warp` skips (`77`) on WARP because WARP uses 4-lane waves. +- `GLC` and `DLC` remain refused on `image_store*` and explicit/policy-checked on `image_atomic_*` (`image_atomic()`). +- Local `offscreen_check` hardware runs reported `debug_layer=unavailable` on `NVIDIA Quadro M1000M`. diff --git a/docs/experiments/native-ldexp-f16.md b/docs/experiments/native-ldexp-f16.md new file mode 100644 index 0000000000..7d092b469d --- /dev/null +++ b/docs/experiments/native-ldexp-f16.md @@ -0,0 +1,26 @@ +# Direct DXIL `v_ldexp_f16` + +Lowers `v_ldexp_f16` (VOP2 `0x3b` / VOP3A `0x13b`) in the native direct-DXIL +compute path (`src/gfx1013_direct_compute.inl`) via exact 32-bit integer +IEEE-754 binary16 scaling while preserving `D[31:16]`. + +## Scope + +- Covers normal scaling, negative 16-bit signed exponents, denormal-to-normal + promotion, normal-to-subnormal underflow with round-to-nearest-even ties, + overflow to `±Inf`, VOP3A `abs`/`neg`/`clamp`, and `D[31:16]` preservation. +- Refuses unsupported modifiers (`omod`, `neg`/`abs` on the integer exponent + `src1`, `op_sel`, unused `src2`). +- Negative controls: flushing denormals, truncating subnormals instead of + round-to-nearest-even, omitting `clamp`, and zeroing `D[31:16]` each differ + from the reference. +- Does not establish full-game execution. + +## Reproduction + +```powershell +.\tools\dev.ps1 +cmake --preset dev +cmake --build --preset dev --target compile_dxil native_store_replay +ctest --preset dev --no-tests=error -R '^native_ldexp_f16_' -V +``` diff --git a/docs/experiments/native-mad32-k.md b/docs/experiments/native-mad32-k.md new file mode 100644 index 0000000000..e6fde9205f --- /dev/null +++ b/docs/experiments/native-mad32-k.md @@ -0,0 +1,35 @@ +# Direct DXIL `v_madmk_f32` and `v_madak_f32` Translation + +Experiment for direct Compute and Pixel DXIL lowering of RDNA 2 unfused literal multiply-adds `v_madmk_f32` (`VOP2 0x20`: `S0 * K + S1`) and `v_madak_f32` (`VOP2 0x21`: `S0 * S1 + K`), addressing `#3249`, `#2935`, and `#3005`. + +## What Changed + +- Extended `unfused_mad` inside `DirectCompute::float_alu()` in [src/gfx1013_direct_compute.inl](../../src/gfx1013_direct_compute.inl) to cover `v_madmk_f32` and `v_madak_f32`: + - Uses the existing `#3005` unfused sequence: flush denormal inputs to signed zero (`ftz`), round `fmul` separately without fast-math/FMA contraction, flush the product, add the flushed addend (`S1` for `v_madmk_f32`, trailing 32-bit literal `K` for `v_madak_f32`), and flush the sum. + - Refuses invalid non-VOP2 forms (`i.wide || i.subword || i.dpp_control || permuted`). +- Added [tests/native_mad32_k_check.py](../../tests/native_mad32_k_check.py) and registered CTest entries in [tests/cmake/native_mad32_k.cmake](../../tests/cmake/native_mad32_k.cmake). + +## Verification + +Host: Windows 10.0.26100, `dev` preset, DXC `10.0.26100.0`. + +- `cmake --build --preset dev --target compile_dxil native_compute_ir_dump native_store_replay offscreen_check`: passed. +- `ctest --preset dev --no-tests=error -R '^(native_mad32_k_|native_mad32_)' -V`: + - `native_mad32_k_ir`: **passed** (`14` cases matched unfused FTZ model; `4` refusals matched). + - `native_mad32_k_controls`: **passed** (`14` cases compiled with separate `fmul`/`fadd` and no `tertiary.f32(i32 46,)` or fast-math flags; `4` refusals matched). + - `native_mad32_k_pixel_warp`: **passed** (`Microsoft Basic Render Driver`, `3` quad draws matched). + - `native_mad32_k_pixel_hardware`: **passed** (`NVIDIA Quadro M1000M`, `3` quad draws matched; debug layer unavailable). + - `native_mad32_k_compute_hardware`: **skipped** (`77`, `Intel(R) HD Graphics 530` `31.0.101.2111` requires SM 6.6 with wave32). + - Neighbor `native_mad32_controls` passed (`native_mad32_hardware` skipped `77` on HD 530). +- `ctest --preset dev --no-tests=error -R '^native_.*_(controls|ir)$' --output-on-failure`: **68/68 passed** (`0` failures, `0` skips). +- Sensitivity mutants in `src/gfx1013_direct_compute.inl` tested against `native_mad32_k_ir`: + - `swap_madmk_madak` (`v_madak_f32` vs `v_madmk_f32` literal role): failed (`rc=8`). + - `drop_ftz_input` (`auto x = a;`): failed (`rc=8`, `madmk_ftz_src0`). + - `drop_vop3_refusal` (bypass `literal_k` non-VOP2 check): failed (`rc=8`, `unsupported v_madmk_f32 encoding`). + - Clean tree restored, rebuilt `native_compute_ir_dump`, and `native_mad32_k_ir` passed again. +- `python -B tests/docs_links_check.py`: passed (`131` Markdown files, `631` links). + +## Limits + +- Direct Compute GPU execution (`native_mad32_k_compute_hardware`) could not run locally because `Intel(R) HD Graphics 530` lacks SM 6.6 wave32 (`77` skip). Compute IR, DXIL `controls`, and Pixel WARP + NVIDIA hardware draws are verified. +- `madak_ftz_sum`, `madmk_zero_inf_nan`, and `madak_neg_zero` (`pixel_safe=False`) are verified in IR/controls/compute fixtures rather than `--startup-pixel-words` because WARP/GPU drivers can differ on raw `-0.0`/qNaN payload patterns on pixel export. diff --git a/docs/experiments/native-packed-dot4.md b/docs/experiments/native-packed-dot4.md index 8df69808a4..c6fcc228f2 100644 --- a/docs/experiments/native-packed-dot4.md +++ b/docs/experiments/native-packed-dot4.md @@ -33,3 +33,28 @@ and a sparse EXEC mask. A third dispatch drops all clamp bits and verifies that the affected words change to the wrapping results. Each dispatch compares 2,048 words and 16 guards. The native replay requires shader model 6.6 and wave32. + +## VOP2 dot-accumulate + +The frontend also translates the VOP2 form `v_dot4c_i32_i8`. It is the signed +byte dot, with the destination register as its accumulator: +`D = dot4(S0, S1) + D`, wrapping modulo 2^32. It uses `Dot4AddI8Packed`, the +same as `v_dot4_i32_i8`. S0 may be a VGPR, an SGPR, an inline constant or a +literal; S1 is a VGPR. + +Only the plain 32-bit VOP2 encoding is accepted. The VOP3 form and any abs, +neg, clamp or output modifier are refused with "unsupported packed byte +dot-accumulate operand modifiers". DPP16 is refused with "unsupported DPP +arithmetic", and SDWA with "unimplemented direct SDWA operand profile". + +```powershell +cmake --build --preset dev --target compile_dxil native_store_replay +ctest --preset dev --no-tests=error -R '^native_dot4c_(ir|hardware)$' -V +``` + +`native_dot4c_ir` checks the DXIL for literal, SGPR, inline and VGPR sources, +and the DPP16 and SDWA refusals. `native_dot4c_hardware` dispatches two 32-lane +groups for each case and compares every output word against expected values. +The cases include accumulators that cross the signed 32-bit boundary in both +directions and a sparse EXEC mask, +under which inactive lanes keep their old destination value. diff --git a/docs/experiments/native-packed-f16-inline.md b/docs/experiments/native-packed-f16-inline.md new file mode 100644 index 0000000000..436284b8de --- /dev/null +++ b/docs/experiments/native-packed-f16-inline.md @@ -0,0 +1,37 @@ +# Inline constants in direct packed binary16 arithmetic and min/max (#3226) + +`src/gfx1013_direct_compute.inl` now accepts inline constant sources in both `DirectCompute::packed_f16_alu()` +(`v_pk_add_f16`, `v_pk_mul_f16`, `v_pk_fma_f16`) and `DirectCompute::packed_minmax()` (`v_pk_min_f16`, `v_pk_max_f16`, +`v_pk_min_{i,u}16`, `v_pk_max_{i,u}16`): + +- **Shared `packed_f16_inline_constant()` contract:** + - Inline binary16 float constants (`240..248`: `0.5`, `-0.5`, `1.0`, `-1.0`, `2.0`, `-2.0`, `4.0`, `-4.0`, `1/(2*pi)`) + decode to the low 16 bits (`0x3800`, `0xb800`, `0x3c00`, `0xbc00`, `0x4000`, `0xc000`, `0x4400`, `0xc400`, `0x3118`) + with bits `[31:16]` zeroed, matching `gfx1013` hardware (`op_sel_hi = 1` reads `+0.0`). + - Inline integer constants (`128..208`: `0..64` and `-1..-16`) decode to full 32-bit sign-extended values (`0..64`, + `0xFFFFFFFF..0xFFFFFFF0`). + - Integer `v_pk_min_{i,u}16` / `v_pk_max_{i,u}16` accept `128..208` and continue refusing float `240..248`. +- **Kept refusals:** `vcc_lo`/`vcc_hi`, `m0`, `exec_lo`/`exec_hi`, `scc`, `clamp` on packed f16 arithmetic, reserved + VOP3P bits, and non-default FP16 MODE writes keep their existing named diagnostics. + +## Fixture + +[`tests/native_packed_f16_inline_check.py`](../../tests/native_packed_f16_inline_check.py) via +[`tests/cmake/native_packed_f16_inline.cmake`](../../tests/cmake/native_packed_f16_inline.cmake) +(`native_packed_f16_inline_ir`, `native_packed_f16_inline_controls`, `native_packed_f16_inline_compute_hardware`, +`native_packed_f16_inline_pixel_warp`, `native_packed_f16_inline_pixel_hardware`): + +- Covers 24 cases: all 9 inline f16 constants `240..248`, `op_sel_hi` high-half zeroing (`+0.0`), `neg_lo`/`neg_hi` + (including `-0.0`), single-rounding FMA tie witness with inline `0.5` (`240`) + `2^-24` (`129`), inline integer + constants (`128..208`), `v_pk_min_f16`/`v_pk_max_f16` (including `193` NaN selection), and `v_pk_min_u16`/`v_pk_max_i16`, + plus 10 refusals. + +Measured on 28.11.2026, `main` `c7215add` plus this change, Windows 10.0.26100 (`dev` preset): +- `native_packed_f16_inline_ir` (24 cases + 10 refusals, `0.68s`), `native_packed_f16_inline_controls` (24 compiled + 10 + refusals, `1.47s`), `native_packed_f16_inline_pixel_warp` (12 paired draws / 24 cases, `2.18s`), and + `native_packed_f16_inline_pixel_hardware` (`Intel(R) HD Graphics 530`, 12 paired draws / 24 cases, `5.20s`) passed. +- `native_packed_f16_inline_compute_hardware` skipped (`77`, `Intel(R) HD Graphics 530` `31.0.101.2111`: requires shader + model 6.6 with wave32, so GPU compute readback is not measured). +- `^native_.*_(controls|ir)$`: 65/65 passed (`80.10s`). +- Four broken-lowering sensitivity checks (`replicate_high_half`, `use_f32_inline`, `zero_extend_neg_int`, + `drop_minmax_float_inline`) each failed `native_packed_f16_inline_ir` (exit `1`). diff --git a/docs/experiments/native-packed-f16.md b/docs/experiments/native-packed-f16.md index 69d9a6611b..4d5be91013 100644 --- a/docs/experiments/native-packed-f16.md +++ b/docs/experiments/native-packed-f16.md @@ -2,9 +2,11 @@ The direct compiler lowers the VOP3P `v_pk_add_f16`, `v_pk_mul_f16`, and `v_pk_fma_f16` instructions. Each result half has independent source-half -selectors and input negation. The packed word uses the normal EXEC-masked -destination write. The lowering accepts numeric registers, literal words, and -inline zero. +selectors, input negation, and optional VOP3P `clamp` (`[+0.0, 1.0]` +saturation per half after rounding, mapping `-0.0` and `NaN` to `+0.0`). The +packed word uses the normal EXEC-masked destination write. The lowering accepts +numeric registers, literal words, inline integers, and inline binary16 float +constants. ADD and MUL widen the inputs, use binary32 arithmetic, then round to binary16 with the existing integer nearest-even conversion. FMA forms the exact 22-bit @@ -16,10 +18,17 @@ binary16 midpoint the exact sum fell on. The final nearest-even conversion therefore agrees with a single binary16 rounding. The supported MODE preserves subnormals, rounds to nearest even, and leaves -`FP16_OVFL` clear. Clamp, unsupported source encodings, and undetermined or -unsupported MODE keep explicit refusals. NaN results use the canonical -`0x7e00` half from the project's arithmetic reference. NaN payload behavior -has not been measured on an RDNA2 device. +`FP16_OVFL` clear. Unused third-operand modifier fields on `add`/`mul`, +unsupported source encodings, and undetermined or unsupported MODE keep +explicit refusals. NaN results without `clamp` use the canonical `0x7e00` half +from the project's arithmetic reference. NaN payload behavior has not been +measured on an RDNA2 device. + +In addition to [native_packed_f16_check.py](../../tests/native_packed_f16_check.py), +[native_packed_f16_clamp_check.py](../../tests/native_packed_f16_clamp_check.py) +verifies VOP3P `clamp` across `v_pk_add_f16`, `v_pk_mul_f16`, and +`v_pk_fma_f16` in IR, DXIL controls, and lossless Pixel readbacks (WARP and +hardware), plus Compute replay where SM 6.6 wave32 is supported. ## Reproduction diff --git a/docs/experiments/native-packed-minmax.md b/docs/experiments/native-packed-minmax.md index f43edaf007..45892d7e76 100644 --- a/docs/experiments/native-packed-minmax.md +++ b/docs/experiments/native-packed-minmax.md @@ -1,14 +1,20 @@ # Packed 16-bit min/max in direct DXIL The native frontend lowers the six gfx1013 VOP3P forms -`v_pk_min/max_{i16,u16,f16}`. Each source supplies one halfword to each -result lane through `op_sel` and `op_sel_hi`. The instruction writes one -packed word and uses the existing vector write predicate. It accepts -numeric VGPRs and SGPRs, literal words and inline zero. It refuses -noncanonical unused source fields, negation and clamp. +`v_pk_min/max_{i16,u16,f16}` for both Compute and Pixel shaders. Each source +supplies one halfword to each result lane through `op_sel` and `op_sel_hi`. The +instruction writes one packed word and uses the existing vector write predicate. +It accepts numeric VGPRs and SGPRs, literal words and inline zero. It refuses +unused third-operand fields (`src2`, `op_sel[2]`, and third-operand +`neg_lo[2]`/`neg_hi[2]`). On the integer variants (`v_pk_min/max_{i16,u16}`), +`neg_lo`, `neg_hi` and `clamp` remain refused. Signed and unsigned integer lanes compare the selected 16-bit values. -Binary16 lanes compare the bit patterns using the startup HLSL +Binary16 lanes (`v_pk_min_f16`, `v_pk_max_f16`) support `neg_lo[1:0]`, +`neg_hi[1:0]` and `clamp`: `neg_lo`/`neg_hi` flip the sign bit of the selected +low/high binary16 input half per operand before comparison, and `clamp` +saturates each resulting half to `[+0.0, 1.0]` with `NaN -> +0.0` after min/max +selection. Binary16 lanes compare the bit patterns using the startup HLSL `minmax16_bits` contract. This preserves signed-zero ordering and subnormal encodings and prefers the numeric operand over a NaN. Two NaNs produce the repository's canonical quiet NaN, a payload convention that @@ -37,8 +43,11 @@ ctest --preset dev --no-tests=error -j 1 -R '^native_packed_minmax_' -V ``` The synthetic Compute replays compare 2,064 words per type, including the -untouched words and guards. A sparse EXEC replay checks that inactive lanes -keep their previous word. Swapping the low and high selector groups changes -the binary16 readback. The Pixel fixture exports each resulting -halfword as an exactly representable binary32 integer and checks both -results. Compute replay requires shader model 6.6 and wave32. +untouched words and guards, plus 9 packed modifier cases (`MOD_CASES` for +`neg_lo`, `neg_hi`, and `clamp` across both `v_pk_min_f16` and `v_pk_max_f16`) +when validating `f16`. A sparse EXEC replay checks that inactive lanes keep +their previous word. Swapping the low and high selector groups changes the +binary16 readback. The Pixel fixture exports each resulting halfword as an +exactly representable binary32 integer and checks both results across 4 integer +cases per integer type and 13 `f16` cases (4 base cases plus 9 modifier cases). +Compute replay requires shader model 6.6 and wave32. diff --git a/docs/experiments/native-rcp-iflag-f32.md b/docs/experiments/native-rcp-iflag-f32.md new file mode 100644 index 0000000000..ad586d23e2 --- /dev/null +++ b/docs/experiments/native-rcp-iflag-f32.md @@ -0,0 +1,32 @@ +# Direct DXIL `v_rcp_iflag_f32` Translation + +Experiment for direct Compute and Pixel DXIL lowering of `v_rcp_iflag_f32` (`VOP1 0x2b`, `VOP3 0x1ab`, SDWA, DPP16), addressing `#3252` and `#2935`. + +## What Changed + +- [src/gfx1013_compute_alu.inl](../../src/gfx1013_compute_alu.inl): added `v_rcp_iflag_f32` alongside `v_rcp_f32` (`1.0 / {0}`, also enabling `alu_rules` lookup in `DirectCompute::dpp()`). +- [src/gfx1013_compute_opcodes.inl](../../src/gfx1013_compute_opcodes.inl): added `case 0x2b: return "v_rcp_iflag_f32";`. +- [src/gfx1013_compute_native.cpp](../../src/gfx1013_compute_native.cpp): added `"v_rcp_iflag_f32"` to the SDWA `floats` set next to `"v_rcp_f32"`. +- [src/gfx1013_direct_compute.inl](../../src/gfx1013_direct_compute.inl): lowered `v_rcp_iflag_f32` identically to `v_rcp_f32` (`fdiv float 1.000000e+00, a`) in `DirectCompute::float_alu()`. +- Added [tests/native_rcp_iflag_check.py](../../tests/native_rcp_iflag_check.py) and registered CTest entries in [tests/cmake/native_rcp_iflag.cmake](../../tests/cmake/native_rcp_iflag.cmake). + +## Verification + +Host: Windows 10.0.26100, `dev` preset, DXC `10.0.26100.0`. + +- `cmake --build --preset dev --target compile_dxil native_store_replay offscreen_check native_compute_ir_dump`: passed. +- `ctest --preset dev --no-tests=error -R '^native_rcp_iflag_' -V`: + - `native_rcp_iflag_controls`: **passed** (`16` Compute + `4` Pixel cases compiled identically to `v_rcp_f32` DXIL; `2` refusals matched). + - `native_rcp_iflag_pixel_warp`: **passed** (`Microsoft Basic Render Driver`, `4` quad draws matched). + - `native_rcp_iflag_pixel_hardware`: **passed** (`NVIDIA Quadro M1000M`, `4` quad draws matched; debug layer unavailable). + - `native_rcp_iflag_compute_hardware`: **skipped** (`77`, `Intel(R) HD Graphics 530` `31.0.101.2111` requires SM 6.6 with wave32). +- `ctest --preset dev --no-tests=error -R '^native_.*_(controls|ir)$' --output-on-failure`: **68/68 passed** (`0` failures, `0` skips). +- Sensitivity mutants verified against `native_rcp_iflag_controls`: + - `drop_direct_iflag` (`src/gfx1013_direct_compute.inl`): failed (`rc=8`, `direct DXIL lowering for v_rcp_iflag_f32`). + - `drop_sdwa_iflag` (`src/gfx1013_compute_native.cpp`): failed (`rc=8`, `unimplemented direct SDWA operand profile`). + - Clean tree restored, rebuilt `compile_dxil`, and `native_rcp_iflag_controls` passed again. +- `python -B tests/docs_links_check.py`: passed (`131` Markdown files, `631` links). + +## Limits + +- Direct Compute GPU execution (`native_rcp_iflag_compute_hardware`) could not run locally because `Intel(R) HD Graphics 530` lacks SM 6.6 wave32 (`77` skip). Compute DXIL (`controls`), Pixel WARP, and Pixel hardware (`NVIDIA Quadro M1000M`) are verified on power-of-two operands (`0 ULP`); non-power-of-two reciprocal ULP tolerance matches DXIL `fdiv` hardware behavior. diff --git a/docs/experiments/native-round-f16.md b/docs/experiments/native-round-f16.md new file mode 100644 index 0000000000..393fbdbcc9 --- /dev/null +++ b/docs/experiments/native-round-f16.md @@ -0,0 +1,25 @@ +# Direct DXIL `v_floor_f16`, `v_ceil_f16`, `v_trunc_f16`, and `v_rndne_f16` + +Lowers `v_floor_f16` (VOP1 `0x5b` / VOP3A `0x1db`), `v_ceil_f16` (VOP1 `0x5c` / +VOP3A `0x1dc`), `v_trunc_f16` (VOP1 `0x5d` / VOP3A `0x1dd`), and `v_rndne_f16` +(VOP1 `0x5e` / VOP3A `0x1de`) in the native direct-DXIL compute path +(`src/gfx1013_direct_compute.inl`) using exact 32-bit integer IEEE-754 binary16 +rounding while preserving `D[31:16]`. + +## Scope + +- Covers `-0.0h`, `±min_sub`, `0.5h`, `1.5h`, `2.5h`, `-1.5h`, and `1023.5h` + (mantissa-to-exponent carry) across VOP1 and VOP3A with pre-seeded `D[31:16]`. +- Refuses unsupported modifiers (`omod`, `op_sel`, unused VOP3 sources). +- Negative controls: round-half-away-from-zero, losing `-0.0h`, and zeroing + `D[31:16]` each differ from the reference. +- Does not establish full-game execution. + +## Reproduction + +```powershell +.\tools\dev.ps1 +cmake --preset dev +cmake --build --preset dev --target compile_dxil native_store_replay +ctest --preset dev --no-tests=error -R '^native_round_f16_' -V +``` diff --git a/docs/experiments/native-salu64-ops.md b/docs/experiments/native-salu64-ops.md index af2388ef64..8f89595cfa 100644 --- a/docs/experiments/native-salu64-ops.md +++ b/docs/experiments/native-salu64-ops.md @@ -7,7 +7,10 @@ offset, writes both words of an aligned SGPR pair, and preserves SCC. `s_not_b64` complements both words and sets SCC when either result word is nonzero. Both take aligned SGPR pairs or constants, with sign extension for inline negatives and zero extension for other integers. They can -write VCC as a pair. EXEC destinations are refused. +write VCC as a pair. `s_bfm_b64` and `s_not_b64` may also write EXEC, as both +words, in wave32 and wave64. `s_cselect_b64` still refuses EXEC destinations. +`s_not_b64` and `s_cselect_b64` also take VCC and EXEC as 64-bit sources +(`tests/native_s_not_b64_exec_check.py`, `ctest --preset dev --no-tests=error -R '^native_s_not_b64_exec_'`). Direct compute also accepts `s_bitreplicate_b64_b32 exec, imm`, writing both EXEC words and preserving SCC. Wave32 lane activity uses only `exec_lo`. @@ -21,10 +24,13 @@ the raw width 64 wrapping to 0. The select cases cover both SCC values, an SGPR pair, inline -1 and the literal `0x80000001`. The complement cases include zero output and output with only the high word nonzero. Hardware without shader model 6.6 and wave32 support returns skip code 77. +`native_wave64_exec_salu_hardware` covers `s_bfm_b64 exec, 16, 0` and `exec, 32, 32` in wave64, 64- and +128-thread groups (the wave32 EXEC destination is accepted but not run), checking which lanes stay active through a per-lane store. ```powershell cmake --build --preset dev --target compile_dxil native_store_replay ctest --preset dev --no-tests=error -R '^native_salu64_(controls|hardware)$' +ctest --preset dev --no-tests=error -R '^native_wave64_exec_salu_hardware$' ``` Results: on an NVIDIA GeForce RTX 5080 (Windows 11, DXC from the Windows SDK 10.0.26100) all fifteen cases diff --git a/docs/experiments/native-saveexec-wrexec.md b/docs/experiments/native-saveexec-wrexec.md new file mode 100644 index 0000000000..91c910c592 --- /dev/null +++ b/docs/experiments/native-saveexec-wrexec.md @@ -0,0 +1,48 @@ +# Remaining SOP1 `*_saveexec_*` and `*_wrexec_*` instructions in direct Compute DXIL + +Issue #3296 (Refs #2935) lowers the remaining 12 SOP1 EXEC-mask instructions in +the direct Compute DXIL path (`src/gfx1013_direct_compute.inl`), updates +`uses_scc_after()` so `SCC` liveness treats all scalar mask and SAVEEXEC/WREXEC +definitions consistently, and updates `transfer()` in +`src/gfx1013_compute_native.cpp` so all wave32 `*_saveexec_b32` and +`*_wrexec_b32` instructions clear symbolic provenance on both the destination +register and `EXEC_LO`. + +## Lowered Instructions + +- **Wave32 (`SOP1`, 32-bit):** + - `s_xor_saveexec_b32` (`0x3e`): `D = EXEC_LO; EXEC_LO = S0 ^ EXEC_LO` + - `s_andn2_saveexec_b32` (`0x3f`): `D = EXEC_LO; EXEC_LO = S0 & ~EXEC_LO` + - `s_orn2_saveexec_b32` (`0x40`): `D = EXEC_LO; EXEC_LO = S0 | ~EXEC_LO` + - `s_nand_saveexec_b32` (`0x41`): `D = EXEC_LO; EXEC_LO = ~(S0 & EXEC_LO)` + - `s_nor_saveexec_b32` (`0x42`): `D = EXEC_LO; EXEC_LO = ~(S0 | EXEC_LO)` + - `s_xnor_saveexec_b32` (`0x43`): `D = EXEC_LO; EXEC_LO = ~(S0 ^ EXEC_LO)` + - `s_andn1_saveexec_b32` (`0x44`): `D = EXEC_LO; EXEC_LO = ~S0 & EXEC_LO` + - `s_orn1_saveexec_b32` (`0x45`): `D = EXEC_LO; EXEC_LO = ~S0 | EXEC_LO` + - `s_andn1_wrexec_b32` (`0x46`): `EXEC_LO = ~S0 & EXEC_LO; D = EXEC_LO` +- **Wave64 (`SOP1`, 64-bit):** + - `s_andn1_saveexec_b64` (`0x37`): `D = EXEC; EXEC = ~S0 & EXEC` + - `s_orn1_saveexec_b64` (`0x38`): `D = EXEC; EXEC = ~S0 | EXEC` + - `s_andn1_wrexec_b64` (`0x39`): `EXEC = ~S0 & EXEC; D = EXEC` + +All 12 instructions update `SCC` from `(new_exec != 0)` across all participating +bits (`EXEC_LO` in wave32; both `EXEC_LO` and `EXEC_HI` in wave64). + +## Destination & Mode Rules + +- Newly lowered wave32 ops require `dst <= 107` (`SGPR` / `VCC`), refusing + `M0`/`EXEC_LO` destinations with `unsupported wave32 SAVEEXEC destination`, and + are restricted to wave32 compute shaders. +- `s_andn1_wrexec_b64` matches `s_andn2_wrexec_b64` rules (`compute && wave64`, + even SGPR pair `<= 104` for both `dst` and `src`). + +## Verification + +- [native_saveexec_wrexec_check.py](../../tests/native_saveexec_wrexec_check.py) + covers all 12 instructions across non-zero (`SCC = 1`), zero-result + (`SCC = 0`), high-word-only (`SCC = 1` from `EXEC_HI`), `dst == src` aliasing, + `vcc_lo`/`exec_lo`/inline/literal sources, partial-wave dispatches, and 8 + negative operand/mode refusal cases. +- CMake/CTest targets (`tests/cmake/native_saveexec_wrexec.cmake`): + `native_saveexec_wrexec_ir`, `native_saveexec_wrexec_controls`, and + `native_saveexec_wrexec_hardware`. diff --git a/docs/experiments/native-sdwa-f16.md b/docs/experiments/native-sdwa-f16.md index 7bd7940738..9d308123a0 100644 --- a/docs/experiments/native-sdwa-f16.md +++ b/docs/experiments/native-sdwa-f16.md @@ -1,19 +1,22 @@ # SDWA binary16 arithmetic in direct compute Issue #2963 adds SDWA to `v_add_f16`, `v_sub_f16`, `v_subrev_f16` and `v_mul_f16`. -Each source must be a VGPR. WORD_0 and DWORD read the low half, and WORD_1 reads the -high half. Source abs clears the binary16 sign bit before neg toggles it. The compiler +Each source can be a VGPR, SGPR, or inline constant. WORD_0 and DWORD read the low +half, and WORD_1 reads the high half. Inline floats use a low-half binary16 encoding +with a zero high half. Source abs clears the binary16 sign bit before neg toggles it. The compiler widens the halves to binary32, performs the operation, and rounds once to binary16 using the integer nearest-even path from the [plain forms](f16-alu-direct.md). The binary16 rounding and denormal mode requirements apply to both forms. WORD_0 and WORD_1 destinations accept UNUSED_PAD, which zeroes the other half, and UNUSED_PRESERVE, which copies it from the old destination. DWORD and byte -destinations, UNUSED_SEXT, byte sources, source sext, scalar and constant sources, +destinations, UNUSED_SEXT, byte sources, source sext, literals, clamp, and output modifiers are refused. SDWA min and max remain refused. Direct wave32 compute SDWA VOPC compares can write a 32-bit mask to `vcc_hi` and read it as a scalar source. +Direct compute `v_cvt_f32_f16_sdwa` supports clamp with WORD_0 or WORD_1 and DWORD/UNUSED_PAD (NaN and -0 become +0), and still refuses omod. + ## Fixture The wave32 GPU fixture also covers SDWA packed RTZ f32-to-f16 placement and add-with-carry, including per-lane VCC input and output before destination placement. @@ -35,8 +38,9 @@ The product of `7bff` and `4000` overflows to `7c000000` with high-half pad. The add of `7e01` and `3c00` expects a NaN in the low half and exactly `a55a` in the preserved high half. The NaN payload and sign may vary. -Compile-only controls cover DWORD destination, BYTE_1 source, SGPR source, -inline constant source, source sext, UNUSED_SEXT, clamp, omod, min and max. +Compile-only controls cover DWORD destination, BYTE_1 source, source sext, +UNUSED_SEXT, clamp, omod, min and max. The scalar-source fixture separately +covers SGPR and inline source selection, literal refusal, and scalar source sext. Swapping WORD_0 and WORD_1 on either source and forcing UNUSED_PRESERVE to pad are manual lowering mutations that must fail the readback comparison. diff --git a/docs/experiments/native-slot67-wave-size.md b/docs/experiments/native-slot67-wave-size.md new file mode 100644 index 0000000000..fb745305a5 --- /dev/null +++ b/docs/experiments/native-slot67-wave-size.md @@ -0,0 +1,72 @@ +# Slot 67 wave size in direct compute + +Issue #2999. Slot 67 compute requests carry no documented wave size, and direct compute used to compile every +`.c67` request as wave32. Bit 20 of `.sa` dword 4 (little-endian; bits 15:0 are Z) now sets +`ComputeRequest::wave32`: set means wave32, clear means wave64. A `.sa` that is not 28 bytes is still refused. + +## Why this bit + +This is an inference from a local capture of 2,689 slot 67 requests, not from documentation. The capture was +decoded up to the first `s_endpgm`, and only counts and instruction shape were kept. + +- Every program with a `*_saveexec_b32` and no `*_saveexec_b64` has the bit set (1,385 of 1,385). Every program + with a `*_saveexec_b64` and no `*_saveexec_b32` has it clear (565 of 565). +- The next best bit of `.sa` or `.sb` agrees on 87%: bit 5 of dword 3, the X = 32 bit. +- `v_mbcnt_hi_u32_b32` appears only with the bit clear (197 programs). Every bit-clear program that uses + `v_mbcnt_lo_u32_b32` also uses `v_mbcnt_hi_u32_b32`. The 84 bit-set programs that use `v_mbcnt_lo_u32_b32` + never use `v_mbcnt_hi_u32_b32`. +- Group sizes mostly follow the bit. Of the 784 requests with a 64-thread group, 739 have it clear. Of the 1,433 + with a 32-thread group, 1,405 have it set. +- Bits 31:16 of dword 4 take only two values in the capture, 0x0000 and 0x0010. + +## Translation + +The direct DXIL route of `translate_compute` compiles a wave64 request through the wave64 path that +`translate_compute_container` already uses for a stage without `wave32` (two 32-lane host waves per guest wave). +A wave64 request whose group has at most 32 threads stays on the wave32 model, as before the wave size was read. +Its one guest wave only has lanes 0..31, so EXEC's high word is zero and `v_mbcnt_hi` adds nothing for its lanes. +One known difference remains: a wave64 compare or carry-out also writes zero to the high word of an SGPR pair +destination, and the wave32 model leaves that word as it was. The legacy HLSL profile and the container route are +unchanged. + +Compute requests keep their `29cs` keys, and revision-28 archives are still read. Published native compute manifests now include `native 1`. +`compile_dxil --watch` rebuilds an older native output under the same key. The stand-in refuses it until +the rebuilt manifest appears, looking again on subsequent dispatches on the ManifestRetry schedule (1 s, doubling up to 32 s). An unmarked +manifest with a `.cs.hlsl` sidecar is a Python translation and stays usable. `--requests` rebuilds +every output, the frontend cache is keyed on a hash of the compiler sources, and the in-process route +translates again in each process. A native publish now removes a `.cs.hlsl` left by the Python translator, +so the pair cannot pass as a Python output. One case is not detected: a directory where an earlier +`compile_dxil` already republished a Python-translated key keeps that key's `.cs.hlsl` next to an unmarked +native manifest. Rerun `--requests` into such a directory once. The reload of a refused +manifest is not covered by a test; each check runs a new process. + +Measured with `compile_dxil --jobs 8 gfx1013-direct-cs@36 --requests` on `cpp-migration` `e0d83759`, before and +after: + +| Requests | Compiled before | Compiled after | Newly compiled | No longer compiled | +|---|---|---|---|---| +| Capture, 2,689 | 389 | 393 | 46 | 42 | +| One start-up run, 2,718 | 402 | 406 | 46 | 42 | + +- The 46 newly compiled requests are wave64 programs with 64-thread groups. +- The 42 that no longer compile are wave64 programs that the wave32 model used to accept. They now stop at + "multi-wave64 exchange requires converged group control flow", a limit of the existing wave64 path. + +## Fixture + +`tests/native_slot67_wave_size_check.py` builds the same program as three slot 67 requests that differ in this +bit and in the group size. The program stores `v_mbcnt_lo` followed by `v_mbcnt_hi` at each thread's index. The +CPU reference expects: + +- with the bit clear and 64-thread groups, `tid % 64`; +- with the bit set and 64-thread groups, `tid % 32`; +- with the bit clear and 32-thread groups, `tid % 32`. + +The fixture also checks every untouched buffer word. + +```powershell +ctest --preset dev --no-tests=error -R '^native_slot67_wave_size_hardware$' -V +``` + +The fixture returns 77 when replay reports that the required adapter capabilities are unavailable. Source-built +fixtures that relied on the wave32 default now set the bit. diff --git a/docs/experiments/patch-manifests.md b/docs/experiments/patch-manifests.md index c5ab890304..c755a9a746 100644 --- a/docs/experiments/patch-manifests.md +++ b/docs/experiments/patch-manifests.md @@ -22,14 +22,47 @@ bytes = "90c3" # the replacement, lowercase hex ``` - **Hash gate:** the manifest applies only to the file whose SHA-256 equals `input_sha256`. Any other input is refused with `manifest is for another input`. +- **Bytes already read:** `load_data(manifest, data)` is `load` for a caller that has already read the input: it hashes `data`, so the bytes that pass the gate are the bytes the caller goes on to use, even if the file changes in between. - **No partial apply:** the whole manifest is validated, and the input hash compared, before the loader returns anything. One bad patch refuses the manifest. - **Every patch** needs a unique `id`, a `kind`, and non-empty `why` and `remove_when`. - **Strict keys:** unknown keys and missing keys are refused at every level, so a misspelled key fails instead of being ignored. -- **Kinds:** `kind` must be a string, and only `memory` is defined. `hook` and `data` are refused as `not supported` until their stages land. +- **Nesting:** `tomllib` recurses once per nested array or inline table. A manifest nested past the interpreter's recursion limit is refused with `manifest is nested too deeply to parse`, and the CLI exits with status 1 instead of printing a traceback. +- **Kinds:** `kind` must be a string, and `memory` and `shader` are defined. `hook`, `data` and any other kind are refused as `not supported`. - **Memory patches:** `bytes` must be non-empty, and every byte it replaces needs an RVA below 2^32: a 1-byte patch at `0xffffffff` is accepted, a 2-byte one is not. Two memory patches may not overlap. Whether the span lies in a mapped section is checked later, by the runtime stage. - **Original bytes are never stored:** `expect_sha256` is a hash of the bytes the patch replaces. The loader only checks its shape; the memory stage will compare it with the mapped image. - **Reporting:** the loader returns `manifest_sha256`, the SHA-256 of the manifest file's bytes, with the patch ids, for run reports to record. +### Shader patches + +A shader patch names the translation files of one shader cache key, for the runtime to read instead +of the shader cache's. The loader checks their shape only. Reading and hashing the files, and +serving them, belong to a later consumer; none exists yet. + +```toml +[[patch]] +id = "s001" +kind = "shader" +why = "" +remove_when = "" +key = "0123456789abcdef" # the cache key, 16 lowercase hex digits +pipeline = "compute" # graphics, compute or mesh86 +revision = "x2w-startup-shader-29cs" +files = [{ ext = ".txt", file = "s001.txt", sha256 = "" }, + { ext = ".cs.cso", file = "s001.cs.cso", sha256 = "" }] +``` + +| `pipeline` | `revision` form | Files the runtime reads | Required | +|---|---|---|---| +| `graphics` | `x2w-startup-shader-` | `.txt`, `.vs.cso`, `.ps.cso` | all three | +| `compute` | `x2w-startup-shader-cs` | `.txt`, `.cs.cso`, `.cs.hlsl` | `.txt`, `.cs.cso` | +| `mesh86` | `x2w-startup-mesh-86-` | `.mesh86.txt`, `.ms.cso`, `.ps.cso` | `.mesh86.txt`, `.ms.cso` | + +The runtime looks for a compute key's `.cs.hlsl`, the Python translator's output, only when its `.txt` has no `native` line, and reads a mesh86 key's `.ps.cso` only for a request with a pixel shader. The loader does not read the `.txt` or the request, so both stay optional. + +- **Revision:** `revision` must have the form of the pipeline's key revision in the runtime (`src/startup_stubs/d3d12_draw.inl`, `src/startup_stubs/mesh86_cache.inl`), where `` is a number without leading zeros, so another pipeline's revision is refused. The loader does not check that `` is the runtime's current one: the runtime bumps it often, and a new revision changes every key. A later consumer that serves the files must compare it with the runtime; none exists yet. +- **Files:** each entry is a table of exactly `ext`, `file` and `sha256`. `ext` is one of the pipeline's files and is listed once; the required ones must all be there. `file` is a bare file name, for a later consumer to resolve in the manifest's directory: a `/` or `\`, a drive (`:`), `.` and `..` are refused. That consumer is the runtime, which runs on Windows, so a name Windows would not open as a file of that name in the directory is refused too: one with `<`, `>`, `"`, `|`, `?`, `*` or a control character, one ending in a dot or a space (Windows drops them), and a device name (`CON`, `PRN`, `AUX`, `NUL`, `COM0`-`COM9`, `LPT0`-`LPT9`, `COM` and `LPT` with a superscript 1 to 3, `CONIN$`, `CONOUT$`) in any case, alone or before an extension, as Microsoft's "Naming Files, Paths, and Namespaces" lists them. `sha256` is lowercase. +- **One patch per key:** two shader patches for the same `key` are refused. Shader patches take no part in the memory overlap check. + Input-specific manifests stay local under `game-files/patches/`, which is gitignored. Do not publish them or the hashes in them. @@ -45,11 +78,17 @@ On Windows: `ctest --preset dev --no-tests=error -R '^patch_manifest_controls$' The check builds a synthetic PE32+ at run time with `build_pe32_plus` from `tests/call_evidence_check.py`. Its manifest replaces two bytes at the start of the `.rdata` section. -- **Bound input:** the manifest loads, and the CLI prints the manifest hash and `p001`. -- **Wrong input:** the same image with its last byte flipped makes the CLI exit with status 1 and `manifest is for another input`, with nothing on stdout. -- **Malformed manifests:** each of these is refused with its own message: a misspelled key, kind `hook`, a list or inline-table `kind`, a missing `why`, a blank `remove_when`, a duplicate id, overlapping patches, odd-length `bytes`, a boolean `rva`, a 2-byte patch at `0xffffffff`, an upper-case `input_sha256`, no patches, and a TOML syntax error. +- **Bound input:** the manifest loads with every field of `p001` as written, and the CLI prints the manifest hash and `p001`. +- **Wrong input:** the same image with its last byte flipped makes the CLI exit with status 1 and `manifest is for another input`, with nothing on stdout. An input file that does not exist also gives status 1, with a `patch manifest: [Errno ...]` message and no traceback. +- **Malformed manifests:** each of these is refused with its own message: a misspelled key, kind `hook`, a list or inline-table `kind`, a missing `why`, a blank `remove_when`, a duplicate id, overlapping patches, odd-length or empty `bytes`, a boolean `rva`, a 2-byte patch at `0xffffffff`, an upper-case `input_sha256`, an `input_sha256` or `expect_sha256` with trailing text, no patches, and a TOML syntax error. - **Edge of the RVA range:** a 1-byte patch at `0xffffffff` loads. +- **Memory patches side by side:** four memory patches load when listed in descending RVA, three of them adjacent and one at RVA 0. Their ids follow neither the RVA order nor its reverse, so no order by id is an order by address. Two patches that share one byte are refused as an overlap, in either order. - **Wrong-type `kind` through the CLI:** exit status 1 with a `patch manifest:` message, and no traceback. +- **Bytes already read:** `load_data` on the image's bytes returns what `load` returns; on the flipped image it is refused as `for another input`. With the input file then replaced by the flipped image, `load_data` on the original bytes still loads and `load` on the file is refused. +- **Shader patches:** one per pipeline loads beside a memory patch, mesh86 with and without its `.ps.cso`, compute with and without its `.cs.hlsl`, and the CLI lists their ids. Each of these is refused with its own message: a 15-digit key, a 17-digit one, an upper-case key, an unknown pipeline, another pipeline's revision (compute, graphics and the mesh57 cache's), a revision without its number, one with a leading zero, an integer revision, an empty `files`, an unknown or a missing file key, another pipeline's extension, an extension listed twice, a missing required file (compute and graphics), an empty `file`, a `file` with a `/` or a `\`, an absolute one, one with a drive, `..` and `.`, a `file` with `*`, `?`, `<`, `>`, `|`, `"`, a tab or U+0001, `s001.txt.` and `s001.txt ` (trailing space), the device names `NUL`, `CON.txt`, `Com1`, `nul .txt`, `CONIN$`, `conout$.txt`, `COM` + U+00B9 and `lpt` + U+00B3 + `.cso`, an upper-case `sha256`, two patches for one key, a memory key on a shader patch, a missing `files`, and kind `shaders`. +- **Files pinned:** each pipeline's extensions are the ones its loader in the runtime reads for a key (`cache_path(..., L"", key, ext)` in `d3d12_draw.inl`, `d3d12_compute_dispatch.inl` and `mesh86_cache.inl`, and mesh86's `load_stage`), and the optional ones are mesh86's `.ps.cso`, read only for a request with a pixel shader, and compute's `.cs.hlsl`, looked for only when the `.txt` has no `native` line (`NativeComputeOutput::unmarked`). +- **Revision forms pinned:** the runtime's current revision of each pipeline, read from its source, has the loader's form. A bump that only raises `` keeps the check green. The fixture uses revisions of each form that are not the runtime's current ones. +- **Deep nesting:** with the recursion limit set to 1000 inside the test, an array nested 2000 deep is refused as `nested too deeply`, by `parse` and through the CLI (status 1, nothing on stdout, no traceback). Shape control: one nested 50 deep gets past `tomllib` and is refused only for its unknown key. - **Mutations:** | Change | Result | @@ -59,6 +98,48 @@ The check builds a synthetic PE32+ at run time with `build_pe32_plus` from | String check on `kind` removed | Both wrong-type cases raise `TypeError`, and the CLI prints a traceback. | | Span check removed | The 2-byte patch at `0xffffffff` is accepted. | | Span check off by one (`>=`) | The 1-byte case at `0xffffffff` is refused. | + | `load_data` compares the target with itself | The flipped image is accepted by `load_data`. | + | Revision form check removed | The other-pipeline, number-less and leading-zero revision cases are accepted. | + | The runtime's graphics revision gets a suffix (`x2w-startup-shader-29b`) | The revision-form pin fails for graphics. | + | The runtime's graphics revision is bumped (`-29` to `-30`), loader untouched | Control: the check stays green. | + | Bare-name check on `file` removed | The six non-bare `file` cases are accepted. | + | Check for `<>"\|?*` in `file` removed | The six cases with one of those characters are accepted. | + | Control-character check on `file` removed | The tab and U+0001 cases are accepted. | + | Trailing dot or space check removed; or it checks the dot only; or the space only | Both cases; the trailing space; the trailing dot are accepted. | + | Device-name check removed | The eight device-name cases are accepted. | + | Device names matched case-sensitively | The upper- and mixed-case ones (`NUL`, `CON.txt`, `Com1`, `CONIN$`, `COM` + U+00B9) are accepted. | + | Device names matched as a prefix (`match`, not `fullmatch`) | `console.txt`, `nulls.cso`, `com10.txt` and `conin.txt` are refused. | + | Device name matched against the whole `file`, not the part before the first dot | `CON.txt`, `nul .txt`, `conout$.txt` and `lpt` + U+00B3 + `.cso` are accepted. | + | Trailing spaces kept on the part before the dot | `nul .txt` is accepted. | + | `CONIN$` and `CONOUT$` dropped from the device names | Both cases are accepted. | + | Superscript `COM` and `LPT` dropped from the device names | Both cases are accepted. | + | The runtime reads `.vx.cso` instead of `.vs.cso` (`d3d12_draw.inl`) | The files pin fails for graphics. | + | Required-file check removed | Both missing-file cases are accepted. | + | Same-key check removed | The two-patches-for-one-key case is accepted. | + | `RecursionError` no longer caught | The deep-nesting case raises `RecursionError`. | + | `SHA256.fullmatch` changed to `match` | The `input_sha256` and `expect_sha256` cases with trailing text are accepted. | + | Shader `KEY.fullmatch` changed to `match` | The 17-digit key is accepted. | + | `bytes` pattern allows zero digit pairs (`*`) | The empty `bytes` case is accepted. | + | Overlap check `<` changed to `<=` | The side-by-side case refuses its adjacent patches. | + | Spans no longer sorted before the overlap check | The side-by-side case refuses its descending order. | + | Spans sorted by id (`key=lambda s: s[2]`), ascending or descending, instead of by address | The side-by-side case refuses its patches, whose ids do not follow the addresses. | + | `rva` lower bound `0 <=` changed to `0 <` | The side-by-side case refuses its patch at RVA 0. | + | `why` dropped from a memory patch | The bound-input case finds a patch without `why`. | + | The CLI catches `ValueError` only | The missing input file ends in a traceback. | Measured on 27.11.2026 on Windows 11 Pro with Python 3.14: 3 tests, all passed. The `python-linux` CI job ran the first version of the check with Python 3.12 and passed. + +With the nesting, shader, `load_data` and side-by-side memory cases: 9 tests, all passed on Linux +(Debian 13) with Python 3.13.5 and pefile 2024.8.26. Each mutation in the table above made the check +fail, and the revision-bump control stayed green. Not yet run on Windows. + +With the side-by-side ids out of step with the addresses: 9 tests, all passed on Linux (Debian 13) with +Python 3.13.5 and pefile 2024.8.26. The ascending id sort above, which passed before this change, and the +descending one now fail the check on the side-by-side case. A sort by span end (`key=lambda s: s[1]`) +still passes: for spans of at least one byte it flags an overlap exactly when the sort by start does, so +it is not counted as a survivor. + +With the Windows file-name refusals (review of `4968e124`): 9 tests, all passed on Linux (Debian 13) with +Python 3.13.5 and pefile 2024.8.26. Each of the twelve mutations of the refusal in the table above made the +check fail, and the 24 earlier loader mutations still did. Not run on Windows. diff --git a/docs/experiments/startup-compute-native-dispatch.md b/docs/experiments/startup-compute-native-dispatch.md index bafceee393..2af49da9b7 100644 --- a/docs/experiments/startup-compute-native-dispatch.md +++ b/docs/experiments/startup-compute-native-dispatch.md @@ -80,7 +80,13 @@ ctest --preset dev --no-tests=error -V -R '^(startup_compute_dispatch(_.*)?|star ## Limits - Compute only. Graphics pipelines are not translated in-process. -- A scalar buffer load, a texture, a sampler and the typed, half and indexed views are refused. +- A scalar buffer load, a texture, a sampler and the typed, half and indexed views are refused. This is the + in-process route. The published-manifest route (`.txt` from `compile_dxil --requests`) binds a + title's 1D, 2D, 2D-array and 3D texture SRV (`srv N tex1d|tex2d|tex2da|tex3d table R B`). For 1D, 2D-array + and 3D the title's view must be described, have the manifest's dimension and fit its texture, otherwise the + Dispatch is refused (on a dimension mismatch the draw path binds a null view instead). "Fits" is + `address_view_fits`: the view format is the storage format or a member of its typeless family, the mip and + slice range lie inside the texture, and ResourceMinLODClamp is 0. Cube texture SRVs are not published. - One descriptor shape was dispatched: stride 4 and 320 records, for the input and for the output. - An indirect Dispatch of a natively translated program was not run. - A captured request starts with a 36-byte prefix of `v_nop` words before `s_inst_prefetch`. The route passes diff --git a/docs/experiments/startup-image-cube.md b/docs/experiments/startup-image-cube.md new file mode 100644 index 0000000000..a4f6b9d85d --- /dev/null +++ b/docs/experiments/startup-image-cube.md @@ -0,0 +1,83 @@ +# Cube image sampling in gfx2hlsl (#2943) + +`tools/startup/gfx2hlsl.py` lowers `image_sample`, `image_sample_lz`, `image_sample_l` and `image_sample_b` with +`dim:SQ_RSRC_IMG_CUBE` to `TextureCube` `Sample`, `SampleLevel` and `SampleBias` (outside a pixel stage the +implicit-LOD form samples level 0 and the bias form is refused, as for 2D textures), and +writes the manifest kind `texcube` for the binding. Before, the stage was refused with +`image dimension SQ_RSRC_IMG_CUBE`. + +## The address + +On gfx10 a cube sample takes three address dwords after any bias: the face coordinates `s` and `t` and the face +id. Mesa's `prepare_cube_coords` (`src/amd/common/nir/ac_nir_lower_tex.c`, read at Mesa 25.0.7 through the +`openbsd/xenocara` mirror, commit `d31967950e30`) builds `s = sc / |ma| + 1.5` and `t = tc / |ma| + 1.5` from +`v_cubesc`, `v_cubetc` and `v_cubema`, and a cube-array id as `8 * layer + face`. LLVM 15.0.7 +`ConstantFoldAMDGCNCubeIntrinsic` (`llvm/lib/Analysis/ConstantFolding.cpp`) defines `v_cubema` as twice the signed +major coordinate, so `s` and `t` lie in [1, 2] and `s - 1`, `t - 1` are the position on the face. + +The translator emits a helper `x2w_cube_dir(s, t, face)` that rebuilds a direction whose major component is +1 or +-1 for the face and whose other components are `u = 2(s - 1.5)` and `v = 2(t - 1.5)` with the signs of the per-face +`sc` and `tc` that the existing `v_cube*` lowering uses: +X (1, -v, -u), -X (-1, -v, u), +Y (u, 1, v), -Y (u, -1, -v), ++Z (u, -v, 1), -Z (-u, -v, -1). Projecting that direction again gives back `u` and `v`. + +## Refused + +- `image_load` and `image_load_mip` on a cube (`Load is not defined on a TextureCube`), `image_sample_d` + (cube derivatives are not converted), `image_get_lod`, `a16` and `d16`. +- A cube in a compute program: the compute dispatch has no `texcube` view binding. +- A constant sampler with `DISABLE_CUBE_WRAP` (`SQ_IMG_SAMP_WORD0` bit 28, Mesa + `src/amd/registers/gfx10-rsrc.json`): the guest then filters without crossing face edges, while a D3D12 cube + always filters across them. With the bit clear both cross. +- Compare, gather and store forms were already limited to 2D and 2D arrays and are unchanged. + +## Limits + +- A cube-array view is not recognisable from the instruction (gfx10 MIMG has no array bit; the descriptor sets + the dimension). The helper keeps the face bits of the id (`id & 7`) and samples layer 0 of a `TextureCube`, + which is wrong for a later layer of a cube array. +- A face id of 6 or 7 maps to face 5, a negative, NaN or huge id to face 0, and `s` or `t` outside `[1, 2]` are + assumed to clamp to `[-1, 1]` on the face edge. Mesa does not produce these for a finite non-zero direction; + clamping outside `[1, 2]` is not tested and none of these out-of-range inputs is measured. +- The implicit-LOD and bias forms take the desktop derivatives of the rebuilt direction. Inside one face these + follow the guest's face coordinates; a quad that straddles a face edge can choose another level. +- Heap and register samplers are not read at translation, so their `DISABLE_CUBE_WRAP` bit is not validated (a set + bit would filter differently at face edges), and their LOD range stays unvalidated as for 2D textures. +- Only pixel-stage draws are measured; the vertex-stage form is translated but not drawn. +- The runtime binding of a `texcube` view landed in PR #2938 (`7fcde81f`). + +## Fixture + +`tests/startup_image_cube_check.py` (controls, `binary `, `draw `). +`offscreen_check --startup-image-cube` binds six 4x4 R32G32B32A32_FLOAT faces as a TextureCube whose texel (x, y) +of face f holds ((1 + x + 4y + 16f) / 128, x, y, f). The sampler is the all-zero inline sampler (point, wrap), and +every `s` and `t` is a texel centre (in `{1.125, 1.375, 1.625, 1.875}`). + +- Seven programs set `(s, t, face)` as constants (`1.125` or `1.875`), without `v_cube*`, so the reference is only the + address meaning (`x = floor(4 * (s - 1))`, `y = floor(4 * (t - 1))`). The desktop driver picks the face of the + rebuilt direction itself, so a wrong face, sign, axis or `2.0 * (s - 1.5)` / `2.0 * (t - 1.5)` scale in the helper + reads another texel. Every face has a case whose texel has x != y. +- `image_sample`, `image_sample_l` and `image_sample_b` each draw one case. +- Controls: the face one higher and `s`, `t` exchanged must read those texels; `image_sample_l` and + `image_sample_b` with the face in the LOD or bias dword must read face 0. +- Fifteen translator mutants edit the emitted helper (for each face the sign of the `u` term flipped, `u` and `v` + exchanged, faces 2 and 3 exchanged, and dropping the `2.0 *` scale on `u` or `v`). Each must read the texel a D3D + cube lookup of its direction gives. +- Six programs run the `v_cube` chain (`v_cubema`, `v_cubesc`, `v_cubetc`, `v_cubeid`, `v_rcp_f32` of `|ma|` and + `v_fma_f32` with 1.5) on one direction per face. Each must match the face texel LLVM's table gives and a desktop + pixel shader that samples the same direction from the TextureCube. + +Measured on 28.11.2026, commit f7da3f69 plus this change, Windows 11 24H2 (10.0.26100.9711), debug layer +unavailable on both adapters: the 22 reference draws (7 literal, 3 forms, 6 chain, 6 desktop TextureCube) matched +on NVIDIA Quadro M1000M (driver 32.0.15.7371) and on WARP (Microsoft Basic Render Driver 10.0.26100.9711), and all +19 controls and mutants read the texel they predict (`dev` and `release` `/O2`). With the translator change reverted, +the controls fail on `image dimension SQ_RSRC_IMG_CUBE`, and dropping the `2.0 *` scale on `u` fails both +`startup_image_cube_controls` and `startup_image_cube_warp`. +The 16 fixture programs reassemble to the recorded words with LLVM 15.0.7. + +```powershell +ctest --preset dev --no-tests=error -R '^startup_image_cube_' -V +``` + +Not shown: that the console's face order and face orientation equal D3D's. That rests on LLVM's cube table being +the D3D cube face table. LOD and bias values on a cube are not tested, because only one mip is bound; the +`image_sample_l` and `image_sample_b` draws only show that the extra address dword is not read as a coordinate. diff --git a/docs/experiments/ttpf-manifest-dds-path.md b/docs/experiments/ttpf-manifest-dds-path.md new file mode 100644 index 0000000000..302ec99114 --- /dev/null +++ b/docs/experiments/ttpf-manifest-dds-path.md @@ -0,0 +1,32 @@ +# TTPF manifest and DDS paths + +The batch exporter rejects a manifest path that names a DDS requested by the +same batch or a supplied history or calibration input. Previously, choosing +`--indices 0 --manifest out/tex_00000.dds -o out` +could report a successful export and then replace that DDS with the JSON +manifest. A failed or skipped export could also lose a DDS preserved from a +previous run when the manifest was published. +Likewise, naming the history or calibration file as the manifest replaced the +input profile with an export-results array, preventing its reuse on the next run. + +The path check runs after reading the pool count, before creating the output +directory or starting any export. It uses the existing resolved-path and file +identity checks. A manifest with the same filename in a different directory is +still accepted. +Profile collisions are rejected before loading the decoder tools. + +The synthetic regression exercises successful, failed and skipped exports with +and without an existing DDS. All six cases fail with the old exporter because +it accepts the collision. The separate-directory control succeeds and verifies +the DDS bytes against the manifest checksum. +Two further cases verify that history and calibration inputs remain unchanged; +both fail with the old exporter because it accepts and overwrites the profile. + +```powershell +python -B tests/ttpf_batch_export_check.py +python -B tests/ttpf_batch_export_cli_check.py +``` + +These checks use the mocked exporter and generated inputs; the optional local +Leonida integration test can skip when its tools are not installed. They make +no claim about image decoding correctness. diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index b5e2e009fd..4b1a3e002d 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -47,15 +47,13 @@ controls for other barrier types, flagged barriers, invalid resources and arrays ## Occlusion queries -Which console methods sit at command-list slots 28 to 30 is not established by any fixture here. The repository -places `ResourceBarrier` at 26 and four additional console methods in the 26 to 31 range -(32 is `SetDescriptorHeaps`, desktop 28 plus four). It also shows that -the plus-four run has ended by 61 (`ExecuteIndirect`, desktop 59 plus two). As a hypothesis, slots 28 to 30 are -implemented as `BeginQuery(heap, type, index)`, `EndQuery(heap, type, index)` and -`ResolveQueryData(heap, type, start, count, buffer, offset)`. Because that is a hypothesis, the bindings are a -diagnostic opt-in: only with `X2W_D3D12_QUERY_SLOTS=1` (in render mode) are the three slots bound. Unset, they stay -no-ops as before. The fixture below calls those slots directly, so it checks the forwarding, the refusals and the -end at Close, not the numbering. +The GXDK 261000 `ID3D12GraphicsCommandList8` table confirms `BeginQuery`, `EndQuery` and +`ResolveQueryData` at command-list slots 28 to 30, and `SetPredication` at 31. Slots 32 to 55 +are the desktop slots 28 to 51 plus four; slots 56 to 58 are `SetMarker`, `BeginEvent` and +`EndEvent`, and `ExecuteIndirect` is 61. The query bindings stay a diagnostic opt-in: only with +`X2W_D3D12_QUERY_SLOTS=1` (in render mode) are the three slots bound. Unset, they stay no-ops +as before. The fixture below calls those slots directly, so it checks the forwarding, the +refusals and the end at Close, not the numbering. The query heap comes from device slot 39 with the desktop desc, which the stand-in keeps. Only occlusion and binary-occlusion queries on an occlusion heap, recorded on a DIRECT list, are forwarded to the desktop list. A @@ -76,7 +74,7 @@ the console `Map`. It then checks that the refused calls, among them resolves ov with a hole and an index ended with the other occlusion type, leave the sentinel untouched with no debug-layer error, and it leaves one query open at Close. `startup_list_queries_default_{warp,hardware}_control` runs it without the switch: the slots stay no-ops and it must report the untouched sentinel in the first word. -`command_list_slot_names.h` still names 56 to 58 as the query methods by the plus-four rule. +Slots 56 to 58 are the desktop marker methods, not query methods. ## Depth target on translated draws @@ -829,8 +827,10 @@ Alternatively, stage one executable and its adjacent DLLs with: .\tools\startup\stage_package.ps1 -PackageDir -Exe .exe -RunDir <fresh run folder> ``` -The destination must be absent or empty and separate from the package. Archives and subdirectories -are not copied. Keep using the package root as `-DataDir`, then run the staged executable: +The destination must be absent or empty and separate from the package. The helper checks resolved +paths as well as their spelling, and stops if Windows cannot resolve an existing path (which can +occur on some network shares). Archives and subdirectories are not copied. Keep using the package +root as `-DataDir`, then run the staged executable: ```powershell .\tools\startup\run.ps1 -Exe <folder>\<title>.exe -DataDir <package root> -LogDir out\startup\run1 ` @@ -921,6 +921,38 @@ It writes: | `<log>/files.txt` | every file the process opened | | `<log>/translate.txt` | with `-Translate`: one line per shader request translated during the run | +### Package on another volume + +A console executable opens its package at a fixed drive letter, so a package that lives on another +volume never mounts: the first open returns "not found", nothing is mounted, and the run usually +stops within a second on a table sized from data that was never loaded. `-MapDrive` rewrites opens on +a mapped letter to the real folder, in the caller's own path structure and inside the debugger's +existing file hook, so the letter does not have to be free and a real volume on it is not disturbed: + +```powershell +.\tools\startup\run.ps1 -Exe <folder>\<title>.exe -DataDir <package root> -LogDir out\startup\run1 ` + -MapDrive "G=D:\package" +``` + +The value is `LETTER=FOLDER`, and several mappings are separated by `;`. The debugger logs a `MAP` +line for each rewrite and the rewritten path in `<log>/files.txt`. An open on a letter that is not +mapped is left untouched. The rewritten name is borrowed for the hooked call only: the caller's +`UNICODE_STRING` is restored (length, buffer pointer and contents) when the call returns, so a +failure or a retry sees the name it built. When the replacement does not fit the caller's buffer the +debugger borrows a name buffer for the duration of that call and returns it to a pool on restore, so +serial opens reuse one buffer instead of allocating per open and overlapping calls do not share one. +One limit remains: only opens that pass through the file hooks are rewritten, so a title that reads +its package through a memory-mapped API is not covered. A call that enters the same hooked function on +another thread is rewritten too: the debugger holds the other threads for each step over a hooked byte +([Concurrent calls through a hooked function](#concurrent-calls-through-a-hooked-function), #1281). +`startup_map_drive` covers the rewrite, the negative control without the option, that an unmapped letter +is left alone, and one caller-owned `UNICODE_STRING` reused across 32 serially opened files with its +length, buffer pointer and contents checked after every return and a single name buffer. +`startup_map_drive_overlap` runs two threads of 32 opens each with their own caller-owned names: all 64 +opens must see the mapped name and succeed, every caller string must be back as built and the debugger must +report no unprotected window, three times. Its control without holding the other threads +(`--suspend-others 0`) must lose opens. + ### Translating shaders during a run With `-Render -Translate`, `run.ps1` starts `tools/startup/gfx2hlsl.py --watch <shader cache>` beside @@ -976,13 +1008,22 @@ The existing dispatch path records the result, and a program is accepted only wi fixture has run through it: root constants, raw table buffers loaded per lane (`buffer_load_dword`) and raw table buffers stored to, with their descriptors in 32-byte table records. Anything else (a scalar buffer load, a texture, a sampler, a typed or indexed view, an instruction the compiler does -not lower) is refused. The first 16 refusals of a process are logged as +not lower) is refused. Programs published as `<key>.txt` also bind 1D, 2D, 2D-array and 3D texture SRVs +(`srv N tex1d|tex2d|tex2da|tex3d table R B`) from the title's described view of that dimension, or are +refused by name; cube texture SRVs are not published. The first 16 refusals of a process are logged as `compute pipeline <key> not translated natively: <reason>`. A refused key is left to the published translations, so `-Translate` can run beside it for those pipelines. A direct module declares wave size 32, so an adapter without 32-lane waves refuses every program by that name. The in-process translation is tried once per key and before a published `<key>.txt`. It covers compute only; graphics pipelines still need a published translation. +Published compute translations from `compile_dxil --requests` and `--watch` carry a `native 1` line in the +`x2w-manifest 2` manifest. The stand-in requires the current native output revision. An unmarked manifest +is accepted with a `<key>.cs.hlsl` sidecar, which identifies a Python translation. `compile_dxil --watch` +rebuilds stale native outputs and leaves Python publications in place. The stand-in retries a stale or +absent manifest on subsequent dispatches on the ManifestRetry schedule (1 s, doubling up to 32 s), so a running process can +pick up a rebuilt output (by the code path; no test covers the reload). Compute request keys stay at `29cs`, and revision-28 archives are still read. + Check with `ctest --preset dev -R '^startup_compute_dispatch_native_(warp|hardware)$' -V` ([`tests/startup_compute_dispatch_native_check.py`](../tests/startup_compute_dispatch_native_check.py); [route, controls and results](experiments/startup-compute-native-dispatch.md)). @@ -1530,7 +1571,7 @@ the two recovery checks are its sole failures), second probe), and `readable`/`writable` boundaries across `PAGE_READONLY`, `PAGE_READWRITE`, `PAGE_WRITECOPY`, `PAGE_NOACCESS`, `PAGE_GUARD`, and `MEM_RESERVE`. A first-chance exception stops the whole process while a debugger is attached, so `probe_readable` and the fault-safe -copies (`guarded_memcpy`: `copy_title_bytes`, the linear-buffer `guarded_copy`) first, when a debugger is attached or `X2W_PROBE_PRECHECK` is set to anything but `0` (read once; otherwise the plain touch / `__try` path runs at no extra cost), ask `VirtualQuery` (one entry per +copies (`guarded_memcpy`: `copy_title_bytes`, the linear-buffer `guarded_copy`) first, when `X2W_PROBE_PRECHECK` is set to anything but `0`, or when it is unset and a debugger is attached (read once; `X2W_PROBE_PRECHECK=0` keeps it off under the debugger that title runs start in, and off, the plain touch / `__try` path runs at no extra cost), ask `VirtualQuery` (one entry per region, cached per thread) whether the source is in free address space (`MEM_FREE`) and refuse it with no exception. Reserved, committed, guard and no-access pages still go through the touch / `__try` path, because a reserved page may be a lazily committed xmem page that the fault handler commits on first touch; `__try` stays the last guard. The render @@ -1604,7 +1645,7 @@ ctest --preset dev --no-tests=error -R '^startup_hook_(window|overlap)$' -V | `X2W_D3D12_CAP_EXISTING_HEAP=1` | opt-in 256 MiB (`unplaced_existing_heap_allowed`) allocation-size cap on `OpenExistingHeapFromAddress` in device slot 133 (`startup_slot133_heap_cap_*`). Unset (default), private allocations larger than 256 MiB keep the formerly aliased path: a capped copied placement is refused by `CopyBufferRegion` (list slot 15) as `title_backed_source`, losing a late guest write made after recording and before submit. Set, allocations larger than 256 MiB skip `OpenExistingHeapFromAddress` so multi-GiB startup blocks are not pinned in `WorkingSetSize` and `NonLocal` GPU memory | | `X2W_D3D12_ROOT_SRV_AT_DRAW=1` | opt-in, render mode: a graphics root SRV (slot 44) without an upload mapping is not copied into the upload ring, since no draw reads that desktop binding (default: a 64 KiB copy at every slot 44 call). Translated draws copy the SRV themselves and are unaffected (`startup_root_srv_draw_*`). See [the experiment note](experiments/startup-root-srv-at-draw.md) | | `X2W_D3D12_RING_RELEASE_AT_SUBMIT=1` | opt-in, render mode: a closed command list releases its upload ring chunks once its submit is fenced instead of holding them until Reset, and the ring grows in 16 MiB chunks up to 512 MiB (default: doubling chunks up to 256 MiB, holds until Reset). The larger ring can add up to about 1 GiB of process commit at peak (startup runs in the experiment note). A later submit of the same list before its Reset fences its unchanged chunks again; if one was reused in between, that list is refused before the execute and logged (`startup_address_console_gate_ring_keep_*`, `upload_reservation`). See [the experiment note](experiments/startup-upload-ring-release-at-submit.md) | -| `X2W_D3D12_QUERY_SLOTS=1` | diagnostic, in render mode: binds command-list slots 28 to 30 to the hypothesised occlusion query methods (see [Occlusion queries](#occlusion-queries)). Unset, the three slots stay no-ops | +| `X2W_D3D12_QUERY_SLOTS=1` | diagnostic, in render mode: binds command-list slots 28 to 30 to the confirmed `BeginQuery`, `EndQuery` and `ResolveQueryData` methods (see [Occlusion queries](#occlusion-queries)). The bindings remain diagnostic because the forwarding behavior is not a console runtime oracle. Unset, the three slots stay no-ops | | `X2W_D3D12_BUDGET=1` | adds [video memory budget and allocation counts](#d3d12-resource-budget) to the D3D12 heartbeat | | `X2W_D3D12_RELEASE_RETIRED=1` | opt-in, effective with `X2W_D3D12_RENDER=1` only (the list handlers that record holds exist only there): frees the desktop object of a released committed 2D texture of one narrow class once no recorded list, submission or release-time fence refers to it ([details](#d3d12-resource-budget)). Unset, nothing changes | | `X2W_D3D12_RELEASE_RETIRED_VIEWS=1` | legacy diagnostic. Logs that clearing live slots is disabled and enables the existing retirement breakdown when base retirement and budgets are on ([details](#d3d12-resource-budget)) | @@ -1622,6 +1663,7 @@ ctest --preset dev --no-tests=error -R '^startup_hook_(window|overlap)$' -V | `X2W_DRAW_DUMP_FRAME=<n>`, `X2W_DRAW_DUMP_DIR`, `X2W_DRAW_DUMP_PIXEL=<x>,<y>` | Full-resolution RGB snapshots of single-sample RGBA8/BGRA8 UNORM or sRGB targets after translated draws. A later present writes completed queue-fenced copies. At most 48 copies are pending or written; a copy whose fence reports device removal (`UINT64_MAX`) is released unwritten and frees its slot (`src/startup_stubs/draw_dump_tracking.h`, `ctest --preset dev --no-tests=error -R '^startup_dump_fence_(removed_control_)?warp$' -V`; the control must fail). With `X2W_DRAW_DUMP_PIXEL`, each copy covers one texel instead and the present writes `pixel_history.txt` in `X2W_DRAW_DUMP_DIR`: one line per translated draw with `draw=`, `frame=`, `x=`, `y=`, `key=`, `count=`, `format=`, `raw=` and, for an 8-bit four-channel target, `rgba=`. The bounded history names the last draw that changed the texel (`src/startup_stubs/pixel_history.h`, `ctest --preset dev --no-tests=error -R '^startup_pixel_history_' -V`). | | `X2W_TEARDOWN_REPORT=1`, `X2W_TEARDOWN_NO_GUARD=<pages, readbacks or all>` | Test accounting for the caches whose destructors run during the module's CRT teardown (`src/startup_stubs/d3d12_teardown.h`, #2572). With `X2W_TEARDOWN_REPORT`, each destroyed cache writes one `x2w-teardown <cache> detached=<n> released=<n>` line to stderr with `WriteFile`, because a stdio buffer would not be flushed from a CRT teardown. `X2W_TEARDOWN_NO_GUARD` names a cache whose detach at process exit becomes an ordinary release again: the negative control `startup_teardown_unload` runs against itself, where the termination check has to fail. Unset, both change nothing and no line is written. | | `X2W_AUDIO_PERMISSIVE=1` | enables the audio stand-ins. Without a DSP provider, `XDspActivate` clears valid outputs and reports unavailable resources, and failed `XDspSubmitCommand` calls leave the sequence unchanged. `XDspDeactivate` and `XDspDisconnect` refuse null and unknown handles with `E_INVALIDARG`. | +| `X2W_AUDIO_ACTIVITY=1` | with `X2W_AUDIO_PERMISSIVE=1`, counts XMA context changes, HAL submits and XApu commands, and logs at most a line per second when a count moved ([Activity counter](#activity-counter)) | | `X2W_RUNTIME_PROXY=1` | proxies the gaming runtime and logs every call. Rewrites regular-IAT `GetProcAddress` and a direct `xgameruntime.dll!QueryApiImpl` import on the main EXE and on DLLs that share its directory (package helpers). Dynamic `QueryApiImpl` / `InitializeApiImpl*` are wrapped only when the provider module's basename is `xgameruntime.dll`. `LdrRegisterDllNotification` only flags that another scan is needed. A worker holds each matching module live while rewriting after linking. Loading a helper and immediately calling it can precede the scan. The enabled proxy stays loaded until process exit. Delay-import IAT slots are not rewritten. Skips this stand-in's own `GetProcAddress` IAT so the hook does not recurse (`src/startup_stubs/runtime_gpa_patch.h`, `ctest --preset dev --no-tests=error -R '^startup_runtime_gpa_patch(_name_only_control)?$'`, and the control must print `FAIL:`; Windows also runs `startup_runtime_proxy_scope` for a late-loaded helper through the real loader) | | `X2W_FAKE_USER=1` | answers the user, gamertag and save APIs for one local user, and creates one offline store context for that user | | `X2W_RUNTIME_LOCAL=1` | with `X2W_RUNTIME_PROXY` and `X2W_FAKE_USER`, for a host where the system gaming runtime cannot initialize (no Gaming Services). The first failed `InitializeApiImpl*` is reported as `S_OK`, and every later initialization call returns `S_OK` without calling the real export. Once initialization failure is latched, a failed real `QueryApiImpl` call can fall back only with an exact match of both GUIDs to a supported provider/interface pair for user (including gamertag), game save, package, title, connectivity or store. Persistent local storage uses its existing fake-user gate and requires its exact provider GUID and IID. Unmatched failed queries keep the real HRESULT. The proxy clears a writable output on failure only when fake user is enabled and the initialization failure is latched. A local object's `QueryInterface` accepts only `IID_IUnknown` and the IID it was created for. The local answers above apply, calls that carry the local user or store handle fail as before, and other unanswered methods return `E_NOTIMPL`. `XUserAddAsync` and async operations completed on behalf of a local answer require the real runtime's `QueryApiImpl` to return the XAsync provider (`073b7dcb`). Those operations complete with `S_OK` through XAsync, or return the query failure if XAsync is unavailable (`ctest --preset dev --no-tests=error -R '^startup_runtime_local(_control)?$'`, and the control must print `FAIL:`). | @@ -2430,7 +2472,12 @@ These are measured on one executable; treat them as hypotheses for others. [#2618](https://github.com/R0Y00/Xbox2Windows/issues/2618) - **Soft asserts.** Retail code keeps `int3` instructions followed by a continuation. Without a debugger the title's handler steps over them; under the startup debugger use - `-ContinueAsserts N`. One of them fires about ten times a second in the texture-streaming path + `-AssertSites N` (`--assert-sites N` for `run.sh`), which steps over every hit at up to N distinct + main-image `int3` sites, so a site that repeats never runs the budget out however long the run is. + The first hit at one more site still stops the run, as do `X2W_STOP_AT` sites. `-ContinueAsserts N` + counts hits instead: it steps over the first N hits at any site. A hit is stepped over when either + budget allows it, and each budget counts only the hits it covers: the site budget takes the first N + distinct sites, and the hit budget counts the hits at other sites. Run `ctest --preset dev --no-tests=error -R "^startup_debug"`. One of them fires about ten times a second in the texture-streaming path (a chunked read whose length ends inside a compressed chunk); its cause is open. - **Struct-returning methods.** When both register arguments of a wrapped method look like objects, the one on the calling thread's stack is the return buffer. @@ -2601,8 +2648,8 @@ These are measured on one executable; treat them as hypotheses for others. for a load. Before, the stage was refused and every draw through its pipeline was skipped. Two source-built pixel stages draw one texel of a 2x2 texture with two slices on WARP and hardware with DXC and FXC; a slice fixed to 0 and exchanged coordinates fail it - (`ctest --preset release --no-tests=error -R "^startup_image_2d_array_"`). Cube, multisampled - and 1D images are still refused. Not covered: binding a single-slice 2D view to an array declaration + (`ctest --preset release --no-tests=error -R "^startup_image_2d_array_"`). Multisampled + and 1D images are still refused here; cube sampling is lowered since #2943 (`startup_image_cube_`). Not covered: binding a single-slice 2D view to an array declaration in the draw path. - **2D array depth comparison.** `image_sample_c_lz` and `image_sample_c` (sampler MAX_LOD 0) with `dim:SQ_RSRC_IMG_2D_ARRAY` take the reference, u, v and the slice as four address registers and lower to @@ -2800,7 +2847,7 @@ These are measured on one executable; treat them as hypotheses for others. `src/startup_stubs/logical_view_table.h` without a device. It covers the first and last records, one past the end, handles inside a record or below the heap, missing heap fields, memory that wraps past the top of the address space, and records crossing the end of a window. -- BCPack DirectStorage requests are decoded for BC7 and BC1 streams into destination memory as single atomic texture payloads; each request decompresses a complete multi-lane rANS chunk directly into its destination buffer and is excluded from chunk continuation caching. Unhandled formats fall back to zero-filled destinations. At process exit, one `x2w-dstorage BCPack summary` line reports request and zero-filled counts for every format 1..15 that was requested. The consumer fixture sends a format 6 request and checks that it succeeds, leaves a zero-filled destination, and appears in both counts; BC1 and BC7 requests must not be counted as zero-filled. +- BCPack DirectStorage requests decode BC1–BC7 complete multi-lane rANS payloads into temporary memory and publish only after success. They are excluded from continuation caching. BC2/BC6H now reconstruct packed blocks; invalid formats and damaged streams fail without publishing blank textures. BC1 uses independent endpoint/index history and exact format dictionaries; the fitted window and quadrant masks have been removed. File and memory sources, outer zlib and physical-page destinations share this path. Historical zero-filled counters remain in the summary log schema but are no longer incremented. [Implementation, synthetic fixtures and oracle reproduction](experiments/bcpack-standalone.md). - The XG stand-in normally uses desktop copyable footprints. Its opt-in BC7 diagnostic reports standard GFX10 4 KiB tiled geometry for a single-slice, single-mip, non-MSAA `BC7_UNORM` 2D texture with an unknown layout, default alignment, and no resource flags. @@ -2847,7 +2894,7 @@ These are measured on one executable; treat them as hypotheses for others. mip 0 and mip 3 instead: `ctest --preset dev --no-tests=error -R '^startup_sampler_lod_' -V`. - The startup shader translator lowers `image_sample_l` (explicit level, 2D and 3D, any `dmask`) to `SampleLevel(sampler, uv, level)`, taking the level from the last address register. Offset, compare, - gather, clamp, cube, 1D and `unorm` forms are refused. Only the translation is checked + gather, clamp, 1D and `unorm` forms are refused; a cube lowers since #2943 ([note](experiments/startup-image-cube.md)). Only the translation is checked (`python -B tests/startup_image_sample_l_check.py`); a WARP readback of distinct mip levels is still open. - `image_sample_b` in a pixel stage lowers to `SampleBias(sampler, uv, bias)` for 2D, 2D-array and 3D textures; the bias is the first address register. Offset, clamp, compare and gather forms, other stages, code after a branch, a sampler with a @@ -3024,7 +3071,8 @@ observed callers. The experimental mode echoes any 32-bit type value at `+0x00` (including unobserved types such as `4`) rather than rejecting it, while keeping payload bytes outside `+0x00` and `+0x04` zero (`+0x34` carries decoded bytes only in the optional Opus build below). Handles are never reused, and each connection's queue buffer is released on `XApuDisconnect`. Default non-permissive mode still traps on every export -(`ctest --preset dev --no-tests=error -R '^startup_xapu_queue$' -V`). +(`ctest --preset dev --no-tests=error -R '^startup_xapu_queue$' -V`). With `X2W_AUDIO_ACTIVITY=1` it also counts +commands by class (see [Activity counter](#activity-counter)). The default build does not depend on libopus. Configuring with `-DX2W_WITH_OPUS=ON` (and `Opus_DIR` pointing at an installed libopus CMake package) links libopus into `xapu.dll`. The stand-ins link the static MSVC runtime, so libopus @@ -3132,6 +3180,48 @@ address validity/mapping exports, then runs 4 threads of 1000 rounds against an ctest --preset dev --no-tests=error -R '^startup_acphal_apu_free$' -V ``` +### Activity counter + +With `X2W_AUDIO_ACTIVITY=1` as well, the stand-ins count what a caller does with the audio processor without decoding +anything. `AcpHal.dll` keeps a copy of the XMA context array that `AcpHalAllocateShapeContexts` hands out and compares +the array with it inside the calls that count (HAL submits, `AcpHalAllocateShapeContexts`, every `ApuFree` once counting +started and `x2w_acphal_xma_activity`), at most once per 10 ms. Each 64-byte context is taken as a whole and no field in +it is read: one that goes from all zero to nonzero counts as filled, one that changes while nonzero as changed, one that +returns to all zero as cleared. HAL slot2 submits are counted by their type argument. `xapu.dll` counts every +`XApuEnqueueCommand` call by command class, taken as the first `UINT32` of the command, with no cap; unreadable commands +and unknown handles are counted apart; `commands=` is the classes plus the unreadable commands, and `rejected=` calls +are not in it. In an `X2W_WITH_OPUS` build with `X2W_XAPU_TYPED_COMPLETIONS=1`, a type 3 command too short to decode +returns `E_POINTER` before the queue and is still counted, as class 3. +Neither DLL starts a thread: a counted call at least a second after a DLL's previous line (or its first +counted call) logs the next line, with the counts since that line, only when a count moved, so nothing of either DLL +runs after a caller unloads it. Until then the counts wait for a later call: counts from the last second before a +caller's final call, and changes after it, are not logged, though the exports still return them. With the fixture's +caller, for example: + +``` +x2w-audio xma-activity t=1.1 s: contexts filled=5 changed=3 cleared=2 live=0/0; hal submits=4 by type 1=2 3=1 other=1 +x2w-audio xapu-activity t=1.1 s: commands=7 by class 1=3 2=2 other=1 unreadable=1; rejected=1 (not in commands) +``` + +`t` is seconds since the process started, the same base in both DLLs; the fixture's line comes after its `ApuFree`, so +no context is watched (`live=0/0`). A context written across a sample counts twice, and one filled and cleared between +two samples is not counted. `ApuFree` of the array ends the count before the block can be reused, and a second +`AcpHalAllocateShapeContexts` samples the old array once more and then watches only the new one. The totals are also +returned by the experimental exports `x2w_acphal_xma_activity` and `x2w_xapu_command_counts`. The 64-byte stride and the +command class are stand-in conventions, not a console layout, and no field inside a context, such as an enable flag, is +identified. With the variable unset nothing runs: no read of caller memory, no line. + +The source-built check runs four child processes: counter on (the exports and the logged lines give exactly what the +caller script did, and an array freed and allocated again is no longer counted), counter on with a caller that writes +only the 64 bytes after the last context and sends nothing (every count 0, no line), counter off (no count, no line), +and an unload case. That one allocates the contexts twice without `ApuFree` (the old array's unsampled change counts, +later ones do not), then frees both DLLs, checks that they are unmapped, waits 1.5 s and must exit 0. Every result, +output, last error and the final context bytes must match between the on and off runs: + +``` +ctest --preset release --no-tests=error -R '^startup_acphal_xma_activity$' -V +``` + ## Uniform first-lane reads The startup shader translator accepts `v_readfirstlane_b32` in straight-line code with the @@ -3238,8 +3328,7 @@ arrive. It reports frame counts and FPS from the graphics heartbeat without infe draws were executed. Network refusals are shown when observed; the window does not establish that all network activity is blocked. To check this presentation with generated logs, run `python -B tests/startup_live_telemetry_check.py`. See [#1199](https://github.com/R0Y00/Xbox2Windows/issues/1199) -for memory accounting and [#1281](https://github.com/R0Y00/Xbox2Windows/issues/1281) for -the launcher's concurrent-hook limitation. +for memory accounting. ```powershell cmake --build --preset release --target xmem_shim startup_stub_xcrdapi xmem_slab_slots_check @@ -3566,9 +3655,13 @@ texels and BC1 to BC7, whose largest mip must then be whole 4x4 blocks). The vie A three-dimensional description is taken in one layout only: `0x105` (4 KiB standard), one sample, -at most 2048 texels on each side and an uncompressed format with a known element size, with one mip -or a mip chain its largest side (depth included) allows, viewed as a Texture3D whose mips fit the -chain. addrlib lays a 3D resource in a standard or display mode out in thick blocks +at most 2048 texels on each side and a format with a known element size (8- to 128-bit texels and +BC1 to BC7, whose largest mip must then be whole 4x4 blocks across and down; the depth is any), with +one mip or a mip chain its largest side (depth included) allows, viewed as a Texture3D whose mips fit +the chain. A block-compressed volume is laid out as the volume of its 4x4 blocks, each one depth layer +deep: the sides are rounded up to whole blocks first, and every mip size after that is counted in +blocks (`ElemLib::AdjustSurfaceInfo`), so a mip whose texel side is not a multiple of 4 can be a block +wider in the layout than in the view. addrlib lays a 3D resource in a standard or display mode out in thick blocks (`Gfx10Lib::HwlIsThick`): the 12 address bits of a block follow the one-pipe rows of `GFX10_SW_4K_S3_PATINFO`, the block is 16x16x16, 8x16x16, 8x16x8, 8x8x8 or 4x8x8 elements for 1- to 16-byte elements, and the volume is stored a layer of blocks (one block deep) at a time. Each layer @@ -3580,7 +3673,7 @@ read as 256-byte micro blocks, gives its origin in x and y (`ComputeSurfaceInfoM depth layer is copied to its own footprint rows. Anything else is refused as before and leaves the destination descriptor unchanged: layout `0` without a live texture, cube views of other arrays, three-dimensional descriptions in any -other layout or with a block-compressed format, multisampled textures, the XOR swizzle modes and +other layout, multisampled textures, the XOR swizzle modes and every other layout value. The texels must be readable and span at most 64 MiB. @@ -3621,9 +3714,10 @@ Limits and choices that are not measured against a console: in `startup_gfx10_layout_check.cpp` (all five element sizes) and in the Python oracle of `startup_address_console_check.py` (4- and 8-byte elements), both written from the same source. - The thick `0x105` volume layout is compared with addrlib itself when the build has it - (`startup_gfx10_volume_addrlib`: every element address of every mip of 305 volumes, 115 of them - with a mip chain). Block-compressed volumes and volumes in the other modes are not handled; they - stay refused. + (`startup_gfx10_volume_addrlib`: every element address of every mip of 501 volumes, 115 of the uncompressed ones + with a mip chain, and 196 block-compressed ones, every mip count of four chains for each of BC1 + to BC7). Only BC1 volumes are drawn. Volumes in the other modes are not handled; they stay + refused. Log lines (stderr and `X2W_TRAP_LOG`): diff --git a/src/direct_compute_cache.cpp b/src/direct_compute_cache.cpp index ac55431eca..b677f0353c 100644 --- a/src/direct_compute_cache.cpp +++ b/src/direct_compute_cache.cpp @@ -3,6 +3,7 @@ #include "gfx1013_isa.h" #include "native_graphics_bindings.h" #include "shader_compute_request.h" +#include "native_compute_output.h" #include "native_shader_revision.h" #include "shader_dxil_compiler.h" #include <atomic> @@ -100,6 +101,9 @@ Bytes encode(const NativeComputeShader &program) { for (unsigned n : {c.root_parameter, c.first_sgpr, c.count}) word(out, n); word(out, program.sampler_heap); + word(out, static_cast<unsigned>(program.stride_srvs.size())); + for (unsigned srv : program.stride_srvs) + word(out, srv); word(out, static_cast<uint32_t>(program.samplers.size())); for (const auto &s : program.samplers) { for (auto n : s.words) @@ -149,6 +153,9 @@ NativeComputeShader decode(std::string_view bytes) { shader.constants.push_back(c); } shader.sampler_heap = in.count(1) != 0; + n = in.count(32); + for (unsigned j = 0; j < n; ++j) + shader.stride_srvs.push_back(in.count(31)); n = in.count(2048); for (unsigned j = 0; j < n; ++j) { ComputeSampler sampler{}; @@ -874,17 +881,51 @@ DirectGraphicsPair prepare_direct_graphics(std::string_view a, std::string_view return verified(std::move(pair)); } -std::optional<std::string> format_compute_runtime_manifest(const NativeComputeShader &program) { - if (!program.group[0] || !program.group[1] || !program.group[2]) +static const char *view_kind_name(ComputeViewKind kind) { + static const char *const names[] = { + "buffer_srv", "typed_buffer_srv", "texture_srv", "texture_uav", "raw_vector_srv", "half_scalar_uav", + "heap_stride_srv", "raw_buffer_uav", "typed_buffer_uav", "half_buffer_uav", "root_buffer_srv", + "comparison_texture_srv", "half2_texture_uav", "half4_texture_uav", "cube_sample_srv", "cube_comparison_srv", + "indexed_atomic_uav", "d16_sample_srv", "byte_window_srv", "heap_buffer_srv", "heap_sampler", + "uint_texture_uav", "float_texture_uav", "float2_texture_uav", "float3_texture_uav"}; + const auto index = static_cast<size_t>(kind); + return index < std::size(names) ? names[index] : "unknown"; +} + +// "SRV kind texture_srv 3d": the binding kind, and for image kinds the ISA dimension and a descriptor array. +static std::string view_shape(const char *type, const ComputeViewBinding &b) { + std::string out = std::string(type) + " kind " + view_kind_name(b.kind); + if (std::string_view(out).find("texture") != std::string_view::npos || + std::string_view(out).find("sample") != std::string_view::npos || + std::string_view(out).find("cube") != std::string_view::npos) { + static const char *const dims[] = {"1d", "2d", "3d", "cube", "1d-array", "2d-array", "2d-msaa", "2d-msaa-array"}; + out += ' '; + out += b.image_dimension < std::size(dims) ? dims[b.image_dimension] : "unknown-dimension"; + } + if (b.array_count != 1) + out += " array"; + return out; +} + +std::optional<std::string> format_compute_runtime_manifest(const NativeComputeShader &program, std::string *reason) { + auto refuse = [&](std::string why) -> std::optional<std::string> { + if (reason) + *reason = std::move(why); return std::nullopt; + }; + if (!program.group[0] || !program.group[1] || !program.group[2]) + return refuse("group size has a zero dimension"); unsigned ud_count = 0; for (const auto &block : program.constants) { - if (block.root_parameter >= 16 || block.count > 8) - return std::nullopt; + if (block.root_parameter >= 16) + return refuse("root constants above root parameter 15"); + if (block.count > 8) + return refuse("more than 8 root constants in one root parameter"); ud_count += block.count; } + ud_count += static_cast<unsigned>(program.stride_srvs.size()); if (ud_count > 32) - return std::nullopt; + return refuse("more than 32 user data words"); auto sorted = program.bindings; std::sort(sorted.begin(), sorted.end(), [](const auto &a, const auto &b) { @@ -897,46 +938,67 @@ std::optional<std::string> format_compute_runtime_manifest(const NativeComputeSh unsigned srv_count = 0, uav_count = 0; std::ostringstream srv_lines, uav_lines, sampler_lines; for (const auto &b : sorted) { + if (b.root_parameter == compute_resource_heap) + return refuse("resource heap view"); + if (b.root_parameter == compute_sampler_heap) + return refuse("sampler heap"); if (b.root_parameter >= 16) - return std::nullopt; + return refuse("view above root parameter 15"); if (!compute_uav(b.kind)) { if (b.shader_register != srv_count++) - return std::nullopt; + return refuse("SRV registers not contiguous"); if (b.kind == ComputeViewKind::buffer_srv || b.kind == ComputeViewKind::raw_vector_srv || b.kind == ComputeViewKind::byte_window_srv) { srv_lines << "srv " << b.shader_register << " buf table " << b.root_parameter << ' ' << b.byte_offset << '\n'; - } else if (b.kind == ComputeViewKind::texture_srv && b.image_dimension == 1 && b.array_count == 1) { - srv_lines << "srv " << b.shader_register << " tex2d table " << b.root_parameter << ' ' << b.byte_offset - << '\n'; + } else if (b.kind == ComputeViewKind::texture_srv && b.array_count == 1 && + (b.image_dimension == 0 || b.image_dimension == 1 || b.image_dimension == 2 || + b.image_dimension == 5)) { + const char *tex = b.image_dimension == 0 ? "tex1d" + : b.image_dimension == 1 ? "tex2d" + : b.image_dimension == 2 ? "tex3d" + : "tex2da"; + srv_lines << "srv " << b.shader_register << ' ' << tex << " table " << b.root_parameter << ' ' + << b.byte_offset << '\n'; } else { - return std::nullopt; + return refuse(view_shape("SRV", b)); } } else { if (b.shader_register != uav_count++) - return std::nullopt; + return refuse("UAV registers not contiguous"); if (b.kind == ComputeViewKind::raw_buffer_uav) { uav_lines << "uav " << b.shader_register << " table " << b.root_parameter << ' ' << b.byte_offset << '\n'; + } else if (b.kind == ComputeViewKind::half_buffer_uav && b.array_count == 1 && + (b.required_bytes == 2 || b.required_bytes == 4 || b.required_bytes == 8)) { + uav_lines << "uav " << b.shader_register << " bufhalf table " << b.root_parameter << ' ' + << b.byte_offset << " bytes " << b.required_bytes << '\n'; } else if (b.kind == ComputeViewKind::uint_texture_uav && b.image_dimension == 1 && b.array_count == 1) { uav_lines << "uav " << b.shader_register << " tex2d uint table " << b.root_parameter << ' ' << b.byte_offset << " channels 1\n"; + } else if (const auto channels = exact_texture_uav_channels(b.kind); channels && b.array_count == 1 && + (b.image_dimension == 1 || b.image_dimension == 2 || b.image_dimension == 5)) { + const char *dimension = b.image_dimension == 2 ? "tex3d" : b.image_dimension == 5 ? "tex2da" : "tex2d"; + uav_lines << "uav " << b.shader_register << ' ' << dimension << " float table " << b.root_parameter + << ' ' << b.byte_offset << " channels " << channels << '\n'; } else if ((b.kind == ComputeViewKind::texture_uav || b.kind == ComputeViewKind::half4_texture_uav) && (b.image_dimension == 1 || b.image_dimension == 5) && b.array_count == 1) { uav_lines << "uav " << b.shader_register << (b.image_dimension == 5 ? " tex2da" : " tex2d") << " float table " << b.root_parameter << ' ' << b.byte_offset << " channels 4\n"; } else { - return std::nullopt; + return refuse(view_shape("UAV", b)); } } } - if (srv_count > 32 || uav_count > 8) - return std::nullopt; + if (srv_count > 32) + return refuse("more than 32 SRVs"); + if (uav_count > 8) + return refuse("more than 8 UAVs"); for (size_t i = 0; i < program.samplers.size(); ++i) { const auto &s = program.samplers[i]; if (s.comparison) - return std::nullopt; + return refuse("comparison sampler"); char line[64]; std::snprintf(line, sizeof(line), "%s %zu %08x %08x %08x %08x\n", s.explicit_lod ? "smpl" : "smp", i, s.words[0], s.words[1], s.words[2], s.words[3]); @@ -950,7 +1012,14 @@ std::optional<std::string> format_compute_runtime_manifest(const NativeComputeSh for (const auto &block : program.constants) for (unsigned j = 0; j < block.count; ++j) out << "udsrc " << ud_index++ << " rootconst " << block.root_parameter << ' ' << j << '\n'; - out << srv_lines.str() << uav_lines.str() << sampler_lines.str(); + for (unsigned srv : program.stride_srvs) { + if (srv >= srv_count || sorted[srv].kind != ComputeViewKind::raw_vector_srv || + sorted[srv].array_count != 1) + return refuse("stride words from a view that is not one raw vector SRV"); + out << "udsrc " << ud_index++ << " stride " << srv << '\n'; + } + out << srv_lines.str() << uav_lines.str() << sampler_lines.str() + << "native " << native_compute_output_revision << '\n'; return out.str(); } diff --git a/src/direct_compute_cache.h b/src/direct_compute_cache.h index 6b4b2ac932..ec388dc541 100644 --- a/src/direct_compute_cache.h +++ b/src/direct_compute_cache.h @@ -34,7 +34,9 @@ DirectGraphicsPair prepare_direct_graphics(std::string_view a, std::string_view std::string_view root = {}, std::string_view input_layout = {}, std::string_view pixel_entry = {}, bool write_cache = true, const std::vector<unsigned> &rtv_formats = {}); -std::optional<std::string> format_compute_runtime_manifest(const NativeComputeShader &program); +// Without a manifest, reason (when given) receives a fixed refusal text: no register numbers, offsets or keys. +std::optional<std::string> format_compute_runtime_manifest(const NativeComputeShader &program, + std::string *reason = nullptr); // rtv_request: the "rtv1 ..." text of an RTV variant, written as the manifest's last line for the runtime to match. std::optional<std::string> format_graphics_runtime_manifest(const DirectGraphicsPair &pair, std::string_view rtv_request = {}); diff --git a/src/dxil_module.h b/src/dxil_module.h index 1aa4b5a3c3..ee64237295 100644 --- a/src/dxil_module.h +++ b/src/dxil_module.h @@ -173,6 +173,9 @@ class DxilModule { << "b, %dx.types.ResourceProperties { i32 14, i32 0 })\n"; return h; } + // DXIL validator 1.8 accepts implicit-derivative operations in compute; every other + // module keeps validator 1.6. + unsigned validator_minor = 6; Text finish_compute(unsigned x, unsigned y, unsigned z, const Text &stage = "cs") { std::ostringstream out; out << "target datalayout = " @@ -233,7 +236,13 @@ class DxilModule { // AMD's DXIL compiler (amdxc64.dll) dereferences Module::getNamedMetadata("llvm.ident") without a null check. const auto ident = node("!\"x2w\""), version = node("i32 1, i32 6"), model = node("!\"" + stage + "\", i32 6, i32 6"); - const unsigned flags = features | (uses_wave ? 524288 : 0); + // 0x8000: more than 8 UAV slots. DXC sums the declared UAV range sizes; the validator + // refuses a module whose flags do not match. + unsigned uav_slots = 0; + for (const auto &r : resources) + if (r.cls == 1) + uav_slots += (std::min)(r.count, 9u); + const unsigned flags = features | (uses_wave ? 524288 : 0) | (uav_slots > 8 ? 0x8000 : 0); Text properties = "null", signature = "null", view_state; if (stage == "cs") { const auto size = @@ -314,7 +323,7 @@ class DxilModule { "readnone\n" "declare %dx.types.Handle " "@dx.op.annotateHandle(i32,%dx.types.Handle,%dx.types.ResourceProperties) nounwind readnone\n"; - out << "!llvm.ident = !{" << ident << "}\n!dx.version = !{" << version << "}\n!dx.valver = !{" << version + out << "!llvm.ident = !{" << ident << "}\n!dx.version = !{" << version << "}\n!dx.valver = !{" << node("i32 1, i32 " + std::to_string(validator_minor)) << "}\n!dx.shaderModel = !{" << model << "}\n"; if (res != "null") out << "!dx.resources = !{" << res << "}\n"; diff --git a/src/era_heap.cpp b/src/era_heap.cpp index 25520fc730..10e0f15cfc 100644 --- a/src/era_heap.cpp +++ b/src/era_heap.cpp @@ -76,7 +76,8 @@ Fields decode(std::uint64_t attributes) noexcept static_cast<std::uint32_t>((attributes >> 16) & 0xff), static_cast<std::uint32_t>((attributes >> 24) & 0x1f), static_cast<std::uint32_t>((attributes >> 29) & 0xf), - attributes >> 33, + static_cast<std::uint32_t>((attributes >> 33) & 1), + static_cast<std::uint32_t>((attributes >> 34) & 0x3fffffff), }; } @@ -87,6 +88,11 @@ void* allocate(std::size_t bytes, std::uint64_t attributes) noexcept if (bytes == 0 || fields.reserved != 0 || fields.page_size == 3) { return nullptr; } + // The title asked for an address below 4 GiB. This allocator does not yet provide + // one, so refuse instead of returning an address above that boundary. + if (fields.address_below_4gib) { + return nullptr; + } const auto alignment = std::size_t{1} << std::max(4u, fields.alignment); // Leave room for CRT alignment bookkeeping even for deliberately oversized input. const auto limit = static_cast<std::size_t>(std::numeric_limits<std::ptrdiff_t>::max()); @@ -112,7 +118,7 @@ void* allocate(std::size_t bytes, std::uint64_t attributes) noexcept // SlimEra commits graphics memory as a separate virtual allocation. The desktop // places it on an allocation-granularity boundary (64 KiB on x64 Windows), which // covers 4 KB and 64 KB pages. Larger page sizes or alignments are not honored here. - constexpr std::size_t page_bytes[]{std::size_t{4} << 10, std::size_t{64} << 10, std::size_t{4} << 20}; + constexpr std::size_t page_bytes[]{std::size_t{4} << 10, std::size_t{64} << 10, std::size_t{2} << 20}; if (std::max(page_bytes[fields.page_size], alignment) > allocation_granularity()) { return nullptr; } diff --git a/src/era_heap.h b/src/era_heap.h index 3c288b390f..515468cfd0 100644 --- a/src/era_heap.h +++ b/src/era_heap.h @@ -3,20 +3,21 @@ #include <cstddef> #include <cstdint> -// Desktop handling of attribute words decoded with the public Xbox One ERA -// XALLOC_ATTRIBUTES layout (SlimEra era.h): objectType:14, pageSize:2, allocatorId:8, -// alignment:5, memoryType:4, reserved:31. That Scarlett uses this layout is an -// assumption; allocator-ID meaning and GPU visibility of graphics types are unconfirmed. +// Desktop handling of attribute words decoded with the XALLOC_ATTRIBUTES layout +// published by the GDK 261000 xmem.h: objectType:14, pageSize:2, allocatorId:8, +// alignment:5, memoryType:4, an address-below-4-GiB bit at 33 and reserved:30 above it. +// Allocator-ID meaning and GPU visibility of graphics types remain unconfirmed. // Heap and graphics memory types are served. Physical memory types, undefined // field values and alignments the desktop cannot honor return a null pointer. namespace era_heap { struct Fields { std::uint32_t object_type; - std::uint32_t page_size; // 0: 4 KB, 1: 64 KB, 2: 4 MB, 3: undefined + std::uint32_t page_size; // 0: 4 KB, 1: 64 KB, 2: 2 MB, 3: undefined std::uint32_t allocator_id; std::uint32_t alignment; // log2 of the requested alignment std::uint32_t memory_type; // 0: heap, 1-6: graphics, 7-9: physical - std::uint64_t reserved; + std::uint32_t address_below_4gib; // 1: the caller asks for an address below 4 GiB + std::uint32_t reserved; // 30 bits, must be zero }; Fields decode(std::uint64_t attributes) noexcept; diff --git a/src/gfx1013_compute_alu.inl b/src/gfx1013_compute_alu.inl index 5cc4a835be..926bf006f2 100644 --- a/src/gfx1013_compute_alu.inl +++ b/src/gfx1013_compute_alu.inl @@ -45,6 +45,7 @@ static const std::map<Name,AluRule> alu_rules = { {"v_mul_u32_u24",{2,AluType::Bits,"({0} & 0xffffffu) * ({1} & 0xffffffu)"}}, {"v_or_b32",{2,AluType::Bits,"{0} | {1}"}}, {"v_rcp_f32",{1,AluType::Float,"1.0 / {0}"}}, + {"v_rcp_iflag_f32",{1,AluType::Float,"1.0 / {0}"}}, {"v_sin_f32",{1,AluType::Float,"sin({0} * 6.283185307)"}}, {"v_sqrt_f32",{1,AluType::Float,"sqrt({0})"}}, {"v_sub_f32",{2,AluType::Float,"{0} - {1}"}}, diff --git a/src/gfx1013_compute_native.cpp b/src/gfx1013_compute_native.cpp index d920892618..16cb36946e 100644 --- a/src/gfx1013_compute_native.cpp +++ b/src/gfx1013_compute_native.cpp @@ -29,6 +29,11 @@ static bool binary16_alu(std::string_view name) { return name == "v_add_f16" || name == "v_sub_f16" || name == "v_subrev_f16" || name == "v_mul_f16"; } +static bool binary16_unary(std::string_view name) { + return name == "v_rcp_f16" || name == "v_sqrt_f16" || name == "v_exp_f16" || + name == "v_rsq_f16"; +} + [[noreturn]] void refuse(unsigned pc, const string &reason) { std::ostringstream out; out << "native compute +0x" << std::hex << pc << ": " << reason; @@ -60,6 +65,7 @@ struct Inst { // 0..255 selects within a quad. Row operations and mirrors cross quads. std::optional<unsigned> dpp_control; unsigned dpp_row_mask = 15, dpp_bank_mask = 15; + std::optional<Word> dpp8_selectors; bool dpp_fetch_inactive = false; bool dpp_bound_zero = false; unsigned mirror_mask() const { return dpp_control == 0x141 ? 7 : dpp_control == 0x140 ? 15 : 0; } @@ -89,8 +95,8 @@ struct Inst { unsigned target() const { return next + 4 * static_cast<int16_t>(a & 65535); } }; unsigned memory_count(const Inst &i) { return 1u << (i.op & 7); } -// Wave32 compute can use both VCC words as scalar data. -unsigned smem_sgpr_limit(bool wave32_compute) { return wave32_compute ? 108 : 106; } +// Direct compute stores both VCC words in scalar registers. +unsigned smem_sgpr_limit(bool direct_compute) { return direct_compute ? 108 : 106; } Inst decode(const string &bytes, unsigned pc,bool direct=false, bool graphics=false, bool wave64=false) { const auto encoded=gfx1013::instruction(bytes,pc); @@ -164,7 +170,7 @@ Inst decode(const string &bytes, unsigned pc,bool direct=false, bool graphics=fa i.dst = (a >> 6) & 127; i.src[0] = (a & 63) * 2; const unsigned soffset = i.b >> 25; - const unsigned limit = smem_sgpr_limit(direct && !graphics && !wave64); + const unsigned limit = smem_sgpr_limit(direct && !graphics); if ((i.b & 0x01f00000u) || (a & 0x14000) || (i.op & ~8u) > 4 || (soffset != 125 && ((!direct && i.op < 8 && i.op != 2) || soffset >= limit))) refuse(pc, "unsupported scalar memory addressing"); @@ -205,13 +211,16 @@ Inst decode(const string &bytes, unsigned pc,bool direct=false, bool graphics=fa refuse(pc, "formatted store needs an index-only linear view and supported component count"); i.name = "buffer_store_format"; } else if (i.op >= 0x1c && i.op <= 0x1f) { - if ((a & (direct && !graphics ? 0x32000u : 0x3e000u)) || - (i.b & (direct && !graphics ? 0xa00000u : 0xe00000u))) + // Direct compute ignores GLC, DLC and SLC cache-policy hints on raw stores. + const bool compute = direct && !graphics; + if ((a & (compute ? 0x32000u : 0x3e000u)) || + (i.b & (compute ? 0xa00000u : 0xe00000u))) refuse(pc, "raw store needs a linear byte offset"); i.name = "buffer_store_raw"; } else if (i.op >= 0x0c && i.op <= 0x0f) { if (direct && !graphics) { - if ((a & 0x0203e000u) || (i.b & 0x00e00000u)) + // GLC, DLC and SLC are cache-policy hints on raw loads. + if ((a & 0x02032000u) || (i.b & 0x00a00000u)) refuse(pc, "raw buffer load needs a linear byte offset and no modifiers"); // The MUBUF encoding has no trailing literal word. const unsigned soffset = i.b >> 24; @@ -293,7 +302,11 @@ Inst decode(const string &bytes, unsigned pc,bool direct=false, bool graphics=fa } else refuse(pc, "unsupported instruction " + string(encoded.name) + " " + hexword(a)); if (!i.wide && (i.enc == Encoding::Vop1 || i.enc == Encoding::Vop2 || i.enc == Encoding::Vopc)) { - const bool half_alu = !graphics && i.enc == Encoding::Vop2 && binary16_alu(encoded.name); + const bool half_alu = !graphics && ((i.enc == Encoding::Vop2 && binary16_alu(encoded.name)) || + (i.enc == Encoding::Vop1 && binary16_unary(encoded.name))); + const bool dpp8 = i.src[0] == 233 || i.src[0] == 234; + if (direct && half_alu && (dpp8 || (i.enc == Encoding::Vop1 && i.src[0] == 250))) + refuse(pc, "unsupported " + string(encoded.name) + " DPP form"); const bool sdwa_logic = i.enc == Encoding::Vop2 && i.op == 0x1d; const bool sdwa_class = i.enc == Encoding::Vopc && (i.op == 0x88 || (direct && i.op == 0x8f)); const bool sdwa_compare = i.enc == Encoding::Vopc && !sdwa_class; @@ -309,7 +322,7 @@ Inst decode(const string &bytes, unsigned pc,bool direct=false, bool graphics=fa static const std::set<Name> floats{ "v_add_f32", "v_sub_f32", "v_subrev_f32", "v_mul_f32", "v_min_f32", "v_max_f32", "v_floor_f32", "v_ceil_f32", "v_fract_f32", "v_trunc_f32", "v_rndne_f32", - "v_exp_f32", "v_log_f32", "v_rcp_f32", "v_rsq_f32", "v_sqrt_f32"}; + "v_exp_f32", "v_log_f32", "v_rcp_f32", "v_rcp_iflag_f32", "v_rsq_f32", "v_sqrt_f32"}; const auto name = encoded.name; const bool fp_input = half_alu || floats.count(name) || name == "v_cvt_u32_f32" || name == "v_cvt_i32_f32" || name == "v_cvt_f16_f32" || name == "v_cvt_f32_f16" || name == "v_cvt_pkrtz_f16_f32" || @@ -333,7 +346,9 @@ Inst decode(const string &bytes, unsigned pc,bool direct=false, bool graphics=fa if (half_alu && ((i.dst_select != 4 && i.dst_select != 5) || (i.dst_unused != 0 && i.dst_unused != 2))) refuse(pc, "unsupported SDWA destination modifier"); - if (i.dst_select == 7 || i.dst_unused == 3 || ((i.clamp || i.scale) && !floats.count(name) && !conversion) || + const bool clamp_only = !graphics && name == "v_cvt_f32_f16"; + if (i.dst_select == 7 || i.dst_unused == 3 || + ((i.scale || (i.clamp && !clamp_only)) && !floats.count(name) && !conversion) || (sources == 1 && (ext & 0xbf000000u))) refuse(pc, "unsupported SDWA destination modifier"); } @@ -341,8 +356,6 @@ Inst decode(const string &bytes, unsigned pc,bool direct=false, bool graphics=fa const unsigned control = (ext >> (16 + 8*j)) & 255; i.src_select[j] = control & 7; i.src_sext[j] = (control & 8) != 0; - if (half_alu && (control & 128)) - refuse(pc, "SDWA binary16 source must be a VGPR"); if (half_alu && i.src_select[j] < 4) refuse(pc, "invalid SDWA source modifier"); if (i.src_select[j] == 7 || (control & 64) || (fp_input && i.src_sext[j]) || (!fp_input && (control & 0x30))) @@ -406,7 +419,12 @@ Inst decode(const string &bytes, unsigned pc,bool direct=false, bool graphics=fa i.src[0]=256+(control&255); i.neg=((control>>20)&1)|((control>>21)&2); i.abs=((control>>21)&1)|((control>>22)&2); - } else if (graphics && (i.src[0] == 233 || i.src[0] == 234) && i.enc != Encoding::Vopc && !lit) { + } else if (direct && !graphics && dpp8 && i.enc != Encoding::Vopc && !lit) { + const Word control = take(); + i.dpp8_selectors = control >> 8; + i.dpp_fetch_inactive = i.src[0] == 234; + i.src[0] = 256 + (control & 255); + } else if (graphics && dpp8 && i.enc != Encoding::Vopc && !lit) { // pixel_aot.parse_dpp: both halves of an octet must select the // same local 2x2 permutation to map to desktop quad operations. const Word control = take(); @@ -462,7 +480,8 @@ static std::optional<unsigned> carry_destination(const Inst &i) { } struct Symbol { enum class Type { unknown, constant, masked, table, descriptor, indexed_descriptor, sampler_heap, sampler_word, root_address, root_stride_one_high, primitive_mask, - stride, byte_stride, zero_stride_word, byte_count, clear_oob, byte_oob, lane_mask, uniform_mask, unbound } type{}; + stride, byte_stride, zero_stride_word, byte_count, clear_oob, byte_oob, lane_mask, uniform_mask, + heap_offset, heap_carry, unbound } type{}; Word value = 0, offset = 0; unsigned index_mask = 0, definition = 0; bool numeric() const { return type == Type::unknown || type == Type::constant || type == Type::masked || type == Type::uniform_mask; } @@ -474,6 +493,8 @@ struct State { // Encoded VGPR and guest lane. A join can lose the identity while // retaining the fact that some path omitted the runtime lane write. std::map<std::pair<unsigned, unsigned>, std::optional<Symbol>> lane_spills; + // SCC, tracked only as the carry of a heap offset add (see heap_offset_add). + Symbol scc{}; Symbol &operator[](unsigned n) { return scalar[n]; } const Symbol &operator[](unsigned n) const { return scalar[n]; } const Symbol &at(unsigned n) const { return scalar.at(n); } @@ -566,6 +587,30 @@ Symbol source(const Inst &i, unsigned code, const State &s) { return {Symbol::Type::constant, i.literal}; return {}; } +// The low word of a resource-heap descriptor address formed by adding a byte offset, as in a waterfall loop over a +// lane-selected slot: s_add_u32 lo, <resource heap>, <byte offset SGPR>, then the carry into the high word. Returns the +// operand index of the offset. A constant offset is not matched: the selected slot must come from GPU data. +static std::optional<unsigned> heap_offset_add(const Inst &i, const State &s) { + if (i.name != "s_add_u32" || i.dst > 105) return {}; + for (unsigned k = 0; k < 2; ++k) { + const auto heap = source(i, i.src[k], s), offset = source(i, i.src[1 - k], s); + if (heap.type == Symbol::Type::table && heap.value == compute_resource_heap && !heap.offset && + i.src[1 - k] <= 105 && offset.numeric() && offset.type != Symbol::Type::constant) + return 1 - k; + } + return {}; +} +// The high word of that address: s_add_u32 hi, 0, src_scc or s_addc_u32 hi, 0, 0. +static bool heap_offset_carry(const Inst &i) { + return i.dst <= 105 && ((i.name == "s_add_u32" && ((i.src[0] == 128 && i.src[1] == 253) || + (i.src[0] == 253 && i.src[1] == 128))) || + (i.name == "s_addc_u32" && i.src[0] == 128 && i.src[1] == 128)); +} +// s[base:base+1] holds the resource-heap base plus a byte offset with its own carry in the high word. +static bool heap_offset_address(const State &s, unsigned base) { + return base + 1 < s.size() && s[base].type == Symbol::Type::heap_offset && + s[base + 1].type == Symbol::Type::heap_carry && s[base + 1].definition == s[base].definition; +} // Derive the rewritten byte-address V# symbolically. Each field carries its // source table/slot identity. Numeric consumption still requires real bits. // heap_window: the direct path under HeapViewContract::raw_buffer also rewrites a @@ -610,6 +655,10 @@ State transfer(const Inst &i, State s, bool wave64, bool graphics, bool heap_win refuse(i.pc, "invalid SGPR"); s[n] = v; }; + const Symbol carry = s.scc; + if (i.enc == Encoding::Sop1 || i.enc == Encoding::Sop2 || i.enc == Encoding::Sopc || i.enc == Encoding::Sopk) + s.scc = {}; + const auto heap_add = direct && !graphics ? heap_offset_add(i, s) : std::nullopt; if (direct && !graphics) { if (i.name == "v_writelane_b32") { if (auto lane = guest_spill_lane(i, wave64)) { @@ -643,6 +692,13 @@ State transfer(const Inst &i, State s, bool wave64, bool graphics, bool heap_win (i.src[0] == 193 || i.src[0] == 128) && (i.src[1] == 193 || i.src[1] == 128)) { set(i.dst,{Symbol::Type::uniform_mask,i.pc,0}); set(i.dst+1,{Symbol::Type::uniform_mask,i.pc,1}); + } else if (heap_add) { + const auto offset = source(i, i.src[*heap_add], s); + set(i.dst, {Symbol::Type::heap_offset, compute_resource_heap, 0, + offset.type == Symbol::Type::masked ? offset.value : ~0u, i.pc}); + s.scc = {Symbol::Type::heap_carry, compute_resource_heap, 0, 0, i.pc}; + } else if (direct && !graphics && carry.type == Symbol::Type::heap_carry && heap_offset_carry(i)) { + set(i.dst, carry); } else if (auto field = byte_descriptor_field(i,s,heap_window)) { set(i.dst,*field); } else if (i.enc == Encoding::FixedSetup) { @@ -652,11 +708,14 @@ State transfer(const Inst &i, State s, bool wave64, bool graphics, bool heap_win } else if (i.enc == Encoding::Smem) { auto base = s[i.src[0]]; const unsigned offset_reg = i.b >> 25; - const Symbol index = offset_reg < smem_sgpr_limit(!graphics && !wave64) ? s[offset_reg] : Symbol{}; + const Symbol index = offset_reg < smem_sgpr_limit(direct && !graphics) ? s[offset_reg] : Symbol{}; unsigned n = memory_count(i); + const bool heap_address = i.op == 2 && i.b >> 25 == 125 && heap_offset_address(s, i.src[0]); for (unsigned j = 0; j < n; ++j) { Symbol v{}; - if (graphics && i.op == 3 && base.type == Symbol::Type::table && base.value == compute_resource_heap) { + if (heap_address) { + v = {Symbol::Type::indexed_descriptor, compute_resource_heap, (i.b & 0xfffff) + 4 * j, base.index_mask, i.pc}; + } else if (graphics && i.op == 3 && base.type == Symbol::Type::table && base.value == compute_resource_heap) { const bool fixed = offset_reg == 125 || index.type == Symbol::Type::constant; const Word offset = (i.b & 0xfffff) + (offset_reg != 125 && fixed ? index.value : 0); v = {Symbol::Type::indexed_descriptor, base.value, offset + 4*j, @@ -677,6 +736,20 @@ State transfer(const Inst &i, State s, bool wave64, bool graphics, bool heap_win set(i.dst, v); if (i.name == "s_mov_b64") set(i.dst + 1, high); + } else if (!graphics && !wave64 && i.enc == Encoding::Sop1 && + ((i.name.size() > 13 && i.name.substr(i.name.size() - 13) == "_saveexec_b32") || + i.name == "s_andn1_wrexec_b32" || i.name == "s_andn2_wrexec_b32")) { + // Both the saved/written destination and the updated EXEC are numeric mask words. + set(i.dst, {}); + set(126, {}); + } else if (!graphics && i.enc == Encoding::Sop1 && i.name.size() >= 13 && + (i.name.substr(i.name.size() - 13) == "_saveexec_b64" || + i.name.substr(i.name.size() - 11) == "_wrexec_b64")) { + // These instructions also overwrite both EXEC words implicitly. + set(i.dst, {}); + set(i.dst + 1, {}); + set(126, {}); + set(127, {}); } else if (i.name == "s_and_b32" || i.name == "s_lshl_b32") { const auto a = source(i, i.src[0], s), b = source(i, i.src[1], s); Symbol out{}; @@ -871,6 +944,10 @@ Program parse(const string &code, unsigned entry, const State &initial, bool gra changed = true; } } + if (!(in.scc == after.scc) && !(in.scc == Symbol{})) { + in.scc = {}; + changed = true; + } for (auto &[key, value] : in.lane_spills) { const auto other = after.lane_spills.find(key); if (value && (other == after.lane_spills.end() || !(other->second == value))) { @@ -1734,11 +1811,13 @@ static NativeComputeShader translate_program(const ComputeRequest &request, unsi initial[next] = {Symbol::Type::table, compute_resource_heap}; initial[next + 1] = {Symbol::Type::table, compute_sampler_heap}; } - // Tagged slot-67 CS state packs group Z into the low 16 bits of word 4 - // and wave32 into bit 20. Leave untagged synthetic request ABIs alone. + // The legacy HLSL profile models wave32. Direct DXIL supports both guest wave sizes. A wave64 request whose + // group has at most 32 threads stays on the wave32 model, as before the wave size was read: its one guest wave + // has lanes 0..31 only, so EXEC's high word is zero and v_mbcnt_hi adds nothing for its lanes. The model + // does not write the zero high word that a wave64 compare or carry-out stores in an SGPR pair destination. const bool packed_state = !stage && direct_dxil && word(request.sa,0)==0x4005cf00 && word(request.sa,4)==0x6c090102; - const bool wave64 = stage ? !stage->wave32 : packed_state && !(word(request.sa,16)&(1u<<20)); + const bool wave64 = stage ? !stage->wave32 : direct_dxil && !request.wave32 && threads > 32; // The byte-address rewrite of a GPU-selected heap descriptor is read only under the raw_buffer contract. const bool heap_window = direct_dxil && heap_view == HeapViewContract::raw_buffer; auto program = parse(request.code, entry, initial, direct_dxil, false, wave64, false, heap_window); diff --git a/src/gfx1013_compute_native.h b/src/gfx1013_compute_native.h index 44d0a9fb1e..d7ccd7f907 100644 --- a/src/gfx1013_compute_native.h +++ b/src/gfx1013_compute_native.h @@ -42,9 +42,20 @@ enum class ComputeViewKind { // fallback and never read. heap_sampler, uint_texture_uav, + float_texture_uav, + float2_texture_uav, + float3_texture_uav, packed_d16_x_uav, // Single low-halfword payload; desktop buffer view determines the element size. indexed_raw_srv // Fixed-stride record read. required_bytes is one complete record and its checked stride. }; +inline unsigned exact_texture_uav_channels(ComputeViewKind kind) { + switch (kind) { + case ComputeViewKind::float_texture_uav: return 1; + case ComputeViewKind::float2_texture_uav: return 2; + case ComputeViewKind::float3_texture_uav: return 3; + default: return 0; + } +} inline bool accepts_cbv_window(ComputeViewKind kind) { return kind == ComputeViewKind::buffer_srv || kind == ComputeViewKind::byte_window_srv; } @@ -64,7 +75,7 @@ struct IndexedAtomicView { inline bool compute_uav(ComputeViewKind kind) { return kind == ComputeViewKind::texture_uav || kind == ComputeViewKind::half_scalar_uav || kind == ComputeViewKind::half2_texture_uav || kind == ComputeViewKind::half4_texture_uav || - kind == ComputeViewKind::uint_texture_uav || compute_buffer_uav(kind); + kind == ComputeViewKind::uint_texture_uav || exact_texture_uav_channels(kind) || compute_buffer_uav(kind); } struct ComputeViewBinding { ComputeViewKind kind; @@ -121,6 +132,8 @@ struct NativeComputeShader { std::vector<MeshHeapRead> mesh_heap_reads; std::vector<GraphicsLinkage> inputs, outputs; std::vector<ComputeConstants> constants; + // Additional b0 words, after root constants, read from these bound SRVs. + std::vector<unsigned> stride_srvs; std::string hlsl, dxil_ir; std::vector<ComputeViewBinding> bindings; std::vector<ComputeSampler> samplers; diff --git a/src/gfx1013_compute_opcodes.inl b/src/gfx1013_compute_opcodes.inl index 5c9499bee6..555e168dff 100644 --- a/src/gfx1013_compute_opcodes.inl +++ b/src/gfx1013_compute_opcodes.inl @@ -92,6 +92,7 @@ static const char* mnemonic(Encoding enc, unsigned op) { case 0x25: return "v_exp_f32"; case 0x27: return "v_log_f32"; case 0x2a: return "v_rcp_f32"; + case 0x2b: return "v_rcp_iflag_f32"; case 0x33: return "v_sqrt_f32"; case 0x35: return "v_sin_f32"; default: break; diff --git a/src/gfx1013_direct_compute.inl b/src/gfx1013_direct_compute.inl index 7790016ee9..2411a4f6dc 100644 --- a/src/gfx1013_direct_compute.inl +++ b/src/gfx1013_direct_compute.inl @@ -4,6 +4,30 @@ struct DirectCompute { // The nine inline float constants as binary16, which an f16 operand reads instead of the f32 pattern. static constexpr Word inline_half_words[]{0x3800, 0xb800, 0x3c00, 0xbc00, 0x4000, 0xc000, 0x4400, 0xc400, 0x3118}; + // D3D exp (sm4 asm) has relative error <= 2^-21, or < 8 ULP for normal f32 results. + // tests/f16_exp_midpoints.py generates the non-tie cases within that window + // using a 90-digit reference. The exact tie at -25 is handled separately. + struct ExpF16Midpoint { Word source, result; }; + static constexpr ExpF16Midpoint exp_f16_midpoints[]{ + {0x11c3, 0x3c00}, {0x11c4, 0x3c00}, {0x11c5, 0x3c01}, {0x11c6, 0x3c01}, + {0x11c7, 0x3c01}, {0x1853, 0x3c01}, {0x1b34, 0x3c02}, {0x1b35, 0x3c03}, + {0x1e7a, 0x3c04}, {0x1fea, 0x3c06}, {0x2164, 0x3c08}, {0x221b, 0x3c08}, + {0x2389, 0x3c0a}, {0x2bdb, 0x3c2c}, {0x2e7c, 0x3c4a}, {0x2ea7, 0x3c4c}, + {0x2fe7, 0x3c5b}, {0x36b6, 0x3d5a}, {0x3863, 0x3dd9}, {0x39f8, 0x3eb5}, + {0x3a8a, 0x3f0c}, {0x3b12, 0x3f62}, {0x3b82, 0x3faa}, {0x3efc, 0x42b5}, + {0x3f45, 0x430c}, {0x3f89, 0x4362}, {0x3fc1, 0x43aa}, {0x417e, 0x46b5}, + {0x437e, 0x4ab5}, {0x44bf, 0x4eb5}, {0x45bf, 0x52b5}, {0x46bf, 0x56b5}, + {0x47bf, 0x5ab5}, {0x8dc3, 0x3c00}, {0x8dc4, 0x3c00}, {0x8dc5, 0x3c00}, + {0x8dc6, 0x3bff}, {0x8dc7, 0x3bff}, {0x8dc8, 0x3bff}, {0x9454, 0x3bff}, + {0x9455, 0x3bfe}, {0x9738, 0x3bfd}, {0x990e, 0x3bfc}, {0x9a80, 0x3bfb}, + {0x9bf2, 0x3bfb}, {0x9e25, 0x3bf7}, {0x9f98, 0x3bf5}, {0xa2b4, 0x3bed}, + {0xa52d, 0x3be3}, {0xa86d, 0x3bd0}, {0xa8b4, 0x3bcc}, {0xa9d1, 0x3bc0}, + {0xabe0, 0x3baa}, {0xaf57, 0x3b63}, {0xaf70, 0x3b62}, {0xb1d8, 0x3b0c}, + {0xb410, 0x3ab5}, {0xb4db, 0x3a7c}, {0xb73a, 0x39d9}, {0xb8a5, 0x395a}, + {0xbc3f, 0x37aa}, {0xbc77, 0x3762}, {0xbcbb, 0x370c}, {0xbd04, 0x36b5}, + {0xc082, 0x32b5}, {0xc282, 0x2eb5}, {0xc441, 0x2ab5}, {0xc541, 0x26b5}, + {0xc641, 0x22b5}, {0xc741, 0x1eb5}, + }; static void validate_lane_shape(const Inst &i, unsigned threads, unsigned width) { const auto constant = constant32(i, i.src[1]); const auto remaining = threads % width; @@ -24,7 +48,7 @@ struct DirectCompute { HeapViewContract heap_view = HeapViewContract::none; // heap_view is raw_buffer and the path is direct: the byte-address rewrite of a heap descriptor is tracked. bool heap_window = false; - // Binary16 add, sub, subrev and mul are lowered only while MODE stays at + // Binary16 arithmetic is lowered only while MODE stays at // the contract this path implements: round-to-nearest-even, f16 denormals // kept on input and output, and FP16_OVFL clear. mode_bits holds the // fields this path tracks (round in [3:0], denorm in [7:4], FP16_OVFL in @@ -34,10 +58,13 @@ struct DirectCompute { bool half_mode_known = true; unsigned mode_bits = 0xf0; std::vector<bool> scc_live; + std::map<std::pair<unsigned,unsigned>,string> descriptor_strides; unsigned label_number = 0; bool pixel_stage = false; bool pixel_heap_enabled = false; struct PixelHeapIndex { string index; unsigned first, last; bool nonuniform; }; + bool complete_compute_quads = false; + bool compute_derivatives = false; // Straight-line graphics stages keep exact SSA definitions; a missing // entry value is resolved through the container's stage signature. std::function<string(unsigned)> graphics_input; @@ -216,6 +243,7 @@ struct DirectCompute { } void initialize(unsigned user, unsigned flags, unsigned x, unsigned y, unsigned z) { unsigned threads = x * y * z; + complete_compute_quads = threads % 4 == 0; if (!virtual_waves) { lane = ir.invoke("i32", "waveGetLaneIndex", 111, {}, "nounwind readnone"); lane_bit = ir.binary("shl", "1", lane); @@ -278,7 +306,7 @@ struct DirectCompute { initialize_constants(); } void initialize_constants(const GraphicsConstantLayout *linked = nullptr) { - unsigned words = 0; + unsigned words = static_cast<unsigned>(descriptor_strides.size()); for (const auto &block : analysis.result.constants) words += block.count; if (words) { @@ -287,18 +315,21 @@ struct DirectCompute { auto h = ir.handle({2, 0, 13, 0, 0, (words + 3) / 4 * 16}); unsigned pos = 0; std::map<unsigned, string> vectors; + const auto word_at = [&](unsigned at) { + auto &vec = vectors[at / 4]; + if (vec.empty()) + vec = ir.invoke("%dx.types.CBufRet.i32", "cbufferLoadLegacy.i32", 59, + {{"%dx.types.Handle", h}, {"i32", to_string(at / 4)}}, "nounwind readonly"); + return ir.value("extractvalue %dx.types.CBufRet.i32 " + vec + ", " + to_string(at % 4)); + }; for (const auto &block : analysis.result.constants) { if (linked) pos = linked->offset(block.root_parameter); - for (unsigned j = 0; j < block.count; ++j, ++pos) { - auto &vec = vectors[pos / 4]; - if (vec.empty()) - vec = ir.invoke("%dx.types.CBufRet.i32", "cbufferLoadLegacy.i32", 59, - {{"%dx.types.Handle", h}, {"i32", to_string(pos / 4)}}, "nounwind readonly"); - write(block.first_sgpr + j, - ir.value("extractvalue %dx.types.CBufRet.i32 " + vec + ", " + to_string(pos % 4))); - } + for (unsigned j = 0; j < block.count; ++j, ++pos) + write(block.first_sgpr + j, word_at(pos)); } + for (auto &entry : descriptor_strides) + entry.second = ir.binary("and",word_at(pos++),"16383"); } } // Refuses a GPU-selected heap read that the contract does not cover. raw_buffer is the only class that is translated. @@ -558,7 +589,7 @@ struct DirectCompute { } if (i.enc == Encoding::Smem) { unsigned so = i.b >> 25; - const unsigned limit = smem_sgpr_limit(!graphics_input && !wave64); + const unsigned limit = smem_sgpr_limit(!graphics_input); const auto &low = s.at(i.src[0]); if (low.type == Symbol::Type::sampler_heap) { if (i.op != 2 || !(s.at(i.src[0] + 1) == Symbol{Symbol::Type::constant, 0})) @@ -593,6 +624,29 @@ struct DirectCompute { return; } const bool root = low.type == Symbol::Type::root_address; + // Table and heap-offset descriptor lowering track identities and slot indices instead of + // loading payload bits. + if (wave64 && !graphics_input && i.op < 8 && + (low.type == Symbol::Type::table || low.type == Symbol::Type::heap_offset) && + i.dst + memory_count(i) > 106) + refuse(i.pc, "symbolic scalar memory destination overlaps wave64 VCC"); + if (low.type == Symbol::Type::heap_offset) { + // A resource-heap address formed by s_add_u32 (heap_offset_add): the same slot read as the SGPR-offset + // load below, with the byte offset in the low word. + if (!heap_offset_address(s, i.src[0])) + refuse(i.pc, "heap descriptor address high word is not the carry of its offset add"); + if (i.op != 2) + refuse(i.pc, "heap descriptor address must load one descriptor with s_load_dwordx4"); + refuse_heap_contract(i.pc); + if (so != 125) + refuse(i.pc, "heap descriptor address with a second offset register"); + if (i.b & 0xfffff) + refuse(i.pc, "heap descriptor load with an immediate offset addresses another slot than the captured selection"); + auto index = ir.binary("lshr", read(i.src[0]), "5"); + for (unsigned j = 0; j < 4; ++j) + write(i.dst + j, index); + return; + } if (!root && low.type == Symbol::Type::table && low.value == compute_resource_heap) { // Reads from the whole descriptor heap: only the indexed descriptor load of a captured raw buffer slot. if (i.op >= 8) @@ -911,8 +965,21 @@ struct DirectCompute { vector_write(256 + i.dst + j, select(have_view, ir.value("bitcast float " + value + " to i32"), "0")); } } + static int image_atomic_binop(unsigned op) { + switch (op) { + case 0x0f: return 8; // Exchange + case 0x11: return 0; // IAdd + case 0x15: return 6; // UMin + case 0x17: return 7; // UMax + case 0x18: return 1; // And + case 0x19: return 2; // Or + case 0x1a: return 3; // Xor + // Signed min/max is not verified on this R32_UINT binding. + default: return -1; + } + } static bool is_image_atomic(const Inst &i) { - return i.enc == Encoding::Image && (i.op == 16 || i.op == 17 || i.op == 23); + return i.enc == Encoding::Image && (i.op == 0x10 || image_atomic_binop(i.op) >= 0); } void image_atomic(const Inst &i, const State &s) { const bool compare_exchange = i.op == 16; @@ -939,7 +1006,7 @@ struct DirectCompute { << "\nimageAtomic" << label << ":\n"; std::vector<std::pair<string, string>> args{{"%dx.types.Handle", handle}}; if (!compare_exchange) - args.emplace_back("i32", i.op == 17 ? "0" : "7"); // AtomicBinOp IADD or UMAX. + args.emplace_back("i32", to_string(image_atomic_binop(i.op))); args.emplace_back("i32", read(256 + coord)); args.emplace_back("i32", read(257 + coord)); args.emplace_back("i32", "undef"); @@ -968,8 +1035,13 @@ struct DirectCompute { const bool compare_gather = i.op == 79; const bool compare = i.op == 40 || i.op == 47 || compare_gather; const bool implicit = i.op == 32 || i.op == 40 || bias || query || i.op == 64; - if (implicit && !pixel_stage) - refuse(i.pc, "implicit derivatives require a pixel stage"); + if (implicit && !pixel_stage) { + if (!complete_compute_quads) + refuse(i.pc, "implicit derivatives require a pixel stage"); + if (virtual_waves) + refuse(i.pc, "implicit derivatives with virtual wave64 groups"); + compute_derivatives = true; + } const bool gather = i.op == 64 || i.op == 71 || compare_gather; const bool gather_lod = i.op == 68; const bool sample = (!gather && implicit) || (compare && !gather) || gradient || i.op == 39 || i.op == 36, @@ -981,14 +1053,19 @@ struct DirectCompute { constexpr unsigned coord_count[]{1, 2, 3, 3, 2, 3, 2, 3}; const unsigned coords = coord_count[dim]; const bool indexed = pixel_stage && !store && s.at(base).type == Symbol::Type::indexed_descriptor; - if ((i.op != 0 && i.op != 1 && !store && !sample && !gather && !gather_lod && !dimensions) || !mask || (i.a & 0x3e0c0u) || + const bool exact_store = store && !half && !graphics_input && (dim == 1 || dim == 2 || dim == 5) && + (mask == 1 || mask == 3 || mask == 7); + // Read-only image ops ignore GLC (bit 13, 0x2000) and DLC (bit 7, 0x0080) cache hints; + // LWE (0x20000), TFE (0x10000), R128 (0x8000), reserved bits (0x4040), and store GLC/DLC stay refused. + if ((i.op != 0 && i.op != 1 && !store && !sample && !gather && !gather_lod && !dimensions) || !mask || + (i.a & (store ? 0x3e0c0u : 0x3c040u)) || (i.b & 0x3c000000u) || (gather && ((mask & (mask - 1)) || (dim != 1 && dim != 3 && dim != 5))) || (query && ((dim != 1 && dim != 3) || (mask & ~3u))) || (compare && (mask != 1 || (dim != 1 && dim != 3 && dim != 5) || (i.a & 0x1000u))) || (compare_gather && dim == 3) || ((sample || gather) && (i.a & 0x1000u) && gradient) || (dimensions && (dim == 4 || dim >= 6 || (i.b & 0x40000000u))) || - (store && !half && mask != 15) || (half && mask != 1 && mask != 3 && mask != 15) || + (store && !half && mask != 15 && !exact_store) || (half && mask != 1 && mask != 3 && mask != 15) || (!indexed && s.at(base).type != Symbol::Type::descriptor)) refuse(i.pc, "direct image opcode or descriptor modifiers"); if (gather_lod && (dim != 1 || (mask & (mask - 1)) || (i.a & 0x1006u) || (i.b & 0xc0000000u) || i.dst > 252)) @@ -997,10 +1074,13 @@ struct DirectCompute { (dim >= 6 && (sample || gather || store || lod))) refuse(i.pc, "unsupported cube or multisample operation"); const bool d16_sample = !store && (i.b >> 31); - const unsigned channels = half && mask == 1 ? 1 : half && mask == 3 ? 2 : 4; + const unsigned channels = (half || exact_store) && mask == 1 ? 1 : + (half || exact_store) && mask == 3 ? 2 : exact_store ? 3 : 4; const bool cube_sample = dim == 3 && (sample || gather); const auto kind = half ? (channels == 1 ? ComputeViewKind::half_scalar_uav : channels == 2 ? ComputeViewKind::half2_texture_uav : ComputeViewKind::half4_texture_uav) + : exact_store ? (channels == 1 ? ComputeViewKind::float_texture_uav : + channels == 2 ? ComputeViewKind::float2_texture_uav : ComputeViewKind::float3_texture_uav) : store ? ComputeViewKind::texture_uav : cube_sample ? (compare ? ComputeViewKind::cube_comparison_srv : ComputeViewKind::cube_sample_srv) : d16_sample ? ComputeViewKind::d16_sample_srv @@ -1366,7 +1446,7 @@ struct DirectCompute { return ir.binary("or", h, sign); } static bool packed_f16_arithmetic(Name n) { - return n == "v_pk_add_f16" || n == "v_pk_mul_f16" || n == "v_pk_fma_f16"; + return n == "v_pk_add_f16" || n == "v_pk_mul_f16" || n == "v_pk_fma_f16" || n == "v_pk_fmac_f16"; } string fused_half_rne(const string &a, const string &b, const string &c) { auto both = [&](const string &x, const string &y) { return ir.value("and i1 " + x + ", " + y); }; @@ -1446,19 +1526,43 @@ struct DirectCompute { return select(nan, "32256", select(product_inf, ir.binary("or", product_sign, "31744"), select(c_inf, c, finite))); } - void packed_f16_alu(const Inst &i) { - const bool fused = i.name == "v_pk_fma_f16"; - if (i.enc != Encoding::Mix || i.clamp || (!fused && (i.src[2] || (i.a & 0x2400) || (i.neg & 4)))) + static std::optional<uint32_t> packed_f16_inline_constant(unsigned r) { + if (r >= 240 && r <= 248) { + // On gfx1013 (RDNA 2), inline binary16 float constants occupy bits [15:0] with bits [31:16] zeroed. + constexpr uint32_t halves[]{0x3800u, 0xb800u, 0x3c00u, 0xbc00u, 0x4000u, + 0xc000u, 0x4400u, 0xc400u, 0x3118u}; + return halves[r - 240]; + } + if (r >= 128 && r <= 192) + return r - 128u; + if (r >= 193 && r <= 208) + return static_cast<uint32_t>(192u - r); + return std::nullopt; + } + void packed_f16_alu(const Inst &i, const string *permuted = nullptr) { + const bool fmac = i.name == "v_pk_fmac_f16"; + const bool fused = i.name == "v_pk_fma_f16" || fmac; + if (fmac) { + if (i.enc != Encoding::Vop2 || i.wide || i.subword || i.dpp_control || permuted || + i.abs || i.neg || i.clamp || i.scale) + refuse(i.pc, "unsupported packed binary16 arithmetic encoding"); + } else if (i.enc != Encoding::Mix || (!fused && (i.src[2] || (i.a & 0x2400) || (i.neg & 4)))) { refuse(i.pc, "unsupported packed binary16 arithmetic encoding"); + } if (!half_mode_known || ((mode_bits ^ 0xf0u) & 0x8000ccu)) refuse(i.pc, "unsupported binary16 rounding or denormal mode"); std::array<string, 3> words; - for (unsigned j = 0; j < (fused ? 3u : 2u); ++j) { + for (unsigned j = 0; j < (fmac ? 2u : fused ? 3u : 2u); ++j) { unsigned r = i.src[j]; - if (r > 105 && r < 256 && r != 128 && r != 255) + if (auto inline_word = packed_f16_inline_constant(r)) + words[j] = to_string(*inline_word); + else if (r <= 105 || r == 255 || (r >= 256 && r < 512)) + words[j] = operand32(i, r); + else refuse(i.pc, "unsupported packed binary16 arithmetic source"); - words[j] = operand32(i, r); } + if (fmac) + words[2] = read(i.dst); auto lane = [&](unsigned selectors, unsigned negate) { auto operand = [&](unsigned j) { auto bits = (selectors & (1u << j)) ? ir.binary("lshr", words[j], "16") @@ -1466,34 +1570,114 @@ struct DirectCompute { return (negate & (1u << j)) ? ir.binary("xor", bits, "32768") : bits; }; auto a = operand(0), b = operand(1); - if (fused) - return fused_half_rne(a, b, operand(2)); - auto widen = [&](const string &bits) { - return ir.invoke("float", "legacyF16ToF32", 131, {{"i32", bits}}, "nounwind readnone"); - }; - const auto op = i.name == "v_pk_mul_f16" ? "fmul" : "fadd"; - auto result = ir.value(string(op) + " float " + widen(a) + ", " + widen(b)); - auto bits = packed_half_rne(ir.value("bitcast float " + result + " to i32")); - return select(cmp("ugt", ir.binary("and", bits, "32767"), "31744"), "32256", bits); + string bits; + if (fused) { + bits = fused_half_rne(a, b, operand(2)); + } else { + auto widen = [&](const string &half_bits) { + return ir.invoke("float", "legacyF16ToF32", 131, {{"i32", half_bits}}, "nounwind readnone"); + }; + const auto op = i.name == "v_pk_mul_f16" ? "fmul" : "fadd"; + auto result = ir.value(string(op) + " float " + widen(a) + ", " + widen(b)); + bits = packed_half_rne(ir.value("bitcast float " + result + " to i32")); + bits = select(cmp("ugt", ir.binary("and", bits, "32767"), "31744"), "32256", bits); + } + if (i.clamp) { + auto nan = cmp("ugt", ir.binary("and", bits, "32767"), "31744"); + auto low = ir.value("or i1 " + nan + ", " + cmp("ne", ir.binary("and", bits, "32768"), "0")); + bits = select(low, "0", select(cmp("ugt", bits, "15359"), "15360", bits)); + } + return bits; }; - // In VOP3P, NEG_HI occupies the ABS field. OP_SEL_HI[2] lives in word 0. - auto low = lane((i.a >> 11) & 7, i.neg); - auto high = lane(((i.b >> 27) & 3) | ((i.a >> 12) & 4), i.abs); + // In VOP3P, NEG_HI occupies the ABS field and OP_SEL_HI[2] lives in word 0. + // VOP2 v_pk_fmac_f16 runs low halves (pair 0) and high halves (pair 1) with no modifiers. + auto low = lane(fmac ? 0u : ((i.a >> 11) & 7u), fmac ? 0u : i.neg); + auto high = lane(fmac ? 7u : (((i.b >> 27) & 3u) | ((i.a >> 12) & 4u)), fmac ? 0u : i.abs); vector_write(i.dst, ir.binary("or", low, ir.binary("shl", high, "16"))); } bool float_alu(const Inst &i, const string *permuted = nullptr) { auto n = i.name; if (packed_f16_arithmetic(n)) { - packed_f16_alu(i); + packed_f16_alu(i, permuted); + return true; + } + const bool dot2c = n == "v_dot2c_f32_f16"; + if (n == "v_dot2_f32_f16" || dot2c) { + if (dot2c) { + if (i.enc != Encoding::Vop2 || i.wide || i.subword || i.dpp_control || permuted || + i.abs || i.neg || i.clamp || i.scale) + refuse(i.pc, "unsupported v_dot2c_f32_f16 encoding"); + } else if (i.enc != Encoding::Mix || i.dpp_control || permuted || (i.a & 0x2400)) { + refuse(i.pc, "unsupported v_dot2_f32_f16 encoding"); + } + if (!half_mode_known || ((mode_bits ^ 0xf0u) & 0x8000ffu)) + refuse(i.pc, "unsupported binary16 rounding or denormal mode"); + auto half_pair = [&](unsigned j) { + const unsigned r = i.src[j]; + if (auto inline_word = packed_f16_inline_constant(r)) + return to_string(*inline_word); + if (r <= 105 || r == 255 || (r >= 256 && r < 512)) + return operand32(i, r); + refuse(i.pc, dot2c ? "unsupported v_dot2c_f32_f16 source" : "unsupported v_dot2_f32_f16 source"); + }; + const auto s0 = half_pair(0), s1 = half_pair(1); + string cbits; + if (dot2c) { + cbits = read(i.dst); + } else { + const unsigned r2 = i.src[2]; + if ((r2 > 105 && r2 < 128) || (r2 > 208 && r2 < 240) || (r2 > 248 && r2 < 255) || r2 >= 512) + refuse(i.pc, "unsupported v_dot2_f32_f16 source"); + cbits = operand32(i, r2); + if (i.neg & 4u) + cbits = ir.binary("xor", cbits, "2147483648"); + } + const auto c = ir.value("bitcast i32 " + cbits + " to float"); + auto term = [&](const string &word, unsigned selector, bool negate) { + auto bits = selector ? ir.binary("lshr", word, "16") : ir.binary("and", word, "65535"); + if (negate) + bits = ir.binary("xor", bits, "32768"); + return ir.invoke("float", "legacyF16ToF32", 131, {{"i32", bits}}, "nounwind readnone"); + }; + // VOP3P pair 0 uses OP_SEL[1:0]/NEG_LO[1:0] and pair 1 uses OP_SEL_HI[1:0]/NEG_HI[1:0] (in ABS). + // VOP2 v_dot2c_f32_f16 always dots low halves (pair 0 = 0) and high halves (pair 1 = 3) with no modifiers. + const unsigned op_sel = dot2c ? 0u : ((i.a >> 11) & 3u); + const unsigned op_sel_hi = dot2c ? 3u : ((i.b >> 27) & 3u); + auto a0 = term(s0, op_sel & 1u, (i.neg & 1u) != 0); + auto b0 = term(s1, (op_sel >> 1) & 1u, (i.neg & 2u) != 0); + auto a1 = term(s0, op_sel_hi & 1u, (i.abs & 1u) != 0); + auto b1 = term(s1, (op_sel_hi >> 1) & 1u, (i.abs & 2u) != 0); + auto p0 = ir.value("fmul float " + a0 + ", " + b0); + auto p1 = ir.value("fmul float " + a1 + ", " + b1); + auto sum = ir.value("fadd float " + p0 + ", " + p1); + auto sum_bits = ir.value("bitcast float " + sum + " to i32"); + auto res = ir.value("fadd float " + sum + ", " + c); + // Desktop DXIL fadd/saturate flush binary32 denormals to zero, whereas + // gfx1013 starts with MODE[5:4] = 3 (keep FP32 denormals). Every nonzero + // binary16*binary16 sum has |sum| >= 2^-48 >> 2^-126, so a binary32 + // subnormal accumulator c is observable iff sum == +/-0.0. + auto c_mag = ir.binary("and", cbits, "2147483647"); + auto sum_zero = cmp("eq", ir.binary("and", sum_bits, "2147483647"), "0"); + auto c_subnormal = ir.value("and i1 " + cmp("ne", c_mag, "0") + ", " + cmp("ult", c_mag, "8388608")); + auto keep_subnormal = ir.value("and i1 " + sum_zero + ", " + c_subnormal); + string res_bits; + if (i.clamp) { + auto sat = ir.invoke("float", "unary.f32", 7, {{"float", res}}, "nounwind readnone"); + auto clamped_sub = select(cmp("slt", cbits, "0"), "0", cbits); + res_bits = select(keep_subnormal, clamped_sub, ir.value("bitcast float " + sat + " to i32")); + } else { + res_bits = select(keep_subnormal, cbits, ir.value("bitcast float " + res + " to i32")); + } + vector_write(i.dst, res_bits); return true; } if ((i.subword || (!i.wide && !i.dpp_control && !permuted)) && (n == "v_cvt_f16_f32" || n == "v_cvt_f32_f16")) { - if (i.scale || i.clamp || i.src_sext[0]) + const bool narrow = n == "v_cvt_f16_f32"; + if (i.scale || (i.clamp && (narrow || !i.subword)) || i.src_sext[0]) refuse(i.pc, "unsupported SDWA half conversion modifier"); string bits = operand32(i, i.src[0]); if (i.subword) bits = subword(bits, i.src_select[0], false); - const bool narrow = n == "v_cvt_f16_f32"; if (i.abs) bits = ir.binary("and", bits, narrow ? "2147483647" : "32767"); if (i.neg) bits = ir.binary("xor", bits, narrow ? "2147483648" : "32768"); if (narrow) { @@ -1502,10 +1686,67 @@ struct DirectCompute { } else { auto f = ir.invoke("float", "legacyF16ToF32", 131, {{"i32",bits}}, "nounwind readnone"); bits = ir.value("bitcast float " + f + " to i32"); + if (i.clamp) { + // Integer clamp, as v_ldexp does: a set sign bit or NaN gives +0, values above 1.0 give 1.0. + // dx.op saturate may keep -0 or flush a denormal depending on the float mode. + auto nan = cmp("ugt", ir.binary("and", bits, "2147483647"), "2139095040"); + auto low = ir.value("or i1 " + nan + ", " + cmp("slt", bits, "0")); + bits = select(low, "0", select(cmp("sgt", bits, "1065353215"), "1065353216", bits)); + } } vector_write(i.dst, place_subword(i, bits)); return true; } + if (n == "v_floor_f16" || n == "v_ceil_f16" || n == "v_trunc_f16" || n == "v_rndne_f16") { + if (i.subword || i.dpp_control || permuted || i.scale || + (i.wide && ((i.a & 0x7800) || ((i.abs | i.neg) & 6) || i.src[1] || i.src[2]))) + refuse(i.pc, "unsupported " + string(n) + " operand modifiers"); + auto bits = ir.binary("and", operand32(i, i.src[0]), "65535"); + if (i.abs & 1) bits = ir.binary("and", bits, "32767"); + if (i.neg & 1) bits = ir.binary("xor", bits, "32768"); + auto sign = ir.binary("and", bits, "32768"); + auto mag = ir.binary("and", bits, "32767"); + auto exp = ir.binary("and", ir.binary("lshr", bits, "10"), "31"); + auto nz = cmp("ne", mag, "0"); + auto neg = cmp("ne", sign, "0"); + auto pos = cmp("eq", sign, "0"); + string sub_one = sign; + if (n == "v_floor_f16") + sub_one = select(ir.value("and i1 " + nz + ", " + neg), "48128", sign); + else if (n == "v_ceil_f16") + sub_one = select(ir.value("and i1 " + nz + ", " + pos), "15360", sign); + else if (n == "v_rndne_f16") + sub_one = select(cmp("ugt", mag, "14336"), ir.binary("or", sign, "15360"), sign); + auto frac_bits = select(cmp("ult", exp, "15"), "1", + select(cmp("ugt", exp, "24"), "1", ir.binary("sub", "25", exp))); + auto unit = ir.binary("shl", "1", frac_bits); + auto mask = ir.binary("sub", unit, "1"); + auto half = ir.binary("lshr", unit, "1"); + auto frac = ir.binary("and", bits, mask); + auto base = ir.binary("and", bits, ir.binary("xor", mask, "65535")); + string mid = base; + if (n != "v_trunc_f16") { + string inc; + if (n == "v_floor_f16") + inc = ir.value("and i1 " + neg + ", " + cmp("ne", frac, "0")); + else if (n == "v_ceil_f16") + inc = ir.value("and i1 " + pos + ", " + cmp("ne", frac, "0")); + else + inc = ir.value("or i1 " + cmp("ugt", frac, half) + ", " + + ir.value("and i1 " + cmp("eq", frac, half) + ", " + + cmp("ne", ir.binary("and", base, unit), "0"))); + mid = select(inc, ir.binary("add", base, unit), base); + } + auto result = select(cmp("uge", exp, "25"), bits, select(cmp("ult", exp, "15"), sub_one, mid)); + if (i.clamp) { + auto nan = cmp("ugt", ir.binary("and", result, "32767"), "31744"); + auto low = ir.value("or i1 " + nan + ", " + cmp("ne", ir.binary("and", result, "32768"), "0")); + result = select(low, "0", select(cmp("ugt", result, "15359"), "15360", result)); + } + auto kept = ir.binary("and", read(i.dst), "4294901760"); + vector_write(i.dst, ir.binary("or", kept, ir.binary("and", result, "65535"))); + return true; + } if (n == "v_pack_b32_f16") { // VOP3 only: D[15:0] = S0.f16, D[31:16] = S1.f16. Every step is an // integer bit operation so signed zeros and NaN payloads survive. @@ -1641,6 +1882,91 @@ struct DirectCompute { vector_write(i.dst, ir.binary("or", kept, ir.binary("and", result, "65535"))); return true; } + const bool fract = n == "v_fract_f16"; + const bool cvt_norm = n == "v_cvt_norm_i16_f16" || n == "v_cvt_norm_u16_f16"; + if (fract || cvt_norm) { + if (i.enc != Encoding::Vop1 || i.subword || i.dpp_control || permuted) + refuse(i.pc, "unsupported " + string(n) + " encoding"); + if (fract ? i.scale : (i.clamp || i.scale)) + refuse(i.pc, fract ? "unsupported v_fract_f16 omod" : ("unsupported " + string(n) + " clamp or omod")); + const unsigned op_sel = i.wide ? ((i.a >> 11) & 15u) : 0u; + if ((i.wide && (((i.abs | i.neg) & 6) || i.src[1] || i.src[2])) || (op_sel & 6u)) + refuse(i.pc, "unsupported " + string(n) + " operand modifiers"); + if ((op_sel & 1u) && i.src[0] < 256) + refuse(i.pc, "unsupported " + string(n) + " high-half op_sel on non-VGPR source"); + if (!half_mode_known || ((mode_bits ^ 0xf0u) & 0x8000ccu)) + refuse(i.pc, "unsupported binary16 rounding or denormal mode"); + const unsigned r = i.src[0]; + string bits; + if (op_sel & 1u) { + bits = ir.binary("lshr", operand32(i, r), "16"); + } else if (r >= 240 && r <= 248) { + bits = to_string(inline_half_words[r - 240]); + } else if (r == 255) { + bits = to_string(i.literal & 65535u); + } else if (r >= 128 && r <= 192) { + bits = to_string((r - 128) & 65535u); + } else if (r >= 193 && r <= 208) { + bits = to_string((192u - r) & 65535u); + } else if (r <= 105 || (r >= 256 && r < 512)) { + bits = ir.binary("and", operand32(i, r), "65535"); + } else { + refuse(i.pc, "unsupported " + string(n) + " source"); + } + if (i.abs & 1u) + bits = ir.binary("and", bits, "32767"); + if (i.neg & 1u) + bits = ir.binary("xor", bits, "32768"); + string result; + if (fract) { + auto non_finite = cmp("uge", ir.binary("and", bits, "32767"), "31744"); + auto a = ir.invoke("float", "legacyF16ToF32", 131, {{"i32", bits}}, "nounwind readnone"); + auto fl = ir.invoke("float", "unary.f32", 27, {{"float", a}}, "nounwind readnone"); + auto diff = ir.value("fsub float " + a + ", " + fl); + auto h = packed_half_rne(ir.value("bitcast float " + diff + " to i32")); + // Tiny negative fractions round x - floor(x) up to 1.0 (0x3c00); hardware clamps strictly below 1.0 (0x3bff). + auto finite = select(cmp("eq", h, "15360"), "15359", h); + result = select(non_finite, i.clamp ? "0" : "32256", finite); + } else { + // Match tools/pixel_aot.py::f16_cvt_norm_result in exact 32-bit integer RNE arithmetic to avoid + // binary32 double-rounding (0x3801..0x3804 / 0xb801..0xb802) and preserve binary16 subnormals. + const bool signed_out = n == "v_cvt_norm_i16_f16"; + auto sign = cmp("ne", ir.binary("and", bits, "32768"), "0"); + auto mag = ir.binary("and", bits, "32767"); + auto is_nan = cmp("ugt", mag, "31744"); + auto is_zero = cmp("eq", mag, "0"); + auto ge_one = cmp("uge", mag, "15360"); + auto exp = ir.binary("lshr", mag, "10"); + auto is_sub = cmp("eq", exp, "0"); + auto mant = select(is_sub, mag, ir.binary("or", "1024", ir.binary("and", mag, "1023"))); + // Keep shift in [1, 24] when mag >= 1.0 (exp >= 15); ge_one selects `scale` there anyway. + auto shift = select(is_sub, "24", select(cmp("ult", exp, "15"), ir.binary("sub", "25", exp), "1")); + const string scale = signed_out ? "32767" : "65535"; + auto prod = ir.binary("mul", mant, scale); + auto q0 = ir.binary("lshr", prod, shift); + auto mid = ir.binary("shl", "1", ir.binary("sub", shift, "1")); + auto mask = ir.binary("sub", ir.binary("shl", "1", shift), "1"); + auto rem = ir.binary("and", prod, mask); + auto tie_even = ir.value("and i1 " + cmp("eq", rem, mid) + ", " + cmp("ne", ir.binary("and", q0, "1"), "0")); + auto round_up = ir.value("or i1 " + cmp("ugt", rem, mid) + ", " + tie_even); + auto q_frac = ir.binary("add", q0, select(round_up, "1", "0")); + auto q_mag = select(ge_one, scale, q_frac); + if (signed_out) { + auto neg_q = ir.binary("and", ir.binary("sub", "0", q_mag), "65535"); + auto signed_val = select(sign, neg_q, q_mag); + result = select(ir.value("or i1 " + is_nan + ", " + is_zero), "0", signed_val); + } else { + auto zero_out = ir.value("or i1 " + is_nan + ", " + ir.value("or i1 " + is_zero + ", " + sign)); + result = select(zero_out, "0", q_mag); + } + } + auto dst_old = read(i.dst); + auto packed_dst = (op_sel & 8u) + ? ir.binary("or", ir.binary("and", dst_old, "65535"), ir.binary("shl", result, "16")) + : ir.binary("or", ir.binary("and", dst_old, "4294901760"), result); + vector_write(i.dst, packed_dst); + return true; + } if (n == "v_ldexp_f32") { // pixel_aot.py ldexp32 (#3013): exact binary32 scaling of S0 by 2^S1. Zero, Inf and NaN pass unchanged, // a denormal S0 is normalized rather than flushed, and a denormal result rounds to nearest even. S1 is @@ -1753,7 +2079,109 @@ struct DirectCompute { vector_write(i.dst, place_subword(i, result)); return true; } - if (n == "v_add_f16" || n == "v_sub_f16" || n == "v_subrev_f16" || n == "v_mul_f16") { + if (n == "v_cvt_pknorm_i16_f32" || n == "v_cvt_pknorm_u16_f32") { + if (i.enc != Encoding::Vop3 || i.subword || i.dpp_control || permuted) + refuse(i.pc, "unsupported " + string(n) + " encoding"); + if (i.clamp || i.scale) + refuse(i.pc, "unsupported " + string(n) + " clamp or omod"); + if ((i.a & 0x7800) || ((i.abs | i.neg) & 4) || i.src[2]) + refuse(i.pc, "unsupported " + string(n) + " operand modifiers"); + const bool signed_out = n == "v_cvt_pknorm_i16_f32"; + const unsigned k = signed_out ? 15u : 16u; + const string scale = signed_out ? "32767" : "65535"; + const string lo_mask = signed_out ? "32767" : "65535"; + auto cvt_lane = [&](unsigned j) { + auto bits = operand32(i, i.src[j]); + if (i.abs & (1u << j)) bits = ir.binary("and", bits, "2147483647"); + if (i.neg & (1u << j)) bits = ir.binary("xor", bits, "2147483648"); + // Exact 32-bit integer RNE of clamp(|x|, 0, 1) * (2^k - 1) via m*(2^k - 1) split at bit k. + auto sign = cmp("ne", ir.binary("and", bits, "2147483648"), "0"); + auto mag = ir.binary("and", bits, "2147483647"); + auto is_nan = cmp("ugt", mag, "2139095040"); + auto too_small = cmp("ult", mag, "922746880"); + auto ge_one = cmp("uge", mag, "1065353216"); + auto exp = ir.binary("lshr", mag, "23"); + auto in_range = ir.value("and i1 " + cmp("uge", exp, "110") + ", " + cmp("ule", exp, "126")); + auto safe_exp = select(in_range, exp, "126"); + auto s2 = ir.binary("sub", to_string(150u - k), safe_exp); + auto m = ir.binary("or", ir.binary("and", mag, "8388607"), "8388608"); + auto m_hi = ir.binary("lshr", m, to_string(k)); + auto m_lo = ir.binary("and", m, lo_mask); + auto borrow = select(cmp("ne", m_lo, "0"), "1", "0"); + auto p_lo = ir.binary("and", ir.binary("sub", "0", m_lo), lo_mask); + auto p_hi = ir.binary("sub", ir.binary("sub", m, m_hi), borrow); + auto q0 = ir.binary("lshr", p_hi, s2); + auto mid_hi = ir.binary("shl", "1", ir.binary("sub", s2, "1")); + auto rem_mask = ir.binary("sub", ir.binary("shl", "1", s2), "1"); + auto rem_hi = ir.binary("and", p_hi, rem_mask); + auto tie_or_above = ir.value("or i1 " + cmp("ne", p_lo, "0") + ", " + + cmp("ne", ir.binary("and", q0, "1"), "0")); + auto round_up = ir.value("or i1 " + cmp("ugt", rem_hi, mid_hi) + ", " + + ir.value("and i1 " + cmp("eq", rem_hi, mid_hi) + ", " + tie_or_above)); + auto q_frac = ir.binary("add", q0, select(round_up, "1", "0")); + auto q_mag = select(too_small, "0", select(ge_one, scale, q_frac)); + if (signed_out) { + auto neg_q = ir.binary("and", ir.binary("sub", "0", q_mag), "65535"); + return select(is_nan, "0", select(sign, neg_q, q_mag)); + } + return select(ir.value("or i1 " + is_nan + ", " + sign), "0", q_mag); + }; + auto low = cvt_lane(0), high = cvt_lane(1); + vector_write(i.dst, ir.binary("or", low, ir.binary("shl", high, "16"))); + return true; + } + if (n == "v_ldexp_f16") { + if (graphics_input) + return false; + if (i.subword || i.dpp_control || permuted || i.scale || + (i.wide && ((i.a & 0x7800) || ((i.abs | i.neg) & 6) || i.src[2]))) + refuse(i.pc, "unsupported v_ldexp_f16 operand modifiers"); + if (!half_mode_known || ((mode_bits ^ 0xf0u) & 0x8000ccu)) + refuse(i.pc, "unsupported binary16 rounding or denormal mode"); + auto inline_s0 = i.src[0] >= 240 && i.src[0] <= 248 ? packed_f16_inline_constant(i.src[0]) : std::nullopt; + auto bits = inline_s0 ? to_string(*inline_s0) : ir.binary("and", operand32(i, i.src[0]), "65535"); + if (i.abs & 1) bits = ir.binary("and", bits, "32767"); + if (i.neg & 1) bits = ir.binary("xor", bits, "32768"); + auto delta = ir.binary("ashr", ir.binary("shl", operand32(i, i.src[1]), "16"), "16"); + auto sign = ir.binary("and", bits, "32768"); + auto exponent = ir.binary("and", ir.binary("lshr", bits, "10"), "31"); + auto mantissa = ir.binary("and", bits, "1023"); + auto keep = ir.value("or i1 " + cmp("eq", exponent, "31") + ", " + + cmp("eq", ir.binary("and", bits, "32767"), "0")); + string x = mantissa, steps = "0"; + for (unsigned k : {8u, 4u, 2u, 1u}) { + auto low = cmp("ult", x, to_string(1u << (11 - k))); + x = select(low, ir.binary("shl", x, to_string(k)), x); + steps = select(low, ir.binary("add", steps, to_string(k)), steps); + } + auto denormal = cmp("eq", exponent, "0"); + mantissa = select(denormal, ir.binary("and", x, "1023"), mantissa); + auto e = select(denormal, ir.binary("sub", "1", steps), exponent); + delta = select(cmp("slt", delta, "-64"), "-64", select(cmp("sgt", delta, "64"), "64", delta)); + e = ir.binary("add", e, delta); + auto normal = ir.binary("or", sign, ir.binary("or", ir.binary("shl", e, "10"), mantissa)); + auto full = ir.binary("or", mantissa, "1024"); + auto amount = select(cmp("sgt", e, "0"), "1", select(cmp("slt", e, "-10"), "11", ir.binary("sub", "1", e))); + auto half = ir.binary("shl", "1", ir.binary("sub", amount, "1")); + auto rest = ir.binary("and", full, ir.binary("sub", ir.binary("shl", half, "1"), "1")); + auto q = ir.binary("lshr", full, amount); + auto up = ir.value("or i1 " + cmp("ugt", rest, half) + ", " + + ir.value("and i1 " + cmp("eq", rest, half) + ", " + + cmp("ne", ir.binary("and", q, "1"), "0"))); + auto subnormal = ir.binary("or", sign, ir.binary("add", q, ir.value("zext i1 " + up + " to i32"))); + string result = select(cmp("sgt", e, "0"), normal, select(cmp("slt", e, "-10"), sign, subnormal)); + result = select(cmp("sgt", e, "30"), ir.binary("or", sign, "31744"), result); + result = select(keep, bits, result); + if (i.clamp) { + auto nan = cmp("ugt", ir.binary("and", result, "32767"), "31744"); + auto low = ir.value("or i1 " + nan + ", " + cmp("ne", ir.binary("and", result, "32768"), "0")); + result = select(low, "0", select(cmp("ugt", result, "15359"), "15360", result)); + } + auto kept = ir.binary("and", read(i.dst), "4294901760"); + vector_write(i.dst, ir.binary("or", kept, ir.binary("and", result, "65535"))); + return true; + } + if (binary16_alu(n) || binary16_unary(n)) { // The graphics frontend shares this ALU. Leave those programs on the // existing refusal; this lowering is the direct compute path. if (graphics_input) @@ -1771,9 +2199,15 @@ struct DirectCompute { if (!j && permuted) { bits = ir.binary("and", *permuted, "65535"); } else if (i.subword) { - // A DWORD selection reads the low half for binary16 arithmetic. + auto inline_word = packed_f16_inline_constant(r); + auto word = inline_word ? to_string(*inline_word) : operand32(i, r); + // Select from the full operand word. DWORD reads the low half. const unsigned sel = i.src_select[j]; - bits = subword(operand32(i, r), sel == 6 ? 4 : sel, false); + // Only the binary16 value of an inline constant is modelled; its other + // half under SDWA is not documented here, so a high-half pick stays refused. + if (inline_word && sel != 4 && sel != 6) + refuse(i.pc, "unsupported SDWA binary16 inline constant selection"); + bits = subword(word, sel == 6 ? 4 : sel, false); } else if (r >= 240 && r <= 248) { // Inline floats are f32 patterns. The f16 operation consumes the // binary16 rounding of that value. @@ -1795,18 +2229,44 @@ struct DirectCompute { auto widen = [&](const string &bits) { return ir.invoke("float", "legacyF16ToF32", 131, {{"i32", bits}}, "nounwind readnone"); }; - auto a = widen(half_bits(0)); - auto b = widen(half_bits(1)); - if (n == "v_subrev_f16") - std::swap(a, b); - const char *op = n == "v_mul_f16" ? "fmul" : n == "v_add_f16" ? "fadd" : "fsub"; - auto widened = ir.value(string(op) + " float " + a + ", " + b); + const auto source = half_bits(0); + auto a = widen(source); + const bool rsq = n == "v_rsq_f16", exp = n == "v_exp_f16"; + string widened; + if (n == "v_rcp_f16") { + widened = ir.value("fdiv float 1.000000e+00, " + a); + } else if (binary16_unary(n)) { + const unsigned opcode = rsq ? 25 : exp ? 21 : 24; + widened = ir.invoke("float", "unary.f32", opcode, {{"float", a}}, "nounwind readnone"); + } else { + auto b = widen(half_bits(1)); + if (n == "v_subrev_f16") + std::swap(a, b); + const char *op = n == "v_mul_f16" ? "fmul" : n == "v_add_f16" ? "fadd" : "fsub"; + widened = ir.value(string(op) + " float " + a + ", " + b); + } auto bits = ir.value("bitcast float " + widened + " to i32"); - // f32 has a 24-bit significand, which covers a correctly rounded f16 - // add, sub or mul (2*11+2). Round with the same integer nearest-even - // conversion v_cvt_f16_f32 uses. + // Round with the same integer nearest-even conversion v_cvt_f16_f32 uses. auto rounded = packed_half_rne(bits); - // D[31:16] keeps its value: LLVM GCNSubtarget::zeroesHigh16BitsOfDest lists these four ops with + if (rsq) { + // Enforce RDNA2's exact special results from the modified half bits. + // The D3D Rsqrt contract does not guarantee a negative infinity for -0. + // Select the other special results explicitly as well. + const auto magnitude = ir.binary("and", source, "32767"); + // Every encoding above +infinity is negative or a positive NaN. + rounded = select(cmp("ugt", source, "31744"), "32256", rounded); + rounded = select(cmp("eq", source, "31744"), "0", rounded); + const auto zero_result = ir.binary("or", source, "31744"); + rounded = select(cmp("eq", magnitude, "0"), zero_result, rounded); + } else if (exp) { + for (const auto &entry : exp_f16_midpoints) + rounded = select(cmp("eq", source, to_string(entry.source)), to_string(entry.result), rounded); + // 2^-25 is exactly halfway between zero and the smallest half subnormal. + rounded = select(cmp("eq", source, to_string(0xce40)), "0", rounded); + const auto magnitude = ir.binary("and", source, "32767"); + rounded = select(cmp("ugt", magnitude, "31744"), "32256", rounded); + } + // D[31:16] keeps its value: LLVM GCNSubtarget::zeroesHigh16BitsOfDest says // "On gfx10, all 16-bit instructions preserve the high bits", as v_cvt_f16_f32 above already does. vector_write(i.dst, i.subword ? place_subword(i, rounded) : ir.binary("or", ir.binary("and", read(i.dst), "4294901760"), @@ -1822,8 +2282,13 @@ struct DirectCompute { refuse(i.pc, "unsupported " + string(n) + " SDWA form"); if (i.scale) refuse(i.pc, "unsupported " + string(n) + " omod"); - if (i.wide && (i.a & 0x7800)) + const unsigned op_sel = i.wide ? (i.a >> 11) & 15u : 0; + if (op_sel && (n != "v_fma_f16" || i.enc != Encoding::Vop3 || i.clamp)) refuse(i.pc, "unsupported " + string(n) + " high-half op_sel"); + for (unsigned j = 0; j < 3; ++j) { + if ((op_sel & (1u << j)) && i.src[j] < 256) + refuse(i.pc, "unsupported v_fma_f16 high-half op_sel on non-VGPR source"); + } if (n == "v_fmac_f16" && i.wide && (((i.abs | i.neg) & 4) || i.src[2])) refuse(i.pc, "unsupported v_fmac_f16 third-source modifier"); if (!half_mode_known || ((mode_bits ^ 0xf0u) & 0x8000ccu)) @@ -1831,7 +2296,9 @@ struct DirectCompute { auto half_bits = [&](unsigned j) { const unsigned r = i.src[j]; string bits; - if (r >= 240 && r <= 248) { + if (op_sel & (1u << j)) { + bits = ir.binary("lshr", operand32(i, r), "16"); + } else if (r >= 240 && r <= 248) { constexpr unsigned halves[]{0x3800, 0xb800, 0x3c00, 0xbc00, 0x4000, 0xc000, 0x4400, 0xc400, 0x3118}; bits = to_string(halves[r - 240]); @@ -1861,8 +2328,10 @@ struct DirectCompute { auto low = ir.value("or i1 " + nan + ", " + cmp("ne", ir.binary("and", result, "32768"), "0")); result = select(low, "0", select(cmp("ugt", result, "15359"), "15360", result)); } - auto kept = ir.binary("and", read(i.dst), "4294901760"); - vector_write(i.dst, ir.binary("or", kept, ir.binary("and", result, "65535"))); + const bool dst_high = (op_sel & 8u) != 0; + auto kept = ir.binary("and", read(i.dst), dst_high ? "65535" : "4294901760"); + auto placed = dst_high ? ir.binary("shl", result, "16") : ir.binary("and", result, "65535"); + vector_write(i.dst, ir.binary("or", kept, placed)); return true; } const auto rule = alu_rules.find(n); @@ -1874,7 +2343,8 @@ struct DirectCompute { n == "v_cvt_flr_i32_f32" || n == "v_cvt_rpi_i32_f32"; const bool cube = n == "v_cubeid_f32" || n == "v_cubesc_f32" || n == "v_cubetc_f32" || n == "v_cubema_f32"; const bool mixed = i.enc == Encoding::Mix && (n == "v_fma_mix_f32" || n == "v_fma_mixlo_f16" || n == "v_fma_mixhi_f16"); - const bool unfused_mad = n == "v_mad_f32" || n == "v_mad_legacy_f32" || n == "v_mac_f32" || n == "v_mac_legacy_f32"; + const bool unfused_mad = n == "v_mad_f32" || n == "v_mad_legacy_f32" || n == "v_mac_f32" || + n == "v_mac_legacy_f32" || n == "v_madmk_f32" || n == "v_madak_f32"; if (!mixed && !to_integer && !byte_to_float && !off_i4_to_float && !round && !cube && !unfused_mad && n != "v_mul_legacy_f32" && n != "v_cos_f32" && (rule == alu_rules.end() || rule->second.type == AluType::Bits)) @@ -1992,10 +2462,18 @@ struct DirectCompute { return ir.value("bitcast i32 " + kept + " to float"); }; const bool legacy = n == "v_mad_legacy_f32" || n == "v_mac_legacy_f32"; + const bool literal_k = n == "v_madmk_f32" || n == "v_madak_f32"; + if (literal_k && (i.wide || i.subword || i.dpp_control || permuted)) + refuse(i.pc, "unsupported " + string(n) + " encoding"); if (n.substr(0, 5) == "v_mac" && ((i.abs | i.neg) & 4)) refuse(i.pc, "unsupported " + string(n) + " accumulator modifier"); - auto x = ftz(a), y = ftz(fp(1)); - auto c = n.substr(0, 5) == "v_mac" ? ir.value("bitcast i32 " + read(i.dst) + " to float") : fp(2); + auto lit_float = [&]() { return ir.value("bitcast i32 " + to_string(i.literal) + " to float"); }; + auto x = ftz(a); + auto y = ftz(n == "v_madmk_f32" ? lit_float() : fp(1)); + auto c = n.substr(0, 5) == "v_mac" ? ir.value("bitcast i32 " + read(i.dst) + " to float") + : n == "v_madak_f32" ? lit_float() + : n == "v_madmk_f32" ? fp(1) + : fp(2); auto product = ir.value("fmul float " + x + ", " + y); if (legacy) { auto zero = ir.value("or i1 " + ir.value("fcmp oeq float " + x + ", 0.0") + ", " + @@ -2047,13 +2525,18 @@ struct DirectCompute { result = unary(26, a); else if (n == "v_floor_f32") result = unary(27, a); - else if (round) + else if (round) { result = unary(n == "v_fract_f32" ? 22 : n == "v_ceil_f32" ? 28 : 29, a); - else if (n == "v_sqrt_f32") + // A host Frc can round tiny negative inputs up to 1.0. The guest's + // result stays below 1.0; an ordered comparison keeps NaNs intact. + if (n == "v_fract_f32") + result = select_float(ir.value("fcmp oge float " + result + ", 1.0"), + ir.value("bitcast i32 1065353215 to float"), result); + } else if (n == "v_sqrt_f32") result = unary(24, a); else if (n == "v_rsq_f32") result = unary(25, a); - else if (n == "v_rcp_f32") + else if (n == "v_rcp_f32" || n == "v_rcp_iflag_f32") result = ir.value("fdiv float 1.000000e+00, " + a); else return false; @@ -2208,20 +2691,27 @@ struct DirectCompute { // result and do not consume the incoming SCC. An explicit // SRC_SCC operand still takes precedence below. const bool mask_scc = n == "s_andn2_b64" || n == "s_and_b64" || n == "s_or_b64" || - n == "s_xor_b64" || n == "s_not_b64" || n == "s_wqm_b32" || n == "s_wqm_b64" || + n == "s_xor_b64" || n == "s_orn2_b64" || n == "s_nand_b64" || n == "s_nor_b64" || + n == "s_xnor_b64" || n == "s_not_b64" || n == "s_wqm_b32" || n == "s_wqm_b64" || n == "s_quadmask_b32" || n == "s_quadmask_b64" || n == "s_and_saveexec_b64" || n == "s_or_saveexec_b64" || n == "s_xor_saveexec_b64" || n == "s_andn2_saveexec_b64" || n == "s_orn2_saveexec_b64" || n == "s_nand_saveexec_b64" || n == "s_nor_saveexec_b64" || n == "s_xnor_saveexec_b64" || - n == "s_andn2_wrexec_b64"; + n == "s_andn1_saveexec_b64" || n == "s_orn1_saveexec_b64" || + n == "s_andn1_wrexec_b64" || n == "s_andn2_wrexec_b64"; const bool overwrites = mask_scc || n == "s_abs_i32" || n == "s_bcnt0_i32_b32" || n == "s_bcnt1_i32_b32" || n == "s_bcnt0_i32_b64" || n == "s_bcnt1_i32_b64" || inst.enc == Encoding::Sopc || n == "s_bfe_u32" || n == "s_and_b32" || - n == "s_or_b32" || n == "s_max_u32" || n == "s_add_u32" || n == "s_sub_u32" || + n == "s_or_b32" || n == "s_max_u32" || n == "s_min_u32" || n == "s_min_i32" || + n == "s_max_i32" || n == "s_absdiff_i32" || n == "s_add_u32" || n == "s_sub_u32" || n == "s_add_i32" || n == "s_sub_i32" || n == "s_and_saveexec_b32" || - n == "s_andn2_wrexec_b32" || n == "s_andn2_b32" || n == "s_orn2_b32" || - n == "s_nor_b32" || n == "s_nand_b32" || n == "s_xnor_b32" || n == "s_not_b32" || + n == "s_or_saveexec_b32" || n == "s_xor_saveexec_b32" || n == "s_andn2_saveexec_b32" || + n == "s_orn2_saveexec_b32" || n == "s_nand_saveexec_b32" || n == "s_nor_saveexec_b32" || + n == "s_xnor_saveexec_b32" || n == "s_andn1_saveexec_b32" || n == "s_orn1_saveexec_b32" || + n == "s_andn1_wrexec_b32" || n == "s_andn2_wrexec_b32" || n == "s_andn2_b32" || + n == "s_orn2_b32" || n == "s_nor_b32" || n == "s_nand_b32" || n == "s_xnor_b32" || + n == "s_not_b32" || n == "s_lshr_b32" || n == "s_lshl_b32" || n == "s_ashr_i32" || n == "s_lshl_b64" || n == "s_lshr_b64" || n == "s_ashr_i64" || n == "s_xor_b32" || n == "s_bfe_u64" || n == "s_bfe_i64" || @@ -2263,6 +2753,56 @@ struct DirectCompute { } return scc_live[program.at.at(definition.next)]; } + void prepare_descriptor_strides() { + const auto &p = analysis.program; + const auto &layout = analysis.layout; + std::map<std::pair<unsigned,unsigned>,size_t> sources; + for (size_t n = 0; n < p.code.size(); ++n) { + if (!p.reached[n]) continue; + const auto &i = p.code[n]; + const auto field = byte_descriptor_field(i,p.before[n],heap_window); + if (!field || (field->type != Symbol::Type::stride && field->type != Symbol::Type::byte_stride) || + field->definition || field->value >= layout.NumParameters || !uses_scc_after(i)) + continue; + const auto ¶meter = layout.pParameters[field->value]; + if (parameter.ParameterType != D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE || + parameter.ShaderVisibility != D3D12_SHADER_VISIBILITY_ALL) + continue; + // The runtime provides the stride only for a fixed buffer SRV. + const auto &table = parameter.DescriptorTable; + const auto slot = field->offset / 32; + uint64_t next = 0; + unsigned srvs = 0, other = 0; + for (unsigned j = 0; j < table.NumDescriptorRanges; ++j) { + const auto &range = table.pDescriptorRanges[j]; + const uint64_t start = range.OffsetInDescriptorsFromTableStart == D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND + ? next : range.OffsetInDescriptorsFromTableStart; + next = start + range.NumDescriptors; + if (start <= slot && slot < next) { + if (range.RangeType == D3D12_DESCRIPTOR_RANGE_TYPE_SRV) ++srvs; + else ++other; + } + } + if (srvs == 1 && !other) + sources.try_emplace({field->value,field->offset},n); + } + for (const auto &[source, n] : sources) { + const auto [root, offset] = source; + if (read_write_raw_views.count(source)) continue; + State descriptor; + for (unsigned j=0; j<4; ++j) + descriptor[j] = {Symbol::Type::descriptor,root,offset+4*j}; + analysis.binding(p.code[n],descriptor,0,4,ComputeViewKind::raw_vector_srv,4); + analysis.result.stride_srvs.push_back(analysis.result.bindings.back().shader_register); + descriptor_strides.try_emplace(source); + } + if (!descriptor_strides.empty()) { + size_t words = descriptor_strides.size(); + for (const auto &block : analysis.result.constants) words += block.count; + if (words > 32) + refuse(p.code.front().pc,"descriptor stride metadata exceeds the 32-word compute entry layout"); + } + } string saturated_add(const string &a, const string &b, bool sign) { auto sum = ir.binary("add", a, b); if (!sign) @@ -2279,16 +2819,23 @@ struct DirectCompute { if (!floating && !signed_int && n != "v_pk_min_u16" && n != "v_pk_max_u16") return false; // VOP3P NEG_HI/LO occupy the usual ABS/NEG fields. The third - // OP_SEL_HI bit is unused here, like the packed add and shift forms. - if (i.clamp || i.abs || i.neg || i.src[2] || (i.a & 0x2000)) + // OP_SEL_HI bit and third-operand modifiers are unused here. + const bool bad_mods = floating ? ((i.abs & 4) || (i.neg & 4)) : (i.clamp || i.abs || i.neg); + if (bad_mods || i.src[2] || (i.a & 0x2000)) refuse(i.pc, "unsupported packed 16-bit min/max encoding"); if (floating && (!half_mode_known || (mode_bits & 0xc0u) != 0xc0u)) refuse(i.pc, "unsupported packed binary16 min/max denormal mode"); auto source = [&](unsigned src) { + if (floating) { + if (auto inline_word = packed_f16_inline_constant(src)) + return to_string(*inline_word); + } else if (src >= 128 && src <= 208) { + return operand32(i, src); + } if (src <= 105) { if (state[src].type == Symbol::Type::masked || state[src].type == Symbol::Type::uniform_mask) refuse(i.pc, "packed 16-bit min/max uses a lane mask"); - } else if (src < 256 && src != 128 && src != 255) { + } else if (src < 256 && src != 255) { refuse(i.pc, "unsupported packed 16-bit min/max source"); } return operand32(i, src); @@ -2307,8 +2854,12 @@ struct DirectCompute { } return signed_int ? ir.binary("xor", bits, "32768") : bits; }; - auto lane = [&](unsigned selectors) { + auto lane = [&](unsigned selectors, unsigned negate) { auto x = half(a, selectors & 1), y = half(b, selectors & 2); + if (floating && (negate & 1u)) + x = ir.binary("xor", x, "32768"); + if (floating && (negate & 2u)) + y = ir.binary("xor", y, "32768"); auto result = select(cmp(maximum ? "ugt" : "ult", order_key(x), order_key(y)), x, y); if (floating) { // Follow the existing startup contract. One NaN selects @@ -2316,22 +2867,41 @@ struct DirectCompute { auto x_nan = cmp("ugt", ir.binary("and", x, "32767"), "31744"); auto y_nan = cmp("ugt", ir.binary("and", y, "32767"), "31744"); result = select(x_nan, select(y_nan, "32256", y), select(y_nan, x, result)); + if (i.clamp) { + auto nan = cmp("ugt", ir.binary("and", result, "32767"), "31744"); + auto low = ir.value("or i1 " + nan + ", " + cmp("ne", ir.binary("and", result, "32768"), "0")); + result = select(low, "0", select(cmp("ugt", result, "15359"), "15360", result)); + } } return result; }; - auto low = lane((i.a >> 11) & 3), high = lane((i.b >> 27) & 3); + auto low = lane((i.a >> 11) & 3, i.neg), high = lane((i.b >> 27) & 3, i.abs); vector_write(i.dst, ir.binary("or", low, ir.binary("shl", high, "16"))); return true; } void arithmetic(const Inst &i, const State &state, const string *permuted = nullptr, bool compute = false) { auto n = i.name; - if (compute && (n == "v_dot4_i32_i8" || n == "v_dot4_u32_u8")) { - // Integer dot products use both packed words as-is. Require the - // canonical VOP3P OP_SEL/OP_SEL_HI and zero NEG_LO/NEG_HI. - if (i.enc != Encoding::Mix || (i.a & 0x7f00) != 0x4000 || (i.b >> 27) != 3) + if (compute) { + if (const auto offset = heap_offset_add(i, state)) { + // The heap base is slot 0 of ResourceDescriptorHeap: the low word keeps the byte offset, the carry is 0. + write(i.dst, operand32(i, i.src[*offset])); + write(128, "0"); + return; + } + } + const bool dot_accumulate = n == "v_dot4c_i32_i8"; + if (compute && (dot_accumulate || n == "v_dot4_i32_i8" || n == "v_dot4_u32_u8")) { + // Integer dots use both packed words as-is. The VOP3P forms + // require canonical OP_SEL/OP_SEL_HI and zero NEG_LO/NEG_HI. + if (dot_accumulate) { + if (i.enc != Encoding::Vop2 || i.wide || i.subword || i.dpp_control || permuted || + i.abs || i.neg || i.clamp || i.scale) + refuse(i.pc, "unsupported packed byte dot-accumulate operand modifiers"); + } else if (i.enc != Encoding::Mix || (i.a & 0x7f00) != 0x4000 || (i.b >> 27) != 3) refuse(i.pc, "unsupported packed byte dot operand modifiers"); - const bool sign = n == "v_dot4_i32_i8"; - auto a = operand32(i, i.src[0]), b = operand32(i, i.src[1]), acc = operand32(i, i.src[2]); + const bool sign = n != "v_dot4_u32_u8"; + auto a = operand32(i, i.src[0]), b = operand32(i, i.src[1]); + auto acc = operand32(i, dot_accumulate ? i.dst : i.src[2]); // The dot alone fits into i32 even for four unsigned 255*255 // products. Saturate only the final addition to the accumulator. auto dot = ir.invoke("i32", "dot4AddPacked.i32", sign ? 163 : 164, @@ -2528,8 +3098,20 @@ struct DirectCompute { // Its SCC is known for every source descriptor. if (field->type == Symbol::Type::byte_oob || field->type == Symbol::Type::root_stride_one_high) write(128, "1"); - else if (n != "s_mul_i32" && uses_scc_after(i)) - refuse(i.pc, "numeric SCC from a symbolic descriptor field"); + else if (n != "s_mul_i32" && uses_scc_after(i)) { + const auto stride = descriptor_strides.find({field->value,field->offset}); + if (stride == descriptor_strides.end() || field->definition || + (field->type != Symbol::Type::stride && field->type != Symbol::Type::byte_stride)) + refuse(i.pc, "numeric SCC from a symbolic descriptor field"); + string condition; + if (field->type == Symbol::Type::stride) + condition = cmp("ne",stride->second,"0"); + else if (source(i,i.src[0],state).type == Symbol::Type::stride) + condition = cmp("ugt",stride->second,"1"); + else + condition = cmp("ult",stride->second,"1"); + write(128,ir.value("zext i1 " + condition + " to i32")); + } if (graphics_input) write(i.dst, {}); return; } @@ -2883,7 +3465,7 @@ struct DirectCompute { return; } if (compute && n == "s_bfm_b64") { - if ((i.dst & 1) || i.dst > 104) + if ((i.dst & 1) || (i.dst > 104 && i.dst != 126)) refuse(i.pc, "invalid s_bfm_b64 destination"); if ((i.src[0] > 105 && !constant32(i, i.src[0])) || (i.src[1] > 105 && !constant32(i, i.src[1]))) @@ -2902,25 +3484,29 @@ struct DirectCompute { return; } if (compute && (n == "s_cselect_b64" || n == "s_not_b64")) { - if ((i.dst & 1) || (i.dst > 104 && i.dst != 106)) + const bool invert = n == "s_not_b64"; + if ((i.dst & 1) || (i.dst > 104 && i.dst != 106 && !(invert && i.dst == 126))) refuse(i.pc, "invalid " + string(n) + " destination"); - auto high = [&](unsigned src) { - if (!wave64 && (src == 106 || src == 126)) + auto scalar64 = [&](unsigned src) -> std::pair<string, string> { + if (!((src <= 104 && !(src & 1)) || src == 106 || src == 126 || + (src >= 128 && src <= 208) || src == 255)) refuse(i.pc, "invalid " + string(n) + " source"); - return pair_high(i, src); + return {operand32(i, src), pair_high(i, src)}; }; - auto lo = val(0), hi = high(i.src[0]); - if (n == "s_cselect_b64") { + auto [lo, hi] = scalar64(i.src[0]); + if (!invert) { + auto [other_lo, other_hi] = scalar64(i.src[1]); auto condition = cmp("ne", read(128), "0"); - lo = select(condition, lo, val(1)); - hi = select(condition, hi, high(i.src[1])); + lo = select(condition, lo, other_lo); + hi = select(condition, hi, other_hi); } else { lo = ir.binary("xor", lo, "4294967295"); hi = ir.binary("xor", hi, "4294967295"); - write(128, ir.value("zext i1 " + cmp("ne", ir.binary("or", lo, hi), "0") + " to i32")); } write(i.dst, lo); write(i.dst + 1, hi); + if (invert) + write(128, ir.value("zext i1 " + cmp("ne", ir.binary("or", lo, hi), "0") + " to i32")); return; } if (compute && (n == "s_lshl_b64" || n == "s_lshr_b64" || n == "s_ashr_i64")) { @@ -3048,7 +3634,7 @@ struct DirectCompute { if (i.dst > 105) refuse(i.pc, "invalid " + string(n) + " destination"); const unsigned s0 = i.src[0]; - const bool s0_pair = s0 <= 104 && !(s0 & 1); + const bool s0_pair = (s0 <= 104 && !(s0 & 1)) || s0 == 126; const bool s0_int = s0 >= 128 && s0 <= 208; if (!(s0_pair || s0_int || s0 == 255)) refuse(i.pc, "invalid " + string(n) + " source"); @@ -3161,36 +3747,56 @@ struct DirectCompute { write(128, ir.value("zext i1 " + cmp("ne", total, "0") + " to i32")); return; } + auto combine_scalar_mask = [&](Name op, const string &left, const string &right) -> string { + if (op == "and" || op == "or" || op == "xor") + return ir.binary(string(op), left, right); + if (op == "andn2" || op == "orn2") + return ir.binary(op == "andn2" ? "and" : "or", left, ir.binary("xor", right, "4294967295")); + if (op == "andn1" || op == "orn1") + return ir.binary(op == "andn1" ? "and" : "or", ir.binary("xor", left, "4294967295"), right); + if (op == "nand" || op == "nor" || op == "xnor") + return ir.binary("xor", ir.binary(op == "nand" ? "and" : op == "nor" ? "or" : "xor", left, right), + "4294967295"); + return {}; + }; if ((i.enc == Encoding::Sop1 || i.enc == Encoding::Sop2) && n.size() > 6 && n.substr(n.size() - 4) == "_b64") { bool save = n.find("_saveexec_") != Name::npos; - const bool write_exec = compute && n == "s_andn2_wrexec_b64"; + const bool wrexec = compute && wave64 && (n == "s_andn2_wrexec_b64" || n == "s_andn1_wrexec_b64"); auto op = n.substr(2, n.find('_', 2) - 2); - if ((i.dst & 1) || (i.dst > 104 && i.dst != 106 && i.dst != 126) || - ((save || write_exec) ? i.enc != Encoding::Sop1 : i.enc != Encoding::Sop2)) + if (wrexec ? ((i.dst | i.src[0]) & 1) || i.dst > 104 || i.src[0] > 104 + : (i.dst & 1) || (i.dst > 104 && i.dst != 106 && i.dst != 126) || + (save ? i.enc != Encoding::Sop1 : i.enc != Encoding::Sop2)) refuse(i.pc, "unsupported wave64 scalar operation"); auto ah = pair_high(i, i.src[0]); - auto bl = save || write_exec ? read(126) : b; - auto bh = save || write_exec ? read(127) : pair_high(i, i.src[1]); - auto combine = [&](const string &left, const string &right) -> string { - if (op == "and" || op == "or" || op == "xor") return ir.binary(string(op), left, right); - if (op == "andn2" || op == "orn2") - return ir.binary(op == "andn2" ? "and" : "or", left, ir.binary("xor", right, "4294967295")); - if (op == "nand" || op == "nor" || op == "xnor") - return ir.binary("xor", ir.binary(op == "nand" ? "and" : op == "nor" ? "or" : "xor", left, right), "4294967295"); + const bool updates_exec = save || wrexec; + auto bl = updates_exec ? read(126) : b; + auto bh = updates_exec ? read(127) : pair_high(i, i.src[1]); + // SAVEEXEC and WREXEC combine the source with old EXEC in ISA operand order. + // WREXEC stores the new mask in the destination pair. + auto lo = combine_scalar_mask(op, a, bl), hi = combine_scalar_mask(op, ah, bh); + if (lo.empty()) refuse(i.pc, "unsupported wave64 scalar mask operation"); - }; - // SAVEEXEC combines its source operand with the old EXEC in ISA operand order. - auto lo = combine(a, bl), hi = combine(ah, bh); write(i.dst, save ? bl : lo); write(i.dst + 1, save ? bh : hi); - if (save || write_exec) { write(126, lo); write(127, hi); } + if (updates_exec) { write(126, lo); write(127, hi); } write(128, ir.value("zext i1 " + cmp("ne", ir.binary("or", lo, hi), "0") + " to i32")); return; } - if (n == "s_and_saveexec_b32" || n == "s_andn2_wrexec_b32") { + const bool saveexec32 = i.enc == Encoding::Sop1 && n.size() > 13 && n.substr(n.size() - 13) == "_saveexec_b32"; + const bool wrexec32 = n == "s_andn2_wrexec_b32" || (compute && !wave64 && n == "s_andn1_wrexec_b32"); + if (n == "s_and_saveexec_b32" || n == "s_andn2_wrexec_b32" || + (compute && !wave64 && (saveexec32 || wrexec32))) { + const bool save = saveexec32; + const bool strict_dst = n != "s_and_saveexec_b32" && n != "s_andn2_wrexec_b32"; + if (strict_dst && i.dst > 107) + refuse(i.pc, "unsupported wave32 SAVEEXEC destination"); + auto op = n.substr(2, n.find('_', 2) - 2); auto old = read(126); - auto mask = ir.binary("and", a, n == "s_and_saveexec_b32" ? old : ir.binary("xor", old, "4294967295")); - write(i.dst, n == "s_and_saveexec_b32" ? old : mask); + // Like s_mov_b32 exec_lo, EXEC keeps every bit; a lane runs only if its own bit is set. + auto mask = combine_scalar_mask(op, a, old); + if (mask.empty()) + refuse(i.pc, "unsupported wave32 scalar mask operation"); + write(i.dst, save ? old : mask); write(126, mask); write(128, ir.value("zext i1 " + cmp("ne", mask, "0") + " to i32")); return; @@ -3686,9 +4292,10 @@ struct DirectCompute { const unsigned mask = i.mirror_mask(); const auto row = i.dpp_row(); const bool row_op = row.op != Inst::DppRowOp::None; - const unsigned group_size = row_op ? 16 : mask ? mask + 1 : 4; + const unsigned group_size = i.dpp8_selectors ? 8 : row_op ? 16 : mask ? mask + 1 : 4; if (threads % group_size) - refuse(i.pc, row_op ? "DPP row shift or rotate needs a thread count divisible by 16" + refuse(i.pc, i.dpp8_selectors ? "DPP8 needs a thread count divisible by eight" + : row_op ? "DPP row shift or rotate needs a thread count divisible by 16" : mask ? "DPP mirror needs complete source lane groups" : "DPP quad_perm needs a thread count divisible by four"); const auto rule = alu_rules.find(i.name); @@ -3697,7 +4304,13 @@ struct DirectCompute { if (i.enc == Encoding::Vop1 && ((i.neg | i.abs) & 2)) refuse(i.pc, "unexpected second DPP source modifier"); string source_lane, source_usable; - if (row_op) { + if (i.dpp8_selectors) { + auto octet_base = ir.binary("and", lane, "4294967288"); + auto octet_lane = ir.binary("and", lane, "7"); + auto shift = ir.binary("mul", octet_lane, "3"); + auto fields = ir.binary("lshr", to_string(*i.dpp8_selectors), shift); + source_lane = ir.binary("or", octet_base, ir.binary("and", fields, "7")); + } else if (row_op) { auto row_base = ir.binary("and", lane, "4294967280"); auto row_lane = ir.binary("and", lane, "15"); auto amount = to_string(row.amount); @@ -3726,7 +4339,8 @@ struct DirectCompute { } string write_enabled; if (!source_usable.empty()) { - if (i.dpp_bound_zero) word = select(source_usable, word, "0"); + // DPP8 supplies zero for a disabled source when FI is clear. + if (i.dpp8_selectors || i.dpp_bound_zero) word = select(source_usable, word, "0"); else write_enabled = source_usable; } // Row and bank masks gate destination writes independently of the source and BOUND_CTRL. @@ -3849,6 +4463,7 @@ struct DirectCompute { [](const Inst &i) { return i.enc == Encoding::Lds; }); if (uses_lds) ir.globals << "@lds = internal addrspace(3) global [" << lds_words << " x i32] undef, align 4\n"; + prepare_descriptor_strides(); const auto &p = analysis.program; mode_bits = 0xf0; bool mode_write = false, conditional = false; @@ -3856,7 +4471,7 @@ struct DirectCompute { if (!p.reached[k]) continue; const auto &op = p.code[k]; - if (binary16_alu(op.name) || + if (binary16_alu(op.name) || binary16_unary(op.name) || op.name == "v_pk_min_f16" || op.name == "v_pk_max_f16" || op.name == "v_cvt_f16_u16" || @@ -3866,12 +4481,16 @@ struct DirectCompute { op.name == "v_fma_f16" || op.name == "v_fmac_f16" || op.name == "v_fmamk_f16" || - op.name == "v_fmaak_f16") + op.name == "v_fmaak_f16" || + op.name == "v_fract_f16" || + op.name == "v_ldexp_f16" || + op.name == "v_cvt_norm_i16_f16" || + op.name == "v_cvt_norm_u16_f16") half_binary = true; if (op.name == "s_round_mode" || op.name == "s_denorm_mode" || op.name == "s_setreg_b32" || op.name == "s_setreg_imm32_b32") mode_write = true; - if (packed_f16_arithmetic(op.name)) + if (packed_f16_arithmetic(op.name) || op.name == "v_dot2_f32_f16" || op.name == "v_dot2c_f32_f16") half_binary = true; if (op.branch() && op.op != 2) conditional = true; @@ -3921,7 +4540,7 @@ struct DirectCompute { if (virtual_waves) yield_virtual_wave(select(pred,to_string(i.target()),to_string(i.next))); else ir.body << " br i1 " << pred << ", label %pc" << i.target() << ", label %pc" << i.next << "\n"; } - } else if (i.dpp_control) + } else if (i.dpp_control || i.dpp8_selectors) lower_dpp(i, p.before[k], x*y*z); else if (i.name == "v_permlane16_b32" || i.name == "v_permlanex16_b32") lower_permlane(i, x*y*z); @@ -3967,7 +4586,15 @@ struct DirectCompute { const unsigned rank_words = !virtual_waves && x * y * z > 64 ? x * y * z : 0; if ((uses_lds ? lds_words : 0) + rank_words + (uses_exchange ? exchange_words : 0) > 8192) refuse(entry, "combined shared storage exceeds 32 KiB"); - r.dxil_ir = virtual_waves ? ir.finish_compute(64,1,1) : ir.finish_compute(x,y,z); + // SM 6.6 forms consecutive linear quads for 1D groups. In 2D it forms + // spatial 2x2 quads, which can cross the guest's consecutive lane quads. + // initialize() still reconstructs guest IDs using the original dimensions. + // The wave64 split occurs at lane 32, a quad boundary. + if (compute_derivatives) + ir.validator_minor = 8; + r.dxil_ir = virtual_waves ? ir.finish_compute(64, 1, 1) + : compute_derivatives ? ir.finish_compute(x * y * z, 1, 1) + : ir.finish_compute(x, y, z); return std::move(r); } }; diff --git a/src/native_buffer_store_view.h b/src/native_buffer_store_view.h index 595a2cbb0e..8e2ec3c099 100644 --- a/src/native_buffer_store_view.h +++ b/src/native_buffer_store_view.h @@ -5,6 +5,15 @@ // Preserve the guest view window. The HLSL resource type determines the desktop component type. namespace x2w { +inline DXGI_FORMAT native_half_buffer_format(unsigned bytes) { + switch (bytes) { + case 2: return DXGI_FORMAT_R16_FLOAT; + case 4: return DXGI_FORMAT_R16G16_FLOAT; + case 8: return DXGI_FORMAT_R16G16B16A16_FLOAT; + default: return DXGI_FORMAT_UNKNOWN; + } +} + inline bool native_buffer_store_view(const ComputeViewBinding &binding, D3D12_UNORDERED_ACCESS_VIEW_DESC &view, UINT64 resource_bytes, IndexedAtomicView *atomic = nullptr) { if (view.ViewDimension != D3D12_UAV_DIMENSION_BUFFER || view.Buffer.CounterOffsetInBytes || @@ -59,9 +68,8 @@ inline bool native_buffer_store_view(const ComputeViewBinding &binding, D3D12_UN view.Format = DXGI_FORMAT_R16_UINT; else return false; } else if (binding.kind == ComputeViewKind::half_buffer_uav) { - if (!((stride == 2 && view.Format == DXGI_FORMAT_R16_FLOAT) || - (stride == 4 && view.Format == DXGI_FORMAT_R16G16_FLOAT) || - (stride == 8 && view.Format == DXGI_FORMAT_R16G16B16A16_FLOAT))) + const auto format = native_half_buffer_format(stride); + if (format == DXGI_FORMAT_UNKNOWN || view.Format != format) return false; } else if (binding.kind == ComputeViewKind::typed_buffer_uav) { const DXGI_FORMAT formats[][3] = { diff --git a/src/native_compute_output.h b/src/native_compute_output.h new file mode 100644 index 0000000000..24b8ccd3ba --- /dev/null +++ b/src/native_compute_output.h @@ -0,0 +1,34 @@ +#pragma once + +#include <charconv> +#include <string_view> + +namespace x2w { +// Bump whenever a native translation of an unchanged request can change meaning. +constexpr unsigned native_compute_output_revision = 1; + +enum class NativeComputeOutput { unmarked, current, incompatible }; + +inline NativeComputeOutput native_compute_output(std::string_view manifest) +{ + auto output = NativeComputeOutput::unmarked; + while (!manifest.empty()) { + const auto end = manifest.find('\n'); + auto line = manifest.substr(0, end); + manifest.remove_prefix(end == std::string_view::npos ? manifest.size() : end + 1); + if (!line.empty() && line.back() == '\r') + line.remove_suffix(1); + if (line != "native" && line.substr(0, 7) != "native ") + continue; + if (output != NativeComputeOutput::unmarked || line.size() <= 7) + return NativeComputeOutput::incompatible; + unsigned revision = 0; + const auto last = line.data() + line.size(); + const auto parsed = std::from_chars(line.data() + 7, last, revision); + if (parsed.ec != std::errc{} || parsed.ptr != last || revision != native_compute_output_revision) + return NativeComputeOutput::incompatible; + output = NativeComputeOutput::current; + } + return output; +} +} diff --git a/src/native_compute_pipeline.cpp b/src/native_compute_pipeline.cpp index ca74343cfe..f0f51b1299 100644 --- a/src/native_compute_pipeline.cpp +++ b/src/native_compute_pipeline.cpp @@ -49,6 +49,7 @@ NativeComputePipeline create_native_compute_pipeline(ID3D12Device *device, Shade } pipeline.uav_count = counts[1]; pipeline.constants = std::move(program.constants); + pipeline.stride_srvs = std::move(program.stride_srvs); for (const auto &block : pipeline.constants) pipeline.constant_words += block.count; pipeline.srv_count = counts[0]; @@ -68,7 +69,8 @@ NativeComputePipeline create_native_compute_pipeline(ID3D12Device *device, Shade D3D12_DESCRIPTOR_RANGE ranges[2]{}; for (const auto &b : pipeline.bindings) pipeline.atomic_views += b.kind == ComputeViewKind::indexed_atomic_uav; - if (unsigned(bool(counts[0])) + unsigned(bool(counts[1])) + pipeline.constant_words + + const auto b0_words = pipeline.constant_words + static_cast<unsigned>(pipeline.stride_srvs.size()); + if (unsigned(bool(counts[0])) + unsigned(bool(counts[1])) + b0_words + 2 * pipeline.atomic_views > D3D12_MAX_ROOT_COST) throw UnsupportedComputeShader("indexed atomic view metadata exceeds root parameter budget"); std::vector<D3D12_ROOT_PARAMETER> params(3 + pipeline.atomic_views); @@ -82,10 +84,10 @@ NativeComputePipeline create_native_compute_pipeline(ID3D12Device *device, Shade param.ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; param.DescriptorTable = {1, &ranges[i]}; } - if (pipeline.constant_words) { + if (b0_words) { auto ¶m = params[param_count++]; param.ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS; - param.Constants.Num32BitValues = pipeline.constant_words; + param.Constants.Num32BitValues = b0_words; } for (const auto &b : pipeline.bindings) { if (b.kind != ComputeViewKind::indexed_atomic_uav) continue; @@ -113,11 +115,14 @@ NativeComputePipeline create_native_compute_pipeline(ID3D12Device *device, Shade void NativeComputePipeline::bind(ID3D12GraphicsCommandList *list, ID3D12DescriptorHeap *heap, D3D12_GPU_DESCRIPTOR_HANDLE first, UINT increment, const unsigned *words, - const std::vector<IndexedAtomicView> &atomic, ID3D12DescriptorHeap *sampler_heap) const { + const std::vector<IndexedAtomicView> &atomic, ID3D12DescriptorHeap *sampler_heap, + const std::vector<unsigned> &strides) const { if (constant_words && !words) throw std::runtime_error("compute root constants missing"); if (atomic.size() != atomic_views) throw std::runtime_error("indexed atomic view metadata missing"); + if (strides.size() != stride_srvs.size()) + throw std::runtime_error("compute descriptor stride metadata missing"); const bool views = srv_count || uav_count || heap_indexed; if (sampler_heap_indexed) { if (!sampler_heap) @@ -141,7 +146,10 @@ void NativeComputePipeline::bind(ID3D12GraphicsCommandList *list, ID3D12Descript if (uav_count) list->SetComputeRootDescriptorTable(parameter++, first); if (constant_words) - list->SetComputeRoot32BitConstants(parameter++, constant_words, words, 0); + list->SetComputeRoot32BitConstants(parameter, constant_words, words, 0); + if (!strides.empty()) + list->SetComputeRoot32BitConstants(parameter, static_cast<UINT>(strides.size()), strides.data(), constant_words); + if (constant_words || !strides.empty()) ++parameter; for (const auto &shape : atomic) { const unsigned pair[]{shape.stride, shape.count}; list->SetComputeRoot32BitConstants(parameter++, 2, pair, 0); diff --git a/src/native_compute_pipeline.h b/src/native_compute_pipeline.h index c25c9ea0f7..6dc3d8044e 100644 --- a/src/native_compute_pipeline.h +++ b/src/native_compute_pipeline.h @@ -13,6 +13,7 @@ struct NativeComputePipeline { Microsoft::WRL::ComPtr<ID3D12PipelineState> state; std::vector<ComputeViewBinding> bindings; std::vector<ComputeConstants> constants; + std::vector<unsigned> stride_srvs; unsigned srv_count = 0; unsigned uav_count = 0; unsigned constant_words = 0, atomic_views = 0; @@ -28,7 +29,8 @@ struct NativeComputePipeline { void bind(ID3D12GraphicsCommandList *list, ID3D12DescriptorHeap *heap, D3D12_GPU_DESCRIPTOR_HANDLE first, UINT increment, const unsigned *words = nullptr, - const std::vector<IndexedAtomicView> &atomic = {}, ID3D12DescriptorHeap *sampler_heap = nullptr) const; + const std::vector<IndexedAtomicView> &atomic = {}, ID3D12DescriptorHeap *sampler_heap = nullptr, + const std::vector<unsigned> &strides = {}) const; }; NativeComputePipeline create_native_compute_pipeline(ID3D12Device *device, ShaderDxilCompiler &compiler, diff --git a/src/shader_compute_request.cpp b/src/shader_compute_request.cpp index dda15d074f..b502e57160 100644 --- a/src/shader_compute_request.cpp +++ b/src/shader_compute_request.cpp @@ -58,17 +58,16 @@ uint64_t parse_request_stem(std::string_view stem, const char *error_message) { throw std::runtime_error(error_message); return expected; } -void parse_pixel_inputs(const fs::path &marker, uint64_t expected, Bytes &entry, Bytes &description) { - fs::path path = marker; - path.replace_extension(".psin"); - std::ifstream file(path, std::ios::binary | std::ios::ate); - const auto size = file.tellg(); - if (size < 0 || size > 128) - throw std::runtime_error("invalid pixel input description"); - Bytes raw(static_cast<size_t>(size), 0); - file.seekg(0); - if (size && !file.read(raw.data(), size)) - throw std::runtime_error("short read"); +} // namespace + +std::string x2w::format_pixel_input_description(uint64_t key, uint32_t ena, uint32_t addr) { + char text[64]; + std::snprintf(text, sizeof(text), "psin1 %016llx ena=0x%04x addr=0x%04x\n", + static_cast<unsigned long long>(key), ena, addr); + return text; +} + +x2w::PixelInputDescription x2w::parse_pixel_input_description(std::string_view raw, uint64_t expected) { std::string_view line = raw; if (!line.empty() && line.back() == '\n') line.remove_suffix(1); @@ -119,30 +118,20 @@ void parse_pixel_inputs(const fs::path &marker, uint64_t expected, Bytes &entry, throw std::runtime_error("pixel input address mask missing from the stream description"); if (ena & ~addr) throw std::runtime_error("contradictory pixel input enable/address masks"); - entry.assign("psin1", 5); + PixelInputDescription parsed; + parsed.ena = ena; + parsed.addr = addr; + parsed.entry.assign("psin1", 5); const uint32_t words[2]{ena, addr}; - entry.append(reinterpret_cast<const char *>(words), sizeof(words)); - char text[64]; - std::snprintf(text, sizeof(text), "psin1 %016llx ena=0x%04x addr=0x%04x\n", - static_cast<unsigned long long>(expected), ena, addr); - description = text; + parsed.entry.append(reinterpret_cast<const char *>(words), sizeof(words)); + parsed.canonical_text = format_pixel_input_description(expected, ena, addr); + return parsed; } -// tools/startup/gfx2hlsl.py request_source: at most 256 bytes of "rtv1 <base key> <format> ..." in decimal with one to -// eight formats and nothing else, whose FNV-1a hash is the key in the file name. The variant is translated from its -// base request's parts, which are read and checked against the base key like any base request. -x2w::GraphicsRequest read_rtv_variant(const fs::path &marker) { - const auto stem = marker.stem().string(); - if (stem.size() != 20 || stem.compare(0, 4, "req_")) - throw std::runtime_error("expected req_<16 hex digits>.rtv"); - const uint64_t expected = parse_request_stem(stem, "invalid RTV variant request key"); - Bytes text; - try { - text = part(marker, ".rtv", 256); - } catch (const std::runtime_error &) { + +x2w::RtvVariantDescription x2w::parse_rtv_variant_text(std::string_view text, uint64_t expected) { + if (text.size() > 256) throw std::runtime_error("invalid RTV variant request"); - } - uint64_t key = 1469598103934665603ull; - hash_bytes(key, text.data(), text.size()); + const uint64_t key = fnv1a_64(text); std::vector<std::string_view> tokens; std::string_view rest = text; bool valid = rest.substr(0, 5) == "rtv1 "; @@ -158,18 +147,102 @@ x2w::GraphicsRequest read_rtv_variant(const fs::path &marker) { } if (!valid || tokens.size() < 2 || tokens.size() > 9 || key != expected) throw std::runtime_error("invalid RTV variant request"); - uint64_t base = 0; - std::vector<unsigned> formats; + RtvVariantDescription result; for (size_t i = 0; i < tokens.size(); ++i) { uint64_t value = 0; const auto parsed = std::from_chars(tokens[i].data(), tokens[i].data() + tokens[i].size(), value); if (parsed.ec != std::errc{} || (i && value > 0xffffffffull)) throw std::runtime_error("invalid RTV variant values"); - if (!i) base = value; - else formats.push_back(static_cast<unsigned>(value)); + if (!i) result.base_key = value; + else result.formats.push_back(static_cast<unsigned>(value)); + } + return result; +} + +std::string x2w::format_rtv_variant_text(uint64_t base_key, const std::vector<unsigned> &formats) { + std::string out = "rtv1 " + std::to_string(base_key); + for (unsigned format : formats) { + out.push_back(' '); + out += std::to_string(format); } + return out; +} + +uint64_t x2w::fnv1a_64(std::string_view bytes) { + uint64_t key = 1469598103934665603ull; + hash_bytes(key, bytes.data(), bytes.size()); + return key; +} + +uint64_t x2w::graphics_request_key(std::string_view a, std::string_view b, std::string_view root, + std::string_view input_layout, std::string_view pixel_entry, + std::string_view revision_override) { + constexpr char revision[] = "x2w-startup-shader-29"; + uint64_t key = fnv1a_64(revision_override.empty() ? std::string_view(revision, sizeof(revision) - 1) + : revision_override); + for (const auto part_view : {a, b, root, input_layout, pixel_entry}) + hash_bytes(key, part_view.data(), part_view.size()); + return key; +} + +uint64_t x2w::compute_request_key(std::string_view code, std::string_view data, std::string_view root, + std::string_view description, std::string_view sa, std::string_view sb, + std::string_view revision_override) { + constexpr char revision[] = "x2w-startup-shader-29cs"; + uint64_t key = fnv1a_64(revision_override.empty() ? std::string_view(revision, sizeof(revision) - 1) + : revision_override); + for (const auto part_view : {code, data, root, description, sa, sb}) { + const uint64_t size = part_view.size(); + hash_bytes(key, &size, sizeof(size)); + hash_bytes(key, part_view.data(), part_view.size()); + } + return key; +} + +uint64_t x2w::mesh57_request_key(std::string_view code, std::string_view ps57, std::string_view root) { + constexpr char revision[] = "x2w-startup-mesh-57-3"; + uint64_t key = fnv1a_64(std::string_view(revision, sizeof(revision) - 1)); + for (const auto part_view : {code, ps57, root}) { + const uint64_t size = part_view.size(); + hash_bytes(key, &size, sizeof(size)); + hash_bytes(key, part_view.data(), part_view.size()); + } + return key; +} + +namespace { +void parse_pixel_inputs(const fs::path &marker, uint64_t expected, Bytes &entry, Bytes &description) { + fs::path path = marker; + path.replace_extension(".psin"); + std::ifstream file(path, std::ios::binary | std::ios::ate); + const auto size = file.tellg(); + if (size < 0 || size > 128) + throw std::runtime_error("invalid pixel input description"); + Bytes raw(static_cast<size_t>(size), 0); + file.seekg(0); + if (size && !file.read(raw.data(), size)) + throw std::runtime_error("short read"); + auto parsed = x2w::parse_pixel_input_description(raw, expected); + entry = std::move(parsed.entry); + description = std::move(parsed.canonical_text); +} +// tools/startup/gfx2hlsl.py request_source: at most 256 bytes of "rtv1 <base key> <format> ..." in decimal with one to +// eight formats and nothing else, whose FNV-1a hash is the key in the file name. The variant is translated from its +// base request's parts, which are read and checked against the base key like any base request. +x2w::GraphicsRequest read_rtv_variant(const fs::path &marker) { + const auto stem = marker.stem().string(); + if (stem.size() != 20 || stem.compare(0, 4, "req_")) + throw std::runtime_error("expected req_<16 hex digits>.rtv"); + const uint64_t expected = parse_request_stem(stem, "invalid RTV variant request key"); + Bytes text; + try { + text = part(marker, ".rtv", 256); + } catch (const std::runtime_error &) { + throw std::runtime_error("invalid RTV variant request"); + } + auto parsed = x2w::parse_rtv_variant_text(text, expected); char name[32]; - std::snprintf(name, sizeof(name), "req_%016llx.a", static_cast<unsigned long long>(base)); + std::snprintf(name, sizeof(name), "req_%016llx.a", static_cast<unsigned long long>(parsed.base_key)); x2w::GraphicsRequest request; try { request = x2w::read_graphics_request(marker.parent_path() / name); @@ -178,7 +251,7 @@ x2w::GraphicsRequest read_rtv_variant(const fs::path &marker) { } request.key = expected; request.rtv_request = std::move(text); - request.rtv_formats = std::move(formats); + request.rtv_formats = std::move(parsed.formats); return request; } void read_pixel_inputs(const fs::path &marker, uint64_t expected, Bytes &entry, Bytes &description) { @@ -216,18 +289,13 @@ x2w::GraphicsRequest x2w::read_graphics_request(const fs::path &marker) { if (fs::exists(fs::path(marker).replace_extension(".ia"))) request.input_layout = part(marker, ".ia", 1 << 20); read_pixel_inputs(marker, expected, request.pixel_entry, request.pixel_input_description); - const auto request_key = [&](std::string_view revision) { - uint64_t key = 1469598103934665603ull; - hash_bytes(key, revision.data(), revision.size()); - for (const auto *p : {&request.a, &request.b, &request.root, &request.input_layout, &request.pixel_entry}) - hash_bytes(key, p->data(), p->size()); - return key; - }; if (request.root.empty()) throw std::runtime_error("graphics request key mismatch or missing root"); // Match new runtime captures and keep revision-28 archives replayable. - constexpr char revision[] = "x2w-startup-shader-29"; - if (request_key(revision) != expected && request_key("x2w-startup-shader-28") != expected) { + if (x2w::graphics_request_key(request.a, request.b, request.root, request.input_layout, request.pixel_entry) != + expected && + x2w::graphics_request_key(request.a, request.b, request.root, request.input_layout, request.pixel_entry, + "x2w-startup-shader-28") != expected) { if (!request.pixel_entry.empty()) throw std::runtime_error("stale pixel input description: graphics request key mismatch"); throw std::runtime_error("graphics request key mismatch or missing root"); @@ -243,22 +311,17 @@ x2w::ComputeRequest x2w::read_compute_request(const fs::path &marker) { auto code = part(marker, ".c67", 1 << 20), data = part(marker, ".data", 1 << 20), root = part(marker, ".root", 16 << 20); auto desc = part(marker, ".desc", 96), sa = part(marker, ".sa", 4096), sb = part(marker, ".sb", 4096); - check_compute_extents(desc, code.size(), data.size(), sa.size(), sb.size()); - const auto request_key = [&](std::string_view revision) { - uint64_t key = 1469598103934665603ull; - hash_bytes(key, revision.data(), revision.size()); - for (const auto *p : {&code, &data, &root, &desc, &sa, &sb}) { - uint64_t size = p->size(); - hash_bytes(key, &size, sizeof(size)); - hash_bytes(key, p->data(), p->size()); - } - return key; - }; - constexpr char revision[] = "x2w-startup-shader-29cs"; - if (request_key(revision) != expected && request_key("x2w-startup-shader-28cs") != expected) + if (desc.size() != 96 || read<uint64_t>(desc, 48) != code.size() || read<uint64_t>(desc, 64) != data.size() || + read<uint64_t>(desc, 16) != sa.size() || read<uint64_t>(desc, 32) != sb.size()) + throw std::runtime_error("inconsistent compute request"); + if (x2w::compute_request_key(code, data, root, desc, sa, sb) != expected && + x2w::compute_request_key(code, data, root, desc, sa, sb, "x2w-startup-shader-28cs") != expected) throw std::runtime_error("compute request key mismatch"); ComputeRequest request{std::move(code), std::move(data), std::move(root), std::move(desc), std::move(sa), std::move(sb), expected}; validate_compute_request_shape(request); + // Bit 20 of dword 4 (bits 15:0 are Z): set for wave32, clear for wave64. Inferred from captured requests + // (docs/experiments/native-slot67-wave-size.md). Read only after the shape check has proved 28 bytes. + request.wave32 = (static_cast<unsigned char>(request.sa[18]) & 0x10) != 0; return request; } diff --git a/src/shader_compute_request.h b/src/shader_compute_request.h index 1de45e0e74..b8bd53dad5 100644 --- a/src/shader_compute_request.h +++ b/src/shader_compute_request.h @@ -2,12 +2,39 @@ #include <cstdint> #include <filesystem> #include <string> +#include <string_view> #include <vector> namespace x2w { +uint64_t fnv1a_64(std::string_view bytes); +uint64_t graphics_request_key(std::string_view a, std::string_view b, std::string_view root, + std::string_view input_layout = {}, std::string_view pixel_entry = {}, + std::string_view revision = {}); +uint64_t compute_request_key(std::string_view code, std::string_view data, std::string_view root, + std::string_view description, std::string_view sa, std::string_view sb, + std::string_view revision = {}); +uint64_t mesh57_request_key(std::string_view code, std::string_view ps57, std::string_view root); + +struct PixelInputDescription { + uint32_t ena{}; + uint32_t addr{}; + std::string entry; + std::string canonical_text; +}; +PixelInputDescription parse_pixel_input_description(std::string_view text, uint64_t expected_key); +std::string format_pixel_input_description(uint64_t key, uint32_t ena, uint32_t addr); + +struct RtvVariantDescription { + uint64_t base_key{}; + std::vector<unsigned> formats; +}; +RtvVariantDescription parse_rtv_variant_text(std::string_view text, uint64_t expected_key); +std::string format_rtv_variant_text(uint64_t base_key, const std::vector<unsigned> &formats); + struct ComputeRequest { std::string code, data, root, description, sa, sb; uint64_t key; + bool wave32 = true; }; struct ComputeContainer { std::string bytes, root; diff --git a/src/startup_stubs/acphal.cpp b/src/startup_stubs/acphal.cpp index 9f3bdaa930..8e66537537 100644 --- a/src/startup_stubs/acphal.cpp +++ b/src/startup_stubs/acphal.cpp @@ -6,6 +6,8 @@ #include "startup_stubs/local_log.h" #include <array> +#include <cstring> +#include <new> #include <utility> X2W_TRAP_EXPORT(2, AcpHalReleaseShapeContexts) @@ -152,6 +154,149 @@ bool heap_give(const void* virtual_address) return done; } +// Activity counter (#1145), off unless X2W_AUDIO_ACTIVITY=1. It watches the XMA context array that +// AcpHalAllocateShapeContexts hands out and counts how its 64-byte contexts change, without reading any field +// in them: a context that goes from all zero to nonzero is filled, one that changes while nonzero is changed, +// one that returns to all zero is cleared. HAL slot2 submits are counted by their type argument. There is no thread: +// the array is compared with a copy inside the calls that count (a HAL submit, AcpHalAllocateShapeContexts, every +// ApuFree once counting started, x2w_acphal_xma_activity), at most once per 10 ms except where a call below says it +// samples now. A context written across a sample counts twice, and one filled and cleared between two samples not at +// all. Such a call at least a second after the previous line (or the first counted event) writes the next line, with +// the counts since that line, if a count moved; until then the counts wait for a later call. +// Nothing here runs outside a call into this DLL, so a caller that unloads it leaves no code of it running. Off, +// nothing here runs: no read of caller memory, no line. +bool activity_on() noexcept { return x2w_local::env_on("X2W_AUDIO_ACTIVITY"); } + +constexpr std::size_t context_words = 64 / sizeof(u64); +constexpr unsigned submit_types = 8; // types 0..7 one by one, then all other types together +struct Activity { + u64 filled, changed, cleared; + u64 submits[submit_types + 1]; +}; +SRWLOCK activity_lock = SRWLOCK_INIT; // guards the eight below +const volatile u64* watched; // the XMA contexts, or null +u64* shadow; // their words at the last sample +std::uint32_t watched_count, live; +Activity activity, reported; // the counts now and at the last line +ULONGLONG last_sample, last_line; // GetTickCount64 of the last sample and of the last line written + // (or of the first counted event) +volatile LONG activity_started; // set with the first counted event, never cleared + +// Compares the watched contexts with the copy and counts the ones that moved. Hold activity_lock. +void sample_locked() noexcept +{ + live = 0; + for (std::uint32_t c = 0; watched && c < watched_count; ++c) { + bool was = false, now = false, moved = false; + for (std::size_t w = 0; w < context_words; ++w) { + const u64 value = watched[c * context_words + w]; // one aligned 8-byte load, never torn + u64& old = shadow[c * context_words + w]; + was = was || old; + now = now || value; + moved = moved || value != old; + old = value; + } + live += now; + if (moved) ++(!was ? activity.filled : now ? activity.changed : activity.cleared); + } +} + +// Samples the contexts (always when now is set, else at most once per 10 ms); if the last line is at least a second old +// and a count moved, writes the next line into text and returns true. Hold activity_lock; log the text after +// releasing it. +bool poll_locked(bool now, char (&text)[512]) noexcept +{ + const ULONGLONG tick = GetTickCount64(); + if (now || tick - last_sample >= 10) { + sample_locked(); + last_sample = tick; + } + if (tick - last_line < 1000 || !std::memcmp(&activity, &reported, sizeof(activity))) return false; + last_line = tick; + char types[256] = ""; + std::size_t used = 0; + u64 submits = 0; + for (unsigned t = 0; t <= submit_types; ++t) { + const u64 n = activity.submits[t] - reported.submits[t]; + submits += n; + if (!n || used >= sizeof(types)) continue; + used += static_cast<std::size_t>(t < submit_types ? std::snprintf(types + used, sizeof(types) - used, " %u=%llu", t, n) + : std::snprintf(types + used, sizeof(types) - used, " other=%llu", n)); + } + std::snprintf(text, sizeof(text), + "x2w-audio xma-activity t=%.1f s: contexts filled=%llu changed=%llu cleared=%llu live=%u/%u; " + "hal submits=%llu by type%s", + x2w_local::process_seconds(), activity.filled - reported.filled, activity.changed - reported.changed, + activity.cleared - reported.cleared, live, watched_count, submits, types); + reported = activity; + return true; +} + +// The first counted event starts the one-second line interval. Hold activity_lock. +void start_locked() noexcept +{ + if (activity_started) return; + activity_started = 1; + last_line = GetTickCount64(); +} + +// Watches a newly allocated XMA array; its content now is the baseline. The caller's last error is kept. +void watch(unsigned char* contexts, std::uint32_t count) noexcept +{ + const DWORD error = GetLastError(); + auto* copy = new (std::nothrow) u64[std::size_t{count} * context_words]; + char text[512]; + AcquireSRWLockExclusive(&activity_lock); + const bool line = poll_locked(true, text); // samples now: an earlier array's last changes still count + delete[] shadow; + shadow = copy; + watched = copy ? reinterpret_cast<const volatile u64*>(contexts) : nullptr; + watched_count = copy ? count : 0; + if (copy) std::memcpy(copy, contexts, std::size_t{count} * 64); + start_locked(); + ReleaseSRWLockExclusive(&activity_lock); + if (line) x2w_local::logf("%s", text); + x2w_local::logf(copy ? "x2w-audio xma-activity: watching %u contexts" : "x2w-audio xma-activity: no memory to watch %u contexts", + count); + SetLastError(error); +} + +// Every ApuFree once counting started: samples (now, if the block is the watched array) and may write the line. ApuFree +// of the watched array: its last changes count, then watching stops before the block can be reused. +void unwatch(const void* block) noexcept +{ + if (!activity_started) return; + const DWORD error = GetLastError(); + char text[512]; + AcquireSRWLockExclusive(&activity_lock); + const bool hit = watched && static_cast<const volatile void*>(watched) == block; + const bool line = poll_locked(hit, text); // samples now if the watched array is freed + if (hit) { + watched = nullptr; + watched_count = live = 0; + delete[] shadow; + shadow = nullptr; + } + ReleaseSRWLockExclusive(&activity_lock); + if (line) x2w_local::logf("%s", text); + if (hit) x2w_local::logf("x2w-audio xma-activity: contexts freed, no longer watched"); + SetLastError(error); +} + +void count_submit(unsigned type) noexcept +{ + if (!activity_on()) return; + const DWORD error = GetLastError(); + char text[512]; + AcquireSRWLockExclusive(&activity_lock); + ++activity.submits[type < submit_types ? type : submit_types]; + start_locked(); + const bool line = poll_locked(false, text); + ReleaseSRWLockExclusive(&activity_lock); + if (line) x2w_local::logf("%s", text); + SetLastError(error); +} + // AcpHal object (not COM: slot 0 is the first method). Seen: slot 0 (0x1000, 0x1000) -> HRESULT, a // connect with two queue lengths; slot 2 (type, id, frame, &value, 0) -> HRESULT, a command submit. // Both succeed and are logged; every other slot traps and names itself. @@ -169,6 +314,7 @@ long __stdcall hal_connect(void*, unsigned commands, unsigned messages) } long __stdcall hal_submit(void*, unsigned type, u64 id, unsigned frame, const unsigned* input, u64 extra) { + count_submit(type); static LONG calls; if (x2w_local::first_calls(calls, 16)) x2w_local::logf("x2w-audio AcpHal::slot2(submit) type=%u id=0x%llx frame=0x%x input=%p [0x%x] extra=0x%llx -> S_OK", type, @@ -271,6 +417,7 @@ extern "C" __declspec(noinline) long AcpHalAllocateShapeContexts(u64 rcx, u64 rd x2w_local::logf("x2w-audio XMA contexts: %u x 64 bytes at %p (apu 0x%x)", counts[i], static_cast<void*>(memory), apu[i]); } + if (allocated[4] && activity_on()) watch(arrays[4], counts[4]); return 0; } @@ -350,6 +497,7 @@ extern "C" __declspec(noinline) long ApuFree(void* virtual_address) x2w_trap::fire(X2W_TRAP_MODULE, X2W_TRAP_MODULE_ID, "ApuFree", 5, reinterpret_cast<u64>(virtual_address), 0, 0, 0, _ReturnAddress()); if (!virtual_address) return 0; + unwatch(virtual_address); const long hr = heap_give(virtual_address) ? 0 : static_cast<long>(0x80070057); static LONG calls; if (FAILED(hr) || x2w_local::first_calls(calls, 4)) @@ -396,3 +544,37 @@ extern "C" __declspec(noinline) std::uint32_t ApuMapVirtualAddress(void* virtual if (x2w_local::first_calls(calls, 4)) x2w_local::logf("x2w-audio ApuMapVirtualAddress %p -> 0x%x", virtual_address, result); return result; } + +// Experimental export for the source-built check (tests/startup_acphal_xma_activity.cpp): samples now, writes the line +// if one is due, as a counted call does, and writes the totals since start to out[0..14]: contexts watched, contexts +// live, filled, changed, cleared, HAL submits, then submits of types 0..7 and of all other types. With +// X2W_AUDIO_ACTIVITY off it writes zeros and returns FALSE. +extern "C" BOOL WINAPI x2w_acphal_xma_activity(ULONGLONG* out) +{ + if (!out) return FALSE; + const bool on = activity_on(); + Activity now{}; + std::uint32_t count = 0, live_now = 0; + char text[512]; + bool line = false; + if (on) { + AcquireSRWLockExclusive(&activity_lock); + line = poll_locked(true, text); + now = activity; + count = watched_count; + live_now = live; + ReleaseSRWLockExclusive(&activity_lock); + } + if (line) x2w_local::logf("%s", text); + out[0] = count; + out[1] = live_now; + out[2] = now.filled; + out[3] = now.changed; + out[4] = now.cleared; + out[5] = 0; + for (unsigned t = 0; t <= submit_types; ++t) { + out[5] += now.submits[t]; + out[6 + t] = now.submits[t]; + } + return on; +} diff --git a/src/startup_stubs/acphal.def b/src/startup_stubs/acphal.def index 70a0480079..d316315427 100644 --- a/src/startup_stubs/acphal.def +++ b/src/startup_stubs/acphal.def @@ -9,3 +9,4 @@ EXPORTS ApuIsVirtualAddressValid ApuMapApuAddress ApuMapVirtualAddress + x2w_acphal_xma_activity diff --git a/src/startup_stubs/bcpack_blocks_extra.inl b/src/startup_stubs/bcpack_blocks_extra.inl new file mode 100644 index 0000000000..0ff5487be1 --- /dev/null +++ b/src/startup_stubs/bcpack_blocks_extra.inl @@ -0,0 +1,173 @@ +// Standalone BC1, BC2 and BC6H block reconstruction from BCPack lane symbols. +// SPDX-License-Identifier: MIT + +template<class State, size_t Count> +inline State bcpack_predictor(size_t block, size_t reference, const State (&history)[256], + const State (&dictionary)[Count]) { + if (reference == 0) return {}; + if (reference <= block) return history[(block - reference) & 255]; + const size_t index = reference - block - 1; + return index < Count ? dictionary[index] : State{}; +} + +inline void bcpack_quad(const uint8_t (&rank)[256][4], uint16_t symbol, size_t quadrant, + const uint8_t* predictor, uint8_t* positions) { + const size_t base = (quadrant >> 1) * 8 + (quadrant & 1) * 2; + constexpr size_t offsets[4] = {0, 1, 4, 5}; + for (size_t k = 0; k < 4; ++k) { + const size_t p = base + offsets[k]; + positions[p] = static_cast<uint8_t>((predictor[p] + rank[symbol & 255][k]) & 3); + } +} + +inline bool decode_bc1_blocks(const std::vector<uint16_t>& symbols, size_t blocks, + uint8_t* output, size_t capacity) { + if (blocks > capacity / 8 || blocks > symbols.size() / 12) return false; + constexpr uint8_t widths[6] = {5,6,5,5,6,5}; + Bc1FullState history[256] = {}; + for (size_t i = 0; i < blocks; ++i) { + // Lane 1 is the index distance. Lane 0 is a zigzag delta from it to + // the endpoint distance; they can select different historical blocks. + const size_t xr = symbols[blocks + i] & 255; + const size_t er = static_cast<size_t>(static_cast<int>(xr) + unzigzag(symbols[i])) & 255; + const auto ep = bcpack_predictor(i,er,history,BC1_FULL_DICTIONARY); + const auto ix = bcpack_predictor(i,xr,history,BC1_FULL_DICTIONARY); + Bc1FullState state{}; + for (size_t c = 0; c < 6; ++c) { + state.ep[c] = static_cast<uint8_t>((ep.ep[c] + unzigzag(symbols[(2+c)*blocks+i])) & ((1u<<widths[c])-1)); + } + for (size_t q = 0; q < 4; ++q) { + bcpack_quad(BC1_POSITION_RANK,symbols[(8+q)*blocks+i],q,ix.ix,state.ix); + } + pack_colour(state.ep,state.ix,output+i*8); + history[i&255] = state; + } + return true; +} + +inline bool decode_bc2_blocks(const std::vector<uint16_t>& symbols, size_t blocks, + uint8_t* output, size_t capacity) { + if (blocks > capacity / 16 || blocks > symbols.size() / 30) return false; + const size_t target = blocks*2; + Bc2State history[256] = {}; + for (size_t i = 0; i < blocks; ++i) { + const uint8_t d = interleave(symbols[2*i],symbols[2*i+1]); + const size_t xr = interleave(symbols[target+2*i],symbols[target+2*i+1]); + const size_t er = static_cast<size_t>(static_cast<int>(xr)+unzigzag(d)) & 255; + const auto ep = bcpack_predictor(i,er,history,BC2_FULL_DICTIONARY); + const auto ix = bcpack_predictor(i,xr,history,BC2_FULL_DICTIONARY); + Bc2State state{}; + uint64_t alpha = 0; + for (size_t p = 0; p < 16; ++p) { + // BC2 stores explicit four-bit alpha, biased around eight. Its + // predictor follows endpoint history, independently of colour indices. + state.alpha[p] = static_cast<uint8_t>((ep.alpha[p]+unzigzag(symbols[(2+p/2)*target+2*i+p%2])) & 15); + alpha |= static_cast<uint64_t>(state.alpha[p]^8) << (4*p); + } + for (size_t c = 0; c < 3; ++c) { + const unsigned bits = c == 1 ? 6 : 5; + for (size_t e = 0; e < 2; ++e) { + state.ep[3*e+c] = static_cast<uint8_t>((ep.ep[3*e+c]+unzigzag(symbols[(10+c)*target+2*i+e])) & ((1u<<bits)-1)); + } + } + for (size_t q = 0; q < 4; ++q) { + bcpack_quad(BC2_POSITION_RANK,symbols[(13+q/2)*target+2*i+q%2],q,ix.ix,state.ix); + } + std::memcpy(output+i*16,&alpha,8); + pack_colour(state.ep,state.ix,output+i*16+8); + history[i&255] = state; + } + return true; +} + +inline uint16_t bcpack_wide(uint16_t even, uint16_t odd) { + uint16_t value = 0; + for (unsigned bit = 0; bit < 8; ++bit) { + value |= static_cast<uint16_t>(((even>>bit)&1)<<(2*bit) | ((odd>>bit)&1)<<(2*bit+1)); + } + return value; +} + +inline uint16_t bcpack_add_aligned(uint16_t predictor, int32_t delta, unsigned shift) { + const uint32_t aligned = static_cast<uint32_t>(static_cast<uint16_t>(delta)) << shift; + return static_cast<uint16_t>((predictor+aligned) & (0xffffu<<shift)); +} + +inline void bcpack_put_bit(uint8_t* output, size_t at, unsigned bit) { + output[at/8] |= static_cast<uint8_t>((bit&1)<<(at%8)); +} + +inline bool decode_bc6_blocks(const std::vector<uint16_t>& symbols, size_t blocks, + uint8_t* output, size_t capacity) { + if (blocks > capacity/16 || blocks > symbols.size()/32) return false; + const size_t target = blocks*2; + constexpr uint8_t codes[14] = {0,1,2,6,10,14,18,22,26,30,3,7,11,15}; + Bc6State history[256] = {}; + for (size_t i = 0; i < blocks; ++i) { + const unsigned mode = symbols[15*target+2*i]+1; + if (mode < 1 || mode > 14) return false; + const bool two = mode <= 10; + const unsigned part = symbols[15*target+2*i+1]&31; + const uint8_t d = interleave(symbols[2*i],symbols[2*i+1]); + const size_t xr = interleave(symbols[target+2*i],symbols[target+2*i+1]); + const size_t er = static_cast<size_t>(static_cast<int>(xr)+unzigzag(d)) & 255; + const auto ep = bcpack_predictor(i,er,history,BC6_DICTIONARY); + const auto ix = bcpack_predictor(i,xr,history,BC6_DICTIONARY); + Bc6State state{}; + // Keep signed/bias-centred values left aligned, so changing modes can + // reuse a predictor without confusing its original precision with this mode's. + for (size_t c = 0; c < 3; ++c) { + const unsigned s0 = 16-BC6_ENDPOINT_BITS[mode][0]; + const unsigned sc = 16-BC6_ENDPOINT_BITS[mode][c+1]; + const uint16_t v0 = bcpack_wide(symbols[(2+c)*target+2*i],symbols[(2+c)*target+2*i+1]); + const uint16_t v1 = bcpack_wide(symbols[(5+c)*target+2*i],symbols[(5+c)*target+2*i+1]); + state.ep[0][c] = bcpack_add_aligned(ep.ep[0][c],unzigzag(v0),s0); + state.ep[1][c] = bcpack_add_aligned(ep.ep[1][c],unzigzag(v1),sc); + if (two) { + state.ep[2][c] = bcpack_add_aligned(ep.ep[2][c],unzigzag(symbols[(8+c)*target+2*i]),sc); + state.ep[3][c] = bcpack_add_aligned(ep.ep[3][c],unzigzag(symbols[(8+c)*target+2*i+1]),sc); + } else { + // One-subset blocks still update the hidden second-subset + // history used by a later two-subset block. + state.ep[2][c] = static_cast<uint16_t>((state.ep[0][c]>>s0)<<sc); + state.ep[3][c] = state.ep[1][c]; + } + } + const unsigned bits = two ? 3 : 4; + for (size_t pair = 0; pair < 8; ++pair) { + const uint16_t v = symbols[(11+pair/2)*target+2*i+pair%2]; + for (size_t h = 0; h < 2; ++h) { + // The last two pairs swap the lane's even/odd bit assignment. + const unsigned parity = pair < 6 ? 1-static_cast<unsigned>(h) : static_cast<unsigned>(h); + uint16_t nibble = 0; + for (unsigned k = 0; k < 4; ++k) nibble |= ((v>>(2*k+parity))&1)<<k; + const size_t p = 2*pair+h; + state.ix[p] = bcpack_add_aligned(ix.ix[p],unzigzag(nibble),16-bits); + } + } + uint8_t* block = output+i*16; + std::memset(block,0,16); + const size_t header = two ? 82 : 65; + for (size_t at = 0; at < header; ++at) { + const auto wire = BC6_WIRE[mode-1][at]; + unsigned value; + if (wire.field == 0) value = codes[mode-1]; + else if (wire.field == 1) value = part; + else { + const unsigned k = (wire.field-2)/3, c = (wire.field-2)%3; + const unsigned shift = 16-BC6_ENDPOINT_BITS[mode][k == 0 ? 0 : c+1]; + value = (state.ep[k][c]^0x8000u)>>shift; + } + bcpack_put_bit(block,at,value>>wire.bit); + } + size_t at = header; + const size_t anchor = two ? ANCHOR_2[part] : 0; + for (size_t p = 0; p < 16; ++p) { + const unsigned width = bits-static_cast<unsigned>(p == 0 || p == anchor); + const unsigned value = (state.ix[p]>>(16-bits))+(1u<<(bits-1)); + for (unsigned b = 0; b < width; ++b) bcpack_put_bit(block,at++,value>>b); + } + history[i&255] = state; + } + return true; +} diff --git a/src/startup_stubs/bcpack_decoder.h b/src/startup_stubs/bcpack_decoder.h index e255040f50..a279b804c5 100644 --- a/src/startup_stubs/bcpack_decoder.h +++ b/src/startup_stubs/bcpack_decoder.h @@ -2,6 +2,7 @@ // Adapted from bcpack-rs by Ahmet Dedeler (https://github.com/Ahmet-Dedeler, https://ahmetdedeler.com). // Source: https://github.com/Ahmet-Dedeler/bcpack-rs // SPDX-License-Identifier: MIT OR Apache-2.0 +// New BC1/2/6H reconstruction in bcpack_blocks_extra.inl is an original MIT contribution. // Incorporates rANS interval models derived from Microsoft silicon-rans (MIT License). #pragma once @@ -1119,48 +1120,6 @@ inline bool decode_bc7_blocks(const std::vector<uint16_t>& symbols, size_t num_b return true; } -inline bool decode_bc1_blocks(const std::vector<uint16_t>& symbols, size_t target, - uint8_t* output, size_t output_capacity) { - if (output_capacity < target * 8) return false; - const uint8_t ENDPOINT_WIDTHS[6] = { 5, 6, 5, 5, 6, 5 }; - uint8_t hist[256][6] = {}; - for (size_t i = 0; i < target; ++i) { - uint16_t l0_sym = symbols[0 * target + i]; - size_t v = l0_sym & 0xFF; - size_t d = (v & 1) ? (255 - (v >> 1)) : (v >> 1); - uint8_t pred[6] = {}; - if (d == 0) { - // zero - } else if (d <= i) { - std::memcpy(pred, hist[(i - d) & 255], 6); - } else { - size_t slot = (static_cast<int>(i) - static_cast<int>(d)) & 255; - std::memcpy(pred, BC1_WINDOW[slot], 6); - } - uint8_t e[6]; - for (int k = 0; k < 6; ++k) { - uint16_t sym = symbols[(2 + k) * target + i]; - int32_t res = unzigzag(sym); - uint32_t mask = (1u << ENDPOINT_WIDTHS[k]) - 1; - e[k] = static_cast<uint8_t>((pred[k] + res) & mask); - } - std::memcpy(hist[i & 255], e, 6); - uint16_t c0 = (static_cast<uint16_t>(e[0]) << 11) | (static_cast<uint16_t>(e[1]) << 5) | e[2]; - uint16_t c1 = (static_cast<uint16_t>(e[3]) << 11) | (static_cast<uint16_t>(e[4]) << 5) | e[5]; - uint32_t idx0 = symbols[8 * target + i] & 0xFF; - uint32_t idx1 = symbols[9 * target + i] & 0xFF; - uint32_t idx2 = symbols[10 * target + i] & 0xFF; - uint32_t idx3 = symbols[11 * target + i] & 0xFF; - uint32_t w = BC1_QUAD_MASKS[0][idx0] | BC1_QUAD_MASKS[1][idx1] | - BC1_QUAD_MASKS[2][idx2] | BC1_QUAD_MASKS[3][idx3]; - uint8_t* blk = output + i * 8; - std::memcpy(blk + 0, &c0, 2); - std::memcpy(blk + 2, &c1, 2); - std::memcpy(blk + 4, &w, 4); - } - return true; -} - inline constexpr uint8_t ALPHA_CODE[8] = { 0, 2, 3, 4, 5, 6, 7, 1 }; inline constexpr uint8_t COLOUR_CODE[4] = { 0, 2, 3, 1 }; @@ -1419,83 +1378,46 @@ inline bool decode_bc3_blocks(const std::vector<uint16_t>& symbols, size_t num_b return true; } +#include "bcpack_blocks_extra.inl" + inline bool decode_bcpack(const unsigned char* input, size_t input_size, unsigned bc_format, unsigned char* output, size_t output_size, size_t* produced) { - if (!input || !output || !produced) return false; - if (input_size == 0 || output_size == 0) return false; - - if (bc_format == 7) { - if (output_size % 16 != 0) return false; - size_t num_blocks = output_size / 16; - size_t target_per_lane = num_blocks * 2; - const uint8_t ab[16] = { 3, 3, 7, 7, 7, 7, 7, 6, 6, 4, 5, 7, 7, 7, 7, 4 }; - std::vector<uint16_t> symbols; - if (!decode_lanes(input, input_size, ab, 16, target_per_lane, symbols)) { - return false; - } - if (!decode_bc7_blocks(symbols, num_blocks, output, output_size)) { - return false; - } - *produced = output_size; - return true; - } else if (bc_format == 1) { - if (output_size % 8 != 0) return false; - size_t num_blocks = output_size / 8; - size_t target_per_lane = num_blocks; - const uint8_t ab[12] = { 7, 7, 4, 5, 4, 4, 5, 4, 7, 7, 7, 7 }; - std::vector<uint16_t> symbols; - if (!decode_lanes(input, input_size, ab, 12, target_per_lane, symbols)) { - return false; - } - if (!decode_bc1_blocks(symbols, num_blocks, output, output_size)) { - return false; - } - *produced = output_size; - return true; - } else if (bc_format == 4) { - if (output_size % 8 != 0) return false; - size_t num_blocks = output_size / 8; - size_t target_per_lane = num_blocks; - const uint8_t ab[12] = { 7, 7, 7, 7, 5, 5, 5, 5, 5, 5, 5, 5 }; - std::vector<uint16_t> symbols; - if (!decode_lanes(input, input_size, ab, 12, target_per_lane, symbols)) { - return false; - } - if (!decode_bc4_blocks(symbols, num_blocks, output, output_size)) { - return false; - } - *produced = output_size; - return true; - } else if (bc_format == 5) { - if (output_size % 16 != 0) return false; - size_t num_blocks = output_size / 16; - size_t target_per_lane = num_blocks * 2; - const uint8_t ab[12] = { 3, 3, 7, 7, 5, 5, 5, 5, 5, 5, 5, 5 }; - std::vector<uint16_t> symbols; - if (!decode_lanes(input, input_size, ab, 12, target_per_lane, symbols)) { - return false; - } - if (!decode_bc5_blocks(symbols, num_blocks, output, output_size)) { - return false; - } - *produced = output_size; - return true; - } else if (bc_format == 3) { - if (output_size % 16 != 0) return false; - size_t num_blocks = output_size / 16; - size_t target_per_lane = num_blocks * 2; - const uint8_t ab[12] = { 3, 3, 7, 5, 5, 5, 5, 4, 5, 4, 7, 7 }; - std::vector<uint16_t> symbols; - if (!decode_lanes(input, input_size, ab, 12, target_per_lane, symbols)) { - return false; - } - if (!decode_bc3_blocks(symbols, num_blocks, output, output_size)) { - return false; - } - *produced = output_size; - return true; + if (!produced) return false; + *produced = 0; + if (!input || !output || input_size == 0 || output_size == 0 || + bc_format < 1 || bc_format > 7) return false; + + // Hardware alphabet indices, not literal symbol bit widths. + static constexpr uint8_t alphabets[7][16] = { + {7,7,4,5,4,4,5,4,7,7,7,7}, + {3,3,3,3,3,3,3,3,3,3,4,5,4,7,7}, + {3,3,7,5,5,5,5,4,5,4,7,7}, + {7,7,7,7,5,5,5,5,5,5,5,5}, + {3,3,7,7,5,5,5,5,5,5,5,5}, + {3,3,7,7,7,4,4,4,5,5,5,7,7,7,7,4}, + {3,3,7,7,7,7,7,6,6,4,5,7,7,7,7,4}, + }; + const size_t bytes_per_block = bc_format == 1 || bc_format == 4 ? 8 : 16; + if (output_size % bytes_per_block) return false; + const size_t blocks = output_size / bytes_per_block; + const size_t target = output_size / 8; + const size_t lanes = bc_format >= 6 ? 16 : bc_format == 2 ? 15 : 12; + std::vector<uint16_t> symbols; + if (target > symbols.max_size() / lanes) return false; + if (!decode_lanes(input, input_size, alphabets[bc_format-1], lanes, target, symbols)) return false; + bool ok = false; + switch (bc_format) { + case 1: ok = decode_bc1_blocks(symbols,blocks,output,output_size); break; + case 2: ok = decode_bc2_blocks(symbols,blocks,output,output_size); break; + case 3: ok = decode_bc3_blocks(symbols,blocks,output,output_size); break; + case 4: ok = decode_bc4_blocks(symbols,blocks,output,output_size); break; + case 5: ok = decode_bc5_blocks(symbols,blocks,output,output_size); break; + case 6: ok = decode_bc6_blocks(symbols,blocks,output,output_size); break; + case 7: ok = decode_bc7_blocks(symbols,blocks,output,output_size); break; } - return false; + if (!ok) return false; + *produced = output_size; + return true; } } // namespace x2w_bcpack diff --git a/src/startup_stubs/bcpack_tables.h b/src/startup_stubs/bcpack_tables.h index 47f2d3d5b4..50dfd8e53d 100644 --- a/src/startup_stubs/bcpack_tables.h +++ b/src/startup_stubs/bcpack_tables.h @@ -1,6 +1,6 @@ // Generated BCPack model and codebook tables. -// Codebook, rank, and dictionary tables (BC7_CONTROL_TABLE, BC7_DICTIONARY, BC1_WINDOW, -// BC1_QUAD_MASKS, plus bcpack_tables_bcn.inl: RANK_PAIR_BC4, BC4_DICTIONARY, RANK_PAIR_BC5, +// Codebook, rank, and dictionary tables (BC7_CONTROL_TABLE, BC7_DICTIONARY, +// plus bcpack_tables_bcn.inl: RANK_PAIR_BC4, BC4_DICTIONARY, RANK_PAIR_BC5, // BC5_DICTIONARY, RANK_PAIR_BC3_ALPHA, RANK_QUAD_BC3_COLOUR, BC3_DICTIONARY) adapted // from bcpack-rs (pinned revision c55c5fad539644b8cf5a705051df214291763fc0) // by Ahmet Dedeler (https://github.com/Ahmet-Dedeler, https://ahmetdedeler.com). @@ -1623,404 +1623,7 @@ inline constexpr Bc7DictEntry BC7_DICTIONARY[255] = { { 0, { { 0x7f, 0x7f, 0x7e, 0x7e, 0x56, 0x3e, 0xfe, 0xfe }, { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }, { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 } }, { { 0x04, 0x04, 0x0a, 0x00, 0x0f, 0x04, 0x01, 0x01, 0x0b, 0x00, 0x0d, 0x0b, 0x0c, 0x0d, 0x0b, 0x04 }, { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 } } }, }; -inline constexpr uint8_t BC1_WINDOW[256][6] = { - { 0, 0, 0, 0, 0, 0 }, - { 7, 29, 6, 8, 30, 7 }, - { 15, 29, 15, 16, 36, 17 }, - { 20, 37, 14, 3, 6, 2 }, - { 0, 0, 0, 0, 0, 0 }, - { 10, 21, 11, 6, 15, 7 }, - { 12, 23, 11, 7, 15, 6 }, - { 12, 26, 12, 7, 15, 7 }, - { 22, 36, 15, 20, 32, 14 }, - { 14, 23, 8, 1, 2, 1 }, - { 23, 5, 30, 9, 5, 30 }, - { 11, 22, 11, 7, 15, 7 }, - { 17, 22, 7, 10, 11, 3 }, - { 12, 25, 12, 7, 16, 7 }, - { 13, 28, 8, 5, 12, 3 }, - { 11, 20, 8, 16, 31, 14 }, - { 23, 32, 30, 17, 12, 29 }, - { 8, 44, 30, 6, 26, 30 }, - { 10, 24, 30, 6, 45, 30 }, - { 10, 12, 4, 8, 8, 2 }, - { 16, 23, 30, 14, 6, 26 }, - { 12, 25, 13, 10, 22, 12 }, - { 19, 27, 10, 13, 16, 5 }, - { 11, 24, 12, 4, 11, 6 }, - { 29, 60, 29, 6, 13, 6 }, - { 17, 31, 11, 1, 2, 1 }, - { 26, 54, 24, 12, 24, 10 }, - { 23, 48, 30, 20, 37, 30 }, - { 16, 23, 10, 10, 15, 6 }, - { 11, 24, 10, 6, 13, 5 }, - { 18, 52, 30, 14, 22, 30 }, - { 14, 51, 30, 9, 34, 30 }, - { 2, 3, 1, 19, 37, 16 }, - { 14, 15, 30, 10, 32, 30 }, - { 29, 57, 27, 27, 52, 25 }, - { 13, 29, 15, 8, 20, 11 }, - { 13, 17, 5, 9, 10, 3 }, - { 18, 50, 29, 15, 10, 29 }, - { 11, 25, 13, 8, 19, 10 }, - { 17, 31, 12, 6, 12, 4 }, - { 22, 18, 30, 19, 41, 30 }, - { 10, 22, 11, 8, 18, 9 }, - { 18, 30, 31, 10, 44, 30 }, - { 25, 50, 24, 2, 4, 1 }, - { 11, 30, 31, 7, 15, 29 }, - { 12, 19, 8, 11, 16, 7 }, - { 19, 29, 30, 14, 55, 28 }, - { 9, 20, 10, 4, 10, 5 }, - { 12, 23, 10, 7, 14, 5 }, - { 26, 53, 25, 6, 13, 6 }, - { 19, 27, 31, 11, 19, 30 }, - { 21, 31, 30, 22, 31, 30 }, - { 10, 19, 5, 11, 21, 6 }, - { 30, 50, 3, 29, 46, 2 }, - { 15, 9, 30, 7, 9, 30 }, - { 14, 18, 6, 11, 14, 4 }, - { 28, 56, 26, 4, 7, 3 }, - { 8, 20, 10, 6, 13, 7 }, - { 28, 58, 26, 15, 32, 14 }, - { 10, 19, 8, 7, 10, 4 }, - { 16, 22, 9, 13, 17, 7 }, - { 1, 2, 1, 14, 28, 12 }, - { 22, 45, 30, 9, 15, 30 }, - { 19, 22, 30, 16, 23, 31 }, - { 25, 50, 24, 21, 43, 20 }, - { 6, 11, 4, 16, 31, 13 }, - { 13, 25, 8, 3, 6, 1 }, - { 5, 9, 3, 12, 24, 10 }, - { 16, 29, 13, 8, 14, 6 }, - { 20, 37, 16, 13, 26, 10 }, - { 18, 35, 15, 5, 9, 3 }, - { 13, 25, 11, 7, 12, 5 }, - { 11, 21, 7, 7, 14, 4 }, - { 20, 39, 16, 11, 21, 8 }, - { 16, 31, 12, 4, 8, 2 }, - { 22, 41, 30, 18, 23, 30 }, - { 24, 50, 24, 9, 20, 8 }, - { 3, 12, 7, 4, 16, 8 }, - { 18, 27, 12, 16, 22, 10 }, - { 24, 49, 23, 13, 28, 12 }, - { 24, 49, 24, 18, 38, 18 }, - { 17, 32, 12, 14, 28, 9 }, - { 20, 10, 31, 13, 10, 31 }, - { 7, 8, 2, 5, 5, 1 }, - { 1, 2, 1, 10, 21, 9 }, - { 10, 18, 6, 1, 1, 0 }, - { 22, 46, 21, 1, 3, 1 }, - { 11, 20, 8, 8, 14, 5 }, - { 17, 35, 31, 14, 14, 29 }, - { 16, 22, 31, 12, 40, 31 }, - { 12, 22, 9, 8, 15, 6 }, - { 18, 15, 30, 15, 33, 31 }, - { 19, 32, 30, 15, 43, 31 }, - { 18, 35, 15, 8, 15, 5 }, - { 21, 43, 20, 18, 37, 17 }, - { 10, 17, 6, 9, 15, 6 }, - { 14, 27, 12, 7, 14, 5 }, - { 8, 15, 7, 12, 26, 11 }, - { 18, 37, 17, 1, 1, 0 }, - { 17, 45, 30, 15, 33, 31 }, - { 13, 24, 11, 8, 17, 7 }, - { 23, 47, 22, 16, 32, 15 }, - { 18, 33, 13, 11, 22, 8 }, - { 4, 10, 4, 8, 17, 7 }, - { 1, 2, 1, 3, 7, 3 }, - { 11, 22, 9, 6, 12, 4 }, - { 16, 28, 11, 13, 24, 9 }, - { 12, 24, 12, 7, 13, 6 }, - { 23, 47, 22, 7, 15, 6 }, - { 11, 32, 30, 11, 31, 30 }, - { 14, 26, 11, 10, 19, 7 }, - { 20, 41, 19, 1, 3, 1 }, - { 14, 27, 12, 8, 17, 6 }, - { 11, 21, 9, 8, 15, 6 }, - { 1, 2, 1, 7, 13, 6 }, - { 19, 34, 14, 16, 30, 12 }, - { 13, 27, 13, 7, 16, 7 }, - { 15, 32, 16, 8, 19, 9 }, - { 15, 42, 31, 11, 22, 30 }, - { 23, 48, 23, 5, 10, 4 }, - { 22, 45, 21, 11, 23, 10 }, - { 31, 62, 30, 31, 61, 29 }, - { 13, 26, 11, 5, 8, 3 }, - { 19, 39, 19, 9, 21, 10 }, - { 7, 14, 2, 6, 12, 2 }, - { 21, 42, 20, 4, 7, 3 }, - { 10, 17, 7, 8, 13, 5 }, - { 10, 22, 8, 11, 19, 7 }, - { 19, 33, 31, 12, 31, 31 }, - { 21, 43, 20, 5, 11, 5 }, - { 9, 21, 8, 8, 13, 7 }, - { 10, 21, 10, 6, 13, 6 }, - { 15, 29, 12, 11, 21, 8 }, - { 21, 43, 20, 9, 19, 8 }, - { 3, 8, 3, 5, 11, 5 }, - { 16, 31, 13, 9, 18, 7 }, - { 11, 21, 11, 6, 13, 6 }, - { 10, 21, 10, 7, 15, 7 }, - { 27, 3, 1, 26, 1, 0 }, - { 18, 37, 18, 16, 32, 16 }, - { 12, 23, 10, 9, 18, 7 }, - { 12, 25, 12, 8, 18, 8 }, - { 11, 20, 9, 2, 5, 1 }, - { 7, 15, 7, 8, 18, 9 }, - { 17, 33, 15, 13, 24, 11 }, - { 9, 19, 9, 7, 15, 7 }, - { 21, 43, 20, 13, 28, 12 }, - { 17, 36, 17, 2, 4, 2 }, - { 10, 19, 9, 6, 13, 5 }, - { 20, 41, 19, 7, 14, 7 }, - { 3, 9, 6, 2, 8, 5 }, - { 13, 24, 10, 11, 20, 8 }, - { 18, 39, 18, 6, 10, 5 }, - { 19, 38, 18, 8, 17, 8 }, - { 16, 35, 17, 4, 11, 4 }, - { 11, 23, 11, 10, 21, 10 }, - { 17, 36, 17, 7, 15, 7 }, - { 13, 27, 13, 7, 13, 7 }, - { 9, 15, 4, 8, 13, 4 }, - { 9, 19, 7, 6, 9, 3 }, - { 19, 39, 19, 11, 25, 11 }, - { 11, 23, 11, 8, 17, 8 }, - { 14, 29, 14, 7, 16, 7 }, - { 12, 22, 8, 5, 9, 4 }, - { 10, 20, 9, 8, 17, 8 }, - { 21, 41, 19, 15, 32, 14 }, - { 14, 28, 13, 1, 2, 0 }, - { 8, 16, 8, 7, 14, 7 }, - { 9, 18, 8, 8, 16, 7 }, - { 10, 17, 7, 3, 4, 1 }, - { 14, 28, 13, 2, 4, 1 }, - { 14, 30, 14, 3, 6, 3 }, - { 19, 38, 18, 5, 11, 5 }, - { 12, 26, 12, 1, 2, 1 }, - { 9, 16, 6, 8, 13, 5 }, - { 8, 13, 4, 7, 11, 4 }, - { 16, 35, 16, 4, 8, 4 }, - { 13, 28, 13, 4, 9, 4 }, - { 15, 31, 15, 6, 13, 6 }, - { 12, 24, 11, 9, 19, 9 }, - { 9, 19, 8, 7, 14, 6 }, - { 14, 28, 13, 5, 10, 4 }, - { 10, 21, 7, 4, 6, 2 }, - { 16, 34, 17, 11, 25, 12 }, - { 15, 30, 15, 8, 16, 8 }, - { 13, 27, 13, 10, 20, 10 }, - { 9, 20, 9, 0, 1, 0 }, - { 16, 32, 15, 2, 4, 2 }, - { 13, 27, 12, 3, 6, 3 }, - { 13, 26, 12, 12, 23, 11 }, - { 12, 25, 12, 5, 11, 5 }, - { 11, 23, 11, 5, 11, 5 }, - { 16, 34, 16, 7, 13, 6 }, - { 16, 35, 31, 15, 25, 31 }, - { 16, 33, 16, 7, 16, 7 }, - { 13, 26, 13, 8, 19, 8 }, - { 18, 35, 17, 11, 23, 10 }, - { 18, 36, 18, 13, 28, 13 }, - { 12, 25, 12, 4, 9, 4 }, - { 9, 18, 7, 6, 11, 4 }, - { 15, 30, 14, 9, 20, 9 }, - { 17, 35, 16, 9, 19, 9 }, - { 11, 24, 11, 2, 4, 2 }, - { 16, 33, 16, 0, 1, 0 }, - { 15, 31, 15, 4, 9, 4 }, - { 16, 31, 15, 14, 27, 13 }, - { 14, 29, 14, 13, 25, 12 }, - { 11, 23, 11, 3, 6, 3 }, - { 16, 32, 16, 10, 22, 10 }, - { 11, 22, 11, 4, 9, 4 }, - { 11, 22, 10, 1, 2, 0 }, - { 8, 14, 5, 2, 4, 1 }, - { 9, 16, 6, 6, 10, 4 }, - { 10, 21, 10, 9, 19, 9 }, - { 14, 29, 14, 11, 23, 11 }, - { 9, 18, 8, 6, 13, 6 }, - { 6, 13, 6, 5, 11, 5 }, - { 7, 14, 6, 0, 1, 0 }, - { 4, 7, 2, 3, 4, 1 }, - { 10, 20, 9, 4, 8, 4 }, - { 9, 17, 7, 5, 9, 3 }, - { 7, 14, 7, 1, 2, 1 }, - { 10, 20, 10, 6, 11, 5 }, - { 8, 15, 5, 4, 6, 2 }, - { 8, 17, 8, 1, 2, 1 }, - { 10, 20, 10, 3, 6, 3 }, - { 7, 10, 3, 6, 8, 3 }, - { 8, 15, 7, 6, 12, 6 }, - { 9, 19, 9, 2, 4, 2 }, - { 6, 11, 4, 3, 4, 1 }, - { 6, 11, 4, 0, 1, 0 }, - { 8, 16, 7, 2, 5, 2 }, - { 16, 34, 16, 15, 29, 15 }, - { 7, 16, 7, 5, 10, 5 }, - { 8, 14, 5, 5, 9, 3 }, - { 9, 18, 8, 4, 8, 4 }, - { 5, 9, 3, 4, 7, 2 }, - { 9, 18, 8, 5, 10, 5 }, - { 6, 12, 6, 2, 4, 2 }, - { 7, 12, 5, 4, 7, 3 }, - { 5, 11, 5, 1, 2, 1 }, - { 8, 17, 8, 3, 6, 3 }, - { 16, 31, 31, 16, 32, 31 }, - { 7, 14, 7, 3, 6, 3 }, - { 5, 11, 6, 4, 9, 4 }, - { 7, 15, 7, 4, 8, 4 }, - { 2, 4, 2, 0, 0, 1 }, - { 5, 11, 5, 3, 6, 3 }, - { 4, 8, 4, 1, 1, 1 }, - { 3, 6, 3, 1, 2, 1 }, - { 2, 4, 1, 1, 2, 1 }, - { 4, 8, 4, 3, 6, 3 }, - { 3, 6, 3, 2, 4, 2 }, - { 4, 9, 4, 2, 4, 2 }, - { 17, 27, 31, 15, 34, 31 }, - { 0, 0, 1, 0, 0, 0 }, -}; - -inline constexpr uint32_t BC1_QUAD_MASKS[4][256] = { - { - 0x00000a0au, 0x00000f0fu, 0x00000000u, 0x00000505u, 0x00000f0au, 0x00000a0fu, 0x00000f0bu, 0x00000b0fu, - 0x00000f0eu, 0x00000e0fu, 0x00000b0bu, 0x00000e0eu, 0x00000d0fu, 0x00000b0au, 0x0000050au, 0x00000a0eu, - 0x0000070fu, 0x00000e0au, 0x00000a0bu, 0x00000f07u, 0x00000f0du, 0x00000a05u, 0x0000050fu, 0x00000f05u, - 0x00000d0du, 0x00000707u, 0x00000606u, 0x00000909u, 0x0000020au, 0x0000080au, 0x00000a02u, 0x00000500u, - 0x00000005u, 0x00000a08u, 0x00000101u, 0x0000090au, 0x00000404u, 0x0000030fu, 0x00000a06u, 0x00000a09u, - 0x00000c0fu, 0x00000b0eu, 0x00000f0cu, 0x00000f03u, 0x0000060au, 0x00000e0bu, 0x0000070eu, 0x00000e07u, - 0x00000d0bu, 0x00000b0du, 0x0000070au, 0x00000a07u, 0x00000d0au, 0x0000000fu, 0x00000a0du, 0x00000507u, - 0x00000d05u, 0x0000000au, 0x0000050du, 0x00000705u, 0x0000020fu, 0x0000060eu, 0x00000f00u, 0x0000080fu, - 0x00000f08u, 0x00000e06u, 0x0000030du, 0x00000f02u, 0x00000b09u, 0x00000205u, 0x0000070cu, 0x0000090bu, - 0x0000030bu, 0x00000805u, 0x00000c0eu, 0x00000e0cu, 0x00000508u, 0x00000b03u, 0x00000d03u, 0x00000a00u, - 0x00000502u, 0x00000d0eu, 0x0000070bu, 0x0000020bu, 0x00000b07u, 0x0000050eu, 0x00000c07u, 0x00000e0du, - 0x0000050bu, 0x00000b02u, 0x0000080eu, 0x00000c0cu, 0x0000060fu, 0x00000109u, 0x00000f06u, 0x0000090fu, - 0x00000604u, 0x00000e08u, 0x00000e05u, 0x00000209u, 0x00000f09u, 0x00000303u, 0x00000406u, 0x00000202u, - 0x00000b05u, 0x00000d07u, 0x0000020du, 0x00000708u, 0x00000506u, 0x00000806u, 0x00000808u, 0x00000608u, - 0x00000901u, 0x00000905u, 0x00000902u, 0x00000d02u, 0x00000807u, 0x0000070du, 0x00000706u, 0x00000607u, - 0x0000090du, 0x00000509u, 0x00000605u, 0x00000d09u, 0x00000105u, 0x00000307u, 0x00000903u, 0x0000050cu, - 0x00000c06u, 0x00000305u, 0x0000060cu, 0x00000c0du, 0x00000309u, 0x00000405u, 0x00000d0cu, 0x00000504u, - 0x00000703u, 0x00000501u, 0x00000503u, 0x00000c05u, 0x0000020eu, 0x0000080bu, 0x0000080du, 0x00000207u, - 0x00000e02u, 0x0000010fu, 0x00000f04u, 0x0000010du, 0x00000d08u, 0x00000f01u, 0x00000702u, 0x00000a03u, - 0x0000040fu, 0x00000704u, 0x00000b08u, 0x00000c0au, 0x0000030au, 0x00000a0cu, 0x00000d01u, 0x00000809u, - 0x00000407u, 0x00000206u, 0x00000602u, 0x00000908u, 0x00000700u, 0x0000000du, 0x00000a01u, 0x0000010au, - 0x0000040au, 0x0000060bu, 0x0000010bu, 0x00000d00u, 0x00000a04u, 0x00000e09u, 0x00000007u, 0x00000b01u, - 0x0000090eu, 0x00000b06u, 0x00000e04u, 0x0000040eu, 0x00000b0cu, 0x00000e03u, 0x0000030eu, 0x00000c0bu, - 0x00000802u, 0x00000301u, 0x00000002u, 0x00000208u, 0x0000040cu, 0x00000103u, 0x00000c04u, 0x00000200u, - 0x0000000eu, 0x0000000bu, 0x00000008u, 0x00000906u, 0x00000800u, 0x00000e00u, 0x00000009u, 0x00000b00u, - 0x00000609u, 0x00000600u, 0x00000006u, 0x00000900u, 0x00000203u, 0x00000907u, 0x0000080cu, 0x00000d06u, - 0x00000201u, 0x0000060du, 0x00000709u, 0x00000302u, 0x00000c08u, 0x00000408u, 0x00000804u, 0x00000107u, - 0x00000102u, 0x00000d04u, 0x0000040du, 0x00000701u, 0x00000001u, 0x00000306u, 0x00000603u, 0x0000090cu, - 0x00000c09u, 0x00000400u, 0x00000004u, 0x00000100u, 0x00000e01u, 0x00000601u, 0x00000904u, 0x00000409u, - 0x0000040bu, 0x0000010eu, 0x00000b04u, 0x00000106u, 0x00000003u, 0x0000000cu, 0x00000c00u, 0x00000402u, - 0x00000801u, 0x00000108u, 0x00000300u, 0x00000204u, 0x00000c03u, 0x0000030cu, 0x00000c02u, 0x00000104u, - 0x00000401u, 0x00000803u, 0x0000020cu, 0x00000308u, 0x00000403u, 0x00000304u, 0x0000010cu, 0x00000c01u, - }, - { - 0x0000a0a0u, 0x0000f0f0u, 0x00000000u, 0x00005050u, 0x0000f0a0u, 0x0000a0f0u, 0x0000f0b0u, 0x0000b0f0u, - 0x0000f0e0u, 0x0000e0f0u, 0x0000b0b0u, 0x0000e0e0u, 0x0000d0f0u, 0x0000b0a0u, 0x000050a0u, 0x0000a0e0u, - 0x000070f0u, 0x0000e0a0u, 0x0000a0b0u, 0x0000f070u, 0x0000f0d0u, 0x0000a050u, 0x000050f0u, 0x0000f050u, - 0x0000d0d0u, 0x00007070u, 0x00006060u, 0x00009090u, 0x000020a0u, 0x000080a0u, 0x0000a020u, 0x00005000u, - 0x00000050u, 0x0000a080u, 0x00001010u, 0x000090a0u, 0x00004040u, 0x000030f0u, 0x0000a060u, 0x0000a090u, - 0x0000c0f0u, 0x0000b0e0u, 0x0000f0c0u, 0x0000f030u, 0x000060a0u, 0x0000e0b0u, 0x000070e0u, 0x0000e070u, - 0x0000d0b0u, 0x0000b0d0u, 0x000070a0u, 0x0000a070u, 0x0000d0a0u, 0x000000f0u, 0x0000a0d0u, 0x00005070u, - 0x0000d050u, 0x000000a0u, 0x000050d0u, 0x00007050u, 0x000020f0u, 0x000060e0u, 0x0000f000u, 0x000080f0u, - 0x0000f080u, 0x0000e060u, 0x000030d0u, 0x0000f020u, 0x0000b090u, 0x00002050u, 0x000070c0u, 0x000090b0u, - 0x000030b0u, 0x00008050u, 0x0000c0e0u, 0x0000e0c0u, 0x00005080u, 0x0000b030u, 0x0000d030u, 0x0000a000u, - 0x00005020u, 0x0000d0e0u, 0x000070b0u, 0x000020b0u, 0x0000b070u, 0x000050e0u, 0x0000c070u, 0x0000e0d0u, - 0x000050b0u, 0x0000b020u, 0x000080e0u, 0x0000c0c0u, 0x000060f0u, 0x00001090u, 0x0000f060u, 0x000090f0u, - 0x00006040u, 0x0000e080u, 0x0000e050u, 0x00002090u, 0x0000f090u, 0x00003030u, 0x00004060u, 0x00002020u, - 0x0000b050u, 0x0000d070u, 0x000020d0u, 0x00007080u, 0x00005060u, 0x00008060u, 0x00008080u, 0x00006080u, - 0x00009010u, 0x00009050u, 0x00009020u, 0x0000d020u, 0x00008070u, 0x000070d0u, 0x00007060u, 0x00006070u, - 0x000090d0u, 0x00005090u, 0x00006050u, 0x0000d090u, 0x00001050u, 0x00003070u, 0x00009030u, 0x000050c0u, - 0x0000c060u, 0x00003050u, 0x000060c0u, 0x0000c0d0u, 0x00003090u, 0x00004050u, 0x0000d0c0u, 0x00005040u, - 0x00007030u, 0x00005010u, 0x00005030u, 0x0000c050u, 0x000020e0u, 0x000080b0u, 0x000080d0u, 0x00002070u, - 0x0000e020u, 0x000010f0u, 0x0000f040u, 0x000010d0u, 0x0000d080u, 0x0000f010u, 0x00007020u, 0x0000a030u, - 0x000040f0u, 0x00007040u, 0x0000b080u, 0x0000c0a0u, 0x000030a0u, 0x0000a0c0u, 0x0000d010u, 0x00008090u, - 0x00004070u, 0x00002060u, 0x00006020u, 0x00009080u, 0x00007000u, 0x000000d0u, 0x0000a010u, 0x000010a0u, - 0x000040a0u, 0x000060b0u, 0x000010b0u, 0x0000d000u, 0x0000a040u, 0x0000e090u, 0x00000070u, 0x0000b010u, - 0x000090e0u, 0x0000b060u, 0x0000e040u, 0x000040e0u, 0x0000b0c0u, 0x0000e030u, 0x000030e0u, 0x0000c0b0u, - 0x00008020u, 0x00003010u, 0x00000020u, 0x00002080u, 0x000040c0u, 0x00001030u, 0x0000c040u, 0x00002000u, - 0x000000e0u, 0x000000b0u, 0x00000080u, 0x00009060u, 0x00008000u, 0x0000e000u, 0x00000090u, 0x0000b000u, - 0x00006090u, 0x00006000u, 0x00000060u, 0x00009000u, 0x00002030u, 0x00009070u, 0x000080c0u, 0x0000d060u, - 0x00002010u, 0x000060d0u, 0x00007090u, 0x00003020u, 0x0000c080u, 0x00004080u, 0x00008040u, 0x00001070u, - 0x00001020u, 0x0000d040u, 0x000040d0u, 0x00007010u, 0x00000010u, 0x00003060u, 0x00006030u, 0x000090c0u, - 0x0000c090u, 0x00004000u, 0x00000040u, 0x00001000u, 0x0000e010u, 0x00006010u, 0x00009040u, 0x00004090u, - 0x000040b0u, 0x000010e0u, 0x0000b040u, 0x00001060u, 0x00000030u, 0x000000c0u, 0x0000c000u, 0x00004020u, - 0x00008010u, 0x00001080u, 0x00003000u, 0x00002040u, 0x0000c030u, 0x000030c0u, 0x0000c020u, 0x00001040u, - 0x00004010u, 0x00008030u, 0x000020c0u, 0x00003080u, 0x00004030u, 0x00003040u, 0x000010c0u, 0x0000c010u, - }, - { - 0x0a0a0000u, 0x0f0f0000u, 0x00000000u, 0x05050000u, 0x0f0a0000u, 0x0a0f0000u, 0x0f0b0000u, 0x0b0f0000u, - 0x0f0e0000u, 0x0e0f0000u, 0x0b0b0000u, 0x0e0e0000u, 0x0d0f0000u, 0x0b0a0000u, 0x050a0000u, 0x0a0e0000u, - 0x070f0000u, 0x0e0a0000u, 0x0a0b0000u, 0x0f070000u, 0x0f0d0000u, 0x0a050000u, 0x050f0000u, 0x0f050000u, - 0x0d0d0000u, 0x07070000u, 0x06060000u, 0x09090000u, 0x020a0000u, 0x080a0000u, 0x0a020000u, 0x05000000u, - 0x00050000u, 0x0a080000u, 0x01010000u, 0x090a0000u, 0x04040000u, 0x030f0000u, 0x0a060000u, 0x0a090000u, - 0x0c0f0000u, 0x0b0e0000u, 0x0f0c0000u, 0x0f030000u, 0x060a0000u, 0x0e0b0000u, 0x070e0000u, 0x0e070000u, - 0x0d0b0000u, 0x0b0d0000u, 0x070a0000u, 0x0a070000u, 0x0d0a0000u, 0x000f0000u, 0x0a0d0000u, 0x05070000u, - 0x0d050000u, 0x000a0000u, 0x050d0000u, 0x07050000u, 0x020f0000u, 0x060e0000u, 0x0f000000u, 0x080f0000u, - 0x0f080000u, 0x0e060000u, 0x030d0000u, 0x0f020000u, 0x0b090000u, 0x02050000u, 0x070c0000u, 0x090b0000u, - 0x030b0000u, 0x08050000u, 0x0c0e0000u, 0x0e0c0000u, 0x05080000u, 0x0b030000u, 0x0d030000u, 0x0a000000u, - 0x05020000u, 0x0d0e0000u, 0x070b0000u, 0x020b0000u, 0x0b070000u, 0x050e0000u, 0x0c070000u, 0x0e0d0000u, - 0x050b0000u, 0x0b020000u, 0x080e0000u, 0x0c0c0000u, 0x060f0000u, 0x01090000u, 0x0f060000u, 0x090f0000u, - 0x06040000u, 0x0e080000u, 0x0e050000u, 0x02090000u, 0x0f090000u, 0x03030000u, 0x04060000u, 0x02020000u, - 0x0b050000u, 0x0d070000u, 0x020d0000u, 0x07080000u, 0x05060000u, 0x08060000u, 0x08080000u, 0x06080000u, - 0x09010000u, 0x09050000u, 0x09020000u, 0x0d020000u, 0x08070000u, 0x070d0000u, 0x07060000u, 0x06070000u, - 0x090d0000u, 0x05090000u, 0x06050000u, 0x0d090000u, 0x01050000u, 0x03070000u, 0x09030000u, 0x050c0000u, - 0x0c060000u, 0x03050000u, 0x060c0000u, 0x0c0d0000u, 0x03090000u, 0x04050000u, 0x0d0c0000u, 0x05040000u, - 0x07030000u, 0x05010000u, 0x05030000u, 0x0c050000u, 0x020e0000u, 0x080b0000u, 0x080d0000u, 0x02070000u, - 0x0e020000u, 0x010f0000u, 0x0f040000u, 0x010d0000u, 0x0d080000u, 0x0f010000u, 0x07020000u, 0x0a030000u, - 0x040f0000u, 0x07040000u, 0x0b080000u, 0x0c0a0000u, 0x030a0000u, 0x0a0c0000u, 0x0d010000u, 0x08090000u, - 0x04070000u, 0x02060000u, 0x06020000u, 0x09080000u, 0x07000000u, 0x000d0000u, 0x0a010000u, 0x010a0000u, - 0x040a0000u, 0x060b0000u, 0x010b0000u, 0x0d000000u, 0x0a040000u, 0x0e090000u, 0x00070000u, 0x0b010000u, - 0x090e0000u, 0x0b060000u, 0x0e040000u, 0x040e0000u, 0x0b0c0000u, 0x0e030000u, 0x030e0000u, 0x0c0b0000u, - 0x08020000u, 0x03010000u, 0x00020000u, 0x02080000u, 0x040c0000u, 0x01030000u, 0x0c040000u, 0x02000000u, - 0x000e0000u, 0x000b0000u, 0x00080000u, 0x09060000u, 0x08000000u, 0x0e000000u, 0x00090000u, 0x0b000000u, - 0x06090000u, 0x06000000u, 0x00060000u, 0x09000000u, 0x02030000u, 0x09070000u, 0x080c0000u, 0x0d060000u, - 0x02010000u, 0x060d0000u, 0x07090000u, 0x03020000u, 0x0c080000u, 0x04080000u, 0x08040000u, 0x01070000u, - 0x01020000u, 0x0d040000u, 0x040d0000u, 0x07010000u, 0x00010000u, 0x03060000u, 0x06030000u, 0x090c0000u, - 0x0c090000u, 0x04000000u, 0x00040000u, 0x01000000u, 0x0e010000u, 0x06010000u, 0x09040000u, 0x04090000u, - 0x040b0000u, 0x010e0000u, 0x0b040000u, 0x01060000u, 0x00030000u, 0x000c0000u, 0x0c000000u, 0x04020000u, - 0x08010000u, 0x01080000u, 0x03000000u, 0x02040000u, 0x0c030000u, 0x030c0000u, 0x0c020000u, 0x01040000u, - 0x04010000u, 0x08030000u, 0x020c0000u, 0x03080000u, 0x04030000u, 0x03040000u, 0x010c0000u, 0x0c010000u, - }, - { - 0xa0a00000u, 0xf0f00000u, 0x00000000u, 0x50500000u, 0xf0a00000u, 0xa0f00000u, 0xf0b00000u, 0xb0f00000u, - 0xf0e00000u, 0xe0f00000u, 0xb0b00000u, 0xe0e00000u, 0xd0f00000u, 0xb0a00000u, 0x50a00000u, 0xa0e00000u, - 0x70f00000u, 0xe0a00000u, 0xa0b00000u, 0xf0700000u, 0xf0d00000u, 0xa0500000u, 0x50f00000u, 0xf0500000u, - 0xd0d00000u, 0x70700000u, 0x60600000u, 0x90900000u, 0x20a00000u, 0x80a00000u, 0xa0200000u, 0x50000000u, - 0x00500000u, 0xa0800000u, 0x10100000u, 0x90a00000u, 0x40400000u, 0x30f00000u, 0xa0600000u, 0xa0900000u, - 0xc0f00000u, 0xb0e00000u, 0xf0c00000u, 0xf0300000u, 0x60a00000u, 0xe0b00000u, 0x70e00000u, 0xe0700000u, - 0xd0b00000u, 0xb0d00000u, 0x70a00000u, 0xa0700000u, 0xd0a00000u, 0x00f00000u, 0xa0d00000u, 0x50700000u, - 0xd0500000u, 0x00a00000u, 0x50d00000u, 0x70500000u, 0x20f00000u, 0x60e00000u, 0xf0000000u, 0x80f00000u, - 0xf0800000u, 0xe0600000u, 0x30d00000u, 0xf0200000u, 0xb0900000u, 0x20500000u, 0x70c00000u, 0x90b00000u, - 0x30b00000u, 0x80500000u, 0xc0e00000u, 0xe0c00000u, 0x50800000u, 0xb0300000u, 0xd0300000u, 0xa0000000u, - 0x50200000u, 0xd0e00000u, 0x70b00000u, 0x20b00000u, 0xb0700000u, 0x50e00000u, 0xc0700000u, 0xe0d00000u, - 0x50b00000u, 0xb0200000u, 0x80e00000u, 0xc0c00000u, 0x60f00000u, 0x10900000u, 0xf0600000u, 0x90f00000u, - 0x60400000u, 0xe0800000u, 0xe0500000u, 0x20900000u, 0xf0900000u, 0x30300000u, 0x40600000u, 0x20200000u, - 0xb0500000u, 0xd0700000u, 0x20d00000u, 0x70800000u, 0x50600000u, 0x80600000u, 0x80800000u, 0x60800000u, - 0x90100000u, 0x90500000u, 0x90200000u, 0xd0200000u, 0x80700000u, 0x70d00000u, 0x70600000u, 0x60700000u, - 0x90d00000u, 0x50900000u, 0x60500000u, 0xd0900000u, 0x10500000u, 0x30700000u, 0x90300000u, 0x50c00000u, - 0xc0600000u, 0x30500000u, 0x60c00000u, 0xc0d00000u, 0x30900000u, 0x40500000u, 0xd0c00000u, 0x50400000u, - 0x70300000u, 0x50100000u, 0x50300000u, 0xc0500000u, 0x20e00000u, 0x80b00000u, 0x80d00000u, 0x20700000u, - 0xe0200000u, 0x10f00000u, 0xf0400000u, 0x10d00000u, 0xd0800000u, 0xf0100000u, 0x70200000u, 0xa0300000u, - 0x40f00000u, 0x70400000u, 0xb0800000u, 0xc0a00000u, 0x30a00000u, 0xa0c00000u, 0xd0100000u, 0x80900000u, - 0x40700000u, 0x20600000u, 0x60200000u, 0x90800000u, 0x70000000u, 0x00d00000u, 0xa0100000u, 0x10a00000u, - 0x40a00000u, 0x60b00000u, 0x10b00000u, 0xd0000000u, 0xa0400000u, 0xe0900000u, 0x00700000u, 0xb0100000u, - 0x90e00000u, 0xb0600000u, 0xe0400000u, 0x40e00000u, 0xb0c00000u, 0xe0300000u, 0x30e00000u, 0xc0b00000u, - 0x80200000u, 0x30100000u, 0x00200000u, 0x20800000u, 0x40c00000u, 0x10300000u, 0xc0400000u, 0x20000000u, - 0x00e00000u, 0x00b00000u, 0x00800000u, 0x90600000u, 0x80000000u, 0xe0000000u, 0x00900000u, 0xb0000000u, - 0x60900000u, 0x60000000u, 0x00600000u, 0x90000000u, 0x20300000u, 0x90700000u, 0x80c00000u, 0xd0600000u, - 0x20100000u, 0x60d00000u, 0x70900000u, 0x30200000u, 0xc0800000u, 0x40800000u, 0x80400000u, 0x10700000u, - 0x10200000u, 0xd0400000u, 0x40d00000u, 0x70100000u, 0x00100000u, 0x30600000u, 0x60300000u, 0x90c00000u, - 0xc0900000u, 0x40000000u, 0x00400000u, 0x10000000u, 0xe0100000u, 0x60100000u, 0x90400000u, 0x40900000u, - 0x40b00000u, 0x10e00000u, 0xb0400000u, 0x10600000u, 0x00300000u, 0x00c00000u, 0xc0000000u, 0x40200000u, - 0x80100000u, 0x10800000u, 0x30000000u, 0x20400000u, 0xc0300000u, 0x30c00000u, 0xc0200000u, 0x10400000u, - 0x40100000u, 0x80300000u, 0x20c00000u, 0x30800000u, 0x40300000u, 0x30400000u, 0x10c00000u, 0xc0100000u, - }, -}; - #include "bcpack_tables_bcn.inl" +#include "bcpack_tables_extra.inl" } // namespace x2w_bcpack diff --git a/src/startup_stubs/bcpack_tables_extra.inl b/src/startup_stubs/bcpack_tables_extra.inl new file mode 100644 index 0000000000..6fcce900d0 --- /dev/null +++ b/src/startup_stubs/bcpack_tables_extra.inl @@ -0,0 +1,1470 @@ +// BCPack format constants reconstructed with synthetic lane streams. +// No SDK binaries or title data are embedded. See docs/experiments/bcpack-standalone.md. +// BC6H wire descriptors adapt the MIT-licensed Microsoft DirectXTex BC6HBC7.cpp. +// Copyright (c) Microsoft Corporation. All rights reserved. +// SPDX-License-Identifier: MIT + +struct Bc1FullState { uint8_t ep[6]; uint8_t ix[16]; }; +struct Bc2State { uint8_t alpha[16]; uint8_t ep[6]; uint8_t ix[16]; }; +struct Bc6State { uint16_t ep[4][3]; uint16_t ix[16]; }; +struct Bc6WireBit { uint8_t field; uint8_t bit; }; + +inline constexpr uint8_t BC1_POSITION_RANK[256][4] = { + { 1, 1, 1, 1 }, + { 2, 2, 2, 2 }, + { 0, 0, 0, 0 }, + { 3, 3, 3, 3 }, + { 1, 1, 2, 2 }, + { 2, 2, 1, 1 }, + { 2, 1, 2, 2 }, + { 2, 2, 2, 1 }, + { 1, 2, 2, 2 }, + { 2, 2, 1, 2 }, + { 2, 1, 2, 1 }, + { 1, 2, 1, 2 }, + { 2, 2, 3, 2 }, + { 1, 1, 2, 1 }, + { 1, 1, 3, 3 }, + { 1, 2, 1, 1 }, + { 2, 2, 2, 3 }, + { 1, 1, 1, 2 }, + { 2, 1, 1, 1 }, + { 2, 3, 2, 2 }, + { 3, 2, 2, 2 }, + { 3, 3, 1, 1 }, + { 2, 2, 3, 3 }, + { 3, 3, 2, 2 }, + { 3, 2, 3, 2 }, + { 2, 3, 2, 3 }, + { 1, 3, 1, 3 }, + { 3, 1, 3, 1 }, + { 1, 1, 1, 0 }, + { 1, 1, 0, 1 }, + { 1, 0, 1, 1 }, + { 0, 0, 3, 3 }, + { 3, 3, 0, 0 }, + { 0, 1, 1, 1 }, + { 3, 0, 3, 0 }, + { 1, 1, 3, 1 }, + { 0, 3, 0, 3 }, + { 2, 2, 2, 0 }, + { 1, 3, 1, 1 }, + { 3, 1, 1, 1 }, + { 2, 2, 0, 2 }, + { 1, 2, 2, 1 }, + { 0, 2, 2, 2 }, + { 2, 0, 2, 2 }, + { 1, 1, 1, 3 }, + { 2, 1, 1, 2 }, + { 1, 2, 2, 3 }, + { 2, 3, 1, 2 }, + { 2, 1, 3, 2 }, + { 3, 2, 2, 1 }, + { 1, 1, 2, 3 }, + { 2, 3, 1, 1 }, + { 1, 1, 3, 2 }, + { 2, 2, 0, 0 }, + { 3, 2, 1, 1 }, + { 2, 3, 3, 3 }, + { 3, 3, 3, 2 }, + { 1, 1, 0, 0 }, + { 3, 2, 3, 3 }, + { 3, 3, 2, 3 }, + { 2, 2, 1, 0 }, + { 1, 2, 1, 3 }, + { 0, 0, 2, 2 }, + { 2, 2, 0, 1 }, + { 0, 1, 2, 2 }, + { 1, 3, 1, 2 }, + { 3, 2, 2, 0 }, + { 1, 0, 2, 2 }, + { 3, 1, 2, 1 }, + { 3, 3, 1, 0 }, + { 0, 2, 2, 3 }, + { 2, 1, 3, 1 }, + { 2, 1, 2, 0 }, + { 3, 3, 0, 1 }, + { 1, 2, 0, 2 }, + { 0, 2, 1, 2 }, + { 0, 1, 3, 3 }, + { 2, 0, 2, 1 }, + { 2, 0, 3, 2 }, + { 0, 0, 1, 1 }, + { 1, 0, 3, 3 }, + { 1, 2, 3, 2 }, + { 2, 1, 2, 3 }, + { 2, 1, 1, 0 }, + { 2, 3, 2, 1 }, + { 1, 2, 3, 3 }, + { 2, 3, 0, 2 }, + { 3, 2, 1, 2 }, + { 2, 1, 3, 3 }, + { 1, 0, 2, 1 }, + { 1, 2, 0, 1 }, + { 0, 2, 0, 2 }, + { 2, 2, 1, 3 }, + { 3, 1, 3, 0 }, + { 1, 3, 2, 2 }, + { 2, 2, 3, 1 }, + { 0, 3, 1, 3 }, + { 0, 1, 1, 2 }, + { 3, 3, 1, 2 }, + { 3, 1, 1, 0 }, + { 3, 1, 2, 2 }, + { 2, 0, 2, 0 }, + { 1, 3, 0, 3 }, + { 1, 0, 1, 0 }, + { 3, 3, 2, 1 }, + { 2, 3, 3, 2 }, + { 3, 2, 1, 0 }, + { 0, 1, 2, 3 }, + { 1, 3, 3, 3 }, + { 1, 3, 0, 1 }, + { 0, 1, 0, 1 }, + { 0, 1, 1, 3 }, + { 3, 0, 3, 1 }, + { 3, 3, 3, 1 }, + { 1, 0, 3, 1 }, + { 1, 0, 3, 2 }, + { 2, 3, 0, 1 }, + { 3, 2, 2, 3 }, + { 1, 3, 2, 3 }, + { 2, 3, 1, 3 }, + { 3, 2, 3, 1 }, + { 3, 1, 3, 3 }, + { 3, 3, 1, 3 }, + { 3, 1, 3, 2 }, + { 3, 3, 3, 0 }, + { 2, 3, 2, 0 }, + { 2, 0, 3, 1 }, + { 0, 2, 3, 3 }, + { 1, 3, 0, 2 }, + { 3, 3, 2, 0 }, + { 0, 2, 1, 3 }, + { 3, 2, 0, 2 }, + { 3, 1, 2, 0 }, + { 3, 3, 0, 3 }, + { 0, 2, 3, 2 }, + { 0, 3, 3, 3 }, + { 2, 0, 2, 3 }, + { 3, 0, 3, 3 }, + { 2, 0, 3, 3 }, + { 3, 3, 0, 2 }, + { 1, 2, 1, 0 }, + { 2, 1, 0, 1 }, + { 3, 2, 0, 1 }, + { 2, 3, 1, 0 }, + { 1, 0, 1, 2 }, + { 2, 2, 3, 0 }, + { 0, 3, 2, 2 }, + { 3, 2, 3, 0 }, + { 0, 1, 3, 2 }, + { 3, 0, 2, 2 }, + { 1, 0, 2, 3 }, + { 2, 0, 1, 1 }, + { 2, 2, 0, 3 }, + { 0, 3, 2, 3 }, + { 0, 1, 2, 1 }, + { 1, 1, 0, 2 }, + { 1, 1, 2, 0 }, + { 0, 2, 1, 1 }, + { 3, 0, 3, 2 }, + { 3, 1, 0, 1 }, + { 2, 3, 0, 3 }, + { 1, 3, 1, 0 }, + { 1, 0, 1, 3 }, + { 0, 1, 3, 1 }, + { 0, 0, 2, 3 }, + { 3, 2, 0, 0 }, + { 3, 0, 1, 1 }, + { 1, 1, 3, 0 }, + { 1, 1, 0, 3 }, + { 2, 1, 1, 3 }, + { 2, 1, 3, 0 }, + { 0, 0, 3, 2 }, + { 0, 3, 1, 1 }, + { 3, 1, 1, 2 }, + { 2, 3, 0, 0 }, + { 3, 0, 2, 1 }, + { 1, 2, 3, 1 }, + { 1, 3, 2, 1 }, + { 0, 3, 1, 2 }, + { 1, 2, 0, 3 }, + { 0, 2, 2, 1 }, + { 2, 0, 1, 2 }, + { 1, 2, 2, 0 }, + { 2, 1, 0, 2 }, + { 1, 0, 0, 1 }, + { 3, 0, 2, 0 }, + { 1, 0, 0, 0 }, + { 0, 1, 1, 0 }, + { 0, 2, 0, 3 }, + { 2, 0, 3, 0 }, + { 0, 3, 0, 2 }, + { 0, 0, 1, 0 }, + { 1, 2, 0, 0 }, + { 2, 1, 0, 0 }, + { 0, 1, 0, 0 }, + { 1, 3, 3, 1 }, + { 0, 0, 0, 1 }, + { 0, 0, 1, 2 }, + { 3, 1, 0, 0 }, + { 0, 0, 2, 1 }, + { 3, 1, 1, 3 }, + { 0, 0, 1, 3 }, + { 1, 3, 0, 0 }, + { 0, 0, 3, 1 }, + { 2, 0, 1, 0 }, + { 2, 3, 3, 1 }, + { 0, 2, 0, 1 }, + { 1, 3, 3, 2 }, + { 3, 0, 1, 0 }, + { 3, 2, 1, 3 }, + { 3, 1, 2, 3 }, + { 1, 0, 2, 0 }, + { 0, 1, 0, 2 }, + { 0, 1, 0, 3 }, + { 0, 3, 0, 1 }, + { 2, 3, 3, 0 }, + { 1, 0, 3, 0 }, + { 0, 3, 3, 2 }, + { 3, 2, 0, 3 }, + { 3, 0, 2, 3 }, + { 3, 0, 0, 0 }, + { 1, 3, 2, 0 }, + { 2, 0, 1, 3 }, + { 0, 2, 3, 1 }, + { 3, 1, 0, 2 }, + { 0, 0, 0, 3 }, + { 0, 3, 0, 0 }, + { 0, 0, 3, 0 }, + { 3, 0, 1, 2 }, + { 1, 3, 3, 0 }, + { 0, 3, 3, 1 }, + { 3, 1, 0, 3 }, + { 2, 1, 0, 3 }, + { 1, 2, 3, 0 }, + { 0, 3, 2, 1 }, + { 3, 0, 1, 3 }, + { 2, 0, 0, 0 }, + { 0, 2, 0, 0 }, + { 0, 0, 0, 2 }, + { 1, 0, 0, 3 }, + { 3, 0, 0, 1 }, + { 0, 1, 3, 0 }, + { 0, 0, 2, 0 }, + { 0, 3, 1, 0 }, + { 2, 0, 0, 2 }, + { 0, 2, 2, 0 }, + { 1, 0, 0, 2 }, + { 3, 0, 0, 3 }, + { 0, 3, 3, 0 }, + { 2, 0, 0, 1 }, + { 0, 2, 1, 0 }, + { 0, 1, 2, 0 }, + { 2, 0, 0, 3 }, + { 0, 3, 2, 0 }, + { 0, 2, 3, 0 }, + { 3, 0, 0, 2 }, +}; + +inline constexpr Bc1FullState BC1_FULL_DICTIONARY[255] = { + { { 0, 0, 1, 0, 0, 0 }, { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 } }, + { { 17, 27, 31, 15, 34, 31 }, { 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3 } }, + { { 4, 9, 4, 2, 4, 2 }, { 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2 } }, + { { 3, 6, 3, 2, 4, 2 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } }, + { { 4, 8, 4, 3, 6, 3 }, { 1, 0, 3, 3, 1, 1, 0, 3, 1, 1, 0, 3, 0, 1, 0, 0 } }, + { { 2, 4, 1, 1, 2, 1 }, { 1, 0, 3, 3, 1, 1, 0, 3, 1, 1, 1, 1, 0, 1, 1, 1 } }, + { { 3, 6, 3, 1, 2, 1 }, { 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 3, 0, 0, 3, 3 } }, + { { 4, 8, 4, 1, 1, 1 }, { 3, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1 } }, + { { 5, 11, 5, 3, 6, 3 }, { 3, 3, 0, 1, 3, 3, 3, 0, 3, 2, 2, 3, 3, 2, 2, 3 } }, + { { 2, 4, 2, 0, 0, 1 }, { 3, 2, 2, 3, 0, 3, 3, 3, 1, 1, 0, 3, 0, 0, 0, 3 } }, + { { 7, 15, 7, 4, 8, 4 }, { 3, 0, 1, 1, 3, 0, 1, 1, 3, 0, 1, 1, 3, 0, 1, 1 } }, + { { 5, 11, 6, 4, 9, 4 }, { 3, 2, 2, 3, 3, 3, 3, 3, 0, 0, 0, 0, 0, 0, 0, 0 } }, + { { 7, 14, 7, 3, 6, 3 }, { 3, 0, 0, 3, 0, 0, 0, 3, 1, 1, 0, 3, 0, 0, 0, 3 } }, + { { 16, 31, 31, 16, 32, 31 }, { 3, 0, 0, 1, 0, 0, 0, 0, 1, 1, 0, 3, 0, 0, 3, 3 } }, + { { 8, 17, 8, 3, 6, 3 }, { 0, 0, 0, 3, 0, 1, 0, 3, 0, 1, 0, 3, 0, 0, 0, 0 } }, + { { 5, 11, 5, 1, 2, 1 }, { 1, 0, 3, 3, 0, 3, 3, 3, 3, 2, 2, 3, 3, 2, 2, 3 } }, + { { 7, 12, 5, 4, 7, 3 }, { 3, 3, 0, 1, 3, 3, 3, 0, 3, 3, 3, 3, 0, 0, 3, 3 } }, + { { 6, 12, 6, 2, 4, 2 }, { 3, 3, 0, 1, 3, 3, 3, 0, 3, 3, 3, 3, 3, 3, 3, 3 } }, + { { 9, 18, 8, 5, 10, 5 }, { 1, 1, 0, 3, 1, 1, 0, 3, 0, 1, 0, 3, 3, 0, 0, 3 } }, + { { 5, 9, 3, 4, 7, 2 }, { 0, 0, 0, 3, 0, 1, 0, 3, 0, 1, 0, 3, 0, 0, 0, 3 } }, + { { 9, 18, 8, 4, 8, 4 }, { 3, 2, 3, 3, 3, 3, 3, 0, 3, 3, 0, 1, 3, 0, 0, 0 } }, + { { 8, 14, 5, 5, 9, 3 }, { 1, 0, 3, 3, 1, 0, 3, 3, 1, 0, 3, 3, 1, 0, 0, 0 } }, + { { 7, 16, 7, 5, 10, 5 }, { 3, 3, 3, 3, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1 } }, + { { 16, 34, 16, 15, 29, 15 }, { 3, 3, 2, 3, 0, 0, 3, 3, 1, 1, 0, 3, 0, 0, 0, 0 } }, + { { 8, 16, 7, 2, 4, 2 }, { 3, 2, 2, 3, 3, 3, 2, 3, 0, 3, 3, 3, 1, 0, 0, 3 } }, + { { 6, 11, 4, 0, 1, 0 }, { 1, 1, 0, 3, 1, 1, 0, 3, 1, 1, 0, 3, 1, 0, 0, 3 } }, + { { 6, 11, 4, 3, 4, 1 }, { 3, 0, 1, 1, 3, 0, 1, 1, 3, 3, 0, 0, 3, 3, 0, 0 } }, + { { 9, 19, 9, 2, 4, 2 }, { 3, 3, 0, 1, 3, 3, 0, 1, 3, 0, 0, 0, 0, 0, 0, 0 } }, + { { 8, 15, 7, 6, 12, 6 }, { 1, 0, 3, 3, 1, 1, 3, 3, 1, 1, 3, 3, 1, 1, 3, 3 } }, + { { 7, 10, 3, 6, 8, 3 }, { 3, 3, 3, 3, 0, 0, 3, 3, 0, 1, 0, 3, 0, 0, 0, 3 } }, + { { 10, 20, 10, 3, 6, 3 }, { 3, 3, 0, 1, 3, 0, 1, 1, 0, 1, 1, 1, 0, 1, 1, 0 } }, + { { 8, 17, 8, 1, 2, 1 }, { 3, 2, 2, 3, 3, 3, 3, 3, 0, 1, 0, 3, 0, 0, 0, 0 } }, + { { 8, 15, 5, 4, 6, 2 }, { 1, 1, 0, 3, 0, 3, 3, 3, 3, 2, 2, 3, 2, 2, 2, 3 } }, + { { 10, 20, 10, 5, 10, 5 }, { 3, 3, 0, 1, 0, 0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0 } }, + { { 7, 14, 7, 1, 2, 1 }, { 0, 0, 0, 3, 1, 1, 0, 3, 1, 1, 0, 3, 0, 0, 0, 3 } }, + { { 9, 17, 7, 5, 9, 3 }, { 1, 1, 1, 1, 0, 0, 1, 1, 3, 3, 0, 1, 3, 3, 0, 1 } }, + { { 10, 20, 9, 4, 8, 4 }, { 3, 3, 3, 3, 3, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0 } }, + { { 4, 7, 2, 3, 4, 1 }, { 3, 3, 3, 3, 3, 2, 3, 3, 3, 3, 3, 3, 0, 0, 0, 0 } }, + { { 7, 14, 6, 0, 1, 0 }, { 3, 0, 1, 1, 3, 0, 0, 0, 3, 3, 3, 3, 3, 3, 2, 2 } }, + { { 6, 13, 6, 5, 11, 5 }, { 3, 0, 0, 3, 3, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1, 1 } }, + { { 9, 18, 8, 6, 13, 6 }, { 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 3, 0, 0, 0, 3 } }, + { { 14, 30, 14, 11, 22, 11 }, { 3, 3, 0, 1, 3, 2, 3, 0, 3, 3, 3, 3, 0, 0, 0, 3 } }, + { { 10, 21, 10, 9, 19, 9 }, { 1, 1, 0, 3, 1, 1, 0, 3, 0, 0, 0, 3, 3, 3, 3, 3 } }, + { { 9, 16, 6, 6, 10, 4 }, { 3, 3, 3, 3, 3, 3, 3, 3, 0, 1, 0, 0, 0, 0, 0, 0 } }, + { { 8, 14, 5, 2, 4, 1 }, { 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 0, 0, 3, 0, 1, 1 } }, + { { 11, 22, 10, 1, 2, 0 }, { 1, 0, 3, 3, 1, 0, 3, 3, 1, 0, 3, 3, 1, 0, 3, 3 } }, + { { 11, 22, 11, 4, 9, 4 }, { 1, 1, 1, 1, 0, 3, 3, 3, 3, 3, 2, 3, 0, 3, 3, 3 } }, + { { 16, 32, 16, 10, 21, 10 }, { 1, 0, 3, 3, 1, 0, 3, 3, 0, 3, 3, 3, 3, 3, 3, 3 } }, + { { 11, 23, 11, 3, 6, 3 }, { 3, 3, 3, 3, 3, 3, 3, 3, 0, 0, 0, 0, 0, 0, 0, 0 } }, + { { 14, 29, 14, 13, 25, 12 }, { 3, 3, 0, 1, 3, 3, 0, 1, 3, 3, 0, 1, 3, 0, 0, 1 } }, + { { 16, 31, 15, 14, 27, 13 }, { 3, 3, 0, 0, 3, 3, 0, 1, 3, 3, 0, 1, 0, 0, 0, 0 } }, + { { 15, 31, 15, 4, 9, 4 }, { 1, 0, 3, 3, 0, 0, 3, 3, 0, 3, 3, 3, 0, 0, 0, 0 } }, + { { 16, 33, 16, 0, 1, 0 }, { 3, 0, 0, 3, 3, 1, 1, 0, 3, 1, 1, 0, 3, 0, 0, 0 } }, + { { 11, 24, 11, 2, 4, 2 }, { 3, 2, 0, 1, 3, 2, 3, 0, 3, 3, 3, 0, 0, 0, 0, 0 } }, + { { 17, 35, 16, 9, 18, 9 }, { 3, 3, 3, 3, 3, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0 } }, + { { 15, 30, 14, 9, 19, 9 }, { 3, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0 } }, + { { 9, 18, 7, 6, 11, 4 }, { 3, 0, 0, 3, 0, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 3 } }, + { { 12, 25, 12, 4, 8, 4 }, { 3, 3, 0, 3, 3, 3, 0, 0, 3, 3, 0, 1, 3, 3, 3, 0 } }, + { { 18, 37, 18, 13, 27, 13 }, { 1, 0, 3, 3, 1, 0, 3, 3, 0, 0, 3, 3, 0, 0, 3, 3 } }, + { { 18, 36, 17, 11, 22, 10 }, { 3, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 3, 0, 0, 0, 0 } }, + { { 13, 27, 13, 8, 18, 8 }, { 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 0, 0, 3, 0, 1, 0 } }, + { { 16, 33, 16, 7, 15, 7 }, { 3, 3, 3, 3, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1 } }, + { { 16, 35, 31, 15, 25, 31 }, { 3, 3, 3, 3, 0, 3, 3, 3, 1, 0, 3, 3, 1, 0, 3, 3 } }, + { { 16, 34, 16, 6, 12, 5 }, { 1, 0, 0, 3, 0, 0, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3 } }, + { { 11, 23, 11, 5, 11, 5 }, { 3, 3, 0, 3, 3, 3, 3, 3, 0, 3, 3, 3, 0, 0, 0, 0 } }, + { { 12, 25, 12, 5, 10, 5 }, { 3, 2, 3, 3, 3, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } }, + { { 13, 26, 12, 12, 23, 11 }, { 3, 3, 3, 3, 3, 0, 0, 0, 3, 3, 1, 1, 3, 3, 0, 0 } }, + { { 13, 27, 12, 3, 6, 3 }, { 3, 3, 3, 3, 3, 3, 3, 3, 0, 3, 3, 3, 1, 0, 3, 3 } }, + { { 16, 32, 15, 2, 4, 2 }, { 1, 1, 0, 0, 0, 0, 0, 0, 3, 3, 3, 3, 3, 2, 2, 3 } }, + { { 9, 20, 9, 0, 1, 0 }, { 3, 3, 0, 3, 0, 0, 0, 3, 1, 1, 0, 0, 1, 0, 0, 0 } }, + { { 13, 27, 13, 10, 20, 10 }, { 3, 3, 0, 3, 3, 0, 0, 3, 3, 3, 0, 3, 3, 0, 0, 0 } }, + { { 15, 30, 15, 8, 16, 8 }, { 3, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3 } }, + { { 16, 34, 17, 11, 25, 12 }, { 0, 0, 0, 0, 0, 0, 3, 3, 1, 0, 3, 3, 1, 0, 3, 3 } }, + { { 10, 20, 7, 4, 6, 2 }, { 3, 3, 0, 1, 3, 3, 0, 1, 3, 3, 0, 1, 0, 0, 0, 0 } }, + { { 14, 28, 13, 5, 10, 4 }, { 3, 2, 3, 3, 2, 2, 3, 0, 3, 3, 0, 1, 3, 0, 0, 1 } }, + { { 9, 19, 8, 7, 14, 6 }, { 3, 2, 2, 3, 0, 3, 3, 3, 1, 1, 1, 0, 1, 1, 1, 1 } }, + { { 12, 24, 11, 9, 19, 9 }, { 3, 0, 1, 1, 3, 3, 0, 0, 3, 3, 3, 3, 3, 3, 3, 3 } }, + { { 15, 31, 15, 6, 13, 6 }, { 0, 0, 0, 3, 3, 0, 0, 3, 3, 3, 3, 3, 3, 3, 3, 3 } }, + { { 13, 28, 13, 4, 9, 4 }, { 3, 3, 2, 3, 0, 0, 3, 3, 1, 1, 1, 0, 1, 1, 1, 1 } }, + { { 16, 34, 16, 3, 7, 3 }, { 3, 3, 2, 3, 0, 3, 3, 3, 1, 0, 0, 0, 0, 0, 0, 0 } }, + { { 8, 13, 4, 7, 11, 4 }, { 1, 0, 3, 3, 0, 3, 3, 3, 3, 3, 3, 3, 2, 2, 3, 3 } }, + { { 9, 16, 6, 8, 13, 5 }, { 3, 0, 0, 0, 3, 0, 1, 0, 3, 0, 0, 0, 3, 0, 0, 0 } }, + { { 12, 26, 12, 1, 2, 1 }, { 3, 0, 0, 0, 3, 0, 0, 0, 3, 3, 0, 0, 2, 3, 0, 0 } }, + { { 19, 38, 18, 5, 11, 5 }, { 3, 3, 3, 3, 0, 0, 3, 3, 1, 1, 3, 3, 0, 0, 0, 3 } }, + { { 14, 30, 14, 3, 6, 3 }, { 1, 1, 0, 3, 0, 0, 0, 0, 3, 3, 0, 0, 3, 3, 0, 0 } }, + { { 14, 28, 13, 2, 4, 1 }, { 0, 0, 0, 3, 0, 0, 3, 3, 0, 0, 3, 3, 0, 0, 0, 0 } }, + { { 10, 17, 7, 3, 4, 1 }, { 3, 2, 0, 1, 3, 2, 0, 1, 3, 3, 0, 1, 3, 3, 0, 1 } }, + { { 9, 18, 8, 8, 16, 7 }, { 1, 0, 0, 1, 0, 3, 3, 0, 0, 3, 3, 3, 0, 0, 0, 0 } }, + { { 8, 16, 8, 7, 14, 7 }, { 1, 1, 1, 1, 0, 0, 0, 0, 3, 3, 0, 0, 3, 0, 0, 0 } }, + { { 14, 29, 13, 1, 1, 0 }, { 3, 0, 0, 3, 3, 0, 0, 3, 3, 3, 0, 3, 3, 0, 0, 0 } }, + { { 21, 42, 19, 15, 31, 14 }, { 3, 3, 3, 3, 3, 2, 3, 3, 3, 3, 0, 3, 3, 0, 1, 0 } }, + { { 10, 20, 9, 8, 17, 8 }, { 3, 2, 2, 2, 3, 2, 2, 3, 3, 3, 3, 3, 0, 0, 0, 0 } }, + { { 12, 22, 9, 5, 8, 3 }, { 3, 0, 0, 1, 3, 3, 0, 1, 3, 3, 3, 0, 3, 3, 3, 3 } }, + { { 14, 29, 14, 7, 15, 7 }, { 1, 1, 1, 1, 0, 0, 0, 0, 3, 3, 3, 3, 2, 2, 2, 2 } }, + { { 11, 23, 11, 8, 17, 8 }, { 0, 0, 0, 3, 0, 0, 0, 3, 0, 3, 3, 3, 0, 3, 2, 3 } }, + { { 19, 40, 19, 11, 24, 11 }, { 3, 3, 0, 1, 3, 3, 0, 1, 3, 3, 0, 0, 3, 3, 0, 0 } }, + { { 10, 19, 7, 5, 9, 3 }, { 3, 3, 0, 3, 3, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } }, + { { 9, 15, 4, 8, 13, 4 }, { 3, 0, 0, 3, 0, 1, 0, 3, 0, 1, 0, 3, 3, 0, 3, 3 } }, + { { 13, 27, 13, 6, 12, 6 }, { 0, 0, 1, 1, 3, 0, 1, 1, 3, 3, 0, 0, 2, 2, 3, 0 } }, + { { 17, 36, 17, 7, 14, 7 }, { 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 0, 0, 3, 3 } }, + { { 11, 23, 11, 10, 21, 10 }, { 3, 0, 0, 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 2, 3 } }, + { { 16, 35, 17, 4, 10, 4 }, { 3, 0, 1, 1, 3, 0, 1, 1, 3, 3, 0, 1, 3, 0, 0, 1 } }, + { { 19, 38, 18, 8, 17, 8 }, { 3, 3, 3, 3, 0, 0, 3, 3, 1, 1, 3, 3, 0, 0, 3, 3 } }, + { { 18, 38, 18, 4, 7, 3 }, { 1, 0, 3, 3, 0, 0, 3, 3, 0, 3, 2, 3, 3, 2, 2, 3 } }, + { { 13, 24, 10, 11, 20, 8 }, { 1, 1, 0, 0, 0, 0, 0, 0, 3, 3, 0, 0, 2, 2, 3, 3 } }, + { { 3, 9, 6, 2, 8, 5 }, { 1, 1, 1, 1, 1, 1, 0, 0, 1, 0, 3, 3, 0, 0, 3, 3 } }, + { { 20, 41, 19, 7, 14, 7 }, { 3, 2, 3, 3, 0, 3, 3, 3, 1, 0, 3, 3, 1, 0, 3, 3 } }, + { { 10, 20, 9, 6, 12, 5 }, { 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 0, 3, 3, 0, 1 } }, + { { 17, 36, 17, 2, 4, 2 }, { 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 3, 3, 3, 3 } }, + { { 21, 43, 20, 13, 27, 12 }, { 3, 3, 3, 3, 3, 3, 3, 3, 0, 0, 3, 3, 1, 0, 0, 3 } }, + { { 9, 19, 9, 7, 15, 7 }, { 0, 0, 0, 3, 1, 0, 3, 3, 1, 0, 3, 3, 0, 0, 3, 0 } }, + { { 17, 33, 15, 13, 24, 11 }, { 3, 3, 3, 3, 3, 2, 2, 3, 3, 2, 2, 3, 2, 2, 2, 3 } }, + { { 7, 15, 7, 8, 18, 9 }, { 3, 2, 2, 3, 3, 2, 2, 3, 3, 3, 3, 0, 3, 0, 0, 1 } }, + { { 11, 21, 9, 2, 4, 1 }, { 1, 0, 3, 3, 1, 0, 3, 3, 1, 0, 2, 3, 1, 0, 3, 3 } }, + { { 12, 25, 12, 8, 17, 8 }, { 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } }, + { { 12, 23, 10, 9, 17, 7 }, { 3, 0, 0, 1, 3, 3, 3, 0, 3, 3, 0, 0, 0, 0, 0, 1 } }, + { { 18, 37, 18, 16, 32, 16 }, { 0, 0, 0, 3, 1, 1, 0, 3, 1, 1, 0, 0, 0, 0, 0, 0 } }, + { { 27, 3, 1, 26, 1, 0 }, { 3, 2, 3, 3, 3, 2, 3, 3, 3, 3, 3, 3, 1, 0, 3, 3 } }, + { { 10, 21, 10, 7, 15, 7 }, { 3, 3, 3, 3, 3, 2, 3, 3, 3, 3, 0, 0, 0, 0, 1, 1 } }, + { { 11, 22, 11, 6, 12, 6 }, { 3, 2, 2, 3, 0, 3, 2, 3, 1, 0, 3, 3, 1, 0, 3, 3 } }, + { { 16, 31, 13, 9, 17, 7 }, { 3, 0, 1, 1, 3, 0, 0, 0, 3, 3, 3, 3, 2, 2, 2, 2 } }, + { { 3, 8, 3, 5, 11, 5 }, { 0, 0, 0, 3, 0, 0, 3, 3, 0, 3, 3, 3, 0, 0, 3, 3 } }, + { { 21, 43, 20, 9, 18, 8 }, { 2, 2, 3, 3, 2, 2, 3, 0, 2, 2, 3, 0, 2, 2, 3, 0 } }, + { { 15, 29, 12, 11, 20, 8 }, { 3, 3, 0, 1, 3, 3, 0, 0, 3, 3, 0, 0, 3, 0, 0, 0 } }, + { { 10, 21, 10, 6, 13, 6 }, { 3, 2, 2, 3, 3, 3, 3, 0, 0, 0, 0, 1, 0, 0, 0, 1 } }, + { { 10, 20, 9, 7, 13, 6 }, { 0, 3, 2, 3, 0, 3, 3, 3, 0, 0, 0, 0, 0, 0, 1, 1 } }, + { { 21, 43, 20, 5, 11, 5 }, { 3, 3, 3, 3, 3, 2, 3, 3, 3, 3, 3, 0, 0, 0, 0, 1 } }, + { { 19, 33, 31, 12, 31, 31 }, { 3, 0, 0, 0, 3, 0, 1, 0, 3, 3, 0, 0, 3, 2, 3, 3 } }, + { { 11, 20, 8, 9, 17, 7 }, { 3, 0, 1, 1, 3, 3, 0, 0, 3, 3, 3, 3, 2, 2, 3, 3 } }, + { { 10, 17, 7, 8, 13, 5 }, { 1, 0, 3, 3, 1, 0, 3, 3, 0, 0, 0, 0, 0, 0, 1, 1 } }, + { { 21, 42, 20, 3, 7, 3 }, { 0, 0, 0, 1, 0, 3, 3, 0, 3, 3, 3, 3, 3, 3, 3, 3 } }, + { { 7, 14, 2, 6, 12, 2 }, { 3, 3, 3, 3, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0 } }, + { { 19, 39, 19, 9, 20, 10 }, { 3, 2, 3, 0, 3, 3, 0, 1, 3, 3, 1, 1, 0, 0, 0, 1 } }, + { { 13, 26, 11, 5, 8, 3 }, { 3, 3, 0, 0, 3, 3, 0, 0, 3, 3, 0, 0, 3, 0, 1, 1 } }, + { { 31, 62, 30, 31, 61, 29 }, { 3, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 0, 0, 3 } }, + { { 22, 45, 21, 11, 22, 10 }, { 3, 3, 0, 0, 3, 3, 0, 1, 3, 0, 1, 1, 0, 0, 1, 1 } }, + { { 23, 48, 23, 4, 9, 4 }, { 3, 3, 0, 0, 3, 3, 3, 3, 3, 3, 3, 0, 3, 2, 3, 0 } }, + { { 15, 42, 31, 11, 22, 30 }, { 3, 0, 1, 1, 3, 0, 0, 0, 0, 0, 3, 3, 0, 0, 3, 3 } }, + { { 15, 33, 16, 8, 18, 9 }, { 3, 2, 2, 2, 0, 3, 2, 3, 0, 3, 2, 2, 0, 0, 2, 2 } }, + { { 13, 27, 13, 7, 15, 7 }, { 3, 3, 3, 3, 3, 3, 3, 3, 0, 3, 3, 3, 0, 0, 0, 0 } }, + { { 19, 35, 14, 16, 29, 12 }, { 3, 0, 0, 3, 0, 0, 1, 0, 3, 0, 0, 3, 3, 3, 3, 2 } }, + { { 1, 2, 1, 7, 13, 6 }, { 3, 0, 0, 3, 0, 0, 0, 0, 3, 3, 3, 0, 3, 2, 2, 3 } }, + { { 11, 21, 9, 8, 15, 6 }, { 1, 0, 3, 3, 1, 0, 3, 3, 0, 3, 2, 3, 3, 3, 2, 3 } }, + { { 14, 28, 12, 8, 16, 6 }, { 3, 3, 3, 3, 0, 3, 3, 3, 1, 3, 3, 3, 1, 0, 3, 3 } }, + { { 20, 41, 19, 1, 3, 1 }, { 3, 0, 0, 1, 3, 3, 0, 1, 3, 3, 3, 0, 3, 2, 2, 3 } }, + { { 14, 26, 11, 10, 18, 7 }, { 1, 0, 3, 3, 0, 0, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3 } }, + { { 11, 32, 30, 11, 31, 30 }, { 3, 0, 0, 0, 3, 0, 0, 0, 3, 3, 3, 3, 3, 3, 3, 3 } }, + { { 23, 47, 22, 7, 14, 6 }, { 3, 3, 0, 1, 3, 3, 0, 0, 3, 3, 3, 3, 0, 0, 3, 3 } }, + { { 12, 24, 12, 6, 12, 6 }, { 3, 2, 3, 3, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 3 } }, + { { 16, 29, 11, 13, 23, 9 }, { 1, 1, 1, 1, 0, 0, 0, 0, 3, 3, 3, 3, 3, 3, 3, 3 } }, + { { 11, 22, 9, 6, 11, 4 }, { 0, 0, 3, 3, 0, 0, 3, 3, 0, 1, 0, 3, 0, 0, 0, 3 } }, + { { 1, 2, 1, 3, 7, 3 }, { 3, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } }, + { { 4, 10, 4, 8, 17, 7 }, { 1, 1, 1, 1, 0, 0, 1, 1, 3, 0, 0, 1, 3, 3, 0, 0 } }, + { { 18, 33, 13, 11, 21, 8 }, { 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 3, 0, 0, 0 } }, + { { 23, 47, 22, 16, 32, 15 }, { 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } }, + { { 13, 25, 11, 8, 16, 7 }, { 0, 0, 0, 3, 0, 0, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3 } }, + { { 17, 45, 30, 15, 33, 31 }, { 3, 2, 3, 3, 3, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1, 1 } }, + { { 18, 37, 17, 1, 1, 0 }, { 3, 0, 0, 1, 3, 3, 0, 0, 3, 3, 0, 0, 2, 3, 0, 0 } }, + { { 8, 16, 7, 12, 25, 11 }, { 1, 1, 0, 3, 0, 1, 1, 0, 3, 0, 1, 1, 3, 3, 0, 1 } }, + { { 14, 27, 12, 7, 13, 5 }, { 0, 0, 0, 3, 3, 0, 0, 3, 3, 3, 3, 3, 3, 0, 0, 0 } }, + { { 10, 17, 6, 9, 15, 6 }, { 3, 0, 0, 3, 3, 0, 0, 3, 3, 0, 0, 3, 3, 0, 0, 3 } }, + { { 21, 43, 20, 18, 37, 17 }, { 3, 3, 2, 3, 0, 0, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3 } }, + { { 18, 35, 15, 8, 15, 5 }, { 1, 1, 0, 0, 0, 0, 0, 0, 3, 3, 0, 0, 3, 3, 0, 0 } }, + { { 19, 32, 30, 15, 43, 31 }, { 1, 1, 1, 1, 1, 0, 0, 0, 0, 3, 3, 3, 3, 3, 3, 3 } }, + { { 18, 15, 30, 15, 33, 31 }, { 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 0, 0, 0, 0 } }, + { { 12, 22, 9, 8, 15, 6 }, { 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 3, 0 } }, + { { 16, 22, 31, 12, 40, 31 }, { 3, 3, 3, 3, 3, 0, 0, 3, 3, 1, 0, 3, 3, 0, 0, 3 } }, + { { 17, 35, 31, 14, 14, 29 }, { 1, 1, 0, 3, 0, 0, 0, 3, 3, 0, 0, 3, 0, 0, 0, 3 } }, + { { 11, 20, 8, 8, 14, 5 }, { 3, 3, 3, 3, 3, 3, 0, 0, 3, 3, 0, 1, 3, 3, 0, 1 } }, + { { 22, 46, 21, 1, 3, 1 }, { 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 3, 3, 0, 0, 3, 3 } }, + { { 10, 18, 6, 1, 1, 0 }, { 3, 0, 0, 1, 3, 3, 0, 1, 3, 3, 3, 0, 2, 2, 2, 3 } }, + { { 1, 2, 1, 10, 21, 9 }, { 0, 0, 0, 3, 3, 3, 3, 3, 3, 3, 3, 3, 0, 0, 3, 3 } }, + { { 7, 8, 2, 5, 5, 1 }, { 1, 0, 0, 0, 3, 3, 3, 0, 3, 3, 3, 0, 0, 0, 0, 0 } }, + { { 20, 10, 31, 13, 10, 31 }, { 3, 3, 0, 3, 3, 2, 3, 0, 3, 3, 3, 0, 0, 0, 0, 0 } }, + { { 17, 33, 12, 14, 27, 9 }, { 1, 0, 0, 3, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 0 } }, + { { 24, 50, 24, 18, 37, 18 }, { 3, 3, 0, 3, 3, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3 } }, + { { 24, 49, 23, 13, 28, 12 }, { 3, 0, 0, 0, 3, 0, 0, 0, 3, 3, 3, 3, 2, 2, 2, 3 } }, + { { 18, 27, 12, 16, 22, 10 }, { 1, 1, 0, 3, 1, 0, 0, 0, 0, 0, 3, 3, 3, 3, 3, 2 } }, + { { 3, 12, 7, 4, 16, 8 }, { 1, 1, 0, 1, 0, 3, 3, 0, 3, 3, 3, 3, 3, 3, 3, 3 } }, + { { 24, 50, 24, 9, 19, 8 }, { 3, 2, 3, 0, 3, 2, 2, 3, 3, 2, 3, 3, 2, 2, 2, 3 } }, + { { 22, 41, 30, 18, 23, 30 }, { 0, 3, 2, 3, 1, 0, 3, 3, 1, 0, 3, 3, 1, 0, 3, 3 } }, + { { 16, 31, 12, 4, 8, 2 }, { 3, 2, 3, 3, 3, 3, 0, 0, 3, 0, 1, 1, 3, 0, 0, 1 } }, + { { 20, 39, 16, 11, 20, 8 }, { 3, 2, 2, 2, 3, 3, 3, 3, 0, 0, 0, 0, 1, 1, 1, 1 } }, + { { 11, 21, 7, 7, 13, 4 }, { 0, 0, 3, 3, 0, 3, 3, 3, 0, 3, 3, 3, 0, 0, 0, 3 } }, + { { 13, 25, 11, 6, 11, 4 }, { 3, 3, 3, 3, 0, 3, 3, 3, 1, 0, 0, 0, 1, 1, 1, 1 } }, + { { 18, 35, 15, 5, 9, 3 }, { 3, 0, 3, 3, 3, 3, 3, 3, 3, 3, 0, 0, 3, 3, 0, 1 } }, + { { 20, 38, 16, 13, 25, 10 }, { 1, 1, 1, 1, 1, 1, 1, 1, 3, 3, 3, 3, 2, 2, 2, 3 } }, + { { 16, 29, 13, 7, 13, 5 }, { 3, 2, 2, 3, 3, 3, 3, 3, 3, 0, 0, 0, 3, 0, 1, 1 } }, + { { 5, 9, 3, 12, 24, 10 }, { 3, 2, 3, 3, 3, 2, 3, 0, 3, 3, 3, 0, 3, 0, 0, 1 } }, + { { 13, 25, 8, 3, 6, 1 }, { 3, 0, 3, 3, 3, 1, 3, 3, 3, 1, 3, 3, 3, 0, 3, 3 } }, + { { 6, 11, 4, 16, 31, 13 }, { 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 0, 0, 1, 1 } }, + { { 25, 50, 24, 21, 43, 20 }, { 3, 0, 0, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3 } }, + { { 19, 22, 30, 16, 23, 31 }, { 3, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1 } }, + { { 22, 45, 30, 9, 15, 30 }, { 3, 0, 0, 3, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0 } }, + { { 1, 2, 1, 14, 28, 12 }, { 1, 3, 2, 3, 1, 3, 2, 3, 1, 3, 2, 3, 0, 3, 2, 3 } }, + { { 16, 22, 9, 13, 17, 7 }, { 3, 3, 3, 1, 3, 3, 3, 1, 3, 3, 3, 1, 0, 3, 0, 1 } }, + { { 11, 19, 8, 6, 9, 4 }, { 3, 3, 3, 3, 3, 0, 0, 3, 3, 0, 0, 0, 3, 0, 0, 0 } }, + { { 28, 58, 26, 15, 32, 14 }, { 1, 0, 0, 3, 1, 0, 0, 3, 1, 0, 0, 0, 0, 0, 0, 0 } }, + { { 9, 20, 10, 5, 13, 7 }, { 3, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 0, 3 } }, + { { 28, 56, 26, 4, 7, 3 }, { 1, 0, 2, 3, 0, 0, 3, 3, 3, 0, 0, 0, 0, 0, 0, 0 } }, + { { 14, 18, 6, 11, 14, 4 }, { 1, 0, 0, 3, 0, 3, 3, 3, 0, 3, 3, 3, 0, 0, 0, 3 } }, + { { 15, 9, 30, 7, 9, 30 }, { 1, 0, 0, 3, 0, 0, 3, 3, 3, 3, 3, 3, 3, 3, 0, 0 } }, + { { 30, 50, 3, 29, 46, 2 }, { 3, 0, 1, 1, 3, 0, 0, 0, 3, 0, 0, 3, 0, 0, 0, 0 } }, + { { 10, 19, 5, 11, 21, 6 }, { 0, 0, 1, 1, 0, 0, 0, 0, 3, 3, 3, 3, 3, 2, 2, 3 } }, + { { 21, 31, 30, 22, 31, 30 }, { 3, 3, 0, 0, 3, 3, 0, 1, 3, 3, 3, 0, 3, 3, 3, 3 } }, + { { 19, 27, 31, 11, 19, 30 }, { 3, 0, 0, 3, 3, 3, 3, 3, 3, 3, 3, 3, 0, 3, 3, 3 } }, + { { 26, 53, 25, 6, 13, 6 }, { 3, 2, 2, 3, 3, 2, 3, 3, 3, 3, 0, 0, 3, 0, 1, 1 } }, + { { 12, 24, 10, 7, 13, 5 }, { 3, 3, 3, 3, 3, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0 } }, + { { 9, 20, 10, 4, 10, 5 }, { 0, 0, 0, 3, 1, 1, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0 } }, + { { 19, 29, 30, 14, 55, 28 }, { 3, 2, 3, 3, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0 } }, + { { 12, 19, 8, 11, 16, 7 }, { 0, 0, 3, 3, 1, 0, 3, 3, 1, 0, 3, 3, 0, 0, 3, 3 } }, + { { 11, 30, 31, 7, 15, 29 }, { 1, 0, 3, 3, 1, 3, 3, 3, 1, 3, 3, 3, 1, 0, 3, 3 } }, + { { 25, 50, 24, 2, 4, 1 }, { 3, 3, 2, 3, 0, 0, 0, 3, 3, 3, 0, 0, 3, 2, 3, 3 } }, + { { 18, 30, 31, 10, 44, 30 }, { 0, 3, 2, 3, 0, 3, 2, 3, 0, 3, 3, 3, 0, 3, 3, 3 } }, + { { 10, 22, 11, 8, 18, 9 }, { 3, 2, 3, 0, 3, 2, 3, 3, 0, 3, 2, 3, 0, 0, 3, 3 } }, + { { 22, 18, 30, 19, 41, 30 }, { 3, 0, 0, 1, 3, 3, 0, 1, 3, 3, 3, 0, 3, 2, 3, 0 } }, + { { 17, 32, 12, 6, 11, 4 }, { 3, 2, 3, 0, 3, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3 } }, + { { 11, 25, 13, 8, 19, 10 }, { 3, 0, 0, 3, 3, 0, 0, 0, 0, 3, 3, 3, 0, 0, 3, 3 } }, + { { 18, 50, 29, 15, 10, 29 }, { 3, 0, 0, 3, 3, 3, 0, 0, 3, 3, 3, 0, 0, 3, 3, 3 } }, + { { 13, 17, 5, 9, 10, 3 }, { 3, 0, 0, 3, 3, 0, 0, 0, 3, 3, 0, 1, 3, 3, 0, 0 } }, + { { 13, 29, 15, 8, 20, 11 }, { 0, 0, 0, 0, 0, 1, 1, 0, 3, 0, 0, 0, 2, 3, 3, 3 } }, + { { 29, 57, 27, 27, 52, 25 }, { 3, 3, 2, 3, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0 } }, + { { 14, 15, 30, 9, 31, 30 }, { 3, 3, 0, 3, 3, 3, 0, 0, 3, 3, 0, 1, 3, 0, 1, 1 } }, + { { 2, 3, 1, 19, 37, 16 }, { 3, 0, 0, 3, 3, 0, 0, 3, 3, 3, 0, 0, 3, 0, 1, 1 } }, + { { 14, 51, 30, 9, 34, 30 }, { 3, 0, 0, 3, 0, 3, 3, 3, 1, 0, 3, 3, 0, 0, 3, 3 } }, + { { 18, 52, 30, 14, 22, 30 }, { 3, 3, 0, 3, 3, 3, 0, 0, 3, 3, 3, 3, 3, 3, 3, 3 } }, + { { 11, 24, 10, 6, 13, 5 }, { 1, 1, 0, 3, 1, 1, 0, 3, 1, 0, 3, 3, 0, 3, 2, 2 } }, + { { 16, 23, 10, 10, 14, 6 }, { 1, 1, 0, 3, 1, 1, 0, 3, 1, 1, 0, 3, 0, 0, 3, 3 } }, + { { 23, 49, 30, 20, 36, 30 }, { 3, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 0, 0, 1, 1 } }, + { { 26, 54, 24, 12, 24, 10 }, { 0, 1, 1, 1, 0, 1, 1, 1, 3, 0, 1, 1, 2, 3, 0, 1 } }, + { { 17, 31, 11, 1, 2, 1 }, { 3, 0, 0, 0, 3, 0, 0, 0, 3, 3, 0, 1, 2, 2, 0, 0 } }, + { { 29, 60, 29, 6, 13, 6 }, { 3, 2, 3, 3, 3, 2, 3, 3, 0, 0, 0, 0, 1, 1, 1, 1 } }, + { { 11, 24, 12, 4, 11, 6 }, { 1, 3, 2, 3, 0, 3, 2, 3, 3, 3, 3, 3, 0, 0, 0, 3 } }, + { { 19, 27, 10, 12, 15, 5 }, { 3, 0, 0, 3, 3, 0, 0, 0, 3, 3, 0, 3, 3, 3, 3, 3 } }, + { { 12, 25, 13, 10, 22, 12 }, { 1, 0, 2, 3, 0, 0, 3, 3, 3, 0, 0, 0, 3, 0, 0, 0 } }, + { { 16, 23, 30, 14, 6, 26 }, { 1, 0, 3, 3, 0, 3, 3, 3, 3, 3, 3, 3, 3, 2, 3, 3 } }, + { { 10, 12, 4, 8, 8, 2 }, { 3, 3, 3, 3, 3, 3, 0, 0, 3, 3, 0, 1, 2, 2, 3, 0 } }, + { { 10, 24, 30, 6, 45, 30 }, { 0, 0, 0, 3, 0, 0, 0, 0, 1, 0, 0, 3, 0, 0, 0, 3 } }, + { { 8, 44, 30, 6, 26, 30 }, { 1, 1, 1, 1, 0, 1, 1, 0, 3, 3, 3, 3, 3, 3, 3, 3 } }, + { { 23, 32, 30, 17, 12, 29 }, { 3, 0, 0, 0, 3, 0, 0, 1, 3, 3, 0, 1, 3, 2, 3, 1 } }, + { { 11, 20, 8, 16, 31, 14 }, { 3, 3, 0, 0, 3, 3, 3, 0, 3, 3, 3, 0, 3, 0, 0, 0 } }, + { { 13, 28, 8, 5, 11, 3 }, { 0, 0, 0, 3, 0, 0, 0, 3, 1, 1, 3, 3, 0, 0, 3, 3 } }, + { { 12, 25, 12, 7, 16, 7 }, { 0, 0, 1, 1, 0, 0, 1, 1, 3, 3, 0, 0, 3, 2, 2, 3 } }, + { { 17, 22, 7, 10, 11, 3 }, { 1, 0, 3, 3, 0, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3 } }, + { { 11, 22, 11, 7, 15, 7 }, { 3, 0, 0, 0, 3, 0, 0, 1, 3, 3, 0, 1, 3, 2, 3, 0 } }, + { { 23, 5, 30, 9, 5, 30 }, { 3, 3, 0, 3, 3, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1 } }, + { { 14, 23, 8, 1, 2, 1 }, { 3, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 3, 2, 3, 3 } }, + { { 22, 36, 15, 20, 32, 14 }, { 3, 3, 0, 1, 3, 3, 0, 1, 3, 3, 0, 1, 3, 3, 0, 1 } }, + { { 12, 26, 12, 7, 14, 7 }, { 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 3, 3, 2, 2, 2, 2 } }, + { { 12, 24, 11, 7, 14, 6 }, { 3, 3, 3, 3, 0, 1, 0, 0, 0, 1, 1, 0, 3, 3, 3, 3 } }, + { { 10, 22, 11, 6, 14, 7 }, { 3, 3, 3, 3, 0, 0, 3, 3, 1, 0, 3, 3, 3, 3, 3, 3 } }, + { { 12, 27, 13, 6, 12, 6 }, { 0, 0, 3, 3, 1, 1, 3, 3, 1, 1, 3, 3, 3, 0, 3, 3 } }, + { { 20, 38, 14, 3, 5, 2 }, { 3, 0, 0, 3, 0, 0, 0, 3, 3, 3, 0, 3, 3, 2, 3, 3 } }, + { { 15, 29, 15, 16, 36, 17 }, { 3, 3, 0, 3, 0, 0, 0, 0, 3, 3, 3, 0, 3, 2, 3, 0 } }, + { { 7, 29, 6, 8, 30, 7 }, { 3, 3, 0, 1, 3, 3, 0, 1, 3, 3, 0, 1, 2, 2, 3, 0 } }, +}; + +inline constexpr uint8_t BC2_POSITION_RANK[256][4] = { + { 1, 1, 1, 1 }, + { 3, 3, 3, 3 }, + { 2, 2, 2, 2 }, + { 0, 0, 0, 0 }, + { 3, 3, 0, 0 }, + { 0, 0, 3, 3 }, + { 3, 3, 1, 1 }, + { 0, 0, 2, 2 }, + { 2, 2, 0, 0 }, + { 1, 1, 3, 3 }, + { 1, 1, 2, 2 }, + { 2, 2, 1, 1 }, + { 3, 3, 2, 2 }, + { 1, 2, 1, 1 }, + { 1, 1, 1, 2 }, + { 2, 1, 1, 1 }, + { 1, 1, 2, 1 }, + { 1, 1, 0, 0 }, + { 2, 2, 3, 3 }, + { 0, 0, 1, 1 }, + { 3, 3, 3, 2 }, + { 3, 3, 2, 3 }, + { 3, 2, 3, 3 }, + { 2, 3, 3, 3 }, + { 1, 1, 0, 1 }, + { 1, 1, 1, 0 }, + { 1, 2, 1, 2 }, + { 1, 0, 1, 1 }, + { 3, 2, 1, 0 }, + { 0, 1, 1, 1 }, + { 3, 3, 2, 1 }, + { 2, 1, 2, 1 }, + { 1, 2, 2, 2 }, + { 0, 1, 2, 3 }, + { 2, 2, 1, 2 }, + { 2, 2, 2, 1 }, + { 1, 0, 3, 2 }, + { 2, 3, 0, 1 }, + { 2, 1, 2, 2 }, + { 3, 3, 1, 0 }, + { 3, 3, 0, 1 }, + { 1, 3, 1, 3 }, + { 3, 1, 3, 1 }, + { 3, 3, 1, 2 }, + { 1, 0, 3, 3 }, + { 1, 2, 3, 3 }, + { 2, 1, 3, 3 }, + { 0, 2, 0, 2 }, + { 0, 1, 3, 3 }, + { 2, 3, 0, 0 }, + { 0, 0, 2, 3 }, + { 3, 2, 3, 2 }, + { 0, 0, 3, 2 }, + { 1, 2, 2, 1 }, + { 3, 2, 0, 0 }, + { 0, 2, 2, 3 }, + { 3, 2, 2, 0 }, + { 0, 0, 1, 2 }, + { 2, 3, 2, 2 }, + { 1, 0, 2, 2 }, + { 2, 1, 0, 0 }, + { 2, 0, 2, 0 }, + { 1, 1, 2, 3 }, + { 2, 3, 1, 1 }, + { 2, 3, 2, 3 }, + { 2, 1, 1, 2 }, + { 1, 2, 0, 0 }, + { 1, 1, 3, 2 }, + { 3, 2, 2, 2 }, + { 3, 2, 1, 1 }, + { 0, 1, 2, 2 }, + { 2, 2, 0, 1 }, + { 2, 2, 2, 3 }, + { 2, 2, 1, 0 }, + { 0, 0, 2, 1 }, + { 2, 3, 0, 2 }, + { 2, 2, 3, 2 }, + { 0, 3, 0, 3 }, + { 2, 0, 3, 2 }, + { 3, 1, 1, 0 }, + { 0, 1, 1, 3 }, + { 0, 2, 1, 3 }, + { 3, 3, 3, 1 }, + { 3, 0, 3, 3 }, + { 1, 3, 3, 3 }, + { 3, 1, 2, 0 }, + { 3, 3, 3, 0 }, + { 3, 3, 0, 3 }, + { 1, 3, 0, 1 }, + { 3, 1, 3, 3 }, + { 0, 3, 3, 3 }, + { 3, 3, 1, 3 }, + { 1, 0, 3, 1 }, + { 0, 1, 1, 2 }, + { 1, 0, 2, 1 }, + { 3, 0, 3, 0 }, + { 2, 1, 1, 0 }, + { 1, 2, 0, 1 }, + { 0, 0, 0, 1 }, + { 1, 0, 0, 0 }, + { 0, 1, 0, 0 }, + { 3, 2, 2, 1 }, + { 1, 2, 2, 3 }, + { 3, 2, 3, 1 }, + { 1, 3, 2, 3 }, + { 2, 3, 1, 2 }, + { 2, 1, 3, 2 }, + { 1, 3, 1, 1 }, + { 0, 0, 1, 0 }, + { 1, 1, 1, 3 }, + { 2, 0, 3, 1 }, + { 1, 3, 0, 2 }, + { 3, 1, 1, 1 }, + { 3, 3, 0, 2 }, + { 3, 1, 3, 2 }, + { 0, 1, 0, 1 }, + { 1, 1, 3, 1 }, + { 2, 3, 1, 3 }, + { 3, 3, 2, 0 }, + { 1, 0, 1, 2 }, + { 1, 0, 1, 0 }, + { 2, 1, 0, 1 }, + { 0, 1, 2, 1 }, + { 2, 0, 3, 3 }, + { 1, 2, 1, 0 }, + { 0, 2, 3, 3 }, + { 0, 2, 2, 2 }, + { 2, 2, 2, 0 }, + { 0, 0, 0, 2 }, + { 2, 2, 0, 2 }, + { 0, 1, 0, 2 }, + { 1, 0, 2, 3 }, + { 2, 0, 2, 2 }, + { 2, 3, 1, 0 }, + { 2, 0, 0, 0 }, + { 1, 2, 0, 2 }, + { 0, 2, 0, 0 }, + { 3, 2, 0, 1 }, + { 0, 2, 1, 2 }, + { 0, 1, 3, 2 }, + { 2, 1, 2, 0 }, + { 3, 2, 2, 3 }, + { 0, 0, 2, 0 }, + { 2, 0, 1, 0 }, + { 2, 3, 3, 2 }, + { 1, 1, 0, 2 }, + { 3, 1, 0, 0 }, + { 2, 0, 2, 1 }, + { 2, 3, 2, 1 }, + { 3, 2, 3, 0 }, + { 1, 2, 1, 3 }, + { 1, 3, 0, 0 }, + { 0, 2, 0, 1 }, + { 1, 2, 3, 2 }, + { 3, 1, 2, 1 }, + { 1, 0, 2, 0 }, + { 0, 0, 1, 3 }, + { 2, 1, 2, 3 }, + { 1, 3, 1, 2 }, + { 0, 0, 3, 1 }, + { 2, 0, 1, 1 }, + { 3, 2, 1, 2 }, + { 0, 3, 2, 3 }, + { 2, 1, 3, 1 }, + { 1, 1, 2, 0 }, + { 0, 2, 1, 1 }, + { 3, 0, 3, 2 }, + { 2, 3, 0, 3 }, + { 0, 1, 3, 1 }, + { 3, 1, 3, 0 }, + { 1, 0, 0, 1 }, + { 1, 3, 2, 2 }, + { 0, 3, 1, 3 }, + { 1, 0, 1, 3 }, + { 0, 1, 1, 0 }, + { 3, 1, 0, 1 }, + { 1, 3, 1, 0 }, + { 0, 2, 0, 3 }, + { 2, 2, 3, 1 }, + { 3, 0, 0, 0 }, + { 2, 2, 1, 3 }, + { 1, 3, 0, 3 }, + { 0, 3, 0, 0 }, + { 3, 1, 2, 2 }, + { 0, 0, 0, 3 }, + { 3, 0, 3, 1 }, + { 3, 0, 2, 0 }, + { 0, 0, 3, 0 }, + { 2, 1, 0, 2 }, + { 2, 3, 2, 0 }, + { 2, 0, 2, 3 }, + { 2, 0, 1, 2 }, + { 0, 2, 2, 1 }, + { 3, 2, 0, 2 }, + { 0, 3, 0, 2 }, + { 0, 2, 3, 2 }, + { 1, 2, 2, 0 }, + { 0, 3, 2, 2 }, + { 3, 0, 1, 1 }, + { 1, 3, 2, 1 }, + { 1, 1, 0, 3 }, + { 2, 0, 3, 0 }, + { 2, 2, 3, 0 }, + { 0, 1, 0, 3 }, + { 3, 0, 1, 0 }, + { 1, 2, 3, 1 }, + { 3, 0, 2, 2 }, + { 2, 2, 0, 3 }, + { 3, 1, 1, 2 }, + { 0, 3, 1, 1 }, + { 2, 1, 1, 3 }, + { 1, 1, 3, 0 }, + { 0, 3, 1, 2 }, + { 0, 3, 0, 1 }, + { 2, 1, 3, 0 }, + { 1, 2, 0, 3 }, + { 1, 0, 3, 0 }, + { 3, 0, 2, 1 }, + { 1, 3, 3, 2 }, + { 2, 3, 3, 1 }, + { 0, 3, 3, 2 }, + { 3, 0, 2, 3 }, + { 2, 0, 0, 1 }, + { 1, 0, 0, 2 }, + { 3, 2, 1, 3 }, + { 3, 1, 2, 3 }, + { 3, 2, 0, 3 }, + { 1, 2, 3, 0 }, + { 2, 3, 3, 0 }, + { 0, 1, 2, 0 }, + { 0, 3, 2, 1 }, + { 0, 2, 3, 1 }, + { 1, 3, 2, 0 }, + { 2, 0, 0, 2 }, + { 0, 2, 1, 0 }, + { 2, 0, 1, 3 }, + { 3, 0, 1, 2 }, + { 2, 1, 0, 3 }, + { 3, 0, 0, 1 }, + { 3, 1, 0, 2 }, + { 1, 0, 0, 3 }, + { 0, 2, 2, 0 }, + { 1, 3, 3, 1 }, + { 0, 1, 3, 0 }, + { 3, 1, 1, 3 }, + { 0, 3, 1, 0 }, + { 0, 3, 3, 0 }, + { 3, 0, 0, 3 }, + { 3, 0, 0, 2 }, + { 2, 0, 0, 3 }, + { 1, 3, 3, 0 }, + { 0, 3, 2, 0 }, + { 0, 2, 3, 0 }, + { 0, 3, 3, 1 }, + { 3, 0, 1, 3 }, + { 3, 1, 0, 3 }, +}; + +inline constexpr Bc2State BC2_FULL_DICTIONARY[255] = { + { { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8 }, { 0, 0, 1, 0, 0, 0 }, { 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3 } }, + { { 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7 }, { 3, 15, 10, 2, 14, 10 }, { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 } }, + { { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8 }, { 12, 25, 12, 11, 22, 11 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } }, + { { 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15 }, { 16, 33, 16, 15, 31, 15 }, { 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2 } }, + { { 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7 }, { 10, 29, 31, 9, 28, 31 }, { 1, 1, 1, 1, 0, 0, 0, 0, 3, 3, 3, 3, 2, 2, 2, 2 } }, + { { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 21, 32, 5, 20, 31, 5 }, { 3, 0, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1 } }, + { { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8 }, { 6, 11, 5, 4, 9, 4 }, { 2, 2, 2, 2, 3, 3, 3, 3, 0, 0, 0, 0, 1, 1, 1, 1 } }, + { { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8 }, { 3, 5, 2, 1, 2, 1 }, { 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 3, 0, 0, 3, 3 } }, + { { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8 }, { 21, 15, 8, 20, 15, 7 }, { 1, 1, 0, 3, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 0 } }, + { { 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7 }, { 31, 63, 31, 0, 0, 0 }, { 3, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1 } }, + { { 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7 }, { 1, 2, 1, 0, 1, 0 }, { 3, 0, 1, 1, 3, 0, 1, 1, 0, 1, 1, 1, 0, 0, 1, 1 } }, + { { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8 }, { 10, 21, 10, 9, 18, 9 }, { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0 } }, + { { 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6 }, { 30, 61, 30, 29, 60, 29 }, { 1, 0, 3, 3, 0, 3, 2, 2, 3, 2, 2, 2, 2, 2, 2, 2 } }, + { { 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7 }, { 30, 49, 15, 29, 49, 15 }, { 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 3, 3, 0, 0 } }, + { { 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15 }, { 2, 63, 15, 1, 62, 15 }, { 0, 0, 0, 3, 1, 1, 0, 3, 1, 1, 0, 3, 0, 0, 3, 3 } }, + { { 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15 }, { 8, 62, 15, 6, 62, 16 }, { 3, 3, 0, 1, 2, 2, 3, 3, 2, 2, 2, 3, 2, 2, 2, 2 } }, + { { 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7 }, { 5, 10, 5, 4, 8, 4 }, { 1, 0, 3, 2, 1, 0, 3, 2, 1, 0, 3, 2, 1, 0, 3, 2 } }, + { { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 16, 31, 16, 15, 34, 16 }, { 1, 1, 0, 3, 1, 0, 3, 2, 0, 3, 2, 2, 3, 2, 2, 2 } }, + { { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8 }, { 31, 63, 31, 0, 0, 0 }, { 1, 1, 0, 3, 1, 1, 0, 3, 1, 1, 0, 3, 1, 0, 3, 2 } }, + { { 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13 }, { 21, 49, 17, 21, 48, 20 }, { 3, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 3, 0, 0, 3, 3 } }, + { { 0, 15, 15, 15, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 31, 32, 31, 31, 30, 31 }, { 3, 3, 0, 1, 3, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0 } }, + { { 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3 }, { 23, 48, 23, 22, 47, 23 }, { 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 0, 0, 0, 0, 1, 1 } }, + { { 15, 15, 0, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15 }, { 12, 62, 15, 10, 62, 15 }, { 3, 2, 2, 3, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1 } }, + { { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8 }, { 29, 18, 8, 28, 18, 8 }, { 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 0, 0, 3 } }, + { { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8 }, { 5, 8, 2, 4, 6, 2 }, { 3, 2, 2, 2, 0, 0, 0, 3, 3, 3, 3, 3, 2, 2, 2, 2 } }, + { { 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7 }, { 11, 21, 10, 9, 17, 8 }, { 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 0, 0, 0, 0 } }, + { { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8 }, { 7, 13, 6, 1, 1, 1 }, { 3, 3, 0, 0, 3, 0, 0, 3, 3, 1, 0, 3, 0, 0, 3, 3 } }, + { { 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7 }, { 16, 13, 8, 13, 10, 6 }, { 1, 1, 0, 3, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0 } }, + { { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8 }, { 18, 37, 17, 1, 2, 4 }, { 3, 2, 2, 2, 3, 2, 2, 2, 0, 3, 2, 2, 0, 0, 2, 2 } }, + { { 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7 }, { 21, 41, 20, 19, 36, 18 }, { 2, 2, 3, 3, 2, 2, 3, 0, 3, 3, 0, 1, 3, 0, 1, 1 } }, + { { 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15 }, { 18, 62, 15, 13, 62, 15 }, { 1, 1, 0, 0, 0, 0, 3, 3, 3, 3, 2, 2, 2, 2, 2, 2 } }, + { { 15, 15, 15, 0, 15, 15, 0, 0, 15, 15, 0, 0, 15, 15, 0, 0 }, { 8, 62, 15, 6, 62, 16 }, { 3, 0, 1, 1, 3, 0, 1, 1, 3, 0, 1, 1, 3, 0, 1, 1 } }, + { { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8 }, { 30, 60, 29, 1, 2, 1 }, { 1, 1, 1, 1, 1, 1, 1, 1, 0, 3, 0, 0, 0, 0, 0, 0 } }, + { { 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7 }, { 30, 55, 19, 30, 54, 18 }, { 1, 0, 3, 3, 1, 0, 3, 2, 1, 0, 3, 2, 0, 0, 3, 2 } }, + { { 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7 }, { 24, 48, 24, 22, 43, 22 }, { 1, 1, 1, 1, 1, 1, 1, 1, 0, 3, 0, 0, 0, 3, 0, 0 } }, + { { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8 }, { 15, 31, 14, 12, 24, 12 }, { 3, 3, 0, 1, 3, 3, 0, 1, 3, 3, 0, 0, 3, 0, 0, 0 } }, + { { 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12 }, { 19, 43, 17, 18, 41, 16 }, { 3, 0, 1, 1, 3, 0, 1, 1, 3, 3, 1, 1, 3, 0, 0, 0 } }, + { { 0, 0, 15, 15, 0, 0, 15, 15, 0, 0, 15, 15, 0, 0, 15, 15 }, { 8, 62, 15, 6, 62, 16 }, { 1, 1, 1, 1, 3, 3, 3, 3, 3, 2, 2, 2, 2, 2, 2, 2 } }, + { { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }, { 16, 32, 31, 15, 31, 31 }, { 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 2, 2, 2, 3 } }, + { { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8 }, { 9, 15, 4, 8, 12, 3 }, { 3, 3, 2, 3, 3, 3, 3, 3, 0, 1, 0, 3, 0, 0, 0, 0 } }, + { { 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11 }, { 17, 31, 31, 15, 31, 31 }, { 1, 1, 0, 3, 1, 1, 0, 3, 0, 1, 1, 0, 0, 0, 0, 0 } }, + { { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8 }, { 7, 20, 9, 5, 18, 9 }, { 3, 0, 0, 3, 0, 0, 0, 0, 1, 1, 1, 1, 0, 1, 1, 1 } }, + { { 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11 }, { 26, 54, 26, 25, 50, 25 }, { 0, 0, 0, 3, 0, 1, 0, 3, 0, 1, 0, 3, 0, 0, 0, 3 } }, + { { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8 }, { 2, 5, 5, 1, 2, 2 }, { 3, 3, 3, 3, 3, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1, 1 } }, + { { 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7 }, { 16, 32, 31, 15, 31, 31 }, { 2, 2, 3, 0, 2, 3, 0, 1, 3, 0, 1, 1, 0, 0, 1, 1 } }, + { { 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2 }, { 24, 43, 20, 23, 41, 19 }, { 1, 1, 1, 1, 1, 1, 1, 1, 3, 3, 3, 3, 2, 2, 2, 2 } }, + { { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8 }, { 23, 43, 20, 1, 6, 1 }, { 0, 0, 1, 1, 3, 3, 0, 0, 2, 3, 3, 3, 2, 2, 2, 2 } }, + { { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4 }, { 27, 53, 24, 26, 50, 23 }, { 3, 2, 2, 2, 3, 2, 2, 3, 0, 3, 3, 3, 1, 1, 1, 1 } }, + { { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8 }, { 21, 40, 17, 15, 30, 14 }, { 0, 0, 0, 3, 0, 0, 0, 3, 1, 1, 0, 3, 0, 0, 3, 3 } }, + { { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8 }, { 19, 39, 20, 16, 34, 17 }, { 1, 1, 1, 1, 0, 0, 1, 1, 3, 3, 1, 1, 3, 3, 0, 1 } }, + { { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8 }, { 11, 23, 11, 7, 14, 7 }, { 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 0, 1, 1 } }, + { { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8 }, { 7, 14, 7, 3, 6, 3 }, { 3, 3, 3, 3, 3, 3, 3, 3, 1, 1, 0, 0, 0, 0, 0, 3 } }, + { { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8 }, { 22, 45, 22, 15, 30, 15 }, { 3, 3, 0, 3, 2, 2, 3, 3, 3, 2, 2, 3, 2, 2, 2, 2 } }, + { { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8 }, { 19, 38, 16, 15, 32, 14 }, { 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 2, 2 } }, + { { 0, 0, 15, 15, 0, 0, 15, 15, 0, 0, 15, 15, 0, 0, 15, 15 }, { 14, 62, 15, 9, 62, 15 }, { 3, 3, 3, 3, 3, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0 } }, + { { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8 }, { 23, 41, 18, 22, 39, 18 }, { 1, 1, 1, 1, 0, 0, 0, 0, 3, 3, 3, 3, 3, 3, 3, 3 } }, + { { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8 }, { 15, 26, 12, 13, 24, 11 }, { 3, 2, 2, 2, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1 } }, + { { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8 }, { 22, 43, 18, 19, 37, 16 }, { 3, 2, 2, 3, 3, 3, 3, 3, 1, 1, 0, 3, 0, 0, 0, 3 } }, + { { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8 }, { 8, 8, 1, 1, 1, 0 }, { 3, 2, 2, 3, 3, 3, 3, 3, 0, 1, 1, 0, 0, 0, 0, 0 } }, + { { 15, 0, 0, 0, 15, 15, 0, 0, 15, 15, 15, 0, 15, 15, 15, 15 }, { 9, 62, 15, 6, 62, 15 }, { 3, 0, 0, 3, 3, 0, 0, 0, 3, 3, 3, 3, 3, 2, 2, 3 } }, + { { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8 }, { 23, 48, 24, 21, 44, 23 }, { 1, 0, 3, 3, 1, 1, 3, 3, 1, 1, 3, 3, 1, 0, 3, 3 } }, + { { 15, 15, 15, 15, 15, 15, 15, 15, 0, 0, 0, 15, 0, 0, 0, 0 }, { 10, 62, 15, 7, 62, 15 }, { 2, 2, 2, 3, 3, 3, 3, 0, 0, 0, 0, 1, 0, 1, 1, 1 } }, + { { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8 }, { 11, 21, 10, 1, 2, 1 }, { 1, 0, 0, 3, 0, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3 } }, + { { 15, 15, 0, 0, 15, 15, 0, 0, 15, 15, 0, 0, 15, 15, 0, 0 }, { 14, 62, 15, 8, 61, 15 }, { 0, 0, 3, 2, 1, 0, 3, 2, 1, 1, 0, 3, 1, 1, 0, 0 } }, + { { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8 }, { 27, 56, 27, 26, 53, 26 }, { 3, 3, 3, 3, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0 } }, + { { 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7 }, { 9, 15, 4, 5, 8, 2 }, { 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 3, 3 } }, + { { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8 }, { 4, 15, 9, 3, 14, 8 }, { 1, 1, 1, 1, 1, 0, 0, 0, 0, 3, 3, 3, 3, 3, 2, 2 } }, + { { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8 }, { 19, 34, 15, 17, 31, 14 }, { 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 3 } }, + { { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8 }, { 23, 48, 23, 1, 2, 1 }, { 3, 3, 3, 3, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 3 } }, + { { 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7 }, { 5, 10, 5, 1, 2, 1 }, { 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 1, 1, 1, 1 } }, + { { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8 }, { 19, 38, 18, 7, 14, 7 }, { 2, 2, 2, 2, 3, 3, 3, 3, 1, 1, 1, 1, 1, 1, 1, 1 } }, + { { 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7 }, { 11, 20, 8, 9, 16, 6 }, { 2, 2, 2, 2, 3, 3, 2, 2, 0, 0, 3, 3, 1, 1, 0, 0 } }, + { { 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9 }, { 2, 5, 2, 1, 3, 1 }, { 3, 3, 3, 3, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1 } }, + { { 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7 }, { 17, 34, 16, 14, 29, 14 }, { 3, 3, 3, 3, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 3 } }, + { { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8 }, { 17, 36, 17, 10, 21, 10 }, { 1, 1, 1, 1, 3, 3, 3, 3, 3, 3, 3, 3, 0, 0, 1, 1 } }, + { { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8 }, { 5, 17, 2, 4, 15, 1 }, { 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 3, 3, 3, 3 } }, + { { 13, 13, 13, 13, 13, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12 }, { 22, 46, 21, 20, 43, 19 }, { 1, 0, 0, 3, 0, 3, 3, 3, 3, 3, 3, 3, 2, 2, 3, 3 } }, + { { 6, 6, 6, 6, 6, 6, 6, 6, 5, 5, 5, 5, 5, 5, 5, 5 }, { 29, 59, 29, 27, 56, 27 }, { 3, 2, 2, 3, 3, 2, 3, 3, 3, 2, 3, 0, 2, 2, 3, 0 } }, + { { 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7 }, { 11, 22, 10, 6, 12, 6 }, { 3, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 0 } }, + { { 5, 5, 5, 5, 5, 5, 5, 5, 6, 6, 6, 5, 6, 6, 6, 6 }, { 29, 59, 29, 27, 56, 27 }, { 3, 3, 0, 1, 0, 3, 3, 0, 1, 1, 0, 0, 0, 0, 0, 0 } }, + { { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8 }, { 15, 30, 14, 1, 2, 1 }, { 1, 0, 3, 3, 1, 0, 3, 3, 1, 0, 3, 3, 1, 0, 0, 0 } }, + { { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8 }, { 11, 28, 15, 7, 21, 11 }, { 0, 0, 0, 0, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3 } }, + { { 14, 15, 0, 1, 14, 15, 0, 1, 14, 15, 0, 1, 14, 15, 0, 0 }, { 11, 62, 15, 7, 60, 15 }, { 3, 3, 3, 3, 0, 1, 1, 0, 3, 3, 3, 3, 2, 2, 2, 3 } }, + { { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8 }, { 27, 49, 22, 26, 47, 22 }, { 3, 0, 0, 1, 3, 3, 0, 1, 3, 3, 3, 0, 3, 3, 3, 3 } }, + { { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8 }, { 28, 57, 26, 2, 3, 1 }, { 3, 2, 3, 3, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0 } }, + { { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8 }, { 31, 62, 31, 26, 52, 26 }, { 3, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 1, 1 } }, + { { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8 }, { 0, 20, 13, 0, 15, 11 }, { 3, 0, 0, 1, 3, 3, 3, 3, 2, 2, 2, 3, 2, 2, 2, 2 } }, + { { 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15 }, { 25, 62, 15, 17, 62, 15 }, { 3, 0, 0, 3, 3, 0, 0, 0, 3, 3, 0, 0, 2, 2, 3, 3 } }, + { { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8 }, { 23, 46, 23, 12, 24, 12 }, { 3, 3, 0, 1, 3, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3 } }, + { { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8 }, { 24, 49, 24, 19, 38, 19 }, { 3, 3, 2, 2, 0, 0, 3, 3, 1, 1, 0, 0, 1, 1, 1, 1 } }, + { { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8 }, { 26, 53, 26, 9, 19, 9 }, { 1, 1, 1, 1, 0, 0, 1, 1, 3, 3, 0, 0, 2, 2, 3, 0 } }, + { { 0, 0, 15, 15, 0, 0, 15, 15, 0, 0, 15, 15, 0, 0, 15, 15 }, { 2, 61, 18, 0, 61, 18 }, { 2, 2, 3, 3, 3, 3, 0, 0, 3, 0, 1, 1, 0, 1, 1, 1 } }, + { { 15, 15, 0, 1, 15, 15, 0, 1, 15, 15, 0, 1, 15, 0, 0, 1 }, { 2, 62, 17, 1, 61, 15 }, { 3, 3, 3, 3, 3, 2, 2, 3, 3, 3, 3, 3, 1, 1, 1, 1 } }, + { { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8 }, { 0, 28, 16, 0, 21, 14 }, { 3, 2, 2, 3, 3, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3 } }, + { { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8 }, { 13, 26, 13, 6, 11, 5 }, { 3, 3, 0, 1, 3, 3, 3, 0, 3, 2, 3, 3, 3, 2, 2, 3 } }, + { { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8 }, { 30, 62, 30, 22, 46, 23 }, { 3, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 0, 0, 0, 0 } }, + { { 0, 0, 15, 14, 1, 0, 15, 14, 1, 0, 15, 14, 1, 0, 15, 14 }, { 11, 60, 15, 7, 60, 15 }, { 1, 1, 1, 1, 0, 0, 1, 1, 3, 0, 0, 0, 3, 0, 0, 3 } }, + { { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8 }, { 24, 43, 17, 22, 39, 16 }, { 0, 0, 3, 3, 0, 0, 3, 3, 0, 0, 3, 3, 0, 0, 0, 3 } }, + { { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8 }, { 25, 50, 23, 22, 44, 20 }, { 1, 3, 2, 3, 1, 3, 2, 3, 1, 3, 2, 3, 1, 0, 3, 3 } }, + { { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 21, 32, 14, 19, 29, 12 }, { 3, 0, 0, 3, 3, 3, 0, 0, 3, 3, 3, 3, 3, 3, 2, 2 } }, + { { 0, 0, 15, 15, 0, 0, 15, 15, 0, 0, 15, 14, 0, 0, 15, 14 }, { 2, 61, 15, 1, 61, 13 }, { 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 0, 0, 3, 3, 0, 3 } }, + { { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8 }, { 25, 47, 19, 18, 37, 15 }, { 3, 3, 0, 0, 3, 3, 0, 0, 3, 3, 0, 0, 3, 0, 0, 3 } }, + { { 4, 5, 5, 5, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5 }, { 29, 58, 28, 27, 54, 26 }, { 3, 3, 3, 3, 3, 3, 0, 1, 3, 3, 0, 1, 3, 0, 0, 0 } }, + { { 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7 }, { 9, 18, 7, 2, 4, 1 }, { 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 0, 0, 0 } }, + { { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 18, 32, 13, 17, 31, 13 }, { 3, 2, 0, 1, 3, 2, 0, 1, 3, 3, 0, 1, 3, 3, 0, 1 } }, + { { 0, 0, 0, 15, 0, 0, 15, 15, 0, 15, 15, 15, 15, 15, 15, 15 }, { 8, 61, 15, 5, 61, 15 }, { 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } }, + { { 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7 }, { 20, 33, 12, 16, 25, 9 }, { 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } }, + { { 5, 5, 5, 4, 5, 5, 4, 4, 5, 5, 4, 4, 5, 5, 4, 4 }, { 28, 56, 28, 25, 51, 25 }, { 1, 1, 1, 1, 1, 1, 1, 0, 0, 3, 3, 3, 3, 3, 3, 3 } }, + { { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 3, 60, 11, 1, 57, 8 }, { 3, 0, 1, 1, 3, 0, 0, 0, 3, 3, 0, 0, 3, 3, 0, 0 } }, + { { 15, 15, 0, 0, 15, 15, 0, 0, 15, 15, 0, 0, 15, 15, 0, 0 }, { 18, 62, 15, 15, 61, 16 }, { 1, 0, 0, 3, 0, 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2 } }, + { { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8 }, { 13, 22, 9, 8, 11, 4 }, { 3, 2, 2, 2, 3, 2, 2, 2, 0, 3, 2, 2, 1, 0, 3, 2 } }, + { { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8 }, { 2, 12, 9, 0, 2, 2 }, { 3, 2, 3, 3, 3, 2, 3, 3, 3, 3, 3, 3, 0, 0, 3, 3 } }, + { { 14, 15, 15, 0, 14, 15, 15, 0, 14, 15, 0, 0, 14, 15, 0, 0 }, { 17, 31, 31, 14, 31, 31 }, { 0, 0, 0, 0, 3, 3, 3, 3, 3, 3, 3, 3, 0, 0, 0, 0 } }, + { { 2, 2, 2, 2, 3, 3, 3, 2, 3, 3, 3, 3, 3, 3, 3, 3 }, { 24, 48, 23, 21, 43, 21 }, { 3, 2, 2, 2, 0, 3, 3, 3, 1, 0, 3, 3, 1, 0, 0, 3 } }, + { { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8 }, { 0, 13, 10, 0, 6, 8 }, { 1, 1, 1, 1, 0, 0, 1, 1, 0, 3, 3, 3, 3, 3, 2, 3 } }, + { { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8 }, { 7, 5, 9, 6, 4, 8 }, { 2, 2, 2, 2, 2, 2, 2, 3, 0, 0, 0, 0, 1, 1, 1, 1 } }, + { { 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0 }, { 2, 61, 19, 1, 60, 19 }, { 3, 3, 0, 1, 2, 3, 0, 1, 2, 2, 3, 0, 2, 2, 2, 3 } }, + { { 10, 10, 10, 11, 10, 10, 10, 11, 10, 10, 10, 11, 10, 10, 10, 11 }, { 17, 35, 17, 16, 34, 16 }, { 3, 3, 3, 3, 2, 2, 2, 3, 3, 3, 3, 3, 0, 0, 0, 3 } }, + { { 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 15, 0 }, { 2, 61, 17, 1, 61, 16 }, { 2, 3, 0, 1, 2, 3, 0, 1, 3, 0, 1, 1, 3, 0, 1, 1 } }, + { { 9, 10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9 }, { 3, 6, 3, 1, 2, 1 }, { 1, 1, 1, 0, 1, 1, 0, 3, 1, 0, 3, 2, 0, 3, 2, 2 } }, + { { 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15 }, { 27, 56, 26, 26, 53, 25 }, { 1, 1, 0, 3, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0 } }, + { { 4, 4, 4, 4, 4, 4, 4, 4, 3, 3, 3, 4, 3, 3, 3, 3 }, { 26, 53, 26, 23, 47, 23 }, { 1, 1, 0, 3, 0, 0, 0, 0, 3, 3, 0, 0, 3, 3, 0, 0 } }, + { { 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7 }, { 19, 38, 18, 13, 25, 12 }, { 3, 3, 3, 3, 3, 2, 2, 3, 3, 3, 3, 3, 0, 0, 0, 0 } }, + { { 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }, { 20, 40, 20, 18, 36, 18 }, { 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 3, 3 } }, + { { 3, 3, 3, 3, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2 }, { 24, 44, 19, 22, 40, 17 }, { 1, 1, 0, 0, 1, 1, 0, 3, 1, 0, 3, 2, 1, 0, 3, 2 } }, + { { 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7 }, { 31, 63, 0, 31, 62, 31 }, { 1, 1, 0, 0, 1, 0, 0, 3, 0, 3, 3, 3, 3, 2, 2, 2 } }, + { { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8 }, { 10, 25, 6, 10, 24, 5 }, { 3, 2, 2, 3, 2, 2, 2, 3, 3, 3, 0, 0, 0, 0, 0, 0 } }, + { { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8 }, { 23, 44, 18, 14, 30, 12 }, { 3, 0, 0, 3, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 1, 1 } }, + { { 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 10, 9, 10, 10, 10, 10 }, { 3, 7, 3, 1, 2, 1 }, { 1, 1, 1, 1, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3 } }, + { { 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7 }, { 14, 28, 12, 4, 8, 3 }, { 1, 0, 2, 3, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1 } }, + { { 1, 0, 15, 14, 2, 0, 15, 14, 2, 1, 15, 14, 1, 1, 15, 14 }, { 2, 60, 17, 1, 60, 16 }, { 0, 0, 3, 3, 0, 0, 3, 3, 0, 3, 3, 3, 3, 3, 3, 3 } }, + { { 0, 0, 15, 15, 1, 0, 15, 15, 1, 1, 0, 15, 1, 1, 0, 0 }, { 2, 61, 15, 1, 61, 13 }, { 3, 3, 3, 3, 3, 3, 0, 0, 3, 3, 0, 1, 0, 0, 0, 0 } }, + { { 15, 15, 15, 15, 15, 15, 15, 15, 0, 15, 15, 15, 15, 15, 15, 15 }, { 18, 37, 18, 14, 28, 14 }, { 1, 1, 0, 0, 0, 0, 0, 0, 3, 3, 3, 3, 2, 2, 2, 2 } }, + { { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8 }, { 29, 58, 28, 16, 33, 16 }, { 1, 1, 0, 3, 0, 1, 1, 0, 3, 3, 0, 1, 3, 3, 0, 0 } }, + { { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8 }, { 28, 49, 17, 24, 41, 14 }, { 1, 1, 0, 3, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0 } }, + { { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8 }, { 22, 38, 12, 16, 25, 7 }, { 3, 0, 0, 1, 3, 0, 0, 1, 0, 3, 3, 3, 0, 0, 3, 3 } }, + { { 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3 }, { 25, 44, 19, 22, 40, 17 }, { 2, 2, 2, 3, 2, 2, 2, 3, 2, 2, 3, 0, 2, 2, 3, 1 } }, + { { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8 }, { 21, 48, 27, 19, 43, 26 }, { 3, 3, 3, 3, 3, 3, 0, 0, 3, 0, 1, 1, 0, 0, 1, 1 } }, + { { 15, 15, 14, 13, 15, 15, 14, 13, 15, 14, 14, 13, 15, 14, 14, 13 }, { 18, 32, 31, 14, 31, 31 }, { 3, 2, 2, 3, 0, 3, 3, 3, 1, 3, 3, 3, 1, 0, 0, 3 } }, + { { 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2 }, { 24, 41, 16, 23, 39, 15 }, { 3, 3, 3, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } }, + { { 0, 0, 15, 15, 0, 0, 15, 15, 0, 0, 15, 15, 0, 0, 15, 15 }, { 19, 61, 14, 14, 60, 13 }, { 3, 3, 3, 3, 3, 3, 3, 3, 0, 0, 0, 0, 0, 0, 0, 0 } }, + { { 2, 1, 15, 14, 2, 1, 15, 13, 2, 1, 14, 13, 1, 1, 15, 14 }, { 12, 58, 14, 7, 58, 15 }, { 1, 0, 3, 2, 1, 1, 0, 3, 1, 1, 0, 0, 0, 0, 0, 0 } }, + { { 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7 }, { 17, 29, 11, 9, 14, 4 }, { 3, 3, 2, 2, 0, 3, 3, 2, 1, 0, 3, 3, 1, 0, 0, 0 } }, + { { 15, 15, 15, 0, 15, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1 }, { 2, 61, 17, 1, 60, 16 }, { 3, 3, 3, 3, 3, 3, 0, 0, 3, 3, 3, 3, 3, 3, 3, 3 } }, + { { 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0 }, { 17, 53, 15, 2, 45, 12 }, { 3, 2, 2, 3, 3, 2, 2, 3, 1, 1, 1, 1, 1, 1, 1, 1 } }, + { { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8 }, { 29, 59, 29, 7, 14, 7 }, { 3, 0, 0, 3, 3, 0, 0, 3, 3, 0, 0, 3, 0, 0, 3, 3 } }, + { { 12, 12, 12, 12, 12, 12, 12, 11, 11, 11, 11, 11, 11, 11, 11, 11 }, { 23, 46, 21, 18, 39, 18 }, { 2, 2, 2, 2, 3, 3, 3, 3, 0, 0, 0, 0, 1, 1, 0, 0 } }, + { { 0, 0, 1, 1, 15, 0, 0, 1, 14, 15, 0, 0, 14, 14, 15, 0 }, { 15, 59, 14, 8, 58, 15 }, { 3, 2, 2, 2, 0, 0, 0, 0, 1, 1, 1, 0, 3, 3, 3, 3 } }, + { { 15, 15, 0, 1, 15, 15, 0, 1, 15, 15, 0, 1, 15, 0, 0, 1 }, { 31, 62, 16, 28, 57, 16 }, { 3, 0, 0, 3, 3, 0, 3, 3, 0, 1, 3, 2, 0, 0, 3, 3 } }, + { { 12, 12, 11, 11, 12, 12, 11, 11, 12, 12, 11, 11, 12, 12, 11, 11 }, { 21, 43, 20, 18, 38, 18 }, { 3, 3, 0, 0, 3, 3, 0, 0, 2, 3, 0, 1, 2, 3, 0, 1 } }, + { { 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 13, 12, 12, 13, 13 }, { 22, 46, 21, 19, 41, 18 }, { 3, 3, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3 } }, + { { 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7 }, { 25, 50, 25, 18, 36, 18 }, { 1, 0, 2, 3, 1, 3, 3, 3, 0, 3, 3, 3, 3, 3, 3, 0 } }, + { { 0, 0, 0, 15, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 17, 56, 11, 5, 53, 7 }, { 3, 3, 0, 1, 3, 3, 3, 0, 3, 3, 3, 3, 3, 3, 3, 3 } }, + { { 0, 15, 14, 14, 0, 0, 15, 15, 0, 0, 0, 15, 0, 1, 0, 0 }, { 16, 59, 14, 7, 58, 14 }, { 3, 3, 3, 3, 0, 0, 3, 3, 1, 1, 0, 3, 0, 0, 0, 3 } }, + { { 11, 11, 11, 11, 11, 11, 12, 11, 11, 11, 11, 11, 11, 11, 11, 11 }, { 16, 32, 21, 15, 31, 20 }, { 3, 0, 0, 1, 3, 3, 3, 3, 3, 3, 3, 0, 0, 0, 1, 1 } }, + { { 15, 14, 15, 15, 15, 15, 15, 0, 15, 0, 0, 1, 0, 0, 1, 1 }, { 16, 59, 15, 9, 58, 15 }, { 3, 0, 1, 1, 3, 0, 0, 1, 3, 3, 0, 1, 2, 2, 3, 1 } }, + { { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8 }, { 29, 57, 26, 20, 39, 16 }, { 3, 0, 0, 3, 3, 0, 0, 0, 3, 3, 3, 3, 2, 2, 2, 2 } }, + { { 1, 1, 0, 15, 1, 1, 15, 14, 1, 0, 15, 14, 0, 15, 14, 14 }, { 15, 58, 15, 7, 58, 14 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 3, 3 } }, + { { 0, 1, 0, 0, 0, 0, 0, 15, 15, 15, 15, 15, 15, 15, 14, 15 }, { 18, 58, 15, 8, 58, 13 }, { 3, 0, 1, 1, 3, 3, 0, 0, 3, 3, 3, 3, 3, 3, 2, 3 } }, + { { 13, 13, 13, 13, 12, 13, 13, 13, 12, 12, 12, 12, 11, 11, 11, 12 }, { 17, 32, 31, 14, 33, 30 }, { 3, 2, 2, 2, 3, 3, 3, 3, 1, 1, 1, 1, 0, 0, 0, 0 } }, + { { 3, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4 }, { 27, 55, 27, 23, 46, 23 }, { 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 3, 3, 3, 3, 3, 3 } }, + { { 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 15 }, { 31, 62, 14, 27, 57, 9 }, { 3, 2, 2, 3, 0, 3, 3, 3, 1, 1, 3, 2, 0, 0, 3, 3 } }, + { { 1, 1, 1, 0, 1, 1, 0, 0, 1, 0, 15, 15, 1, 0, 15, 14 }, { 2, 60, 17, 1, 60, 18 }, { 1, 0, 3, 3, 1, 0, 0, 3, 1, 1, 0, 0, 1, 1, 1, 1 } }, + { { 3, 3, 4, 4, 2, 3, 4, 4, 2, 3, 4, 4, 2, 3, 3, 4 }, { 27, 54, 26, 23, 46, 22 }, { 0, 0, 1, 1, 0, 0, 0, 0, 3, 3, 3, 3, 3, 3, 3, 3 } }, + { { 15, 15, 15, 15, 15, 15, 15, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 17, 33, 16, 15, 31, 15 }, { 0, 0, 1, 1, 3, 3, 0, 0, 3, 3, 3, 3, 2, 2, 3, 3 } }, + { { 9, 9, 9, 9, 9, 9, 9, 9, 10, 9, 9, 9, 10, 9, 9, 9 }, { 3, 5, 3, 1, 1, 1 }, { 3, 3, 3, 3, 3, 3, 3, 3, 0, 3, 3, 3, 0, 0, 3, 3 } }, + { { 9, 9, 9, 10, 9, 9, 9, 10, 9, 9, 10, 10, 9, 9, 10, 10 }, { 4, 8, 4, 1, 2, 1 }, { 1, 1, 0, 3, 3, 3, 3, 3, 3, 3, 3, 0, 0, 0, 0, 1 } }, + { { 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0 }, { 21, 34, 15, 19, 30, 13 }, { 3, 0, 0, 3, 3, 3, 3, 3, 0, 3, 3, 3, 1, 0, 3, 0 } }, + { { 14, 14, 0, 1, 14, 14, 0, 1, 14, 15, 1, 2, 15, 0, 1, 2 }, { 16, 59, 15, 9, 57, 15 }, { 3, 0, 0, 3, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0 } }, + { { 3, 2, 2, 1, 3, 3, 2, 2, 3, 3, 2, 2, 3, 3, 3, 2 }, { 25, 50, 24, 21, 42, 20 }, { 0, 0, 3, 3, 0, 3, 3, 3, 0, 3, 3, 0, 0, 3, 0, 1 } }, + { { 14, 15, 0, 2, 13, 15, 1, 2, 13, 14, 1, 2, 14, 15, 0, 2 }, { 3, 60, 16, 2, 58, 17 }, { 1, 1, 1, 1, 0, 0, 0, 1, 3, 3, 3, 0, 2, 2, 2, 3 } }, + { { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8 }, { 0, 24, 15, 0, 10, 9 }, { 2, 2, 3, 3, 2, 2, 3, 0, 2, 3, 0, 1, 2, 3, 0, 1 } }, + { { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8 }, { 16, 25, 8, 3, 4, 1 }, { 0, 0, 1, 1, 3, 0, 1, 1, 2, 3, 0, 0, 2, 2, 3, 0 } }, + { { 0, 0, 0, 0, 15, 0, 0, 0, 15, 0, 0, 1, 15, 0, 0, 0 }, { 18, 35, 17, 16, 33, 16 }, { 1, 1, 0, 0, 1, 0, 0, 3, 0, 0, 3, 2, 3, 3, 2, 2 } }, + { { 14, 15, 1, 2, 14, 14, 1, 2, 13, 14, 1, 2, 13, 14, 0, 1 }, { 16, 59, 15, 8, 56, 15 }, { 1, 0, 3, 3, 0, 0, 3, 3, 0, 3, 3, 3, 0, 0, 0, 3 } }, + { { 14, 15, 0, 1, 14, 15, 0, 1, 14, 14, 0, 1, 14, 14, 15, 0 }, { 21, 54, 16, 4, 51, 16 }, { 1, 1, 0, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3 } }, + { { 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15 }, { 10, 60, 16, 9, 57, 22 }, { 2, 2, 2, 2, 2, 2, 2, 3, 2, 2, 3, 0, 3, 3, 0, 1 } }, + { { 15, 0, 1, 1, 15, 0, 1, 1, 14, 15, 0, 1, 14, 14, 15, 1 }, { 2, 61, 17, 1, 60, 16 }, { 1, 1, 0, 3, 1, 1, 0, 0, 0, 3, 0, 3, 3, 3, 3, 3 } }, + { { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8 }, { 16, 27, 9, 13, 21, 7 }, { 3, 3, 3, 3, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 3, 3 } }, + { { 2, 1, 14, 12, 3, 1, 14, 12, 3, 2, 14, 12, 3, 2, 14, 13 }, { 10, 57, 16, 5, 57, 16 }, { 0, 0, 0, 0, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 2, 3 } }, + { { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8 }, { 1, 35, 19, 0, 30, 17 }, { 0, 3, 2, 2, 3, 2, 2, 2, 3, 2, 2, 3, 2, 2, 2, 3 } }, + { { 15, 15, 15, 0, 15, 15, 0, 0, 15, 0, 0, 1, 15, 0, 1, 1 }, { 25, 58, 12, 11, 54, 10 }, { 1, 1, 0, 0, 1, 1, 0, 0, 3, 3, 0, 0, 2, 2, 3, 3 } }, + { { 10, 11, 11, 12, 10, 10, 11, 11, 10, 10, 10, 11, 9, 10, 10, 10 }, { 8, 16, 8, 2, 5, 3 }, { 3, 3, 3, 0, 3, 3, 0, 0, 3, 3, 0, 0, 2, 3, 0, 0 } }, + { { 0, 0, 1, 1, 15, 0, 0, 1, 15, 15, 0, 0, 14, 15, 15, 0 }, { 26, 59, 13, 13, 54, 11 }, { 0, 0, 0, 0, 1, 1, 1, 0, 3, 3, 3, 3, 2, 2, 2, 2 } }, + { { 13, 13, 14, 13, 12, 12, 13, 12, 12, 11, 11, 12, 11, 11, 11, 11 }, { 13, 26, 13, 5, 10, 5 }, { 3, 0, 0, 0, 3, 0, 0, 0, 3, 3, 0, 1, 3, 0, 0, 1 } }, + { { 1, 1, 0, 0, 1, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0 }, { 19, 39, 19, 15, 30, 15 }, { 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 1, 0, 0, 0 } }, + { { 9, 9, 9, 9, 9, 9, 9, 9, 11, 10, 9, 9, 13, 11, 10, 10 }, { 21, 42, 18, 14, 33, 15 }, { 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 0, 3, 3, 0, 1 } }, + { { 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7 }, { 15, 23, 3, 7, 11, 1 }, { 1, 1, 0, 3, 1, 0, 0, 3, 0, 0, 3, 3, 0, 0, 0, 3 } }, + { { 11, 11, 12, 12, 11, 11, 11, 12, 11, 11, 12, 13, 11, 11, 12, 12 }, { 23, 47, 22, 18, 40, 19 }, { 0, 0, 0, 0, 3, 3, 3, 3, 3, 3, 3, 3, 0, 0, 1, 1 } }, + { { 15, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2 }, { 21, 42, 21, 15, 30, 15 }, { 3, 3, 3, 3, 3, 3, 0, 0, 3, 3, 0, 0, 0, 0, 0, 1 } }, + { { 10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 12, 12, 12, 12 }, { 9, 18, 9, 3, 6, 3 }, { 3, 0, 0, 3, 3, 0, 0, 1, 3, 3, 3, 0, 3, 3, 3, 3 } }, + { { 0, 1, 2, 3, 1, 1, 2, 3, 2, 2, 3, 4, 3, 3, 4, 4 }, { 26, 54, 26, 22, 44, 22 }, { 0, 0, 1, 1, 3, 0, 0, 1, 3, 3, 3, 0, 2, 2, 2, 3 } }, + { { 12, 11, 11, 11, 12, 12, 12, 12, 14, 14, 14, 14, 15, 15, 15, 15 }, { 15, 30, 15, 6, 12, 6 }, { 3, 3, 0, 1, 3, 3, 0, 0, 3, 0, 0, 3, 3, 0, 0, 3 } }, + { { 0, 0, 0, 15, 15, 15, 15, 14, 13, 13, 13, 13, 13, 12, 12, 12 }, { 18, 36, 18, 8, 18, 9 }, { 3, 0, 0, 1, 3, 3, 3, 3, 3, 3, 3, 3, 0, 0, 0, 0 } }, + { { 12, 12, 11, 11, 11, 11, 11, 11, 11, 10, 10, 10, 10, 10, 10, 10 }, { 9, 18, 9, 3, 7, 3 }, { 3, 3, 0, 3, 3, 3, 0, 3, 3, 3, 0, 3, 3, 3, 3, 3 } }, + { { 0, 0, 0, 0, 15, 15, 15, 15, 15, 15, 15, 15, 14, 14, 14, 14 }, { 17, 33, 16, 12, 25, 12 }, { 1, 1, 1, 1, 3, 3, 3, 3, 3, 3, 3, 3, 0, 0, 0, 0 } }, + { { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 15, 15 }, { 21, 32, 4, 21, 30, 4 }, { 3, 3, 3, 3, 3, 3, 3, 0, 3, 3, 0, 1, 3, 3, 0, 0 } }, + { { 3, 3, 2, 2, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1, 0, 0 }, { 23, 47, 23, 17, 34, 17 }, { 3, 0, 0, 1, 3, 3, 0, 1, 2, 2, 3, 0, 2, 2, 3, 0 } }, + { { 2, 3, 3, 3, 2, 2, 3, 3, 1, 1, 2, 2, 0, 0, 1, 1 }, { 24, 49, 24, 18, 37, 18 }, { 3, 3, 3, 3, 3, 3, 3, 0, 3, 3, 3, 0, 3, 3, 3, 0 } }, + { { 14, 13, 13, 13, 14, 14, 14, 14, 15, 14, 14, 14, 15, 15, 15, 15 }, { 15, 30, 15, 10, 20, 10 }, { 3, 3, 2, 3, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 1 } }, + { { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8 }, { 17, 38, 23, 9, 25, 17 }, { 0, 0, 1, 1, 0, 0, 0, 0, 3, 3, 3, 3, 2, 2, 2, 2 } }, + { { 0, 15, 14, 14, 0, 15, 14, 14, 0, 0, 15, 14, 0, 0, 15, 15 }, { 18, 53, 17, 3, 53, 17 }, { 1, 1, 0, 3, 0, 0, 1, 0, 3, 3, 0, 1, 3, 3, 3, 0 } }, + { { 10, 10, 11, 13, 9, 10, 11, 11, 9, 9, 10, 10, 9, 9, 9, 10 }, { 23, 45, 18, 14, 34, 15 }, { 3, 3, 2, 3, 0, 0, 3, 3, 0, 0, 0, 0, 0, 0, 1, 1 } }, + { { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8 }, { 28, 54, 23, 13, 23, 8 }, { 3, 2, 3, 3, 3, 3, 3, 0, 3, 3, 0, 0, 0, 0, 0, 0 } }, + { { 14, 15, 0, 1, 14, 15, 0, 2, 14, 15, 0, 2, 14, 15, 0, 1 }, { 25, 60, 15, 15, 57, 14 }, { 3, 3, 3, 3, 3, 3, 3, 3, 0, 1, 1, 0, 0, 0, 0, 0 } }, + { { 3, 2, 1, 0, 4, 3, 1, 0, 4, 3, 2, 1, 4, 4, 3, 2 }, { 26, 54, 26, 22, 45, 23 }, { 3, 3, 3, 3, 3, 3, 3, 3, 0, 0, 0, 0, 1, 1, 1, 1 } }, + { { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 3, 53, 23, 1, 55, 23 }, { 1, 1, 1, 1, 2, 2, 2, 3, 2, 2, 2, 2, 2, 2, 2, 2 } }, + { { 11, 10, 10, 10, 11, 11, 10, 10, 12, 11, 10, 10, 12, 11, 11, 10 }, { 9, 18, 9, 3, 6, 3 }, { 3, 3, 3, 0, 2, 3, 0, 0, 3, 0, 1, 0, 3, 0, 0, 0 } }, + { { 2, 2, 2, 3, 2, 2, 3, 3, 2, 2, 3, 3, 2, 2, 3, 3 }, { 25, 50, 24, 18, 39, 19 }, { 3, 0, 0, 3, 0, 0, 0, 3, 0, 3, 3, 3, 3, 3, 2, 2 } }, + { { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8 }, { 1, 18, 17, 0, 2, 2 }, { 1, 1, 1, 1, 0, 3, 3, 0, 1, 1, 0, 1, 1, 1, 1, 1 } }, + { { 11, 11, 11, 11, 11, 11, 11, 10, 11, 11, 10, 10, 11, 11, 10, 10 }, { 8, 15, 8, 3, 7, 3 }, { 1, 0, 2, 3, 1, 0, 3, 0, 0, 3, 0, 0, 3, 0, 0, 1 } }, + { { 13, 13, 12, 12, 13, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12 }, { 5, 0, 0, 3, 0, 0 }, { 1, 1, 0, 3, 3, 3, 3, 3, 3, 3, 3, 3, 0, 0, 0, 3 } }, + { { 12, 12, 12, 12, 13, 13, 12, 12, 14, 14, 14, 14, 14, 14, 14, 14 }, { 17, 27, 30, 14, 26, 30 }, { 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 3, 3, 3, 3 } }, + { { 10, 10, 10, 11, 10, 10, 11, 11, 10, 11, 11, 12, 11, 11, 12, 13 }, { 10, 20, 10, 3, 7, 4 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 3 } }, + { { 0, 0, 15, 15, 0, 15, 15, 15, 15, 15, 14, 14, 15, 14, 14, 14 }, { 15, 54, 19, 6, 55, 19 }, { 3, 3, 0, 3, 3, 0, 0, 3, 3, 3, 3, 3, 3, 3, 3, 3 } }, + { { 10, 11, 12, 12, 10, 11, 12, 12, 10, 11, 12, 12, 10, 11, 12, 12 }, { 9, 32, 30, 4, 30, 28 }, { 3, 2, 3, 0, 3, 2, 3, 0, 3, 3, 0, 0, 3, 3, 0, 0 } }, + { { 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7 }, { 24, 48, 23, 12, 24, 11 }, { 1, 0, 3, 3, 0, 0, 3, 3, 3, 3, 3, 3, 3, 2, 3, 3 } }, + { { 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11 }, { 7, 14, 7, 4, 8, 4 }, { 3, 0, 3, 3, 0, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3 } }, + { { 4, 4, 3, 2, 4, 4, 2, 2, 4, 3, 2, 1, 3, 3, 2, 1 }, { 27, 54, 26, 22, 45, 22 }, { 3, 3, 0, 1, 3, 2, 3, 0, 3, 3, 3, 3, 0, 0, 0, 0 } }, + { { 13, 12, 12, 11, 13, 12, 11, 11, 12, 11, 11, 10, 12, 11, 11, 11 }, { 11, 23, 11, 4, 9, 5 }, { 3, 2, 3, 1, 3, 2, 3, 1, 2, 2, 3, 1, 2, 2, 3, 0 } }, + { { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8 }, { 19, 43, 26, 3, 6, 3 }, { 3, 0, 0, 3, 0, 0, 3, 3, 1, 0, 3, 3, 1, 0, 3, 3 } }, + { { 7, 3, 13, 8, 7, 3, 12, 8, 7, 3, 11, 8, 7, 3, 12, 8 }, { 14, 31, 11, 2, 8, 3 }, { 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 0, 0, 3, 0, 1, 1 } }, + { { 1, 15, 14, 14, 2, 0, 14, 14, 2, 1, 15, 14, 2, 1, 0, 15 }, { 13, 57, 14, 6, 56, 14 }, { 3, 3, 2, 3, 3, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3 } }, + { { 12, 14, 1, 3, 12, 13, 1, 3, 12, 13, 2, 3, 13, 14, 1, 3 }, { 13, 59, 15, 8, 53, 15 }, { 3, 3, 0, 1, 3, 3, 0, 0, 3, 3, 3, 3, 0, 0, 0, 3 } }, + { { 11, 11, 10, 10, 12, 11, 10, 10, 14, 13, 11, 10, 0, 13, 12, 11 }, { 16, 32, 14, 5, 12, 6 }, { 3, 2, 2, 2, 3, 3, 3, 3, 3, 0, 0, 0, 3, 3, 0, 3 } }, + { { 3, 3, 3, 3, 2, 2, 2, 2, 1, 0, 1, 0, 0, 15, 15, 15 }, { 26, 53, 27, 22, 45, 23 }, { 3, 3, 2, 2, 3, 3, 3, 2, 0, 3, 3, 3, 0, 0, 0, 0 } }, + { { 14, 14, 13, 13, 14, 14, 14, 14, 0, 15, 15, 15, 0, 0, 15, 15 }, { 18, 37, 18, 9, 17, 9 }, { 3, 0, 0, 3, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3 } }, + { { 0, 14, 14, 14, 0, 15, 15, 14, 1, 1, 0, 15, 2, 2, 1, 0 }, { 3, 59, 17, 2, 58, 17 }, { 3, 3, 0, 0, 3, 3, 0, 1, 3, 3, 0, 0, 0, 0, 0, 0 } }, + { { 8, 11, 1, 7, 8, 12, 1, 7, 8, 13, 2, 7, 8, 13, 3, 7 }, { 14, 29, 10, 1, 4, 2 }, { 3, 3, 0, 3, 3, 0, 0, 3, 3, 0, 0, 3, 3, 0, 0, 3 } }, + { { 15, 15, 0, 0, 14, 14, 15, 15, 12, 12, 13, 13, 11, 11, 12, 12 }, { 19, 38, 18, 7, 16, 8 }, { 0, 3, 2, 2, 0, 3, 2, 2, 1, 0, 3, 2, 1, 0, 3, 2 } }, + { { 14, 14, 15, 0, 14, 15, 0, 1, 15, 0, 1, 2, 0, 1, 2, 2 }, { 2, 60, 17, 1, 58, 17 }, { 0, 0, 0, 3, 0, 0, 0, 0, 3, 3, 0, 0, 3, 3, 0, 0 } }, + { { 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7 }, { 18, 37, 17, 3, 6, 3 }, { 3, 0, 0, 3, 0, 0, 3, 3, 0, 3, 3, 3, 3, 2, 2, 3 } }, + { { 11, 11, 11, 12, 12, 12, 12, 13, 13, 13, 14, 14, 13, 14, 15, 15 }, { 16, 31, 15, 5, 11, 6 }, { 3, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 3, 0, 1, 1 } }, + { { 14, 13, 12, 12, 15, 14, 12, 12, 15, 14, 13, 12, 14, 14, 13, 12 }, { 16, 33, 16, 6, 13, 6 }, { 0, 3, 2, 2, 1, 0, 3, 2, 1, 0, 3, 3, 1, 0, 0, 3 } }, + { { 0, 15, 15, 0, 1, 1, 1, 1, 3, 3, 3, 3, 3, 3, 4, 4 }, { 27, 54, 27, 22, 45, 22 }, { 1, 1, 0, 3, 0, 0, 0, 0, 3, 3, 3, 3, 3, 3, 3, 3 } }, + { { 15, 0, 1, 2, 14, 15, 0, 2, 13, 13, 15, 0, 12, 12, 14, 15 }, { 23, 49, 23, 19, 40, 20 }, { 3, 0, 0, 3, 0, 0, 3, 3, 1, 3, 3, 3, 0, 3, 3, 0 } }, + { { 0, 1, 2, 3, 15, 0, 3, 3, 15, 1, 3, 3, 0, 1, 2, 3 }, { 26, 54, 26, 22, 46, 23 }, { 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 3 } }, + { { 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15 }, { 21, 49, 22, 3, 50, 20 }, { 3, 0, 3, 3, 0, 0, 3, 3, 0, 3, 3, 3, 3, 2, 3, 3 } }, + { { 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 12, 11, 11 }, { 7, 15, 7, 5, 10, 5 }, { 3, 0, 0, 3, 3, 0, 0, 3, 3, 3, 3, 3, 3, 3, 3, 3 } }, + { { 14, 14, 15, 0, 14, 14, 15, 0, 14, 15, 15, 0, 15, 15, 0, 0 }, { 21, 52, 20, 4, 51, 19 }, { 3, 3, 3, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1 } }, + { { 13, 12, 11, 11, 14, 13, 12, 12, 0, 15, 14, 13, 2, 2, 0, 15 }, { 23, 47, 22, 18, 37, 18 }, { 0, 0, 0, 0, 0, 3, 3, 3, 0, 0, 0, 0, 0, 0, 0, 0 } }, + { { 14, 15, 15, 0, 14, 14, 15, 15, 13, 14, 15, 15, 13, 14, 14, 15 }, { 17, 34, 17, 9, 19, 10 }, { 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 0, 1, 3, 3, 0, 1 } }, + { { 0, 13, 12, 12, 14, 13, 12, 11, 13, 12, 11, 11, 12, 12, 11, 11 }, { 17, 34, 16, 5, 11, 5 }, { 3, 3, 3, 3, 0, 3, 3, 3, 0, 3, 2, 3, 0, 3, 2, 3 } }, + { { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8 }, { 29, 56, 21, 5, 7, 1 }, { 3, 0, 0, 3, 3, 0, 0, 0, 3, 3, 0, 1, 2, 2, 0, 1 } }, + { { 9, 9, 9, 9, 9, 9, 9, 9, 9, 10, 10, 11, 10, 11, 12, 13 }, { 21, 42, 19, 15, 33, 15 }, { 3, 2, 2, 2, 0, 0, 0, 0, 3, 3, 0, 3, 3, 3, 3, 3 } }, + { { 11, 12, 13, 15, 10, 11, 12, 13, 10, 10, 12, 12, 10, 10, 11, 11 }, { 13, 26, 12, 4, 8, 4 }, { 0, 0, 0, 3, 0, 0, 3, 3, 3, 3, 3, 3, 2, 2, 2, 3 } }, + { { 7, 7, 7, 6, 2, 2, 1, 0, 15, 14, 13, 12, 9, 9, 8, 8 }, { 20, 41, 18, 5, 11, 6 }, { 0, 3, 3, 3, 0, 3, 3, 0, 0, 3, 3, 0, 3, 3, 0, 0 } }, + { { 11, 11, 13, 14, 11, 12, 14, 15, 12, 13, 15, 1, 13, 14, 0, 2 }, { 23, 47, 22, 17, 37, 18 }, { 1, 0, 2, 3, 0, 3, 3, 3, 3, 3, 3, 0, 3, 0, 0, 0 } }, + { { 12, 12, 12, 11, 14, 15, 14, 14, 1, 1, 1, 0, 2, 3, 3, 2 }, { 18, 37, 17, 5, 12, 7 }, { 3, 2, 3, 3, 2, 2, 3, 0, 3, 3, 3, 0, 3, 3, 0, 1 } }, + { { 10, 10, 11, 12, 10, 10, 12, 13, 10, 11, 13, 14, 11, 12, 13, 1 }, { 17, 36, 16, 5, 9, 5 }, { 1, 0, 0, 1, 0, 3, 3, 0, 0, 3, 3, 3, 0, 0, 0, 0 } }, + { { 0, 15, 14, 13, 1, 0, 14, 13, 1, 0, 14, 13, 1, 0, 14, 13 }, { 14, 50, 19, 4, 50, 19 }, { 3, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 2, 3, 0 } }, + { { 5, 5, 3, 0, 4, 3, 1, 15, 0, 15, 13, 11, 14, 12, 9, 9 }, { 16, 33, 14, 7, 17, 9 }, { 3, 3, 3, 3, 3, 3, 3, 3, 0, 3, 3, 3, 1, 0, 3, 3 } }, + { { 2, 15, 12, 11, 13, 12, 11, 11, 11, 11, 10, 10, 11, 10, 10, 10 }, { 19, 40, 18, 13, 29, 14 }, { 3, 3, 3, 3, 0, 3, 3, 3, 0, 3, 3, 3, 0, 3, 3, 3 } }, + { { 9, 8, 8, 8, 13, 12, 11, 11, 0, 0, 15, 15, 6, 7, 6, 6 }, { 16, 33, 14, 7, 17, 9 }, { 3, 0, 0, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3 } }, + { { 3, 3, 2, 2, 3, 2, 2, 2, 3, 2, 2, 2, 3, 3, 2, 2 }, { 15, 31, 15, 14, 30, 15 }, { 0, 0, 0, 3, 0, 1, 0, 0, 3, 3, 3, 3, 0, 0, 0, 0 } }, +}; + +inline constexpr Bc6State BC6_DICTIONARY[255] = { + { { { 32768, 33088, 32768 }, { 32768, 32768, 32768 }, { 32768, 32768, 32768 }, { 32768, 32768, 32768 } }, { 32768, 32768, 32768, 32768, 32768, 32768, 32768, 32768, 32768, 32768, 32768, 32768, 32768, 32768, 32768, 32768 } }, + { { { 62592, 62592, 59520 }, { 32768, 32768, 32768 }, { 32768, 32768, 32768 }, { 32768, 32768, 32768 } }, { 32768, 24576, 32768, 24576, 24576, 24576, 24576, 24576, 32768, 24576, 32768, 24576, 24576, 24576, 24576, 24576 } }, + { { { 32768, 33536, 62336 }, { 32768, 32768, 32768 }, { 32768, 32768, 32768 }, { 32768, 32768, 32768 } }, { 32768, 24576, 32768, 24576, 32768, 24576, 32768, 24576, 32768, 24576, 32768, 24576, 32768, 24576, 32768, 24576 } }, + { { { 62144, 32768, 32768 }, { 32768, 32768, 32768 }, { 32768, 32768, 32768 }, { 32768, 32768, 32768 } }, { 32768, 32768, 32768, 32768, 32768, 32768, 32768, 32768, 32768, 32768, 32768, 32768, 32768, 32768, 32768, 32768 } }, + { { { 32768, 32768, 32768 }, { 32768, 32768, 63488 }, { 32768, 32768, 32768 }, { 32768, 32768, 63488 } }, { 32768, 0, 24576, 57344, 40960, 8192, 16384, 49152, 49152, 16384, 8192, 40960, 57344, 24576, 0, 32768 } }, + { { { 58176, 58176, 57856 }, { 34816, 36864, 36864 }, { 32768, 32768, 32768 }, { 32768, 32768, 32768 } }, { 32768, 16384, 16384, 40960, 32768, 16384, 16384, 40960, 32768, 16384, 16384, 40960, 40960, 16384, 16384, 40960 } }, + { { { 53760, 52992, 52480 }, { 37888, 43008, 45056 }, { 39936, 47104, 45056 }, { 38912, 43008, 43008 } }, { 40960, 32768, 32768, 24576, 40960, 32768, 32768, 24576, 40960, 32768, 32768, 24576, 40960, 32768, 32768, 24576 } }, + { { { 64128, 64128, 64256 }, { 32768, 32768, 32768 }, { 32768, 32768, 32768 }, { 32768, 32768, 32768 } }, { 49152, 24576, 8192, 32768, 49152, 16384, 8192, 40960, 40960, 8192, 16384, 49152, 32768, 8192, 24576, 49152 } }, + { { { 52864, 54688, 52000 }, { 34816, 36864, 36864 }, { 34816, 36864, 36864 }, { 32768, 36864, 36864 } }, { 32768, 32768, 32768, 32768, 24576, 24576, 24576, 24576, 32768, 32768, 32768, 32768, 24576, 24576, 24576, 24576 } }, + { { { 52608, 54272, 51840 }, { 34816, 40960, 36864 }, { 36864, 36864, 36864 }, { 34816, 36864, 36864 } }, { 32768, 49152, 0, 16384, 40960, 57344, 8192, 24576, 24576, 8192, 57344, 40960, 16384, 0, 49152, 32768 } }, + { { { 63904, 63936, 63968 }, { 34816, 36864, 36864 }, { 34816, 36864, 36864 }, { 32768, 32768, 36864 } }, { 32768, 40960, 24576, 16384, 49152, 57344, 8192, 0, 0, 8192, 57344, 49152, 16384, 24576, 40960, 32768 } }, + { { { 48768, 49024, 51456 }, { 32768, 32768, 32768 }, { 32768, 32768, 32768 }, { 32768, 32768, 32768 } }, { 32768, 16384, 57344, 24576, 32768, 16384, 57344, 24576, 32768, 16384, 57344, 24576, 32768, 16384, 57344, 24576 } }, + { { { 57344, 57344, 55296 }, { 26624, 26624, 25600 }, { 22528, 22528, 21504 }, { 25600, 25600, 25600 } }, { 40960, 32768, 16384, 24576, 57344, 49152, 0, 8192, 8192, 0, 49152, 57344, 24576, 16384, 32768, 40960 } }, + { { { 55936, 55936, 54272 }, { 20480, 22528, 20480 }, { 12288, 16384, 16384 }, { 18432, 20480, 20480 } }, { 32768, 0, 24576, 57344, 40960, 8192, 16384, 49152, 49152, 16384, 8192, 40960, 57344, 24576, 0, 32768 } }, + { { { 51712, 51200, 53248 }, { 38912, 45056, 45056 }, { 36864, 40960, 38912 }, { 37888, 43008, 43008 } }, { 32768, 0, 32768, 24576, 32768, 0, 32768, 24576, 32768, 0, 32768, 24576, 32768, 0, 32768, 24576 } }, + { { { 53600, 54240, 53152 }, { 34816, 36864, 36864 }, { 34816, 36864, 36864 }, { 34816, 36864, 36864 } }, { 32768, 57344, 16384, 16384, 57344, 8192, 16384, 8192, 8192, 16384, 8192, 49152, 16384, 8192, 57344, 32768 } }, + { { { 57088, 56704, 55552 }, { 20480, 20480, 20480 }, { 14336, 16384, 16384 }, { 18432, 20480, 20480 } }, { 32768, 40960, 49152, 57344, 57344, 8192, 16384, 24576, 24576, 16384, 8192, 0, 57344, 49152, 40960, 32768 } }, + { { { 56576, 56320, 54784 }, { 26624, 20480, 20480 }, { 23552, 14336, 16384 }, { 26624, 18432, 20480 } }, { 32768, 49152, 8192, 16384, 57344, 8192, 16384, 8192, 16384, 16384, 0, 49152, 16384, 0, 49152, 32768 } }, + { { { 56064, 56064, 54528 }, { 26624, 20480, 18432 }, { 24576, 14336, 16384 }, { 26624, 18432, 20480 } }, { 57344, 57344, 0, 8192, 57344, 57344, 0, 0, 0, 0, 57344, 57344, 0, 0, 57344, 57344 } }, + { { { 57280, 58944, 55168 }, { 24576, 24576, 24576 }, { 18432, 16384, 12288 }, { 22528, 20480, 20480 } }, { 32768, 16384, 16384, 40960, 40960, 16384, 16384, 40960, 40960, 16384, 16384, 40960, 40960, 16384, 16384, 40960 } }, + { { { 56576, 56448, 55424 }, { 45056, 45056, 43008 }, { 49152, 49152, 47104 }, { 43008, 43008, 43008 } }, { 32768, 40960, 40960, 40960, 16384, 16384, 16384, 16384, 16384, 16384, 16384, 16384, 40960, 40960, 40960, 40960 } }, + { { { 55552, 57024, 55296 }, { 40960, 38912, 40960 }, { 45056, 43008, 43008 }, { 40960, 38912, 40960 } }, { 32768, 40960, 40960, 57344, 40960, 49152, 57344, 0, 49152, 0, 8192, 16384, 8192, 16384, 16384, 24576 } }, + { { { 60032, 61056, 59136 }, { 22528, 22528, 20480 }, { 18432, 18432, 14336 }, { 20480, 24576, 20480 } }, { 40960, 57344, 8192, 24576, 32768, 49152, 0, 16384, 16384, 0, 49152, 32768, 24576, 8192, 57344, 40960 } }, + { { { 59520, 59840, 59008 }, { 18432, 18432, 18432 }, { 22528, 22528, 22528 }, { 14336, 20480, 20480 } }, { 49152, 0, 49152, 16384, 40960, 0, 49152, 16384, 40960, 0, 49152, 16384, 40960, 0, 49152, 16384 } }, + { { { 54912, 54656, 53504 }, { 49152, 47104, 49152 }, { 14336, 22528, 24576 }, { 47104, 43008, 43008 } }, { 32768, 40960, 40960, 40960, 16384, 16384, 16384, 16384, 16384, 16384, 16384, 16384, 40960, 40960, 40960, 40960 } }, + { { { 60800, 60992, 62656 }, { 45056, 45056, 36864 }, { 40960, 40960, 34816 }, { 38912, 38912, 34816 } }, { 49152, 49152, 40960, 40960, 16384, 16384, 8192, 8192, 8192, 8192, 16384, 16384, 40960, 40960, 40960, 49152 } }, + { { { 63936, 64320, 64640 }, { 38912, 57344, 53248 }, { 38912, 61440, 49152 }, { 36864, 61440, 57344 } }, { 49152, 0, 8192, 16384, 40960, 40960, 49152, 57344, 57344, 49152, 40960, 40960, 16384, 8192, 0, 49152 } }, + { { { 56064, 55808, 55040 }, { 16384, 16384, 16384 }, { 18432, 20480, 22528 }, { 40960, 40960, 36864 } }, { 32768, 40960, 49152, 0, 0, 8192, 16384, 24576, 16384, 16384, 8192, 0, 0, 49152, 40960, 40960 } }, + { { { 56320, 55808, 54272 }, { 24576, 24576, 22528 }, { 26624, 25600, 24576 }, { 24576, 23552, 21504 } }, { 32768, 49152, 0, 16384, 49152, 0, 16384, 16384, 0, 16384, 16384, 0, 16384, 16384, 0, 32768 } }, + { { { 54912, 53952, 51584 }, { 24576, 22528, 24576 }, { 18432, 16384, 20480 }, { 20480, 22528, 24576 } }, { 49152, 40960, 16384, 16384, 0, 57344, 0, 8192, 8192, 0, 49152, 57344, 16384, 16384, 40960, 40960 } }, + { { { 54976, 51200, 50112 }, { 20480, 22528, 22528 }, { 20480, 16384, 18432 }, { 22528, 22528, 22528 } }, { 32768, 40960, 40960, 49152, 40960, 49152, 57344, 8192, 49152, 0, 8192, 16384, 8192, 16384, 16384, 16384 } }, + { { { 54016, 54016, 51968 }, { 38912, 49152, 53248 }, { 27648, 22528, 8192 }, { 36864, 45056, 51200 } }, { 32768, 49152, 0, 16384, 49152, 0, 16384, 16384, 8192, 16384, 16384, 0, 16384, 16384, 57344, 32768 } }, + { { { 52992, 53248, 51456 }, { 25600, 14336, 14336 }, { 26624, 16384, 16384 }, { 35840, 38912, 51200 } }, { 57344, 57344, 49152, 40960, 0, 57344, 57344, 49152, 0, 57344, 57344, 49152, 0, 57344, 57344, 57344 } }, + { { { 59456, 60480, 57152 }, { 38912, 36864, 36864 }, { 40960, 40960, 45056 }, { 38912, 36864, 40960 } }, { 49152, 0, 8192, 16384, 40960, 57344, 8192, 16384, 16384, 0, 49152, 40960, 16384, 8192, 57344, 40960 } }, + { { { 61824, 62080, 60992 }, { 34816, 34816, 24576 }, { 34816, 34816, 18432 }, { 34816, 32768, 24576 } }, { 57344, 40960, 49152, 16384, 0, 40960, 49152, 8192, 8192, 49152, 40960, 57344, 16384, 57344, 40960, 49152 } }, + { { { 55552, 54528, 53760 }, { 27648, 14336, 10240 }, { 37888, 51200, 53248 }, { 36864, 45056, 51200 } }, { 40960, 49152, 0, 24576, 49152, 40960, 49152, 8192, 8192, 49152, 40960, 49152, 24576, 0, 49152, 40960 } }, + { { { 54528, 54528, 53632 }, { 16384, 16384, 14336 }, { 16384, 20480, 20480 }, { 14336, 20480, 18432 } }, { 40960, 49152, 8192, 24576, 49152, 32768, 49152, 8192, 8192, 49152, 32768, 49152, 24576, 8192, 49152, 40960 } }, + { { { 55040, 55040, 53504 }, { 25600, 14336, 14336 }, { 36864, 40960, 43008 }, { 27648, 16384, 16384 } }, { 32768, 8192, 16384, 0, 49152, 16384, 16384, 57344, 8192, 16384, 8192, 40960, 16384, 16384, 0, 32768 } }, + { { { 54272, 54272, 52480 }, { 25600, 14336, 16384 }, { 26624, 18432, 20480 }, { 25600, 14336, 18432 } }, { 32768, 49152, 0, 16384, 40960, 57344, 8192, 16384, 49152, 0, 16384, 57344, 57344, 8192, 16384, 40960 } }, + { { { 62272, 32768, 61440 }, { 32768, 32768, 34816 }, { 32768, 32768, 38912 }, { 32768, 32768, 36864 } }, { 57344, 8192, 16384, 16384, 40960, 49152, 0, 8192, 40960, 40960, 49152, 0, 16384, 57344, 40960, 40960 } }, + { { { 52736, 51712, 51200 }, { 37888, 38912, 37888 }, { 44032, 46080, 44032 }, { 38912, 39936, 38912 } }, { 57344, 16384, 57344, 40960, 57344, 8192, 57344, 40960, 49152, 0, 0, 40960, 40960, 0, 8192, 49152 } }, + { { { 59232, 59296, 55744 }, { 36864, 40960, 40960 }, { 36864, 45056, 40960 }, { 34816, 40960, 40960 } }, { 57344, 49152, 32768, 32768, 57344, 57344, 32768, 32768, 57344, 57344, 32768, 32768, 0, 57344, 40960, 32768 } }, + { { { 56704, 57536, 55488 }, { 22528, 20480, 16384 }, { 26624, 24576, 20480 }, { 26624, 24576, 24576 } }, { 32768, 40960, 49152, 57344, 49152, 57344, 8192, 16384, 8192, 16384, 16384, 16384, 16384, 16384, 57344, 40960 } }, + { { { 59552, 32800, 32800 }, { 59392, 32768, 32768 }, { 59392, 32768, 32768 }, { 57344, 32768, 32768 } }, { 32768, 0, 16384, 16384, 8192, 16384, 16384, 8192, 16384, 8192, 57344, 49152, 57344, 49152, 40960, 40960 } }, + { { { 57600, 57856, 56448 }, { 40960, 40960, 43008 }, { 43008, 43008, 45056 }, { 40960, 40960, 43008 } }, { 57344, 49152, 40960, 40960, 8192, 0, 57344, 57344, 16384, 16384, 8192, 8192, 16384, 8192, 49152, 40960 } }, + { { { 40960, 38912, 36864 }, { 38912, 36864, 37888 }, { 38912, 35840, 34816 }, { 38912, 36864, 35840 } }, { 57344, 16384, 49152, 16384, 49152, 8192, 49152, 8192, 40960, 8192, 40960, 0, 40960, 0, 40960, 49152 } }, + { { { 57856, 57856, 56320 }, { 18432, 17408, 15360 }, { 16384, 14336, 13312 }, { 19456, 18432, 16384 } }, { 32768, 49152, 8192, 16384, 40960, 49152, 0, 16384, 40960, 57344, 0, 16384, 40960, 8192, 8192, 16384 } }, + { { { 41984, 37888, 36864 }, { 39936, 35840, 35840 }, { 39936, 35840, 34816 }, { 40960, 36864, 36864 } }, { 32768, 16384, 16384, 16384, 49152, 0, 8192, 8192, 8192, 49152, 49152, 49152, 16384, 40960, 40960, 40960 } }, + { { { 57600, 57344, 55552 }, { 18432, 16384, 17408 }, { 18432, 18432, 17408 }, { 18432, 18432, 17408 } }, { 32768, 16384, 49152, 40960, 0, 16384, 49152, 40960, 16384, 16384, 49152, 40960, 16384, 8192, 49152, 40960 } }, + { { { 47104, 46080, 41984 }, { 51200, 50176, 45056 }, { 54272, 52224, 50176 }, { 52224, 50176, 44032 } }, { 32768, 40960, 0, 16384, 40960, 49152, 8192, 16384, 40960, 0, 16384, 8192, 57344, 8192, 16384, 40960 } }, + { { { 62144, 62592, 63488 }, { 45056, 43008, 43008 }, { 43008, 43008, 43008 }, { 38912, 38912, 38912 } }, { 32768, 8192, 16384, 8192, 16384, 16384, 8192, 57344, 16384, 0, 49152, 40960, 0, 57344, 40960, 40960 } }, + { { { 49664, 49664, 48128 }, { 23552, 23552, 22528 }, { 23552, 24576, 23552 }, { 43008, 38912, 39936 } }, { 32768, 57344, 16384, 16384, 16384, 16384, 8192, 8192, 49152, 49152, 49152, 49152, 40960, 40960, 40960, 40960 } }, + { { { 59008, 58752, 58240 }, { 18432, 20480, 18432 }, { 45056, 38912, 38912 }, { 18432, 22528, 22528 } }, { 32768, 40960, 40960, 40960, 49152, 57344, 57344, 57344, 16384, 16384, 16384, 16384, 16384, 8192, 49152, 40960 } }, + { { { 49664, 46592, 47104 }, { 37888, 36864, 36864 }, { 38912, 38912, 37888 }, { 36864, 35840, 34816 } }, { 32768, 40960, 40960, 57344, 40960, 49152, 0, 8192, 57344, 0, 16384, 16384, 16384, 16384, 0, 40960 } }, + { { { 47104, 45056, 46592 }, { 39936, 38912, 37888 }, { 36864, 35840, 34816 }, { 38912, 37888, 37888 } }, { 32768, 32768, 32768, 40960, 16384, 16384, 16384, 16384, 40960, 40960, 40960, 40960, 16384, 16384, 24576, 24576 } }, + { { { 58112, 57536, 56768 }, { 47104, 45056, 47104 }, { 18432, 20480, 16384 }, { 18432, 20480, 18432 } }, { 32768, 49152, 57344, 8192, 16384, 49152, 0, 16384, 16384, 0, 57344, 16384, 8192, 0, 49152, 40960 } }, + { { { 59392, 59712, 59776 }, { 16384, 18432, 12288 }, { 16384, 20480, 20480 }, { 14336, 26624, 36864 } }, { 57344, 40960, 57344, 16384, 8192, 49152, 49152, 16384, 16384, 49152, 40960, 0, 16384, 57344, 40960, 49152 } }, + { { { 544, 1408, 2112 }, { 20480, 16384, 16384 }, { 22528, 16384, 12288 }, { 22528, 16384, 16384 } }, { 32768, 16384, 8192, 57344, 0, 16384, 0, 49152, 16384, 8192, 57344, 40960, 16384, 0, 49152, 32768 } }, + { { { 32768, 32768, 58752 }, { 34816, 32768, 53248 }, { 34816, 32768, 53248 }, { 34816, 32768, 49152 } }, { 57344, 40960, 0, 16384, 16384, 8192, 8192, 16384, 57344, 57344, 57344, 0, 49152, 40960, 40960, 40960 } }, + { { { 58304, 58176, 60416 }, { 47104, 43008, 43008 }, { 47104, 43008, 43008 }, { 49152, 36864, 28672 } }, { 57344, 57344, 57344, 57344, 57344, 57344, 57344, 57344, 49152, 57344, 57344, 57344, 49152, 57344, 57344, 57344 } }, + { { { 53760, 53760, 40448 }, { 19456, 22528, 32768 }, { 17408, 16384, 34816 }, { 18432, 20480, 34816 } }, { 57344, 0, 16384, 16384, 40960, 40960, 49152, 49152, 0, 8192, 16384, 16384, 40960, 40960, 49152, 49152 } }, + { { { 53504, 53760, 51712 }, { 38912, 53248, 55296 }, { 36864, 49152, 51200 }, { 28672, 22528, 20480 } }, { 57344, 8192, 16384, 8192, 49152, 57344, 16384, 0, 40960, 57344, 8192, 49152, 40960, 57344, 16384, 40960 } }, + { { { 58304, 57536, 56768 }, { 18432, 18432, 16384 }, { 22528, 20480, 20480 }, { 38912, 38912, 38912 } }, { 32768, 8192, 57344, 40960, 49152, 16384, 57344, 40960, 8192, 16384, 0, 40960, 16384, 16384, 8192, 49152 } }, + { { { 51200, 50176, 51200 }, { 57344, 57344, 57344 }, { 57344, 59392, 58368 }, { 57344, 58368, 57344 } }, { 32768, 16384, 32768, 24576, 32768, 16384, 32768, 24576, 32768, 16384, 32768, 24576, 32768, 16384, 40960, 24576 } }, + { { { 53728, 50624, 50240 }, { 20480, 12288, 16384 }, { 20480, 12288, 12288 }, { 22528, 16384, 16384 } }, { 32768, 49152, 0, 16384, 16384, 8192, 57344, 49152, 16384, 8192, 57344, 40960, 8192, 8192, 57344, 40960 } }, + { { { 53888, 53760, 52864 }, { 16384, 18432, 14336 }, { 43008, 40960, 43008 }, { 16384, 20480, 16384 } }, { 57344, 49152, 49152, 40960, 16384, 16384, 8192, 0, 57344, 49152, 49152, 40960, 16384, 8192, 0, 49152 } }, + { { { 60928, 60928, 61312 }, { 47104, 49152, 45056 }, { 43008, 43008, 40960 }, { 40960, 43008, 40960 } }, { 40960, 40960, 40960, 40960, 49152, 49152, 57344, 49152, 16384, 16384, 16384, 16384, 16384, 0, 49152, 40960 } }, + { { { 49920, 50176, 48640 }, { 39936, 51200, 53248 }, { 35840, 57344, 24576 }, { 39936, 47104, 47104 } }, { 57344, 16384, 57344, 49152, 8192, 16384, 57344, 49152, 16384, 16384, 57344, 40960, 8192, 8192, 49152, 40960 } }, + { { { 59584, 60384, 61888 }, { 4096, 8192, 10240 }, { 4096, 8192, 16384 }, { 0, 4096, 6144 } }, { 57344, 32768, 57344, 40960, 0, 40960, 0, 40960, 8192, 40960, 8192, 49152, 16384, 49152, 16384, 49152 } }, + { { { 49664, 48128, 46592 }, { 38912, 39936, 39936 }, { 35840, 36864, 35840 }, { 40960, 43008, 45056 } }, { 32768, 32768, 32768, 57344, 32768, 32768, 32768, 57344, 32768, 32768, 32768, 0, 32768, 32768, 32768, 8192 } }, + { { { 59136, 60000, 61760 }, { 57344, 53248, 55296 }, { 61440, 57344, 55296 }, { 61440, 53248, 45056 } }, { 32768, 40960, 40960, 16384, 40960, 49152, 0, 16384, 40960, 49152, 8192, 16384, 40960, 49152, 8192, 16384 } }, + { { { 59584, 60160, 60416 }, { 14336, 20480, 12288 }, { 10240, 26624, 36864 }, { 16384, 20480, 20480 } }, { 49152, 0, 8192, 16384, 40960, 49152, 0, 8192, 40960, 49152, 57344, 8192, 40960, 40960, 40960, 49152 } }, + { { { 57472, 56960, 56192 }, { 47104, 45056, 43008 }, { 14336, 18432, 22528 }, { 16384, 18432, 20480 } }, { 32768, 40960, 40960, 40960, 0, 0, 0, 40960, 16384, 16384, 8192, 49152, 16384, 16384, 16384, 49152 } }, + { { { 58048, 57984, 57280 }, { 47104, 45056, 47104 }, { 16384, 22528, 22528 }, { 47104, 43008, 43008 } }, { 49152, 49152, 40960, 40960, 16384, 16384, 8192, 0, 57344, 0, 16384, 16384, 40960, 40960, 49152, 49152 } }, + { { { 32768, 59392, 32768 }, { 34816, 0, 32768 }, { 34816, 0, 32768 }, { 34816, 0, 32768 } }, { 32768, 8192, 16384, 8192, 40960, 8192, 16384, 8192, 40960, 8192, 16384, 8192, 40960, 0, 8192, 40960 } }, + { { { 55552, 55200, 53120 }, { 28672, 8192, 8192 }, { 34816, 36864, 40960 }, { 34816, 36864, 40960 } }, { 32768, 49152, 8192, 16384, 40960, 57344, 8192, 16384, 40960, 57344, 8192, 8192, 40960, 40960, 49152, 40960 } }, + { { { 54912, 54528, 53632 }, { 49152, 49152, 49152 }, { 45056, 43008, 40960 }, { 22528, 22528, 22528 } }, { 32768, 57344, 8192, 16384, 8192, 16384, 16384, 16384, 16384, 8192, 16384, 8192, 40960, 40960, 40960, 40960 } }, + { { { 56576, 56064, 54528 }, { 37888, 47104, 49152 }, { 26624, 12288, 10240 }, { 26624, 18432, 16384 } }, { 57344, 49152, 40960, 49152, 8192, 8192, 8192, 8192, 16384, 8192, 8192, 8192, 0, 57344, 40960, 40960 } }, + { { { 58848, 59712, 62208 }, { 49152, 0, 8192 }, { 53248, 63488, 4096 }, { 53248, 2048, 24576 } }, { 49152, 40960, 40960, 40960, 8192, 57344, 49152, 40960, 16384, 8192, 57344, 40960, 16384, 16384, 8192, 49152 } }, + { { { 44544, 38912, 41728 }, { 59392, 47104, 47104 }, { 57344, 34816, 30720 }, { 57344, 45056, 47104 } }, { 32768, 49152, 16384, 16384, 40960, 49152, 8192, 16384, 49152, 49152, 0, 8192, 16384, 0, 49152, 49152 } }, + { { { 54080, 53952, 52352 }, { 36864, 36864, 36864 }, { 38912, 38912, 38912 }, { 36864, 36864, 36864 } }, { 57344, 49152, 57344, 0, 49152, 49152, 8192, 8192, 49152, 57344, 16384, 16384, 16384, 8192, 57344, 40960 } }, + { { { 52096, 51712, 50688 }, { 49152, 49152, 49152 }, { 55296, 53248, 53248 }, { 47104, 49152, 47104 } }, { 32768, 49152, 0, 16384, 40960, 49152, 0, 16384, 49152, 49152, 57344, 8192, 24576, 57344, 40960, 40960 } }, + { { { 55424, 55424, 54912 }, { 12288, 16384, 16384 }, { 51200, 36864, 30720 }, { 14336, 18432, 16384 } }, { 32768, 49152, 4096, 20480, 36864, 53248, 8192, 20480, 40960, 57344, 12288, 24576, 45056, 61440, 12288, 24576 } }, + { { { 57344, 57344, 56320 }, { 37888, 37888, 39936 }, { 20480, 21504, 21504 }, { 22528, 24576, 22528 } }, { 32768, 49152, 8192, 16384, 40960, 49152, 49152, 57344, 16384, 16384, 16384, 8192, 49152, 49152, 49152, 40960 } }, + { { { 49152, 49152, 48128 }, { 45056, 45056, 46080 }, { 27648, 27648, 26624 }, { 38912, 39936, 38912 } }, { 40960, 57344, 8192, 16384, 16384, 40960, 57344, 8192, 49152, 16384, 40960, 57344, 32768, 57344, 16384, 49152 } }, + { { { 54656, 53632, 52128 }, { 40960, 45056, 45056 }, { 38912, 40960, 45056 }, { 26624, 12288, 28672 } }, { 57344, 8192, 49152, 57344, 49152, 0, 8192, 0, 40960, 49152, 8192, 16384, 40960, 49152, 0, 16384 } }, + { { { 55936, 55488, 54208 }, { 47104, 47104, 47104 }, { 55296, 55296, 55296 }, { 43008, 43008, 43008 } }, { 32768, 49152, 16384, 16384, 40960, 57344, 16384, 0, 40960, 57344, 16384, 49152, 40960, 49152, 16384, 40960 } }, + { { { 1664, 2528, 3264 }, { 43008, 45056, 45056 }, { 40960, 40960, 45056 }, { 38912, 40960, 40960 } }, { 57344, 8192, 16384, 57344, 40960, 8192, 8192, 49152, 49152, 8192, 57344, 40960, 16384, 8192, 57344, 40960 } }, + { { { 51200, 53248, 53248 }, { 52224, 54272, 53248 }, { 33792, 33792, 33792 }, { 39936, 40960, 40960 } }, { 57344, 40960, 40960, 16384, 8192, 57344, 40960, 49152, 16384, 8192, 57344, 40960, 16384, 16384, 8192, 49152 } }, + { { { 58944, 60352, 61248 }, { 47104, 45056, 43008 }, { 47104, 36864, 26624 }, { 47104, 43008, 47104 } }, { 40960, 40960, 40960, 49152, 8192, 16384, 16384, 16384, 16384, 8192, 57344, 40960, 16384, 8192, 57344, 40960 } }, + { { { 63712, 64704, 256 }, { 59392, 61440, 61440 }, { 20480, 4096, 4096 }, { 40960, 49152, 49152 } }, { 49152, 40960, 49152, 8192, 40960, 49152, 57344, 16384, 40960, 0, 8192, 16384, 49152, 0, 8192, 16384 } }, + { { { 54432, 55072, 52512 }, { 34816, 45056, 24576 }, { 34816, 40960, 16384 }, { 34816, 40960, 4096 } }, { 57344, 49152, 40960, 40960, 8192, 0, 57344, 49152, 49152, 8192, 8192, 0, 40960, 0, 16384, 16384 } }, + { { { 56320, 56000, 55104 }, { 47104, 47104, 47104 }, { 43008, 43008, 43008 }, { 24576, 22528, 24576 } }, { 57344, 0, 16384, 8192, 57344, 49152, 8192, 0, 40960, 49152, 49152, 40960, 49152, 16384, 57344, 40960 } }, + { { { 59872, 59776, 59072 }, { 24576, 4096, 61440 }, { 24576, 8192, 61440 }, { 26624, 4096, 57344 } }, { 32768, 40960, 0, 16384, 8192, 8192, 16384, 16384, 49152, 57344, 57344, 0, 40960, 40960, 40960, 49152 } }, + { { { 36352, 24576, 1024 }, { 10240, 6144, 5120 }, { 53248, 57344, 59392 }, { 10240, 7168, 6144 } }, { 32768, 0, 57344, 16384, 49152, 16384, 49152, 8192, 57344, 16384, 40960, 57344, 57344, 16384, 40960, 40960 } }, + { { { 59328, 59776, 59776 }, { 49152, 40960, 47104 }, { 45056, 43008, 47104 }, { 6144, 28672, 36864 } }, { 57344, 49152, 40960, 40960, 40960, 0, 57344, 57344, 49152, 0, 8192, 8192, 8192, 8192, 8192, 16384 } }, + { { { 55168, 55296, 54912 }, { 8192, 10240, 14336 }, { 14336, 18432, 16384 }, { 49152, 36864, 28672 } }, { 57344, 49152, 40960, 49152, 8192, 57344, 57344, 16384, 16384, 0, 0, 8192, 49152, 40960, 49152, 49152 } }, + { { { 57536, 57024, 56256 }, { 49152, 45056, 49152 }, { 47104, 43008, 45056 }, { 22528, 22528, 22528 } }, { 40960, 16384, 49152, 32768, 57344, 40960, 16384, 57344, 8192, 57344, 40960, 16384, 16384, 8192, 0, 49152 } }, + { { { 59840, 60352, 61248 }, { 8192, 18432, 16384 }, { 53248, 36864, 24576 }, { 14336, 22528, 16384 } }, { 32768, 40960, 16384, 57344, 57344, 0, 57344, 49152, 16384, 8192, 49152, 40960, 16384, 16384, 49152, 40960 } }, + { { { 55296, 55296, 53760 }, { 12288, 16384, 12288 }, { 12288, 16384, 16384 }, { 18432, 26624, 34816 } }, { 49152, 40960, 16384, 49152, 0, 49152, 16384, 49152, 8192, 49152, 8192, 40960, 8192, 49152, 8192, 40960 } }, + { { { 47360, 46464, 46336 }, { 51200, 51200, 53248 }, { 45056, 45056, 45056 }, { 47104, 47104, 47104 } }, { 32768, 40960, 40960, 40960, 49152, 49152, 40960, 32768, 16384, 8192, 49152, 40960, 24576, 16384, 57344, 40960 } }, + { { { 58176, 57984, 57792 }, { 16384, 18432, 14336 }, { 53248, 38912, 38912 }, { 18432, 20480, 20480 } }, { 57344, 8192, 8192, 0, 40960, 49152, 57344, 0, 16384, 16384, 8192, 0, 8192, 0, 49152, 40960 } }, + { { { 55136, 54464, 52416 }, { 36864, 40960, 40960 }, { 34816, 40960, 40960 }, { 30720, 49152, 32768 } }, { 32768, 16384, 16384, 16384, 49152, 49152, 0, 0, 8192, 0, 57344, 49152, 16384, 16384, 16384, 40960 } }, + { { { 54784, 54784, 53632 }, { 14336, 18432, 14336 }, { 12288, 28672, 34816 }, { 14336, 16384, 18432 } }, { 32768, 16384, 49152, 40960, 49152, 57344, 8192, 49152, 0, 0, 8192, 16384, 8192, 8192, 8192, 16384 } }, + { { { 59456, 59904, 60288 }, { 51200, 40960, 49152 }, { 10240, 28672, 36864 }, { 45056, 43008, 45056 } }, { 49152, 16384, 57344, 40960, 0, 8192, 8192, 8192, 57344, 8192, 8192, 8192, 49152, 57344, 49152, 40960 } }, + { { { 57216, 57088, 56512 }, { 47104, 47104, 49152 }, { 16384, 24576, 24576 }, { 43008, 43008, 43008 } }, { 32768, 49152, 40960, 49152, 49152, 8192, 8192, 8192, 49152, 0, 16384, 16384, 49152, 57344, 8192, 16384 } }, + { { { 56320, 55680, 55040 }, { 16384, 20480, 14336 }, { 45056, 40960, 45056 }, { 45056, 43008, 49152 } }, { 32768, 57344, 24576, 49152, 32768, 57344, 16384, 40960, 40960, 0, 8192, 40960, 40960, 8192, 8192, 32768 } }, + { { { 62368, 64160, 64032 }, { 32768, 0, 30720 }, { 36864, 45056, 22528 }, { 32768, 57344, 28672 } }, { 32768, 49152, 16384, 16384, 40960, 49152, 16384, 0, 40960, 49152, 16384, 49152, 40960, 49152, 16384, 40960 } }, + { { { 63104, 62816, 63296 }, { 18432, 16384, 40960 }, { 16384, 24576, 36864 }, { 20480, 12288, 36864 } }, { 57344, 8192, 16384, 16384, 49152, 0, 8192, 16384, 40960, 57344, 0, 8192, 40960, 40960, 49152, 40960 } }, + { { { 56512, 56448, 55360 }, { 16384, 20480, 18432 }, { 40960, 38912, 38912 }, { 45056, 43008, 47104 } }, { 49152, 16384, 16384, 8192, 49152, 16384, 16384, 0, 40960, 8192, 8192, 49152, 49152, 16384, 0, 40960 } }, + { { { 52992, 54400, 51968 }, { 30720, 0, 61440 }, { 34816, 36864, 36864 }, { 34816, 36864, 36864 } }, { 57344, 16384, 49152, 49152, 16384, 16384, 0, 0, 0, 0, 49152, 49152, 49152, 49152, 40960, 40960 } }, + { { { 59584, 33024, 44544 }, { 4096, 32768, 36864 }, { 61440, 32768, 38912 }, { 2048, 32768, 36864 } }, { 32768, 8192, 16384, 16384, 40960, 8192, 16384, 16384, 49152, 8192, 8192, 8192, 16384, 57344, 40960, 40960 } }, + { { { 62624, 61504, 61568 }, { 16384, 36864, 28672 }, { 18432, 36864, 36864 }, { 28672, 4096, 12288 } }, { 49152, 0, 16384, 16384, 16384, 40960, 49152, 0, 57344, 0, 8192, 40960, 40960, 49152, 49152, 49152 } }, + { { { 55872, 54080, 52736 }, { 22528, 20480, 20480 }, { 24576, 24576, 20480 }, { 38912, 40960, 45056 } }, { 32768, 49152, 40960, 49152, 16384, 8192, 0, 8192, 16384, 16384, 16384, 16384, 8192, 8192, 8192, 40960 } }, + { { { 54784, 54272, 53248 }, { 26624, 26624, 25600 }, { 40960, 40960, 43008 }, { 41984, 39936, 39936 } }, { 32768, 49152, 8192, 16384, 40960, 0, 8192, 49152, 49152, 8192, 57344, 40960, 16384, 8192, 49152, 40960 } }, + { { { 50176, 49152, 47104 }, { 40960, 41984, 43008 }, { 43008, 45056, 47104 }, { 36864, 36864, 36864 } }, { 32768, 16384, 49152, 40960, 49152, 8192, 49152, 40960, 8192, 0, 40960, 40960, 16384, 0, 40960, 40960 } }, + { { { 55232, 54752, 52992 }, { 40960, 45056, 45056 }, { 24576, 16384, 16384 }, { 38912, 40960, 40960 } }, { 49152, 40960, 49152, 0, 16384, 8192, 8192, 0, 0, 16384, 8192, 40960, 49152, 8192, 8192, 40960 } }, + { { { 61088, 61536, 62048 }, { 26624, 20480, 16384 }, { 26624, 16384, 16384 }, { 34816, 40960, 45056 } }, { 53248, 49152, 40960, 40960, 4096, 0, 57344, 49152, 12288, 12288, 4096, 0, 20480, 20480, 16384, 12288 } }, + { { { 41984, 41984, 41984 }, { 34816, 33792, 33792 }, { 56320, 56320, 55296 }, { 53248, 53248, 51200 } }, { 32768, 40960, 57344, 24576, 57344, 40960, 40960, 49152, 8192, 0, 49152, 40960, 16384, 16384, 8192, 49152 } }, + { { { 55552, 55552, 54912 }, { 14336, 16384, 14336 }, { 40960, 38912, 40960 }, { 16384, 18432, 16384 } }, { 57344, 49152, 49152, 16384, 49152, 40960, 49152, 8192, 57344, 57344, 8192, 49152, 8192, 16384, 8192, 40960 } }, + { { { 39936, 39936, 39936 }, { 56320, 56320, 56320 }, { 34816, 33792, 33792 }, { 57344, 57344, 56320 } }, { 57344, 57344, 0, 0, 49152, 57344, 57344, 57344, 32768, 32768, 32768, 40960, 32768, 32768, 32768, 32768 } }, + { { { 48128, 47872, 46080 }, { 38912, 47104, 51200 }, { 37888, 47104, 47104 }, { 29696, 36864, 55296 } }, { 32768, 40960, 40960, 16384, 57344, 57344, 57344, 8192, 8192, 8192, 8192, 49152, 16384, 16384, 16384, 40960 } }, + { { { 59968, 60192, 61184 }, { 57344, 61440, 57344 }, { 57344, 0, 45056 }, { 61440, 0, 10240 } }, { 32768, 40960, 40960, 40960, 57344, 57344, 49152, 49152, 8192, 8192, 8192, 0, 16384, 16384, 16384, 16384 } }, + { { { 63264, 64128, 65376 }, { 40960, 49152, 49152 }, { 45056, 49152, 53248 }, { 26624, 0, 61440 } }, { 32768, 16384, 16384, 0, 40960, 57344, 57344, 49152, 49152, 0, 49152, 40960, 49152, 0, 16384, 40960 } }, + { { { 44800, 41728, 41984 }, { 58368, 45056, 49152 }, { 58368, 47104, 45056 }, { 55296, 34816, 30720 } }, { 49152, 40960, 49152, 24576, 57344, 40960, 40960, 49152, 8192, 57344, 40960, 40960, 16384, 8192, 57344, 40960 } }, + { { { 59648, 59328, 59968 }, { 26624, 36864, 43008 }, { 12288, 36864, 47104 }, { 24576, 34816, 47104 } }, { 32768, 40960, 57344, 57344, 32768, 32768, 57344, 57344, 32768, 32768, 0, 57344, 32768, 32768, 57344, 57344 } }, + { { { 59008, 46336, 56064 }, { 24576, 34816, 38912 }, { 14336, 32768, 43008 }, { 20480, 32768, 40960 } }, { 57344, 49152, 49152, 16384, 16384, 8192, 57344, 57344, 16384, 8192, 57344, 49152, 57344, 57344, 40960, 40960 } }, + { { { 45056, 44800, 41472 }, { 57344, 49152, 47104 }, { 13312, 26624, 30720 }, { 55296, 43008, 45056 } }, { 32768, 57344, 8192, 8192, 8192, 8192, 16384, 16384, 49152, 49152, 49152, 49152, 8192, 16384, 0, 49152 } }, + { { { 58112, 58048, 57536 }, { 18432, 20480, 20480 }, { 22528, 22528, 22528 }, { 43008, 36864, 38912 } }, { 32768, 40960, 49152, 49152, 16384, 57344, 0, 57344, 49152, 0, 8192, 8192, 40960, 49152, 8192, 16384 } }, + { { { 62976, 63744, 64960 }, { 24576, 8192, 12288 }, { 36864, 53248, 57344 }, { 26624, 8192, 8192 } }, { 32768, 49152, 0, 16384, 24576, 8192, 0, 57344, 49152, 49152, 40960, 40960, 40960, 40960, 40960, 40960 } }, + { { { 47616, 47360, 45568 }, { 38912, 47104, 51200 }, { 29696, 36864, 49152 }, { 37888, 47104, 49152 } }, { 40960, 57344, 8192, 24576, 32768, 40960, 49152, 0, 49152, 40960, 40960, 49152, 24576, 57344, 40960, 40960 } }, + { { { 53248, 51712, 48896 }, { 45056, 47104, 44032 }, { 51200, 53248, 52224 }, { 43008, 43008, 40960 } }, { 49152, 40960, 40960, 40960, 0, 57344, 49152, 49152, 40960, 16384, 8192, 0, 16384, 0, 40960, 16384 } }, + { { { 43520, 43008, 44032 }, { 45056, 46080, 44032 }, { 35840, 36864, 35840 }, { 53248, 53248, 51200 } }, { 32768, 49152, 16384, 49152, 57344, 57344, 16384, 49152, 8192, 8192, 16384, 40960, 16384, 8192, 16384, 40960 } }, + { { { 46592, 37376, 40960 }, { 15360, 36864, 36864 }, { 25600, 34816, 36864 }, { 16384, 35840, 38912 } }, { 32768, 16384, 57344, 40960, 40960, 16384, 57344, 40960, 40960, 16384, 57344, 40960, 49152, 16384, 57344, 40960 } }, + { { { 50688, 50176, 48128 }, { 41984, 43008, 45056 }, { 40960, 39936, 44032 }, { 27648, 27648, 25600 } }, { 32768, 16384, 8192, 49152, 40960, 16384, 0, 49152, 49152, 0, 57344, 49152, 16384, 57344, 49152, 40960 } }, + { { { 55808, 49664, 54912 }, { 55296, 40960, 51200 }, { 43008, 38912, 57344 }, { 49152, 34816, 26624 } }, { 32768, 57344, 8192, 8192, 8192, 8192, 8192, 0, 57344, 8192, 16384, 57344, 40960, 49152, 16384, 49152 } }, + { { { 51776, 47424, 48192 }, { 38912, 57344, 53248 }, { 36864, 53248, 53248 }, { 36864, 49152, 49152 } }, { 49152, 8192, 57344, 40960, 40960, 8192, 8192, 57344, 49152, 8192, 8192, 8192, 8192, 8192, 57344, 40960 } }, + { { { 50176, 49152, 48128 }, { 50176, 48128, 48128 }, { 52224, 51200, 51200 }, { 35840, 34816, 33792 } }, { 57344, 8192, 16384, 8192, 40960, 49152, 57344, 49152, 40960, 57344, 0, 49152, 0, 8192, 16384, 49152 } }, + { { { 54432, 51744, 51328 }, { 26624, 20480, 20480 }, { 26624, 20480, 20480 }, { 34816, 45056, 49152 } }, { 32768, 16384, 8192, 57344, 16384, 16384, 57344, 49152, 8192, 57344, 40960, 40960, 49152, 49152, 40960, 40960 } }, + { { { 49664, 49152, 48128 }, { 43008, 44032, 44032 }, { 51200, 53248, 54272 }, { 39936, 40960, 40960 } }, { 57344, 49152, 40960, 49152, 49152, 49152, 49152, 16384, 49152, 49152, 49152, 16384, 16384, 8192, 57344, 40960 } }, + { { { 58880, 57344, 55040 }, { 37888, 34816, 26624 }, { 38912, 34816, 14336 }, { 37888, 34816, 24576 } }, { 32768, 57344, 16384, 16384, 16384, 49152, 49152, 49152, 16384, 49152, 40960, 40960, 0, 49152, 49152, 40960 } }, + { { { 43520, 43264, 38912 }, { 58368, 49152, 47104 }, { 56320, 43008, 45056 }, { 11264, 26624, 30720 } }, { 32768, 40960, 0, 16384, 49152, 57344, 0, 57344, 57344, 0, 8192, 40960, 8192, 16384, 16384, 40960 } }, + { { { 60416, 60352, 31936 }, { 16384, 16384, 32768 }, { 16384, 14336, 32768 }, { 22528, 22528, 32768 } }, { 49152, 16384, 49152, 40960, 0, 49152, 8192, 40960, 8192, 49152, 8192, 49152, 16384, 0, 40960, 57344 } }, + { { { 56768, 56512, 55104 }, { 47104, 47104, 47104 }, { 40960, 40960, 40960 }, { 51200, 51200, 51200 } }, { 32768, 40960, 40960, 49152, 0, 49152, 49152, 0, 16384, 57344, 49152, 16384, 16384, 8192, 0, 49152 } }, + { { { 47104, 46848, 44288 }, { 16384, 14336, 14336 }, { 22528, 36864, 40960 }, { 16384, 14336, 18432 } }, { 49152, 40960, 40960, 40960, 8192, 57344, 49152, 40960, 16384, 8192, 49152, 40960, 16384, 8192, 49152, 40960 } }, + { { { 51200, 50176, 54272 }, { 57344, 57344, 59392 }, { 58368, 58368, 59392 }, { 55296, 55296, 57344 } }, { 32768, 40960, 40960, 40960, 24576, 57344, 49152, 57344, 57344, 57344, 0, 24576, 40960, 40960, 40960, 40960 } }, + { { { 54080, 53760, 52544 }, { 49152, 47104, 47104 }, { 43008, 43008, 43008 }, { 43008, 43008, 43008 } }, { 49152, 49152, 49152, 40960, 40960, 8192, 0, 57344, 0, 49152, 49152, 16384, 16384, 8192, 0, 49152 } }, + { { { 51712, 51200, 49920 }, { 38912, 49152, 51200 }, { 38912, 45056, 47104 }, { 34816, 36864, 26624 } }, { 57344, 0, 8192, 8192, 49152, 57344, 0, 0, 8192, 57344, 49152, 40960, 0, 49152, 40960, 40960 } }, + { { { 61440, 34304, 34176 }, { 36864, 32768, 32768 }, { 36864, 32768, 32768 }, { 34816, 32768, 32768 } }, { 57344, 40960, 57344, 16384, 49152, 8192, 57344, 8192, 40960, 0, 40960, 57344, 40960, 57344, 16384, 49152 } }, + { { { 51456, 45824, 48640 }, { 25600, 40960, 40960 }, { 24576, 43008, 43008 }, { 26624, 40960, 40960 } }, { 32768, 8192, 16384, 16384, 49152, 0, 8192, 16384, 49152, 49152, 57344, 57344, 40960, 40960, 40960, 40960 } }, + { { { 51712, 46592, 43776 }, { 51200, 45056, 43008 }, { 47104, 38912, 36864 }, { 51200, 49152, 54272 } }, { 49152, 49152, 40960, 49152, 0, 8192, 16384, 8192, 40960, 49152, 49152, 57344, 8192, 8192, 16384, 8192 } }, + { { { 50432, 51712, 48896 }, { 25600, 16384, 14336 }, { 34816, 26624, 6144 }, { 25600, 14336, 14336 } }, { 57344, 16384, 49152, 0, 8192, 57344, 49152, 57344, 49152, 57344, 8192, 8192, 57344, 0, 8192, 40960 } }, + { { { 58560, 58560, 57856 }, { 18432, 22528, 12288 }, { 47104, 43008, 51200 }, { 40960, 38912, 40960 } }, { 40960, 40960, 49152, 40960, 49152, 57344, 57344, 57344, 16384, 8192, 16384, 8192, 40960, 8192, 16384, 40960 } }, + { { { 59712, 59392, 60288 }, { 49152, 43008, 57344 }, { 51200, 43008, 51200 }, { 36864, 28672, 24576 } }, { 49152, 40960, 49152, 0, 8192, 49152, 0, 16384, 49152, 49152, 8192, 0, 49152, 57344, 16384, 40960 } }, + { { { 49152, 44032, 41984 }, { 48128, 44032, 38912 }, { 41984, 52224, 33792 }, { 43008, 53248, 36864 } }, { 57344, 0, 49152, 40960, 8192, 0, 49152, 57344, 16384, 57344, 40960, 16384, 8192, 57344, 49152, 49152 } }, + { { { 53760, 53248, 52736 }, { 36864, 36864, 36864 }, { 45056, 46080, 45056 }, { 46080, 47104, 46080 } }, { 32768, 40960, 57344, 16384, 16384, 8192, 57344, 57344, 8192, 0, 49152, 49152, 57344, 49152, 40960, 40960 } }, + { { { 59456, 59328, 60544 }, { 8192, 20480, 14336 }, { 36864, 26624, 22528 }, { 10240, 22528, 18432 } }, { 49152, 8192, 40960, 16384, 49152, 57344, 8192, 57344, 40960, 49152, 0, 40960, 40960, 49152, 0, 16384 } }, + { { { 60224, 60992, 61120 }, { 10240, 22528, 47104 }, { 0, 61440, 43008 }, { 10240, 26624, 40960 } }, { 40960, 40960, 40960, 40960, 40960, 40960, 40960, 49152, 49152, 57344, 8192, 24576, 24576, 0, 40960, 40960 } }, + { { { 45056, 44032, 44032 }, { 43008, 43008, 41984 }, { 50176, 34816, 29696 }, { 43008, 43008, 40960 } }, { 49152, 49152, 49152, 16384, 49152, 57344, 57344, 49152, 49152, 8192, 16384, 49152, 49152, 16384, 16384, 49152 } }, + { { { 60416, 59392, 52224 }, { 60416, 58368, 47104 }, { 59392, 56320, 38912 }, { 59392, 58368, 46080 } }, { 32768, 8192, 57344, 49152, 16384, 8192, 8192, 49152, 49152, 8192, 8192, 49152, 49152, 8192, 8192, 49152 } }, + { { { 53248, 53504, 51200 }, { 25600, 16384, 16384 }, { 24576, 16384, 16384 }, { 28672, 26624, 34816 } }, { 57344, 40960, 40960, 57344, 40960, 57344, 8192, 8192, 8192, 8192, 57344, 49152, 8192, 0, 57344, 40960 } }, + { { { 55296, 48000, 52480 }, { 51200, 43008, 57344 }, { 28672, 34816, 38912 }, { 49152, 40960, 45056 } }, { 32768, 16384, 0, 49152, 8192, 8192, 8192, 57344, 8192, 8192, 8192, 8192, 8192, 57344, 49152, 40960 } }, + { { { 60672, 60864, 61440 }, { 16384, 22528, 16384 }, { 16384, 18432, 14336 }, { 57344, 36864, 24576 } }, { 40960, 40960, 49152, 49152, 16384, 8192, 8192, 8192, 40960, 57344, 8192, 16384, 8192, 8192, 0, 49152 } }, + { { { 45824, 45056, 42496 }, { 56320, 47104, 45056 }, { 56320, 45056, 45056 }, { 11264, 22528, 24576 } }, { 57344, 16384, 16384, 8192, 0, 16384, 8192, 0, 49152, 57344, 49152, 40960, 40960, 40960, 40960, 40960 } }, + { { { 40960, 27392, 46848 }, { 54272, 28672, 49152 }, { 53248, 28672, 47104 }, { 52224, 28672, 43008 } }, { 32768, 16384, 49152, 8192, 0, 57344, 0, 0, 16384, 49152, 8192, 49152, 57344, 57344, 0, 40960 } }, + { { { 60736, 32768, 60000 }, { 57344, 49152, 0 }, { 61440, 49152, 45056 }, { 4096, 49152, 61440 } }, { 57344, 24576, 57344, 49152, 49152, 57344, 49152, 49152, 49152, 49152, 49152, 49152, 16384, 8192, 49152, 40960 } }, + { { { 55680, 55296, 54016 }, { 16384, 20480, 16384 }, { 51200, 49152, 55296 }, { 47104, 43008, 47104 } }, { 40960, 40960, 40960, 40960, 40960, 40960, 40960, 40960, 40960, 40960, 40960, 40960, 40960, 40960, 40960, 40960 } }, + { { { 45056, 44544, 44032 }, { 44032, 44032, 44032 }, { 38912, 38912, 38912 }, { 53248, 54272, 54272 } }, { 32768, 16384, 16384, 8192, 40960, 16384, 8192, 8192, 49152, 8192, 57344, 57344, 40960, 57344, 40960, 40960 } }, + { { { 44032, 43520, 39936 }, { 45056, 39936, 45056 }, { 38912, 39936, 40960 }, { 1024, 29696, 34816 } }, { 32768, 40960, 49152, 57344, 40960, 57344, 8192, 16384, 49152, 8192, 16384, 16384, 40960, 49152, 49152, 49152 } }, + { { { 41984, 36864, 40960 }, { 46080, 36864, 41984 }, { 36864, 32768, 55296 }, { 36864, 32768, 57344 } }, { 40960, 40960, 49152, 16384, 40960, 40960, 49152, 8192, 49152, 49152, 40960, 57344, 8192, 16384, 8192, 49152 } }, + { { { 59776, 60416, 61504 }, { 51200, 43008, 49152 }, { 26624, 36864, 40960 }, { 45056, 40960, 45056 } }, { 32768, 40960, 49152, 16384, 49152, 40960, 40960, 57344, 0, 49152, 40960, 40960, 16384, 0, 40960, 40960 } }, + { { { 50688, 50176, 45568 }, { 21504, 10240, 38912 }, { 38912, 43008, 40960 }, { 22528, 8192, 34816 } }, { 32768, 40960, 49152, 57344, 40960, 49152, 57344, 0, 53248, 57344, 4096, 16384, 0, 8192, 16384, 24576 } }, + { { { 44032, 46336, 41728 }, { 45056, 45056, 45056 }, { 44032, 49152, 45056 }, { 39936, 28672, 34816 } }, { 40960, 0, 8192, 16384, 40960, 57344, 8192, 16384, 49152, 49152, 8192, 16384, 16384, 49152, 57344, 16384 } }, + { { { 44544, 39936, 38912 }, { 40960, 40960, 41984 }, { 29696, 34816, 34816 }, { 38912, 40960, 41984 } }, { 32768, 8192, 16384, 8192, 40960, 49152, 8192, 16384, 57344, 57344, 49152, 0, 8192, 8192, 8192, 40960 } }, + { { { 59200, 59840, 60864 }, { 0, 8192, 14336 }, { 6144, 20480, 16384 }, { 49152, 36864, 24576 } }, { 57344, 49152, 0, 8192, 0, 8192, 16384, 16384, 16384, 16384, 16384, 8192, 8192, 8192, 0, 40960 } }, + { { { 43264, 44800, 40960 }, { 47104, 43008, 47104 }, { 41984, 28672, 36864 }, { 46080, 43008, 47104 } }, { 32768, 49152, 0, 16384, 40960, 57344, 16384, 49152, 49152, 16384, 57344, 40960, 16384, 0, 40960, 40960 } }, + { { { 50432, 50688, 48384 }, { 22528, 14336, 18432 }, { 22528, 12288, 20480 }, { 27648, 32768, 34816 } }, { 32768, 32768, 32768, 32768, 40960, 32768, 32768, 32768, 57344, 57344, 57344, 49152, 0, 57344, 57344, 49152 } }, + { { { 54912, 54784, 54016 }, { 49152, 49152, 49152 }, { 49152, 49152, 47104 }, { 34816, 26624, 24576 } }, { 32768, 0, 8192, 8192, 16384, 0, 8192, 16384, 8192, 49152, 49152, 8192, 0, 40960, 49152, 40960 } }, + { { { 60800, 32832, 59712 }, { 49152, 32768, 16384 }, { 53248, 32768, 36864 }, { 59392, 32768, 47104 } }, { 40960, 8192, 16384, 49152, 49152, 57344, 57344, 57344, 40960, 0, 8192, 8192, 8192, 8192, 8192, 49152 } }, + { { { 53888, 47616, 47968 }, { 10240, 16384, 16384 }, { 51200, 20480, 20480 }, { 55296, 40960, 40960 } }, { 49152, 0, 49152, 57344, 40960, 40960, 49152, 57344, 40960, 49152, 49152, 0, 8192, 8192, 16384, 16384 } }, + { { { 54656, 50048, 52992 }, { 45056, 45056, 53248 }, { 45056, 45056, 45056 }, { 28672, 34816, 40960 } }, { 40960, 40960, 40960, 40960, 40960, 40960, 49152, 57344, 49152, 57344, 16384, 16384, 8192, 16384, 8192, 40960 } }, + { { { 64096, 64160, 63968 }, { 40960, 53248, 24576 }, { 36864, 45056, 24576 }, { 8192, 12288, 34816 } }, { 40960, 16384, 57344, 40960, 40960, 0, 0, 40960, 40960, 49152, 16384, 49152, 40960, 49152, 16384, 57344 } }, + { { { 18432, 18432, 33792 }, { 55296, 53248, 13312 }, { 56320, 51200, 13312 }, { 56320, 54272, 51200 } }, { 32768, 8192, 16384, 16384, 40960, 40960, 40960, 49152, 57344, 57344, 49152, 40960, 16384, 16384, 57344, 49152 } }, + { { { 5120, 62464, 62464 }, { 10240, 62464, 61440 }, { 10240, 62464, 62464 }, { 12288, 62464, 62464 } }, { 32768, 16384, 40960, 40960, 0, 57344, 40960, 8192, 8192, 8192, 0, 57344, 16384, 16384, 8192, 8192 } }, + { { { 59840, 60032, 61120 }, { 40960, 43008, 47104 }, { 40960, 43008, 43008 }, { 28672, 36864, 40960 } }, { 32768, 8192, 40960, 8192, 8192, 8192, 57344, 0, 8192, 8192, 49152, 8192, 57344, 57344, 57344, 0 } }, + { { { 53248, 53248, 51200 }, { 24576, 16384, 14336 }, { 28672, 26624, 36864 }, { 24576, 14336, 20480 } }, { 32768, 40960, 40960, 40960, 40960, 40960, 40960, 40960, 40960, 49152, 49152, 49152, 0, 0, 16384, 24576 } }, + { { { 39360, 58752, 59072 }, { 32768, 20480, 20480 }, { 34816, 16384, 14336 }, { 32768, 22528, 22528 } }, { 32768, 40960, 57344, 16384, 40960, 40960, 57344, 8192, 16384, 16384, 0, 49152, 8192, 8192, 49152, 40960 } }, + { { { 52224, 52480, 50944 }, { 26624, 14336, 14336 }, { 35840, 36864, 26624 }, { 26624, 12288, 12288 } }, { 57344, 40960, 40960, 49152, 0, 49152, 49152, 0, 8192, 0, 0, 8192, 16384, 16384, 16384, 16384 } }, + { { { 48128, 46592, 37376 }, { 23552, 25600, 35840 }, { 18432, 25600, 37888 }, { 16384, 25600, 36864 } }, { 32768, 57344, 8192, 16384, 8192, 49152, 0, 16384, 16384, 8192, 49152, 8192, 8192, 8192, 49152, 40960 } }, + { { { 6656, 14848, 19456 }, { 56320, 8192, 8192 }, { 50176, 13312, 11264 }, { 55296, 52224, 52224 } }, { 57344, 8192, 8192, 0, 16384, 8192, 0, 57344, 0, 57344, 49152, 8192, 49152, 57344, 16384, 40960 } }, + { { { 27392, 49152, 25856 }, { 47104, 26624, 36864 }, { 45056, 20480, 36864 }, { 46080, 12288, 36864 } }, { 40960, 40960, 49152, 16384, 40960, 40960, 49152, 8192, 40960, 40960, 57344, 57344, 40960, 49152, 24576, 40960 } }, + { { { 48128, 36864, 35840 }, { 52224, 35840, 36864 }, { 53248, 36864, 39936 }, { 53248, 36864, 37888 } }, { 32768, 49152, 57344, 16384, 16384, 49152, 57344, 0, 49152, 8192, 16384, 0, 49152, 57344, 49152, 49152 } }, + { { { 58592, 56288, 53536 }, { 26624, 61440, 45056 }, { 26624, 61440, 45056 }, { 34816, 45056, 45056 } }, { 40960, 40960, 40960, 16384, 57344, 57344, 8192, 8192, 8192, 8192, 57344, 57344, 16384, 40960, 40960, 40960 } }, + { { { 57024, 61184, 61632 }, { 45056, 45056, 24576 }, { 40960, 40960, 38912 }, { 45056, 36864, 10240 } }, { 40960, 16384, 49152, 57344, 16384, 57344, 49152, 8192, 40960, 57344, 0, 49152, 16384, 49152, 49152, 49152 } }, + { { { 53248, 53248, 51712 }, { 24576, 24576, 20480 }, { 38912, 38912, 39936 }, { 26624, 25600, 23552 } }, { 32768, 40960, 57344, 16384, 57344, 57344, 8192, 8192, 24576, 49152, 49152, 49152, 40960, 40960, 40960, 40960 } }, + { { { 43008, 39424, 38912 }, { 39936, 41984, 43008 }, { 38912, 39936, 39936 }, { 28672, 34816, 35840 } }, { 57344, 49152, 49152, 8192, 49152, 8192, 8192, 16384, 57344, 8192, 0, 49152, 57344, 49152, 40960, 40960 } }, + { { { 54560, 54400, 52160 }, { 28672, 45056, 40960 }, { 47104, 36864, 36864 }, { 28672, 40960, 40960 } }, { 32768, 49152, 40960, 49152, 8192, 8192, 8192, 16384, 16384, 16384, 16384, 16384, 16384, 16384, 16384, 16384 } }, + { { { 63072, 63680, 64448 }, { 26624, 8192, 4096 }, { 36864, 53248, 61440 }, { 36864, 53248, 53248 } }, { 32768, 8192, 16384, 0, 8192, 0, 49152, 49152, 16384, 8192, 57344, 49152, 0, 8192, 8192, 49152 } }, + { { { 51200, 50944, 45312 }, { 51200, 40960, 43008 }, { 13312, 24576, 36864 }, { 12288, 22528, 49152 } }, { 57344, 16384, 49152, 49152, 57344, 49152, 49152, 57344, 16384, 8192, 49152, 49152, 8192, 16384, 8192, 40960 } }, + { { { 48384, 47616, 44288 }, { 24576, 0, 49152 }, { 25600, 63488, 36864 }, { 35840, 51200, 45056 } }, { 36864, 36864, 36864, 40960, 57344, 57344, 61440, 61440, 12288, 12288, 16384, 16384, 20480, 24576, 24576, 24576 } }, + { { { 33792, 38912, 32768 }, { 33792, 62464, 32768 }, { 32768, 32768, 32768 }, { 32768, 56320, 37888 } }, { 49152, 49152, 57344, 8192, 8192, 49152, 49152, 8192, 49152, 57344, 49152, 0, 40960, 8192, 8192, 8192 } }, + { { { 49152, 50944, 48128 }, { 39936, 51200, 53248 }, { 39936, 47104, 49152 }, { 35840, 26624, 24576 } }, { 40960, 40960, 40960, 40960, 40960, 49152, 49152, 40960, 49152, 8192, 0, 40960, 16384, 16384, 8192, 49152 } }, + { { { 49664, 50688, 47616 }, { 39936, 49152, 49152 }, { 38912, 49152, 49152 }, { 28672, 26624, 34816 } }, { 49152, 4096, 16384, 24576, 45056, 61440, 12288, 20480, 40960, 57344, 12288, 20480, 36864, 49152, 4096, 16384 } }, + { { { 48128, 46592, 46080 }, { 41984, 41984, 43008 }, { 43008, 43008, 40960 }, { 35840, 34816, 29696 } }, { 32768, 16384, 16384, 16384, 8192, 16384, 16384, 16384, 16384, 16384, 16384, 8192, 16384, 16384, 0, 32768 } }, + { { { 60416, 3072, 60416 }, { 62464, 11264, 61440 }, { 62464, 11264, 62464 }, { 62464, 13312, 62464 } }, { 32768, 40960, 40960, 40960, 49152, 57344, 8192, 16384, 24576, 8192, 0, 57344, 49152, 40960, 40960, 40960 } }, + { { { 54528, 48896, 52736 }, { 37888, 47104, 59392 }, { 27648, 55296, 53248 }, { 27648, 36864, 43008 } }, { 49152, 40960, 40960, 40960, 16384, 49152, 40960, 40960, 40960, 8192, 57344, 49152, 0, 49152, 8192, 49152 } }, + { { { 59968, 33280, 59584 }, { 2048, 32768, 63488 }, { 4096, 32768, 16384 }, { 61440, 32768, 12288 } }, { 32768, 16384, 49152, 57344, 49152, 0, 49152, 8192, 57344, 57344, 49152, 8192, 8192, 57344, 49152, 0 } }, + { { { 15872, 18944, 43008 }, { 7168, 12288, 54272 }, { 7168, 11264, 51200 }, { 58368, 51200, 54272 } }, { 40960, 49152, 8192, 8192, 16384, 0, 49152, 40960, 40960, 57344, 8192, 16384, 8192, 0, 49152, 40960 } }, + { { { 57312, 56384, 54816 }, { 38912, 49152, 53248 }, { 26624, 8192, 4096 }, { 26624, 8192, 0 } }, { 32768, 32768, 32768, 32768, 32768, 32768, 32768, 32768, 40960, 32768, 32768, 32768, 16384, 49152, 40960, 32768 } }, + { { { 45056, 40960, 46080 }, { 62464, 60416, 11264 }, { 62464, 60416, 17408 }, { 61440, 59392, 14336 } }, { 32768, 16384, 57344, 49152, 16384, 16384, 8192, 49152, 49152, 0, 8192, 8192, 40960, 40960, 49152, 57344 } }, + { { { 32768, 32768, 32768 }, { 62464, 32768, 32768 }, { 32768, 32768, 32768 }, { 62464, 32768, 32768 } }, { 40960, 8192, 40960, 8192, 40960, 8192, 49152, 8192, 40960, 8192, 8192, 8192, 49152, 8192, 8192, 49152 } }, + { { { 54272, 54272, 53248 }, { 21504, 20480, 20480 }, { 36864, 36864, 36864 }, { 25600, 25600, 24576 } }, { 40960, 40960, 40960, 40960, 16384, 16384, 16384, 0, 40960, 40960, 40960, 40960, 16384, 16384, 0, 49152 } }, + { { { 32768, 64864, 62976 }, { 34816, 49152, 49152 }, { 34816, 61440, 45056 }, { 34816, 57344, 4096 } }, { 32768, 0, 16384, 40960, 49152, 57344, 8192, 0, 0, 57344, 16384, 8192, 8192, 0, 8192, 40960 } }, + { { { 55808, 46080, 39424 }, { 34816, 34816, 52224 }, { 34816, 35840, 49152 }, { 34816, 34816, 51200 } }, { 40960, 40960, 40960, 40960, 16384, 16384, 16384, 16384, 0, 0, 57344, 49152, 49152, 40960, 40960, 40960 } }, + { { { 57472, 57728, 56448 }, { 38912, 22528, 20480 }, { 36864, 22528, 22528 }, { 16384, 34816, 30720 } }, { 32768, 57344, 8192, 57344, 0, 8192, 0, 57344, 16384, 49152, 8192, 8192, 57344, 57344, 8192, 49152 } }, + { { { 64224, 64224, 64032 }, { 49152, 61440, 22528 }, { 20480, 20480, 49152 }, { 4096, 12288, 32768 } }, { 40960, 49152, 16384, 16384, 40960, 49152, 0, 16384, 40960, 40960, 40960, 49152, 40960, 40960, 40960, 40960 } }, + { { { 45568, 44544, 41472 }, { 45056, 41984, 46080 }, { 29696, 29696, 33792 }, { 39936, 39936, 43008 } }, { 32768, 49152, 49152, 57344, 57344, 8192, 16384, 49152, 16384, 49152, 49152, 49152, 16384, 0, 49152, 40960 } }, + { { { 64448, 64256, 64288 }, { 47104, 20480, 12288 }, { 36864, 28672, 57344 }, { 36864, 32768, 4096 } }, { 57344, 0, 61440, 53248, 4096, 4096, 61440, 53248, 12288, 8192, 61440, 53248, 12288, 8192, 61440, 45056 } }, + { { { 62528, 61568, 61728 }, { 24576, 49152, 40960 }, { 38912, 40960, 40960 }, { 24576, 61440, 40960 } }, { 49152, 24576, 49152, 49152, 49152, 57344, 57344, 0, 49152, 40960, 57344, 16384, 49152, 49152, 49152, 49152 } }, + { { { 52736, 48640, 48128 }, { 36864, 35840, 23552 }, { 38912, 36864, 8192 }, { 40960, 36864, 22528 } }, { 40960, 16384, 49152, 57344, 49152, 57344, 49152, 49152, 16384, 8192, 8192, 8192, 57344, 49152, 49152, 40960 } }, + { { { 55040, 54528, 51968 }, { 16384, 12288, 14336 }, { 47104, 47104, 38912 }, { 8192, 10240, 18432 } }, { 49152, 49152, 40960, 49152, 0, 49152, 57344, 0, 57344, 49152, 49152, 8192, 49152, 40960, 57344, 24576 } }, + { { { 53248, 52224, 49152 }, { 23552, 23552, 22528 }, { 28672, 27648, 34816 }, { 20480, 20480, 24576 } }, { 32768, 49152, 57344, 0, 16384, 8192, 49152, 49152, 40960, 49152, 49152, 49152, 8192, 16384, 16384, 8192 } }, + { { { 41472, 42496, 38912 }, { 44032, 40960, 43008 }, { 34816, 29696, 34816 }, { 45056, 40960, 43008 } }, { 32768, 49152, 49152, 16384, 49152, 0, 0, 49152, 49152, 8192, 8192, 57344, 49152, 0, 8192, 16384 } }, + { { { 51712, 51200, 50688 }, { 21504, 23552, 20480 }, { 55296, 34816, 27648 }, { 24576, 23552, 20480 } }, { 40960, 49152, 49152, 16384, 40960, 49152, 57344, 0, 40960, 40960, 57344, 8192, 40960, 40960, 57344, 16384 } }, + { { { 16384, 0, 57344 }, { 58368, 59392, 59392 }, { 56320, 55296, 56320 }, { 56320, 3072, 4096 } }, { 40960, 49152, 49152, 40960, 16384, 8192, 49152, 40960, 16384, 16384, 49152, 49152, 49152, 0, 49152, 40960 } }, + { { { 49664, 43008, 47104 }, { 50176, 35840, 25600 }, { 47104, 37888, 61440 }, { 44032, 38912, 38912 } }, { 32768, 8192, 8192, 0, 16384, 49152, 57344, 8192, 49152, 49152, 57344, 0, 49152, 0, 57344, 49152 } }, + { { { 48896, 40448, 38912 }, { 51200, 40960, 54272 }, { 61440, 34816, 39936 }, { 8192, 34816, 37888 } }, { 49152, 8192, 49152, 8192, 57344, 8192, 57344, 57344, 8192, 49152, 8192, 49152, 8192, 49152, 16384, 40960 } }, + { { { 43520, 43008, 36864 }, { 5120, 25600, 36864 }, { 6144, 25600, 34816 }, { 53248, 35840, 40960 } }, { 36864, 40960, 61440, 20480, 36864, 40960, 57344, 20480, 36864, 40960, 53248, 16384, 40960, 40960, 53248, 16384 } }, + { { { 44544, 36352, 37888 }, { 27648, 36864, 39936 }, { 35840, 38912, 39936 }, { 63488, 35840, 36864 } }, { 40960, 40960, 40960, 49152, 49152, 0, 8192, 16384, 49152, 8192, 8192, 49152, 49152, 16384, 49152, 40960 } }, + { { { 52736, 51712, 48128 }, { 21504, 22528, 20480 }, { 23552, 21504, 18432 }, { 28672, 28672, 35840 } }, { 40960, 40960, 40960, 49152, 49152, 49152, 0, 16384, 16384, 8192, 57344, 49152, 49152, 40960, 40960, 40960 } }, + { { { 50688, 50176, 48640 }, { 41984, 43008, 43008 }, { 53248, 56320, 57344 }, { 50176, 53248, 53248 } }, { 32768, 49152, 49152, 57344, 49152, 0, 16384, 16384, 49152, 49152, 49152, 49152, 8192, 8192, 8192, 49152 } }, + { { { 44032, 43008, 36864 }, { 8192, 26624, 34816 }, { 55296, 36864, 40960 }, { 6144, 27648, 35840 } }, { 32768, 40960, 49152, 16384, 0, 57344, 40960, 40960, 16384, 16384, 0, 57344, 16384, 16384, 16384, 8192 } }, + { { { 47616, 45056, 38912 }, { 46080, 36864, 48128 }, { 8192, 27648, 37888 }, { 8192, 27648, 40960 } }, { 40960, 49152, 49152, 8192, 16384, 8192, 49152, 57344, 57344, 49152, 57344, 49152, 49152, 49152, 16384, 49152 } }, + { { { 45568, 45568, 43008 }, { 56320, 2048, 51200 }, { 38912, 38912, 37888 }, { 37888, 38912, 37888 } }, { 40960, 16384, 49152, 8192, 49152, 16384, 49152, 8192, 57344, 0, 49152, 0, 8192, 49152, 16384, 40960 } }, + { { { 48128, 48128, 46592 }, { 46080, 44032, 47104 }, { 34816, 29696, 28672 }, { 45056, 44032, 43008 } }, { 40960, 49152, 49152, 49152, 49152, 16384, 8192, 49152, 49152, 16384, 16384, 49152, 40960, 49152, 40960, 40960 } }, + { { { 4096, 4096, 13312 }, { 4096, 4096, 15360 }, { 62464, 62464, 62464 }, { 1024, 1024, 9216 } }, { 40960, 40960, 40960, 40960, 49152, 40960, 49152, 24576, 0, 57344, 57344, 49152, 24576, 0, 49152, 40960 } }, + { { { 51712, 52224, 50688 }, { 17408, 22528, 20480 }, { 33792, 28672, 26624 }, { 22528, 23552, 19456 } }, { 32768, 16384, 16384, 16384, 57344, 8192, 24576, 16384, 40960, 0, 16384, 24576, 49152, 0, 16384, 24576 } }, + { { { 48128, 48128, 46080 }, { 45056, 44032, 46080 }, { 43008, 44032, 43008 }, { 33792, 29696, 26624 } }, { 36864, 36864, 36864, 40960, 36864, 36864, 36864, 36864, 36864, 36864, 36864, 40960, 40960, 40960, 40960, 45056 } }, + { { { 41472, 42496, 35840 }, { 47104, 26624, 36864 }, { 49152, 27648, 36864 }, { 46080, 27648, 38912 } }, { 49152, 49152, 49152, 49152, 8192, 16384, 57344, 57344, 40960, 49152, 49152, 16384, 49152, 57344, 49152, 49152 } }, + { { { 32768, 32768, 60288 }, { 32768, 32768, 51200 }, { 32768, 32768, 57344 }, { 32768, 32768, 43008 } }, { 36864, 36864, 36864, 36864, 45056, 45056, 40960, 40960, 0, 61440, 57344, 57344, 20480, 20480, 20480, 16384 } }, + { { { 36352, 59456, 29952 }, { 32768, 18432, 34816 }, { 32768, 12288, 34816 }, { 32768, 12288, 34816 } }, { 40960, 49152, 57344, 16384, 49152, 49152, 49152, 49152, 49152, 49152, 57344, 16384, 57344, 8192, 8192, 40960 } }, + { { { 53248, 40960, 48640 }, { 48128, 37888, 41984 }, { 43008, 34816, 24576 }, { 40960, 34816, 21504 } }, { 40960, 49152, 0, 49152, 40960, 40960, 16384, 49152, 57344, 49152, 8192, 49152, 16384, 0, 49152, 40960 } }, + { { { 53760, 52736, 51200 }, { 27648, 27648, 20480 }, { 43008, 41984, 46080 }, { 48128, 33792, 26624 } }, { 40960, 49152, 40960, 16384, 49152, 49152, 57344, 0, 8192, 57344, 49152, 57344, 8192, 57344, 0, 16384 } }, + { { { 50176, 49664, 48640 }, { 22528, 25600, 20480 }, { 23552, 24576, 18432 }, { 35840, 34816, 26624 } }, { 32768, 49152, 16384, 57344, 49152, 8192, 0, 49152, 16384, 57344, 40960, 40960, 57344, 40960, 40960, 40960 } }, + { { { 45568, 43008, 44032 }, { 49152, 43008, 53248 }, { 41984, 43008, 38912 }, { 29696, 33792, 28672 } }, { 32768, 40960, 57344, 16384, 40960, 40960, 57344, 16384, 57344, 40960, 49152, 57344, 16384, 49152, 40960, 49152 } }, + { { { 52736, 49152, 46080 }, { 34816, 28672, 16384 }, { 43008, 43008, 54272 }, { 40960, 39936, 55296 } }, { 32768, 24576, 49152, 49152, 49152, 40960, 49152, 49152, 8192, 49152, 49152, 40960, 16384, 0, 57344, 40960 } }, + { { { 54016, 52992, 50944 }, { 14336, 12288, 22528 }, { 53248, 51200, 46080 }, { 55296, 55296, 40960 } }, { 32768, 0, 40960, 40960, 16384, 0, 16384, 40960, 16384, 0, 16384, 40960, 16384, 57344, 8192, 16384 } }, + { { { 45568, 42496, 36352 }, { 22528, 28672, 34816 }, { 4096, 36864, 43008 }, { 64512, 35840, 39936 } }, { 32768, 32768, 32768, 40960, 32768, 32768, 32768, 32768, 40960, 32768, 32768, 32768, 24576, 32768, 32768, 32768 } }, + { { { 50176, 49152, 47104 }, { 55296, 38912, 4096 }, { 18432, 27648, 20480 }, { 57344, 35840, 26624 } }, { 49152, 49152, 16384, 8192, 49152, 57344, 49152, 49152, 49152, 24576, 49152, 49152, 57344, 49152, 49152, 49152 } }, + { { { 49664, 47616, 44544 }, { 52224, 38912, 44032 }, { 25600, 27648, 62464 }, { 29696, 34816, 37888 } }, { 40960, 24576, 40960, 16384, 49152, 0, 57344, 8192, 40960, 49152, 49152, 49152, 49152, 49152, 40960, 40960 } }, + { { { 50688, 49664, 49152 }, { 17408, 26624, 20480 }, { 15360, 18432, 20480 }, { 29696, 33792, 27648 } }, { 57344, 49152, 0, 8192, 57344, 8192, 0, 0, 40960, 49152, 0, 49152, 16384, 49152, 57344, 40960 } }, + { { { 53248, 52736, 51200 }, { 19456, 21504, 17408 }, { 29696, 34816, 35840 }, { 18432, 20480, 24576 } }, { 32768, 40960, 8192, 24576, 40960, 49152, 57344, 0, 40960, 0, 49152, 49152, 49152, 16384, 49152, 40960 } }, + { { { 53760, 52736, 50176 }, { 21504, 23552, 25600 }, { 45056, 41984, 44032 }, { 20480, 28672, 34816 } }, { 40960, 40960, 49152, 49152, 40960, 49152, 49152, 57344, 49152, 49152, 57344, 16384, 16384, 57344, 49152, 16384 } }, + { { { 51712, 52224, 48640 }, { 13312, 20480, 18432 }, { 34816, 29696, 36864 }, { 25600, 20480, 24576 } }, { 32768, 40960, 0, 16384, 32768, 40960, 49152, 0, 32768, 32768, 40960, 49152, 32768, 32768, 32768, 40960 } }, + { { { 45056, 40960, 38400 }, { 0, 38912, 45056 }, { 29696, 37888, 36864 }, { 12288, 26624, 45056 } }, { 32768, 24576, 49152, 40960, 49152, 0, 40960, 40960, 8192, 49152, 32768, 40960, 16384, 40960, 40960, 40960 } }, +}; + +inline constexpr uint8_t BC6_ENDPOINT_BITS[15][4] = { + { 0, 0, 0, 0 }, + { 10, 5, 5, 5 }, + { 7, 6, 6, 6 }, + { 11, 5, 4, 4 }, + { 11, 4, 5, 4 }, + { 11, 4, 4, 5 }, + { 9, 5, 5, 5 }, + { 8, 6, 5, 5 }, + { 8, 5, 6, 5 }, + { 8, 5, 5, 6 }, + { 6, 6, 6, 6 }, + { 10, 10, 10, 10 }, + { 11, 9, 9, 9 }, + { 12, 8, 8, 8 }, + { 16, 4, 4, 4 }, +}; + +// 0 = mode bit, 1 = partition bit; 2 + 3 * endpoint + channel = endpoint bit. +inline constexpr Bc6WireBit BC6_WIRE[14][82] = { + { // Mode 1 + { 0, 0 }, { 0, 1 }, { 9, 4 }, { 10, 4 }, { 13, 4 }, { 2, 0 }, { 2, 1 }, { 2, 2 }, { 2, 3 }, { 2, 4 }, + { 2, 5 }, { 2, 6 }, { 2, 7 }, { 2, 8 }, { 2, 9 }, { 3, 0 }, { 3, 1 }, { 3, 2 }, { 3, 3 }, { 3, 4 }, + { 3, 5 }, { 3, 6 }, { 3, 7 }, { 3, 8 }, { 3, 9 }, { 4, 0 }, { 4, 1 }, { 4, 2 }, { 4, 3 }, { 4, 4 }, + { 4, 5 }, { 4, 6 }, { 4, 7 }, { 4, 8 }, { 4, 9 }, { 5, 0 }, { 5, 1 }, { 5, 2 }, { 5, 3 }, { 5, 4 }, + { 12, 4 }, { 9, 0 }, { 9, 1 }, { 9, 2 }, { 9, 3 }, { 6, 0 }, { 6, 1 }, { 6, 2 }, { 6, 3 }, { 6, 4 }, + { 13, 0 }, { 12, 0 }, { 12, 1 }, { 12, 2 }, { 12, 3 }, { 7, 0 }, { 7, 1 }, { 7, 2 }, { 7, 3 }, { 7, 4 }, + { 13, 1 }, { 10, 0 }, { 10, 1 }, { 10, 2 }, { 10, 3 }, { 8, 0 }, { 8, 1 }, { 8, 2 }, { 8, 3 }, { 8, 4 }, + { 13, 2 }, { 11, 0 }, { 11, 1 }, { 11, 2 }, { 11, 3 }, { 11, 4 }, { 13, 3 }, { 1, 0 }, { 1, 1 }, { 1, 2 }, + { 1, 3 }, { 1, 4 }, + }, + { // Mode 2 + { 0, 0 }, { 0, 1 }, { 9, 5 }, { 12, 4 }, { 12, 5 }, { 2, 0 }, { 2, 1 }, { 2, 2 }, { 2, 3 }, { 2, 4 }, + { 2, 5 }, { 2, 6 }, { 13, 0 }, { 13, 1 }, { 10, 4 }, { 3, 0 }, { 3, 1 }, { 3, 2 }, { 3, 3 }, { 3, 4 }, + { 3, 5 }, { 3, 6 }, { 10, 5 }, { 13, 2 }, { 9, 4 }, { 4, 0 }, { 4, 1 }, { 4, 2 }, { 4, 3 }, { 4, 4 }, + { 4, 5 }, { 4, 6 }, { 13, 3 }, { 13, 5 }, { 13, 4 }, { 5, 0 }, { 5, 1 }, { 5, 2 }, { 5, 3 }, { 5, 4 }, + { 5, 5 }, { 9, 0 }, { 9, 1 }, { 9, 2 }, { 9, 3 }, { 6, 0 }, { 6, 1 }, { 6, 2 }, { 6, 3 }, { 6, 4 }, + { 6, 5 }, { 12, 0 }, { 12, 1 }, { 12, 2 }, { 12, 3 }, { 7, 0 }, { 7, 1 }, { 7, 2 }, { 7, 3 }, { 7, 4 }, + { 7, 5 }, { 10, 0 }, { 10, 1 }, { 10, 2 }, { 10, 3 }, { 8, 0 }, { 8, 1 }, { 8, 2 }, { 8, 3 }, { 8, 4 }, + { 8, 5 }, { 11, 0 }, { 11, 1 }, { 11, 2 }, { 11, 3 }, { 11, 4 }, { 11, 5 }, { 1, 0 }, { 1, 1 }, { 1, 2 }, + { 1, 3 }, { 1, 4 }, + }, + { // Mode 3 + { 0, 0 }, { 0, 1 }, { 0, 2 }, { 0, 3 }, { 0, 4 }, { 2, 0 }, { 2, 1 }, { 2, 2 }, { 2, 3 }, { 2, 4 }, + { 2, 5 }, { 2, 6 }, { 2, 7 }, { 2, 8 }, { 2, 9 }, { 3, 0 }, { 3, 1 }, { 3, 2 }, { 3, 3 }, { 3, 4 }, + { 3, 5 }, { 3, 6 }, { 3, 7 }, { 3, 8 }, { 3, 9 }, { 4, 0 }, { 4, 1 }, { 4, 2 }, { 4, 3 }, { 4, 4 }, + { 4, 5 }, { 4, 6 }, { 4, 7 }, { 4, 8 }, { 4, 9 }, { 5, 0 }, { 5, 1 }, { 5, 2 }, { 5, 3 }, { 5, 4 }, + { 2, 10 }, { 9, 0 }, { 9, 1 }, { 9, 2 }, { 9, 3 }, { 6, 0 }, { 6, 1 }, { 6, 2 }, { 6, 3 }, { 3, 10 }, + { 13, 0 }, { 12, 0 }, { 12, 1 }, { 12, 2 }, { 12, 3 }, { 7, 0 }, { 7, 1 }, { 7, 2 }, { 7, 3 }, { 4, 10 }, + { 13, 1 }, { 10, 0 }, { 10, 1 }, { 10, 2 }, { 10, 3 }, { 8, 0 }, { 8, 1 }, { 8, 2 }, { 8, 3 }, { 8, 4 }, + { 13, 2 }, { 11, 0 }, { 11, 1 }, { 11, 2 }, { 11, 3 }, { 11, 4 }, { 13, 3 }, { 1, 0 }, { 1, 1 }, { 1, 2 }, + { 1, 3 }, { 1, 4 }, + }, + { // Mode 4 + { 0, 0 }, { 0, 1 }, { 0, 2 }, { 0, 3 }, { 0, 4 }, { 2, 0 }, { 2, 1 }, { 2, 2 }, { 2, 3 }, { 2, 4 }, + { 2, 5 }, { 2, 6 }, { 2, 7 }, { 2, 8 }, { 2, 9 }, { 3, 0 }, { 3, 1 }, { 3, 2 }, { 3, 3 }, { 3, 4 }, + { 3, 5 }, { 3, 6 }, { 3, 7 }, { 3, 8 }, { 3, 9 }, { 4, 0 }, { 4, 1 }, { 4, 2 }, { 4, 3 }, { 4, 4 }, + { 4, 5 }, { 4, 6 }, { 4, 7 }, { 4, 8 }, { 4, 9 }, { 5, 0 }, { 5, 1 }, { 5, 2 }, { 5, 3 }, { 2, 10 }, + { 12, 4 }, { 9, 0 }, { 9, 1 }, { 9, 2 }, { 9, 3 }, { 6, 0 }, { 6, 1 }, { 6, 2 }, { 6, 3 }, { 6, 4 }, + { 3, 10 }, { 12, 0 }, { 12, 1 }, { 12, 2 }, { 12, 3 }, { 7, 0 }, { 7, 1 }, { 7, 2 }, { 7, 3 }, { 4, 10 }, + { 13, 1 }, { 10, 0 }, { 10, 1 }, { 10, 2 }, { 10, 3 }, { 8, 0 }, { 8, 1 }, { 8, 2 }, { 8, 3 }, { 13, 0 }, + { 13, 2 }, { 11, 0 }, { 11, 1 }, { 11, 2 }, { 11, 3 }, { 9, 4 }, { 13, 3 }, { 1, 0 }, { 1, 1 }, { 1, 2 }, + { 1, 3 }, { 1, 4 }, + }, + { // Mode 5 + { 0, 0 }, { 0, 1 }, { 0, 2 }, { 0, 3 }, { 0, 4 }, { 2, 0 }, { 2, 1 }, { 2, 2 }, { 2, 3 }, { 2, 4 }, + { 2, 5 }, { 2, 6 }, { 2, 7 }, { 2, 8 }, { 2, 9 }, { 3, 0 }, { 3, 1 }, { 3, 2 }, { 3, 3 }, { 3, 4 }, + { 3, 5 }, { 3, 6 }, { 3, 7 }, { 3, 8 }, { 3, 9 }, { 4, 0 }, { 4, 1 }, { 4, 2 }, { 4, 3 }, { 4, 4 }, + { 4, 5 }, { 4, 6 }, { 4, 7 }, { 4, 8 }, { 4, 9 }, { 5, 0 }, { 5, 1 }, { 5, 2 }, { 5, 3 }, { 2, 10 }, + { 10, 4 }, { 9, 0 }, { 9, 1 }, { 9, 2 }, { 9, 3 }, { 6, 0 }, { 6, 1 }, { 6, 2 }, { 6, 3 }, { 3, 10 }, + { 13, 0 }, { 12, 0 }, { 12, 1 }, { 12, 2 }, { 12, 3 }, { 7, 0 }, { 7, 1 }, { 7, 2 }, { 7, 3 }, { 7, 4 }, + { 4, 10 }, { 10, 0 }, { 10, 1 }, { 10, 2 }, { 10, 3 }, { 8, 0 }, { 8, 1 }, { 8, 2 }, { 8, 3 }, { 13, 1 }, + { 13, 2 }, { 11, 0 }, { 11, 1 }, { 11, 2 }, { 11, 3 }, { 13, 4 }, { 13, 3 }, { 1, 0 }, { 1, 1 }, { 1, 2 }, + { 1, 3 }, { 1, 4 }, + }, + { // Mode 6 + { 0, 0 }, { 0, 1 }, { 0, 2 }, { 0, 3 }, { 0, 4 }, { 2, 0 }, { 2, 1 }, { 2, 2 }, { 2, 3 }, { 2, 4 }, + { 2, 5 }, { 2, 6 }, { 2, 7 }, { 2, 8 }, { 10, 4 }, { 3, 0 }, { 3, 1 }, { 3, 2 }, { 3, 3 }, { 3, 4 }, + { 3, 5 }, { 3, 6 }, { 3, 7 }, { 3, 8 }, { 9, 4 }, { 4, 0 }, { 4, 1 }, { 4, 2 }, { 4, 3 }, { 4, 4 }, + { 4, 5 }, { 4, 6 }, { 4, 7 }, { 4, 8 }, { 13, 4 }, { 5, 0 }, { 5, 1 }, { 5, 2 }, { 5, 3 }, { 5, 4 }, + { 12, 4 }, { 9, 0 }, { 9, 1 }, { 9, 2 }, { 9, 3 }, { 6, 0 }, { 6, 1 }, { 6, 2 }, { 6, 3 }, { 6, 4 }, + { 13, 0 }, { 12, 0 }, { 12, 1 }, { 12, 2 }, { 12, 3 }, { 7, 0 }, { 7, 1 }, { 7, 2 }, { 7, 3 }, { 7, 4 }, + { 13, 1 }, { 10, 0 }, { 10, 1 }, { 10, 2 }, { 10, 3 }, { 8, 0 }, { 8, 1 }, { 8, 2 }, { 8, 3 }, { 8, 4 }, + { 13, 2 }, { 11, 0 }, { 11, 1 }, { 11, 2 }, { 11, 3 }, { 11, 4 }, { 13, 3 }, { 1, 0 }, { 1, 1 }, { 1, 2 }, + { 1, 3 }, { 1, 4 }, + }, + { // Mode 7 + { 0, 0 }, { 0, 1 }, { 0, 2 }, { 0, 3 }, { 0, 4 }, { 2, 0 }, { 2, 1 }, { 2, 2 }, { 2, 3 }, { 2, 4 }, + { 2, 5 }, { 2, 6 }, { 2, 7 }, { 12, 4 }, { 10, 4 }, { 3, 0 }, { 3, 1 }, { 3, 2 }, { 3, 3 }, { 3, 4 }, + { 3, 5 }, { 3, 6 }, { 3, 7 }, { 13, 2 }, { 9, 4 }, { 4, 0 }, { 4, 1 }, { 4, 2 }, { 4, 3 }, { 4, 4 }, + { 4, 5 }, { 4, 6 }, { 4, 7 }, { 13, 3 }, { 13, 4 }, { 5, 0 }, { 5, 1 }, { 5, 2 }, { 5, 3 }, { 5, 4 }, + { 5, 5 }, { 9, 0 }, { 9, 1 }, { 9, 2 }, { 9, 3 }, { 6, 0 }, { 6, 1 }, { 6, 2 }, { 6, 3 }, { 6, 4 }, + { 13, 0 }, { 12, 0 }, { 12, 1 }, { 12, 2 }, { 12, 3 }, { 7, 0 }, { 7, 1 }, { 7, 2 }, { 7, 3 }, { 7, 4 }, + { 13, 1 }, { 10, 0 }, { 10, 1 }, { 10, 2 }, { 10, 3 }, { 8, 0 }, { 8, 1 }, { 8, 2 }, { 8, 3 }, { 8, 4 }, + { 8, 5 }, { 11, 0 }, { 11, 1 }, { 11, 2 }, { 11, 3 }, { 11, 4 }, { 11, 5 }, { 1, 0 }, { 1, 1 }, { 1, 2 }, + { 1, 3 }, { 1, 4 }, + }, + { // Mode 8 + { 0, 0 }, { 0, 1 }, { 0, 2 }, { 0, 3 }, { 0, 4 }, { 2, 0 }, { 2, 1 }, { 2, 2 }, { 2, 3 }, { 2, 4 }, + { 2, 5 }, { 2, 6 }, { 2, 7 }, { 13, 0 }, { 10, 4 }, { 3, 0 }, { 3, 1 }, { 3, 2 }, { 3, 3 }, { 3, 4 }, + { 3, 5 }, { 3, 6 }, { 3, 7 }, { 9, 5 }, { 9, 4 }, { 4, 0 }, { 4, 1 }, { 4, 2 }, { 4, 3 }, { 4, 4 }, + { 4, 5 }, { 4, 6 }, { 4, 7 }, { 12, 5 }, { 13, 4 }, { 5, 0 }, { 5, 1 }, { 5, 2 }, { 5, 3 }, { 5, 4 }, + { 12, 4 }, { 9, 0 }, { 9, 1 }, { 9, 2 }, { 9, 3 }, { 6, 0 }, { 6, 1 }, { 6, 2 }, { 6, 3 }, { 6, 4 }, + { 6, 5 }, { 12, 0 }, { 12, 1 }, { 12, 2 }, { 12, 3 }, { 7, 0 }, { 7, 1 }, { 7, 2 }, { 7, 3 }, { 7, 4 }, + { 13, 1 }, { 10, 0 }, { 10, 1 }, { 10, 2 }, { 10, 3 }, { 8, 0 }, { 8, 1 }, { 8, 2 }, { 8, 3 }, { 8, 4 }, + { 13, 2 }, { 11, 0 }, { 11, 1 }, { 11, 2 }, { 11, 3 }, { 11, 4 }, { 13, 3 }, { 1, 0 }, { 1, 1 }, { 1, 2 }, + { 1, 3 }, { 1, 4 }, + }, + { // Mode 9 + { 0, 0 }, { 0, 1 }, { 0, 2 }, { 0, 3 }, { 0, 4 }, { 2, 0 }, { 2, 1 }, { 2, 2 }, { 2, 3 }, { 2, 4 }, + { 2, 5 }, { 2, 6 }, { 2, 7 }, { 13, 1 }, { 10, 4 }, { 3, 0 }, { 3, 1 }, { 3, 2 }, { 3, 3 }, { 3, 4 }, + { 3, 5 }, { 3, 6 }, { 3, 7 }, { 10, 5 }, { 9, 4 }, { 4, 0 }, { 4, 1 }, { 4, 2 }, { 4, 3 }, { 4, 4 }, + { 4, 5 }, { 4, 6 }, { 4, 7 }, { 13, 5 }, { 13, 4 }, { 5, 0 }, { 5, 1 }, { 5, 2 }, { 5, 3 }, { 5, 4 }, + { 12, 4 }, { 9, 0 }, { 9, 1 }, { 9, 2 }, { 9, 3 }, { 6, 0 }, { 6, 1 }, { 6, 2 }, { 6, 3 }, { 6, 4 }, + { 13, 0 }, { 12, 0 }, { 12, 1 }, { 12, 2 }, { 12, 3 }, { 7, 0 }, { 7, 1 }, { 7, 2 }, { 7, 3 }, { 7, 4 }, + { 7, 5 }, { 10, 0 }, { 10, 1 }, { 10, 2 }, { 10, 3 }, { 8, 0 }, { 8, 1 }, { 8, 2 }, { 8, 3 }, { 8, 4 }, + { 13, 2 }, { 11, 0 }, { 11, 1 }, { 11, 2 }, { 11, 3 }, { 11, 4 }, { 13, 3 }, { 1, 0 }, { 1, 1 }, { 1, 2 }, + { 1, 3 }, { 1, 4 }, + }, + { // Mode 10 + { 0, 0 }, { 0, 1 }, { 0, 2 }, { 0, 3 }, { 0, 4 }, { 2, 0 }, { 2, 1 }, { 2, 2 }, { 2, 3 }, { 2, 4 }, + { 2, 5 }, { 12, 4 }, { 13, 0 }, { 13, 1 }, { 10, 4 }, { 3, 0 }, { 3, 1 }, { 3, 2 }, { 3, 3 }, { 3, 4 }, + { 3, 5 }, { 9, 5 }, { 10, 5 }, { 13, 2 }, { 9, 4 }, { 4, 0 }, { 4, 1 }, { 4, 2 }, { 4, 3 }, { 4, 4 }, + { 4, 5 }, { 12, 5 }, { 13, 3 }, { 13, 5 }, { 13, 4 }, { 5, 0 }, { 5, 1 }, { 5, 2 }, { 5, 3 }, { 5, 4 }, + { 5, 5 }, { 9, 0 }, { 9, 1 }, { 9, 2 }, { 9, 3 }, { 6, 0 }, { 6, 1 }, { 6, 2 }, { 6, 3 }, { 6, 4 }, + { 6, 5 }, { 12, 0 }, { 12, 1 }, { 12, 2 }, { 12, 3 }, { 7, 0 }, { 7, 1 }, { 7, 2 }, { 7, 3 }, { 7, 4 }, + { 7, 5 }, { 10, 0 }, { 10, 1 }, { 10, 2 }, { 10, 3 }, { 8, 0 }, { 8, 1 }, { 8, 2 }, { 8, 3 }, { 8, 4 }, + { 8, 5 }, { 11, 0 }, { 11, 1 }, { 11, 2 }, { 11, 3 }, { 11, 4 }, { 11, 5 }, { 1, 0 }, { 1, 1 }, { 1, 2 }, + { 1, 3 }, { 1, 4 }, + }, + { // Mode 11 + { 0, 0 }, { 0, 1 }, { 0, 2 }, { 0, 3 }, { 0, 4 }, { 2, 0 }, { 2, 1 }, { 2, 2 }, { 2, 3 }, { 2, 4 }, + { 2, 5 }, { 2, 6 }, { 2, 7 }, { 2, 8 }, { 2, 9 }, { 3, 0 }, { 3, 1 }, { 3, 2 }, { 3, 3 }, { 3, 4 }, + { 3, 5 }, { 3, 6 }, { 3, 7 }, { 3, 8 }, { 3, 9 }, { 4, 0 }, { 4, 1 }, { 4, 2 }, { 4, 3 }, { 4, 4 }, + { 4, 5 }, { 4, 6 }, { 4, 7 }, { 4, 8 }, { 4, 9 }, { 5, 0 }, { 5, 1 }, { 5, 2 }, { 5, 3 }, { 5, 4 }, + { 5, 5 }, { 5, 6 }, { 5, 7 }, { 5, 8 }, { 5, 9 }, { 6, 0 }, { 6, 1 }, { 6, 2 }, { 6, 3 }, { 6, 4 }, + { 6, 5 }, { 6, 6 }, { 6, 7 }, { 6, 8 }, { 6, 9 }, { 7, 0 }, { 7, 1 }, { 7, 2 }, { 7, 3 }, { 7, 4 }, + { 7, 5 }, { 7, 6 }, { 7, 7 }, { 7, 8 }, { 7, 9 }, + }, + { // Mode 12 + { 0, 0 }, { 0, 1 }, { 0, 2 }, { 0, 3 }, { 0, 4 }, { 2, 0 }, { 2, 1 }, { 2, 2 }, { 2, 3 }, { 2, 4 }, + { 2, 5 }, { 2, 6 }, { 2, 7 }, { 2, 8 }, { 2, 9 }, { 3, 0 }, { 3, 1 }, { 3, 2 }, { 3, 3 }, { 3, 4 }, + { 3, 5 }, { 3, 6 }, { 3, 7 }, { 3, 8 }, { 3, 9 }, { 4, 0 }, { 4, 1 }, { 4, 2 }, { 4, 3 }, { 4, 4 }, + { 4, 5 }, { 4, 6 }, { 4, 7 }, { 4, 8 }, { 4, 9 }, { 5, 0 }, { 5, 1 }, { 5, 2 }, { 5, 3 }, { 5, 4 }, + { 5, 5 }, { 5, 6 }, { 5, 7 }, { 5, 8 }, { 2, 10 }, { 6, 0 }, { 6, 1 }, { 6, 2 }, { 6, 3 }, { 6, 4 }, + { 6, 5 }, { 6, 6 }, { 6, 7 }, { 6, 8 }, { 3, 10 }, { 7, 0 }, { 7, 1 }, { 7, 2 }, { 7, 3 }, { 7, 4 }, + { 7, 5 }, { 7, 6 }, { 7, 7 }, { 7, 8 }, { 4, 10 }, + }, + { // Mode 13 + { 0, 0 }, { 0, 1 }, { 0, 2 }, { 0, 3 }, { 0, 4 }, { 2, 0 }, { 2, 1 }, { 2, 2 }, { 2, 3 }, { 2, 4 }, + { 2, 5 }, { 2, 6 }, { 2, 7 }, { 2, 8 }, { 2, 9 }, { 3, 0 }, { 3, 1 }, { 3, 2 }, { 3, 3 }, { 3, 4 }, + { 3, 5 }, { 3, 6 }, { 3, 7 }, { 3, 8 }, { 3, 9 }, { 4, 0 }, { 4, 1 }, { 4, 2 }, { 4, 3 }, { 4, 4 }, + { 4, 5 }, { 4, 6 }, { 4, 7 }, { 4, 8 }, { 4, 9 }, { 5, 0 }, { 5, 1 }, { 5, 2 }, { 5, 3 }, { 5, 4 }, + { 5, 5 }, { 5, 6 }, { 5, 7 }, { 2, 10 }, { 2, 11 }, { 6, 0 }, { 6, 1 }, { 6, 2 }, { 6, 3 }, { 6, 4 }, + { 6, 5 }, { 6, 6 }, { 6, 7 }, { 3, 10 }, { 3, 11 }, { 7, 0 }, { 7, 1 }, { 7, 2 }, { 7, 3 }, { 7, 4 }, + { 7, 5 }, { 7, 6 }, { 7, 7 }, { 4, 10 }, { 4, 11 }, + }, + { // Mode 14 + { 0, 0 }, { 0, 1 }, { 0, 2 }, { 0, 3 }, { 0, 4 }, { 2, 0 }, { 2, 1 }, { 2, 2 }, { 2, 3 }, { 2, 4 }, + { 2, 5 }, { 2, 6 }, { 2, 7 }, { 2, 8 }, { 2, 9 }, { 3, 0 }, { 3, 1 }, { 3, 2 }, { 3, 3 }, { 3, 4 }, + { 3, 5 }, { 3, 6 }, { 3, 7 }, { 3, 8 }, { 3, 9 }, { 4, 0 }, { 4, 1 }, { 4, 2 }, { 4, 3 }, { 4, 4 }, + { 4, 5 }, { 4, 6 }, { 4, 7 }, { 4, 8 }, { 4, 9 }, { 5, 0 }, { 5, 1 }, { 5, 2 }, { 5, 3 }, { 2, 10 }, + { 2, 11 }, { 2, 12 }, { 2, 13 }, { 2, 14 }, { 2, 15 }, { 6, 0 }, { 6, 1 }, { 6, 2 }, { 6, 3 }, { 3, 10 }, + { 3, 11 }, { 3, 12 }, { 3, 13 }, { 3, 14 }, { 3, 15 }, { 7, 0 }, { 7, 1 }, { 7, 2 }, { 7, 3 }, { 4, 10 }, + { 4, 11 }, { 4, 12 }, { 4, 13 }, { 4, 14 }, { 4, 15 }, + }, +}; diff --git a/src/startup_stubs/command_list_slot_names.h b/src/startup_stubs/command_list_slot_names.h index 472ef63155..4900e6d6de 100644 --- a/src/startup_stubs/command_list_slot_names.h +++ b/src/startup_stubs/command_list_slot_names.h @@ -2,25 +2,24 @@ // `x2w-noop` log so a line reads "CommandList::slot14(Dispatch)" instead of "CommandList::slot14". // Plain standard C++ with no Windows types, so the table can be compiled and tested on its own. // -// What is claimed, and why: -// - Slots 0 to 9 and 12 to 25 follow the public desktop ID3D12GraphicsCommandList order. The -// implemented slots agree with it at both ends of every run: 7 (GetDevice), 9 (Close), 12 and 13 -// (the draws), 20 to 23 (topology, viewports, scissors, blend factor) and 25 (pipeline state), so -// the slots between them (0 to 6, 8, 14 to 19, 24) take the desktop names. -// - Slots 10 and 11 are not named. The desktop order puts Reset and ClearState there, but this -// console list resets through slot 139, so the desktop order is not known to hold at 10 and 11. -// - Slot 26 accepts the UAV form of ResourceBarrier. Slots 27 to 31 are not named here. The slots -// that follow are the desktop ones moved up by four -// (32 is SetDescriptorHeaps, desktop 28), so four console methods sit somewhere in 26 to 31. -// As a hypothesis, d3d12_xs_device.cpp binds 28, 29 and 30 as BeginQuery, EndQuery and -// ResolveQueryData, only with the diagnostic X2W_D3D12_QUERY_SLOTS=1. No fixture here establishes -// which console methods sit there. -// - Slots 32 to 59 are named as the desktop slots 28 to 55 plus four. Implemented and checked -// against the desktop order: 32, 34, 36, 40, 42, 44, 47, 48, 50 and 52. Past 52 the rule is not -// checked: ExecuteIndirect (desktop 59) is at 61, desktop plus two, so the run of four has ended -// by then. The 56 to 58 names below are kept as the rule gives them. -// - Slots 61 (ExecuteIndirect) and 139 (Reset) are implemented in d3d12_xs_device.cpp. -// - Other slots have no confirmed meaning. +// The 0 to 61, 139 and 148 rows were checked against the GXDK 261000 +// ID3D12GraphicsCommandList8 function table through a local oracle outside the repository. The +// header itself is not copied into this repository; only the public desktop method names and the +// slot numbers are recorded. +// - Slots 0 to 8 are IUnknown, ID3D12Object and ID3D12DeviceChild. +// - 9 Close, 10 Reset and 11 ClearState. +// - 12 to 27 follow the desktop ID3D12GraphicsCommandList order through ExecuteBundle. +// - 28 to 31 are BeginQuery, EndQuery, ResolveQueryData and SetPredication. They sit before the +// desktop SetDescriptorHeaps rather than after DiscardResource. +// - 32 to 55 are the desktop slots 28 to 51 plus four: SetDescriptorHeaps through DiscardResource. +// - 56 to 58 are the unshifted desktop SetMarker, BeginEvent and EndEvent. +// - 59 and 60 are console-only marker methods and stay unnamed in this repository. +// - 61 is ExecuteIndirect (desktop 59, plus two). +// - 139 is the console reset path the title calls. The base Reset is at 10; the log calls the +// console path "Reset (console)" so both rows have distinct names. +// - 62 to 138 and 140 and above are console-only methods. They stay unnamed because their names +// and signatures are not needed by the current log. Slot 148 is the allocation path used by +// list_allocate_upload; it stays unnamed here for the same reason. #pragma once #include <cstddef> @@ -48,7 +47,9 @@ static_assert(desktop_method_count == 51, "ID3D12GraphicsCommandList has 51 meth inline constexpr int console_shift = 4; // console slot = desktop slot + 4, from SetDescriptorHeaps on inline constexpr int resource_barrier_slot = 26; inline constexpr int first_shifted_slot = 32; -inline constexpr int last_shifted_slot = 59; +inline constexpr int last_shifted_slot = 55; +inline constexpr int first_desktop_marker_slot = 56; +inline constexpr int last_desktop_marker_slot = 58; inline constexpr int execute_indirect_slot = 61; inline constexpr int reset_slot = 139; @@ -58,11 +59,14 @@ inline const char* name(int slot) noexcept const auto desktop = [](int index) { return desktop_names[index - first_desktop_method]; }; static constexpr const char* iunknown[] = {"QueryInterface", "AddRef", "Release", "GetPrivateData", "SetPrivateData", "SetPrivateDataInterface", "SetName", "GetDevice", "GetType"}; + static constexpr const char* query[] = {"BeginQuery", "EndQuery", "ResolveQueryData", "SetPredication"}; if (slot >= 0 && slot < first_desktop_method) return iunknown[slot]; - if (slot == first_desktop_method || (slot >= 12 && slot <= resource_barrier_slot)) return desktop(slot); + if (slot >= first_desktop_method && slot <= 27) return desktop(slot); + if (slot >= 28 && slot <= 31) return query[slot - 28]; if (slot >= first_shifted_slot && slot <= last_shifted_slot) return desktop(slot - console_shift); + if (slot >= first_desktop_marker_slot && slot <= last_desktop_marker_slot) return desktop(slot); if (slot == execute_indirect_slot) return "ExecuteIndirect"; - if (slot == reset_slot) return "Reset"; + if (slot == reset_slot) return "Reset (console)"; return nullptr; } diff --git a/src/startup_stubs/d3d12_compute_dispatch.inl b/src/startup_stubs/d3d12_compute_dispatch.inl index e2a665dbf1..a5b384dd3a 100644 --- a/src/startup_stubs/d3d12_compute_dispatch.inl +++ b/src/startup_stubs/d3d12_compute_dispatch.inl @@ -2,8 +2,9 @@ // the key of its published request; gfx2hlsl.py --pending answers the request with <key>.txt (`stage cs`) and // <key>.cs.cso. Bound from the compute tables recorded by slot 35 and compute root SRVs recorded by slot 43: raw // buffers (`srv <i> buf table <param> <byte>` and `srv <i> buf root <param>` inputs, `uav <i> table <param> <byte>` -// outputs) named by hardware buffer descriptors or 64-bit root SRV addresses, and textures -// (`srv <i> tex2d table <param> <byte>` inputs, `uav <i> tex1d/tex2d/tex2da/tex3d float table <param> <byte> channels 4` outputs) named +// outputs, or `uav <i> bufhalf table <param> <byte> bytes <stride>` for typed half stores) +// named by hardware buffer descriptors or 64-bit root SRV addresses, and textures +// (`srv <i> tex1d|tex2d|tex2da|tex3d table <param> <byte>` inputs, `uav <i> tex1d/tex2d/tex2da/tex3d float table <param> <byte> channels <n>` outputs) named // by the token of a view the title created (device slots 18 and 19). `smp`, `smpl` and `smpc` lines become static samplers. Entry // values come from the compute root constants of slots 37 and 39, or from the descriptor a buffer input or output is // bound from: its stride and word 3 (`stride`, `descword3`), and word 3, the upper half of word 1 and the record @@ -36,17 +37,22 @@ struct ComputeTranslation { D3D12_UAV_DIMENSION uav_dimension = D3D12_UAV_DIMENSION_UNKNOWN; bool root = false; bool atomic_uint_texture = false; + unsigned channels = 4; + D3D12_SRV_DIMENSION srv_dimension = D3D12_SRV_DIMENSION_UNKNOWN; + unsigned half_buffer_bytes = 0; }; u64 key = 0; int state = 0; // 0 not loaded, 1 ready, 2 unavailable - x2w_startup::ManifestRetry manifest_retry; // only an absent manifest can become ready later + x2w_startup::ManifestRetry manifest_retry; // absent and stale manifests can become ready later std::vector<Slot> uds, srvs, uavs; + UINT heap_srvs = 0; x2w_startup::TranslatedSamplers samplers; // static ones only x2w_startup::ComPtr<ID3D12RootSignature> root; x2w_startup::ComPtr<ID3D12PipelineState> pipeline; const char* unmodelled = nullptr; // why a manifest that exists cannot be used u64 dispatches = 0, translated = 0; // census: Dispatch calls with this key bound, and those recorded const char* first_refusal = nullptr; // reason of the first refused call + bool input_path_logged = false; // the first time a placed input came from a GPU copy or a title snapshot std::uint32_t refusal_words[4] = {}; // the table descriptor that reason was about, if any; a view token's // last word is replaced by its view format | dimension << 16 ~ComputeTranslation() @@ -60,23 +66,39 @@ struct ComputeTranslation { } }; -// Formats a `float` typed output may be viewed with: the program stores float4. -bool float_output_format(DXGI_FORMAT format) +// Component counts of the float and normalized formats accepted for typed outputs. +unsigned float_output_channels(DXGI_FORMAT format) { switch (format) { case DXGI_FORMAT_R32G32B32A32_FLOAT: case DXGI_FORMAT_R16G16B16A16_FLOAT: case DXGI_FORMAT_R16G16B16A16_UNORM: - case DXGI_FORMAT_R16G16B16A16_SNORM: case DXGI_FORMAT_R32G32_FLOAT: case DXGI_FORMAT_R10G10B10A2_UNORM: - case DXGI_FORMAT_R11G11B10_FLOAT: case DXGI_FORMAT_R8G8B8A8_UNORM: case DXGI_FORMAT_R8G8B8A8_SNORM: - case DXGI_FORMAT_R16G16_FLOAT: case DXGI_FORMAT_R16G16_UNORM: case DXGI_FORMAT_R16G16_SNORM: case DXGI_FORMAT_R32_FLOAT: - case DXGI_FORMAT_R8G8_UNORM: case DXGI_FORMAT_R8G8_SNORM: case DXGI_FORMAT_R16_FLOAT: case DXGI_FORMAT_R16_UNORM: - case DXGI_FORMAT_R16_SNORM: case DXGI_FORMAT_R8_UNORM: case DXGI_FORMAT_R8_SNORM: case DXGI_FORMAT_B8G8R8A8_UNORM: - return true; + case DXGI_FORMAT_R16G16B16A16_SNORM: case DXGI_FORMAT_R10G10B10A2_UNORM: + case DXGI_FORMAT_R8G8B8A8_UNORM: case DXGI_FORMAT_R8G8B8A8_SNORM: case DXGI_FORMAT_B8G8R8A8_UNORM: + return 4; + case DXGI_FORMAT_R11G11B10_FLOAT: + return 3; + case DXGI_FORMAT_R32G32_FLOAT: case DXGI_FORMAT_R16G16_FLOAT: case DXGI_FORMAT_R16G16_UNORM: + case DXGI_FORMAT_R16G16_SNORM: case DXGI_FORMAT_R8G8_UNORM: case DXGI_FORMAT_R8G8_SNORM: + return 2; + case DXGI_FORMAT_R32_FLOAT: case DXGI_FORMAT_R16_FLOAT: case DXGI_FORMAT_R16_UNORM: + case DXGI_FORMAT_R16_SNORM: case DXGI_FORMAT_R8_UNORM: case DXGI_FORMAT_R8_SNORM: + return 1; default: - return false; + return 0; } } + +bool half_buffer_descriptor_matches(const std::uint32_t* words, unsigned bytes) +{ + // gfx10 V# with identity selectors for each stored component and structured + // bounds (OOB_SELECT=0). Swizzled or padded records need a different view. + const unsigned format = bytes == 2 ? 13 : bytes == 4 ? 29 : 71; + const unsigned selectors = (1u << (3 * (bytes / 2))) - 1; + return (words[1] >> 16) == bytes && (words[3] & (0xfffff000u | selectors)) == + (0x01000000u | (format << 12) | (0xfacu & selectors)); +} std::unordered_map<u64, ComputeTranslation>& compute_translations() { static std::unordered_map<u64, ComputeTranslation> m; return m; } LONG compute_dispatches_translated, compute_dispatches_refused, compute_dispatches_untranslated, compute_dispatches_unmodelled; +LONG compute_inputs_gpu_copied, compute_inputs_snapshot, compute_inputs_snapshot_kib; // inputs by path: this list's GPU copy, a title snapshot // The root signature and pipeline of a translation whose entry values and views are filled in. Returns why it is // unavailable, or null when it is ready. @@ -84,7 +106,7 @@ const char* create_compute_pipeline(ComputeTranslation& tr, const void* code, st { // Parameter 0 keeps one constant for a program without entry values: a constants parameter cannot be empty. if (FAILED(x2w_startup::create_translated_root(device_of(the_device), static_cast<UINT>(tr.uds.empty() ? 1 : tr.uds.size()), - static_cast<UINT>(tr.srvs.size()), tr.samplers, &tr.root, static_cast<UINT>(tr.uavs.size())))) + static_cast<UINT>(tr.srvs.size()), tr.samplers, &tr.root, static_cast<UINT>(tr.uavs.size()), tr.heap_srvs))) return "root signature creation failed"; D3D12_COMPUTE_PIPELINE_STATE_DESC desc{}; desc.pRootSignature = tr.root.Get(); @@ -105,6 +127,21 @@ const char* load_compute_translation(ComputeTranslation& tr) tr.manifest_retry.missed(GetTickCount64()); return nullptr; } + // A native manifest from another compiler revision, or an unmarked one without the Python translator's + // <key>.cs.hlsl, is stale: it is looked for again on the same schedule as an absent one. + const auto output = x2w::native_compute_output(manifest); + if (output == x2w::NativeComputeOutput::incompatible) { + tr.manifest_retry.missed(GetTickCount64()); + return "native translation from another compiler revision; rebuild it"; + } + if (output == x2w::NativeComputeOutput::unmarked) { + const DWORD attributes = cache_path(path, L"", tr.key, L".cs.hlsl") + ? GetFileAttributesW(path) : INVALID_FILE_ATTRIBUTES; + if (attributes == INVALID_FILE_ATTRIBUTES || (attributes & FILE_ATTRIBUTE_DIRECTORY)) { + tr.manifest_retry.missed(GetTickCount64()); + return "native translation without a revision; rebuild it"; + } + } tr.manifest_retry.found(); unsigned declared_uds = 0, line_number = 0; for (std::size_t at = 0; at < manifest.size(); ++line_number) { @@ -121,6 +158,7 @@ const char* load_compute_translation(ComputeTranslation& tr) if (line != "stage cs") return "not a compute manifest"; continue; } + if (line.compare(0, 7, "native ") == 0) continue; unsigned i = 0, x = 0, y = 0, z = 0, w = 0; int a = 0, b = 0, c = 0, d = 0, used = 0; char name[16] = ""; @@ -139,6 +177,13 @@ const char* load_compute_translation(ComputeTranslation& tr) if (!std::strcmp(name, "tex3d")) return D3D12_UAV_DIMENSION_TEXTURE3D; return D3D12_UAV_DIMENSION_UNKNOWN; }; + const auto srv_dimension = [&] { + if (!std::strcmp(name, "tex1d")) return D3D12_SRV_DIMENSION_TEXTURE1D; + if (!std::strcmp(name, "tex2d")) return D3D12_SRV_DIMENSION_TEXTURE2D; + if (!std::strcmp(name, "tex2da")) return D3D12_SRV_DIMENSION_TEXTURE2DARRAY; + if (!std::strcmp(name, "tex3d")) return D3D12_SRV_DIMENSION_TEXTURE3D; + return D3D12_SRV_DIMENSION_UNKNOWN; + }; if (line.empty() || (std::sscanf(line.c_str(), "group %u %u %u%n", &x, &y, &z, &used) == 3 && whole())) continue; if (std::sscanf(line.c_str(), "ud %u%n", &declared_uds, &used) == 1 && whole()) continue; if (std::sscanf(line.c_str(), "udsrc %u rootconst %d %d%n", &i, &a, &b, &used) == 3 && whole() && i == tr.uds.size()) @@ -164,19 +209,34 @@ const char* load_compute_translation(ComputeTranslation& tr) tr.srvs.push_back({c, d, false, true, a, b, x, y}); else if (std::sscanf(line.c_str(), "uav %u table %d %d%n", &i, &a, &b, &used) == 3 && whole() && i == tr.uavs.size()) tr.uavs.push_back({a, b}); + else if (std::sscanf(line.c_str(), "uav %u bufhalf table %d %d bytes %u%n", &i, &a, &b, &x, &used) == 4 && + whole() && i == tr.uavs.size() && x2w::native_half_buffer_format(x) != DXGI_FORMAT_UNKNOWN) { + tr.uavs.push_back({a, b}); + tr.uavs.back().half_buffer_bytes = x; + } else if (std::sscanf(line.c_str(), "uav %u tex2d uint table %d %d channels 1%n", &i, &a, &b, &used) == 3 && whole() && i == tr.uavs.size()) { tr.uavs.push_back({a, b, true}); tr.uavs.back().uav_dimension = D3D12_UAV_DIMENSION_TEXTURE2D; tr.uavs.back().atomic_uint_texture = true; } - else if (std::sscanf(line.c_str(), "uav %u %15s float table %d %d channels 4%n", &i, name, &a, &b, &used) == 4 && whole() && - i == tr.uavs.size() && uav_dimension() != D3D12_UAV_DIMENSION_UNKNOWN) { + else if (std::sscanf(line.c_str(), "uav %u %15s float table %d %d channels %u%n", &i, name, &a, &b, &x, &used) == 5 && + whole() && i == tr.uavs.size() && x >= 1 && x <= 4 && uav_dimension() != D3D12_UAV_DIMENSION_UNKNOWN && + (x == 4 || uav_dimension() != D3D12_UAV_DIMENSION_TEXTURE1D)) { tr.uavs.push_back({a, b, true}); tr.uavs.back().uav_dimension = uav_dimension(); + tr.uavs.back().channels = x; } - else if (std::sscanf(line.c_str(), "srv %u tex2d table %d %d%n", &i, &a, &b, &used) == 3 && whole() && i == tr.srvs.size()) + else if (std::sscanf(line.c_str(), "srv %u %15s table %d %d%n", &i, name, &a, &b, &used) == 4 && whole() && + i == tr.srvs.size() && srv_dimension() != D3D12_SRV_DIMENSION_UNKNOWN) { tr.srvs.push_back({a, b, true}); + tr.srvs.back().srv_dimension = srv_dimension(); + } + else if (std::sscanf(line.c_str(), "resheap %u %u%n", &x, &y, &used) == 2 && whole()) { + if (tr.heap_srvs || !x || x > x2w_startup::max_translated_resheap || y != x2w_startup::translated_resheap_space) + return "a resource heap range outside the supported layout"; + tr.heap_srvs = x; + } // A static sampler, decoded as the draw path does: plain (smp), with the descriptor's LOD clamp (smpl) or a // comparison one (smpc). Not modelled here: the run-time sampler heap table (smpheap). else if (line.rfind("smpheap", 0) == 0) return "a sampler from the sampler heap"; @@ -185,8 +245,8 @@ const char* load_compute_translation(ComputeTranslation& tr) std::sscanf(line.c_str(), "smpc %u %x %x %x %x%n", &i, &x, &y, &z, &w, &used) == 5) && whole() && i == tr.samplers.statics.size()) tr.samplers.read_manifest_line(line.c_str()); - else return line.rfind("srv", 0) == 0 ? "a resource that is not a raw table buffer or a 2D texture" - : line.rfind("uav", 0) == 0 ? "an output that is not a raw table buffer or a 1D/2D/2D-array/3D float texture" + else return line.rfind("srv", 0) == 0 ? "a resource that is not a raw table buffer or a 1D/2D/2D-array/3D texture" + : line.rfind("uav", 0) == 0 ? "an unsupported compute output view" : line.rfind("udsrc", 0) == 0 ? "an entry value that is not a root constant or a buffer descriptor word" : line.rfind("smp", 0) == 0 ? "a sampler that is not a plain static one" : "an unknown manifest line"; } @@ -209,7 +269,7 @@ const char* load_compute_translation(ComputeTranslation& tr) // X2W_NATIVE_SHADERS=<directory of dxcompiler.dll and dxil.dll>: the first Dispatch of a slot 67 request translates // it in this process with the C++ compiler (src/gfx1013_compute_native.cpp), before a published <key>.txt is read // and with no offline translator running. The dispatch path below binds the result, so a program is accepted only -// with root constants, raw table buffers it loads per lane (buffer_load_dword) and raw table buffers it stores to. +// with root constants, raw table buffers and exact-width typed texture outputs. // A refusal is logged and leaves the key to the published translations. draw_lock held. Returns whether tr is ready. bool translate_compute_natively(ComputeTranslation& tr) { @@ -225,17 +285,35 @@ bool translate_compute_natively(ComputeTranslation& tr) for (const auto& block : program.constants) for (unsigned word = 0; word < block.count; ++word) tr.uds.push_back({static_cast<int>(block.root_parameter), static_cast<int>(word)}); + for (unsigned srv : program.stride_srvs) { + const bool present = std::any_of(program.bindings.begin(), program.bindings.end(), [srv](const auto& view) { + return view.kind == x2w::ComputeViewKind::raw_vector_srv && view.shader_register == srv; + }); + if (!present) throw std::runtime_error("descriptor stride source is not a bound SRV"); + ComputeTranslation::Slot slot{}; + slot.a = static_cast<int>(srv); + slot.source = ComputeTranslation::input_stride; + tr.uds.push_back(slot); + } std::sort(program.bindings.begin(), program.bindings.end(), [](const auto& a, const auto& b) { return a.shader_register < b.shader_register; }); for (const auto& view : program.bindings) { - // The two kinds a fixture has run through this path: a raw buffer read per lane, and one written. - const bool output = view.kind == x2w::ComputeViewKind::raw_buffer_uav; + const unsigned channels = x2w::exact_texture_uav_channels(view.kind); + const bool output = channels || view.kind == x2w::ComputeViewKind::raw_buffer_uav; auto& slots = output ? tr.uavs : tr.srvs; if ((!output && view.kind != x2w::ComputeViewKind::raw_vector_srv) || view.array_count != 1 || view.root_parameter >= 16 || view.shader_register != slots.size()) throw std::runtime_error("view kind " + std::to_string(static_cast<unsigned>(view.kind)) + " is not bound for a natively translated program"); slots.push_back({static_cast<int>(view.root_parameter), static_cast<int>(view.byte_offset)}); + if (channels) { + auto& slot = slots.back(); + slot.texture = true; + slot.channels = channels; + slot.uav_dimension = view.image_dimension == 2 ? D3D12_UAV_DIMENSION_TEXTURE3D : + view.image_dimension == 5 ? D3D12_UAV_DIMENSION_TEXTURE2DARRAY : + D3D12_UAV_DIMENSION_TEXTURE2D; + } } if (!program.samplers.empty() || tr.uds.size() > 32 || tr.srvs.size() > 32 || tr.uavs.size() > 8) throw std::runtime_error("a sampler, or more entry values, inputs or outputs than the dispatch path binds"); @@ -355,11 +433,11 @@ const char* record_translated_dispatch(Wrapper* self, const TranslatedDispatch& union { D3D12_SHADER_RESOURCE_VIEW_DESC srv; D3D12_UNORDERED_ACCESS_VIEW_DESC uav; - } desc; // a texture view's description, as the title gave it with a desktop format + } desc; // a described desktop texture or typed buffer view Wrapper* wrapper; std::uint32_t words[4]; // a buffer's descriptor words as it was bound from, and its stride UINT stride; - } views[40]{}; + }; static_assert(sizeof(D3D12_SHADER_RESOURCE_VIEW_DESC) >= ViewRecord::srv_desc_bytes); static_assert(sizeof(D3D12_UNORDERED_ACCESS_VIEW_DESC) >= ViewRecord::uav_desc_bytes); const auto type = list->GetType(); @@ -393,6 +471,9 @@ const char* record_translated_dispatch(Wrapper* self, const TranslatedDispatch& if (tr->uds[i].source == ComputeTranslation::root_constant && !pass.compute_constants.is_bound(tr->uds[i].a, tr->uds[i].b, 1)) reason = "an entry value was not set since the compute root"; const std::size_t inputs = reason ? 0 : tr->srvs.size(), count = reason ? 0 : inputs + tr->uavs.size(); + std::vector<View> views(reason ? 0 : count + tr->heap_srvs); + if (!reason && dispatch.signature && tr->heap_srvs) + reason = "translated indirect Dispatch requires fixed-table raw buffers"; for (std::size_t i = 0; i < count && !reason; ++i) { const bool output = i >= inputs; const ComputeTranslation::Slot slot = output ? tr->uavs[i - inputs] : tr->srvs[i]; @@ -436,7 +517,8 @@ const char* record_translated_dispatch(Wrapper* self, const TranslatedDispatch& } // A heap record sits at the 32-bit byte offset the program computes, the index shifted left by 5, in the // title memory of the list's view heap: a literal byte offset, as a table's is. - const u64 entry = slot.heap ? (slot.word_param >= 0 || slot.a >= 0 ? pass.title_view_heap.record(std::uint32_t{index << 5}, 16) : 0) + const u64 entry = slot.heap ? ((slot.word_param >= 0 || slot.a >= 0) && index < pass.title_view_heap_entries + ? pass.title_view_heap.record(std::uint32_t{index << 5}, 16) : 0) : slot.a < 0 || slot.b < 0 ? 0 : pass.compute_tables.table(slot.a).record(static_cast<u64>(slot.b), slot.texture ? 32 : 16); const std::size_t entry_bytes = slot.texture ? 32 : 16; if (!entry || !x2w_local::readable(reinterpret_cast<const void*>(entry), entry_bytes)) { @@ -471,6 +553,21 @@ const char* record_translated_dispatch(Wrapper* self, const TranslatedDispatch& if (!known || record.slot != 18) reason = "an input texture entry is not the token of a shader resource view"; else if (!texture || (resource.Flags & D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE)) reason = "an input texture has no desktop texture to sample"; + else if (slot.srv_dimension != D3D12_SRV_DIMENSION_TEXTURE2D) { + // 1D, 2D array and 3D: only the title's own described view of that dimension, inside its texture. + const bool one = slot.srv_dimension == D3D12_SRV_DIMENSION_TEXTURE1D; + const bool array = slot.srv_dimension == D3D12_SRV_DIMENSION_TEXTURE2DARRAY; + if (!described) + reason = one ? "an input 1D texture has no recorded view description" + : array ? "an input 2D array texture has no recorded view description" + : "an input 3D texture has no recorded view description"; + else if (desc.ViewDimension != slot.srv_dimension) + reason = one ? "an input texture view is not 1D" : array ? "an input texture view is not 2D array" + : "an input texture view is not 3D"; + else if (!x2w_startup::address_view_fits(resource, desc)) + reason = "an input texture view does not fit its texture"; + else if (x2w_startup::packed_target_format(desc.Format)) reason = "an input texture view has a packed format"; + } else if (described ? desc.ViewDimension != D3D12_SRV_DIMENSION_TEXTURE2D : resource.Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE2D || resource.DepthOrArraySize != 1) reason = "an input texture view is not 2D"; @@ -524,7 +621,19 @@ const char* record_translated_dispatch(Wrapper* self, const TranslatedDispatch& if (!reason && x2w_startup::packed_target_format(format)) reason = "an output texture view has a packed format"; if (!reason && slot.atomic_uint_texture && format != DXGI_FORMAT_R32_UINT) reason = "an image atomic requires an R32_UINT UAV"; - if (!reason && !slot.atomic_uint_texture && !float_output_format(format)) + if (!reason && slot.channels < 4) { + if (float_output_channels(format) != slot.channels || float_output_channels(resource.Format) != slot.channels) + reason = "an exact-width image store requires a matching output texture channel count"; + else { + D3D12_FEATURE_DATA_FORMAT_SUPPORT support{resource.Format}; + if (FAILED(device_of(the_device)->CheckFeatureSupport(D3D12_FEATURE_FORMAT_SUPPORT, &support, + sizeof(support))) || + !(support.Support2 & D3D12_FORMAT_SUPPORT2_UAV_TYPED_STORE)) + reason = "an exact-width image store requires typed UAV store support"; + desc.Format = resource.Format; + } + } + if (!reason && !slot.atomic_uint_texture && !float_output_channels(format)) reason = "an output texture format is not a float or normalized one"; // One state per resource here: a texture read and written by the same call is refused. Two outputs // of one texture (two mips) share the unordered access state. @@ -537,7 +646,17 @@ const char* record_translated_dispatch(Wrapper* self, const TranslatedDispatch& } if (!output) { // Each condition of a complete GPU-backed buffer range has its own reason. - const IndirectBufferView view = indirect_table_buffer(self, words, false, &reason, 16u << 20); + const IndirectBufferView view = indirect_table_buffer(self, words, false, &reason, 16u << 20, true); + if (view.source == 1) InterlockedIncrement(&compute_inputs_gpu_copied); + if (view.source == 2) { + InterlockedIncrement(&compute_inputs_snapshot); + InterlockedExchangeAdd(&compute_inputs_snapshot_kib, static_cast<LONG>((view.bytes + 1023) / 1024)); + } + if (view.source && !tr->input_path_logged) { + tr->input_path_logged = true; + log("x2w-draw compute %016llx input %zu (%s %d %d) comes from %s (%llu bytes)", key, i, slot.heap ? "heap" : "table", slot.a, slot.b, + view.source == 1 ? "a GPU copy this list made" : view.source == 3 ? "zeros for a null descriptor" : "a snapshot of title memory", view.bytes); + } if (view.resource && view.offset % D3D12_RAW_UAV_SRV_BYTE_ALIGNMENT) reason = "an input buffer range is not 16-byte aligned in its resource"; if (reason && !tr->first_refusal) // once per key: which input, and where its descriptor was read log("x2w-draw compute %016llx first refused input %zu (%s %d %d), descriptor at 0x%llx", key, i, @@ -549,21 +668,73 @@ const char* record_translated_dispatch(Wrapper* self, const TranslatedDispatch& } // An output is written by the GPU: only a placed buffer that aliases the title's memory shows the result // to the title. shortcut: view tokens and copied placements are refused, add them with their first user. + // Each refused condition has its own reason. const u64 address = words[0] | (u64{words[1] & 0xffff} << 32); const UINT stride = (words[1] >> 16) & 0x3fff; + const unsigned half_bytes = slot.half_buffer_bytes; + const unsigned alignment = half_bytes ? half_bytes : D3D12_RAW_UAV_SRV_BYTE_ALIGNMENT; const u64 bytes = u64{stride ? stride : 1} * words[2]; - const auto placed = words[0] == view_token_magic || !bytes || bytes % 4 || bytes > (16u << 20) - ? PlacedVertexView{} : placed_buffer_range(self->own().list_device, address, bytes); + const bool sized = words[0] != view_token_magic && bytes && (half_bytes || bytes % 4 == 0) && bytes <= (16u << 20); + const auto placed = sized ? placed_buffer_range(self->own().list_device, address, bytes) : PlacedVertexView{}; const ResourceInfo* info = placed.alias ? resource_info(placed.owner) : nullptr; const u64 offset = placed.alias ? address - reinterpret_cast<u64>(placed.owner->own().title_memory) : 0; - if (!info || info->initial_state != D3D12_RESOURCE_STATE_COMMON || offset % D3D12_RAW_UAV_SRV_BYTE_ALIGNMENT || - !(placed.alias->GetDesc().Flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS)) - reason = "an output is not an aliased placed buffer range with unordered access"; + if (words[0] == view_token_magic) reason = "an output buffer descriptor is a view token"; + else if (half_bytes && !half_buffer_descriptor_matches(words, half_bytes)) + reason = "a half buffer store requires matching format, stride and structured bounds"; + else if (!bytes) reason = "an output buffer descriptor has zero records"; + else if (!sized) reason = half_bytes ? "an output half buffer range is over 16 MiB" + : "an output buffer range is over 16 MiB or not whole dwords"; + else if (placed.reject) reason = "an output range crosses the end of a placed buffer"; + else if (!placed.owner) reason = "an output is in title memory outside any placed buffer"; + else if (!placed.alias) reason = "an output is in a placed buffer that does not alias title memory"; + else if (!info || info->initial_state != D3D12_RESOURCE_STATE_COMMON) + reason = "an output buffer's resource was not created in the common state"; + else if (offset % alignment) reason = half_bytes ? "an output half buffer is not element-aligned in its resource" + : "an output buffer range is not 16-byte aligned in its resource"; + else if (!(placed.alias->GetDesc().Flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS)) + reason = "an output buffer has no unordered access"; for (std::size_t input = 0; input < inputs && !reason; ++input) if (views[input].resource == placed.alias) reason = "an output buffer is also an input"; views[i] = {placed.alias, offset, bytes, true}; + if (!reason && half_bytes) { + const auto format = x2w::native_half_buffer_format(half_bytes); + D3D12_FEATURE_DATA_FORMAT_SUPPORT support{format}; + constexpr UINT required = D3D12_FORMAT_SUPPORT1_BUFFER | D3D12_FORMAT_SUPPORT1_TYPED_UNORDERED_ACCESS_VIEW; + if (FAILED(device_of(the_device)->CheckFeatureSupport(D3D12_FEATURE_FORMAT_SUPPORT, &support, sizeof(support))) || + (support.Support1 & required) != required || + !(support.Support2 & D3D12_FORMAT_SUPPORT2_UAV_TYPED_STORE)) { + reason = "an output half buffer format does not support typed UAV stores"; + } else { + views[i].described = true; + D3D12_UNORDERED_ACCESS_VIEW_DESC desc{}; + desc.Format = format; + desc.ViewDimension = D3D12_UAV_DIMENSION_BUFFER; + desc.Buffer.FirstElement = offset / half_bytes; + desc.Buffer.NumElements = words[2]; + views[i].desc.uav = desc; + } + } std::memcpy(views[i].words, words, sizeof(views[i].words)); } + for (UINT r = 0; r < tr->heap_srvs && !reason; ++r) { + std::memset(words, 0, sizeof(words)); + const u64 entry = r < pass.title_view_heap_entries ? pass.title_view_heap.record(u64{r} << 5, 16) : 0; + if (!entry || !x2w_local::readable(reinterpret_cast<const void*>(entry), 16)) { + reason = "a heap record is outside the list's view heap"; + break; + } + std::memcpy(words, reinterpret_cast<const void*>(entry), 16); + const IndirectBufferView view = indirect_table_buffer(self, words, false, &reason, 16u << 20); + if (view.resource && view.offset % D3D12_RAW_UAV_SRV_BYTE_ALIGNMENT) + reason = "an input buffer range is not 16-byte aligned in its resource"; + if (reason && !tr->first_refusal) + log("x2w-draw compute %016llx first refused heap record %u, descriptor at 0x%llx", key, r, entry); + for (std::size_t output = inputs; output < count && !reason; ++output) + if (views[output].resource == view.resource) reason = "an output buffer is also an input"; + views[count + r] = {view.resource, view.offset, view.bytes, !view.upload}; + views[count + r].stride = view.stride; + std::memcpy(views[count + r].words, words, sizeof(views[count + r].words)); + } if (dispatch.argument) for (std::size_t i = 0; i < count && !reason; ++i) if (views[i].resource == dispatch.argument) reason = "the indirect argument buffer is also a bound shader resource"; @@ -609,14 +780,14 @@ const char* record_translated_dispatch(Wrapper* self, const TranslatedDispatch& log("x2w-draw compute %016llx Dispatch(%u, %u, %u) refused: %s", key, x, y, z, reason); return reason; } - const UINT n = static_cast<UINT>(count); + const UINT n = static_cast<UINT>(count + tr->heap_srvs); UINT first = static_cast<UINT>(InterlockedExchangeAdd(&draw_heap_cursor, static_cast<LONG>(n))) % draw_heap_size; if (first + n > draw_heap_size) { first = 0; InterlockedExchange(&draw_heap_cursor, static_cast<LONG>(n)); } D3D12_CPU_DESCRIPTOR_HANDLE dest{draw_heap->GetCPUDescriptorHandleForHeapStart().ptr + std::size_t{first} * draw_heap_increment}; - for (std::size_t i = 0; i < count; ++i, dest.ptr += draw_heap_increment) { + for (std::size_t i = 0; i < n; ++i, dest.ptr += draw_heap_increment) { const View& view = views[i]; if (i < inputs && view.texture) { // A compute list accepts no pixel-shader or depth state in a transition. @@ -626,13 +797,13 @@ const char* record_translated_dispatch(Wrapper* self, const TranslatedDispatch& view.described ? &view.desc.srv : nullptr, dest); continue; } - if (i < inputs) { + if (i < inputs || i >= count) { if (view.transition) require_state(self, view.resource, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE); buffer_view(dest, view.resource, view.offset, static_cast<std::size_t>(view.bytes)); continue; } require_state(self, view.resource, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); - if (view.texture) { + if (view.texture || view.described) { device_of(the_device)->CreateUnorderedAccessView(view.resource, nullptr, view.described ? &view.desc.uav : nullptr, dest); continue; diff --git a/src/startup_stubs/d3d12_draw.inl b/src/startup_stubs/d3d12_draw.inl index 972e6d89b2..3d18422106 100644 --- a/src/startup_stubs/d3d12_draw.inl +++ b/src/startup_stubs/d3d12_draw.inl @@ -157,6 +157,9 @@ struct Translation { enum UdKind { rect, base_vertex, start_instance, root_constant, stride, mrt_bits, d16_unorm16, desc_word3 }; struct Ud { int kind, a, b; }; int state = 0; // 1 ready, 2 unavailable +#ifdef X2W_NATIVE_SHADERS + bool native_graphics_attempted = false; +#endif x2w_startup::ManifestRetry manifest_retry; // Only an absent manifest can become ready on a later draw. std::vector<Srv> srvs; std::vector<PixelUav> uavs; // manifest 'uav N tex2d table P O' (#1996 F): u0.. after the SRVs @@ -432,13 +435,13 @@ bool publish_shader_request(u64 key, const wchar_t* ext, const void* data, std:: return GetFileAttributesW(path) != INVALID_FILE_ATTRIBUTES; } -void load_translation(Translation& tr, const std::string& rtv_request = {}) +void load_translation(Translation& tr, const std::string& rtv_request = {}, std::string manifest = {}) { tr.state = 2; wchar_t path[MAX_PATH]; - std::string manifest; if (!cache_path(path, L"", tr.key, L".txt")) return; - if (!read_text(path, manifest)) { + const bool provided = !manifest.empty(); + if (!provided && !read_text(path, manifest)) { if (!tr.manifest_retry.pending()) { InterlockedIncrement(&translation_missing); static LONG missing; @@ -525,8 +528,8 @@ void load_translation(Translation& tr, const std::string& rtv_request = {}) (ud.a < 0 || static_cast<std::size_t>(ud.a) >= tr.srvs.size() || !tr.d16_srvs.requires_exact(static_cast<unsigned>(ud.a)))) return; } - if (!cache_path(path, L"", tr.key, L".vs.cso") || FAILED(D3DReadFileToBlob(path, &tr.vs))) return; - if (!cache_path(path, L"", tr.key, L".ps.cso") || FAILED(D3DReadFileToBlob(path, &tr.ps))) return; + if (!provided && (!cache_path(path, L"", tr.key, L".vs.cso") || FAILED(D3DReadFileToBlob(path, &tr.vs)))) return; + if (!provided && (!cache_path(path, L"", tr.key, L".ps.cso") || FAILED(D3DReadFileToBlob(path, &tr.ps)))) return; const HRESULT hr = x2w_startup::create_translated_root(device_of(the_device), static_cast<UINT>(tr.uds.size()), static_cast<UINT>(tr.srvs.size()), tr.samplers, &tr.root, static_cast<UINT>(tr.uavs.size())); if (FAILED(hr)) { @@ -541,6 +544,58 @@ void load_translation(Translation& tr, const std::string& rtv_request = {}) tr.key, tr.uds.size(), tr.srvs.size(), tr.uavs.size(), tr.samplers.statics.size(), tr.samplers.heap ? 1u : 0u); } +#ifdef X2W_NATIVE_SHADERS +static bool try_native_graphics(Translation& tr) +{ + wchar_t sdk[MAX_PATH], path[MAX_PATH]; + const auto length = GetEnvironmentVariableW(L"X2W_NATIVE_SHADERS", sdk, MAX_PATH); + if (!length || length >= MAX_PATH || !cache_path(path, L"req_", tr.key, L".a")) return false; + try { + const auto request = x2w::read_graphics_request(path); + const auto cache = std::filesystem::path(path).parent_path(); + bool frontend_hit = false; + const auto pair = x2w::prepare_direct_graphics(request.a, request.b, cache, frontend_hit, + request.root, request.input_layout, request.pixel_entry); + auto manifest = x2w::format_graphics_runtime_manifest(pair); + if (!manifest) throw std::runtime_error("unsupported graphics binding layout"); + auto compiler = x2w::ShaderDxilCompiler::runtime_worker(sdk); + auto stage = [&](const std::string& ir, const wchar_t* profile, bool& hit) { + const auto output = compiler.compile(ir, profile, cache, x2w::ShaderSourceFormat::dxil_ir); + hit = output.cache_hit; + x2w_startup::ComPtr<ID3DBlob> blob; + if (FAILED(D3DCreateBlob(output.dxil.size(), &blob))) throw std::bad_alloc(); + std::memcpy(blob->GetBufferPointer(), output.dxil.data(), output.dxil.size()); + return blob; + }; + bool vs_hit, ps_hit; + auto vs = stage(pair.vertex.dxil_ir, L"vs_6_6", vs_hit); + auto ps = stage(pair.pixel.dxil_ir, L"ps_6_6", ps_hit); + Translation candidate; + candidate.key = tr.key; + candidate.manifest_retry = tr.manifest_retry; + candidate.native_graphics_attempted = true; + candidate.vs = vs.Get(); + candidate.ps = ps.Get(); + // Source-built first-draw fixture: fail after both stages have compiled and + // the local candidate holds both blobs. The later disk load stays valid. + if (GetEnvironmentVariableW(L"X2W_TEST_NATIVE_GRAPHICS_BAD_MANIFEST", nullptr, 0)) + *manifest = "x2w-manifest 0\n"; + load_translation(candidate, {}, std::move(*manifest)); + const bool ready = candidate.state == 1; + log("x2w-draw native graphics %016llx ready=%u cache(frontend,vs,ps)=%u,%u,%u", + tr.key, ready, frontend_hit, vs_hit, ps_hit); + if (!ready) return false; + vs.Detach(); + ps.Detach(); + tr = std::move(candidate); + return true; + } catch (const std::exception& error) { + log("x2w-draw native graphics %016llx refused: %s", tr.key, error.what()); + return false; + } +} +#endif + // draw_lock held. Both pipeline forms use the same request writer and shader cache. Translation* cached_translation(const void* a, std::size_t a_bytes, const void* b, std::size_t b_bytes, const std::vector<unsigned char>& root_blob, const std::string& layout = {}) @@ -1066,6 +1121,12 @@ Translation* translation_for_targets(Translation* base, const Pass& pass) if (std::none_of(pass.target_formats, pass.target_formats + pass.target_count, needs_rtv_variant)) { if (base->manifest_retry.due(GetTickCount64())) load_translation(*base); +#ifdef X2W_NATIVE_SHADERS + if (base->manifest_retry.pending() && !base->native_graphics_attempted) { + base->native_graphics_attempted = true; + try_native_graphics(*base); + } +#endif return base; } std::string request = "rtv1 " + std::to_string(base->key); @@ -2284,14 +2345,24 @@ struct IndirectBufferView { u64 offset = 0, bytes = 0; UINT stride = 0; bool upload = false; + int source = 0; // 0 aliased or any other backing, 1 a GPU copy this list made (X2W_TRANSLATED_INDIRECT_COPY_RANGES), 2 a snapshot of title memory, 3 zeros for a null descriptor }; +// X2W_TRANSLATED_TITLE_INPUT_SNAPSHOT=1: a translated compute input in a placed buffer that does not alias title memory +// (a committed default buffer that holds zeros) is read from title memory, snapshotted into its own recycled pool. +bool title_input_snapshot_enabled() +{ + static const bool enabled = x2w_local::env_on("X2W_TRANSLATED_TITLE_INPUT_SNAPSHOT"); + return enabled; +} + // For indirect draws, bind the complete descriptor range on a known GPU backing. There is no // fallback to copying an unrelated or stale title allocation into the draw upload ring. // why, when given, receives the condition an empty result failed on. IndirectBufferView indirect_table_buffer(Wrapper* self, const std::uint32_t* words, bool allow_address_alias = false, const char** why = nullptr, - u64 limit = u64{4} << D3D12_REQ_BUFFER_RESOURCE_TEXEL_COUNT_2_TO_EXP) + u64 limit = u64{4} << D3D12_REQ_BUFFER_RESOURCE_TEXEL_COUNT_2_TO_EXP, + bool allow_title_snapshot = false) { const auto refuse = [why](const char* reason) { if (why) *why = reason; @@ -2349,12 +2420,23 @@ IndirectBufferView indirect_table_buffer(Wrapper* self, const std::uint32_t* wor stride = (words[1] >> 16) & 0x3fff; bytes = u64{stride ? stride : 1} * words[2]; } + // A compute input whose four descriptor words are all zero is an unbound (null) buffer: the hardware reads zeros from + // it, so the dispatch gets 16 bytes of zeros instead of being refused. Any other empty range is still refused. + if (!bytes && allow_title_snapshot && !words[0] && !words[1] && !words[2] && !words[3]) { + u64 zero_offset = 0; + ID3D12Resource* zero_ring = nullptr; + unsigned char* zero_bytes = reserve_upload_ring(self, 16, &zero_offset, &zero_ring, true); + if (!zero_bytes || !zero_ring) return refuse("a null input could not get its zero bytes"); + std::memset(zero_bytes, 0, 16); + return {zero_ring, zero_offset, 16, 0, true, 3}; + } if (!bytes) return refuse("an input buffer descriptor has zero records"); if (bytes > limit || bytes % 4) return refuse(limit == (16u << 20) ? "an input buffer range is over 16 MiB or not whole dwords" : "an input buffer range exceeds the D3D12 raw SRV limit or is not whole dwords"); ID3D12Resource* native = nullptr; bool upload = false; + int input_source = 0; Wrapper* device = self->own().list_device; if (address) { if (const auto allocation = list_upload_range(self, address, bytes); allocation.resource) { @@ -2375,8 +2457,24 @@ IndirectBufferView indirect_table_buffer(Wrapper* self, const std::uint32_t* wor owner = placed.owner; native = static_cast<ID3D12Resource*>(owner->own().real); offset = address - reinterpret_cast<u64>(owner->own().title_memory); - if (!placed.alias && (!native || !list_copied_gpu_range(self, native, offset, bytes))) - return refuse("an input is in a placed buffer that does not alias title memory"); + if (!placed.alias) { + if (native && list_copied_gpu_range(self, native, offset, bytes)) { + input_source = 1; // a GPU copy of this list filled the range: the GPU buffer is the truth + } else if (allow_title_snapshot && title_input_snapshot_enabled() && bytes <= (u64{16} << 20)) { + // The buffer is a committed default buffer that holds zeros (it does not alias title memory), so the + // bytes the title wrote are only in title memory: snapshot the range into the snapshot pool now. A later + // guest write is not seen (as title_backed_source for copies); data a GPU pass wrote into this buffer is not either. + u64 ring_offset = 0; + ID3D12Resource* ring = nullptr; + if (readable_window(address, static_cast<std::size_t>(bytes)) < bytes) + return refuse("an input range in title memory is not readable"); + if (!ring_copy(self, address, static_cast<std::size_t>(bytes), &ring_offset, &ring, true) || !ring) + return refuse("an input range could not be copied from title memory"); + return {ring, ring_offset, bytes, stride, true, 2}; + } else { + return refuse("an input is in a placed buffer that does not alias title memory"); + } + } } else if (own_memory) { native = static_cast<ID3D12Resource*>(owner->own().real); } else if (owner && !owner->own().title_memory) { @@ -2400,7 +2498,7 @@ IndirectBufferView indirect_table_buffer(Wrapper* self, const std::uint32_t* wor const auto desc = native->GetDesc(); if (desc.Dimension != D3D12_RESOURCE_DIMENSION_BUFFER || (desc.Flags & D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE) || offset > desc.Width || bytes > desc.Width - offset) return refuse("an input range is outside its desktop buffer"); - return {native, offset, bytes, stride, upload}; + return {native, offset, bytes, stride, upload, input_source}; } struct FormattedBufferDescriptor { @@ -3239,6 +3337,7 @@ void __stdcall list_set_descriptor_heaps(Wrapper* self, UINT count, void* const* x2w_startup::SamplerSource source; u64 sampler_wrapper = 0; x2w_startup::ViewTable heap_records; + UINT heap_entries = 0; x2w_startup::ViewHeapSelection view_heaps; if (count && count <= 4 && x2w_local::readable(heaps, std::size_t{count} * sizeof(*heaps))) { AcquireSRWLockShared(¬e_lock); @@ -3248,9 +3347,11 @@ void __stdcall list_set_descriptor_heaps(Wrapper* self, UINT count, void* const* heap.type == D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV) view_heaps.note(heap.wrapper, heap.desktop_gpu != 0, heap.logical_count, heap.count); if (heap.wrapper == reinterpret_cast<u64>(heaps[i]) && - heap.type == D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV) + heap.type == D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV) { heap_records = x2w_startup::resolve_view_table(heap.desktop_gpu, heap.title_cpu, heap.logical_count, heap.increment, heap.desktop_gpu); + if (heap_records.address) heap_entries = heap.logical_count; + } if (heap.wrapper == reinterpret_cast<u64>(heaps[i]) && heap.type == D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER && heap.desktop_gpu) { sampler_wrapper = heap.wrapper; @@ -3269,6 +3370,7 @@ void __stdcall list_set_descriptor_heaps(Wrapper* self, UINT count, void* const* pass.title_samplers = source; pass.sampler_heap_wrapper = sampler_wrapper; pass.title_view_heap = heap_records; + pass.title_view_heap_entries = heap_entries; } // The table at a title GPU handle, looked up in the title's view heap (the one set by slot 32 when known). diff --git a/src/startup_stubs/d3d12_xs_device.cpp b/src/startup_stubs/d3d12_xs_device.cpp index 4750e8f40b..aa9f1ffa0c 100644 --- a/src/startup_stubs/d3d12_xs_device.cpp +++ b/src/startup_stubs/d3d12_xs_device.cpp @@ -83,9 +83,11 @@ #include "title_heap_memory.h" #include "startup_stubs/xmem_section_buffer.h" #include "native_buffer_store_view.h" +#include "native_compute_output.h" #ifdef X2W_NATIVE_SHADERS // d3d12_xs_shim only: the C++ shader compiler (startup_stubs/d3d12_compute_dispatch.inl) #include "gfx1013_compute_native.h" #include "shader_dxil_compiler.h" +#include "direct_compute_cache.h" #endif #include <d3d12sdklayers.h> #include <d3d12shader.h> @@ -181,7 +183,7 @@ struct alignas(16) WrapperOwn { bool list_open; // CommandList (render mode): recording between reset and close x2w_upload::Arena* list_uploads; // Current recording's allocations, owned by its desktop allocator. ID3D12Resource* list_scratch; // Current recording's rectangle-list argument scratch, owned by its desktop allocator. - UploadChunkMask upload_chunks; // Ring chunks referenced by this recording, including while closed. + UploadChunkMask upload_chunks; // Ring and snapshot chunks referenced by this recording, including while closed. bool list_close_failed; // Desktop Reset repeats a failed Close result indefinitely. bool unplaced_srv_backing; // Resource: synthetic backing for an address-only buffer SRV. bool exact_copy; // Resource: synthetic backing that starts at the view address. @@ -1477,6 +1479,7 @@ std::unordered_map<Wrapper*, TitleAllocator> title_allocators; std::unordered_map<Wrapper*, DesktopAllocator*> list_recordings; // list -> allocator holding its recording std::unordered_map<ID3D12CommandQueue*, UploadQueue<ID3D12Fence>> queue_submits; std::vector<UploadRingChunk> upload_chunks; // allocator_lock also protects recording holds and queue fence values +std::vector<UploadRingChunk> snapshot_chunks; // the title input snapshot pool: same rules, its own chunks and budget // X2W_D3D12_RING_RELEASE_AT_SUBMIT=1 (allocator_lock): chunks each closed list released at a fenced submit, until its Reset. std::unordered_map<Wrapper*, ReleasedUploadChunks> released_upload_chunks; LONG upload_resubmits_refused; // closed lists submitted again after a released chunk was reused; not executed @@ -1486,7 +1489,7 @@ LONG allocator_swaps, allocator_creates; void release_upload_recording(Wrapper* list) { AcquireSRWLockExclusive(&allocator_lock); - discard_upload_chunks(list->own().upload_chunks, upload_chunks.data()); + discard_upload_chunks(list->own().upload_chunks, upload_chunks.data(), snapshot_chunks.data()); released_upload_chunks.erase(list); ReleaseSRWLockExclusive(&allocator_lock); } @@ -1716,13 +1719,13 @@ bool released_chunks_recycled(Wrapper* list) const auto released = released_upload_chunks.find(list); if (released == released_upload_chunks.end()) return false; UploadChunkMask recycled = 0; - resubmitted_upload_chunks(released->second, upload_chunks.data(), recycled); + resubmitted_upload_chunks(released->second, upload_chunks.data(), recycled, snapshot_chunks.data()); if (!recycled) return false; InterlockedIncrement(&upload_resubmits_refused); static LONG logged; if (first_calls(logged, 8)) - log("x2w-draw upload ring: closed list %p submitted again after its released chunks 0x%x were reused; " - "refused, it is not executed", static_cast<void*>(list), static_cast<unsigned>(recycled)); + log("x2w-draw upload ring: closed list %p submitted again after its released chunks 0x%llx were reused; " + "refused, it is not executed", static_cast<void*>(list), static_cast<unsigned long long>(recycled)); return true; } @@ -1748,7 +1751,7 @@ void note_submits(ID3D12CommandQueue* queue, const std::vector<Wrapper*>& lists) if (released == released_upload_chunks.end()) continue; // A list with a reused chunk was refused before the execute, under the same locks: all of them are intact. UploadChunkMask reused = 0; - chunks |= resubmitted_upload_chunks(released->second, upload_chunks.data(), reused); + chunks |= resubmitted_upload_chunks(released->second, upload_chunks.data(), reused, snapshot_chunks.data()); } const bool signaled = fence && SUCCEEDED(queue->Signal(fence, value + 1)); if (signaled) ++value; @@ -1758,7 +1761,7 @@ void note_submits(ID3D12CommandQueue* queue, const std::vector<Wrapper*>& lists) if (!list->own().upload_chunks) continue; try { release_upload_chunks_at_submit(list->own().upload_chunks, upload_chunks.data(), - released_upload_chunks[list]); + released_upload_chunks[list], snapshot_chunks.data()); } catch (const std::bad_alloc&) { // Keep the holds: the list then pins its chunks until its Reset, as without the switch. } @@ -1897,7 +1900,7 @@ HRESULT __stdcall list_reset(Wrapper* self, void* allocator) if (on) --on->lists; on = title.current; ++on->lists; - discard_upload_chunks(state.upload_chunks, upload_chunks.data()); + discard_upload_chunks(state.upload_chunks, upload_chunks.data(), snapshot_chunks.data()); released_upload_chunks.erase(self); state.list_uploads = nullptr; state.list_scratch = nullptr; @@ -1940,7 +1943,7 @@ HRESULT __stdcall list_close(Wrapper* self) state.list_ready = SUCCEEDED(hr); state.list_close_failed = FAILED(hr); if (FAILED(hr)) { - discard_upload_chunks(state.upload_chunks, upload_chunks.data()); + discard_upload_chunks(state.upload_chunks, upload_chunks.data(), snapshot_chunks.data()); if (const auto found = list_recordings.find(self); found != list_recordings.end() && found->second) found->second->close_failed = true; } @@ -2689,30 +2692,37 @@ ID3D12PipelineState* build_stream_pipeline(const D3D12_PIPELINE_STATE_STREAM_DES // Transient guest data is copied into mapped upload chunks. Chunks grow from // 16 MiB up to 256 MiB in total and stay alive for the process. A full chunk can be reused once // no recording can submit its bytes and every queue that used it has finished. With -// X2W_D3D12_RING_RELEASE_AT_SUBMIT=1 every chunk is 16 MiB, up to 512 MiB, and a fenced submit releases its lists. +// X2W_D3D12_RING_RELEASE_AT_SUBMIT=1 the ring uses 16 MiB chunks (larger for oversized reservations), +// up to 512 MiB. A fenced submit releases the list's holds in both pools. volatile LONG64 upload_ring_reserved_bytes, upload_ring_capacity_bytes; volatile LONG upload_ring_reservations, upload_ring_refusals; -UploadReservation reserve_upload_ring(Wrapper* list, std::size_t bytes) +// snapshot = true takes the reservation from the title input snapshot pool (128 MiB, chunks numbered after the ring's). +UploadReservation reserve_upload_ring(Wrapper* list, std::size_t bytes, bool snapshot = false) { - constexpr u64 max_alloc_bytes = max_upload_ring_bytes / 4; + const u64 max_pool_bytes = snapshot ? max_snapshot_pool_bytes : max_upload_ring_bytes; + const unsigned base = snapshot ? snapshot_chunk_base : 0; + const u64 max_alloc_bytes = max_pool_bytes / 4; UploadReservation reservation; if (bytes == 0 || bytes > max_alloc_bytes) return reservation; const u64 rounded = (static_cast<u64>(bytes) + 511) & ~u64{511}; - const auto note_reserved = [](u64 reserved) { + const auto note_reserved = [snapshot](u64 reserved) { + if (snapshot) return; InterlockedAdd64(&upload_ring_reserved_bytes, static_cast<LONG64>(reserved)); InterlockedIncrement(&upload_ring_reservations); }; - auto& chunks = upload_chunks; - static unsigned active = 0; - static u64 total_bytes = 0; + auto& chunks = snapshot ? snapshot_chunks : upload_chunks; + static unsigned actives[2] = {0, 0}; + static u64 totals[2] = {0, 0}; + unsigned& active = actives[snapshot ? 1 : 0]; + u64& total_bytes = totals[snapshot ? 1 : 0]; AcquireSRWLockExclusive(&allocator_lock); const auto finish = [&](unsigned index) { active = index; - chunks[index].hold(list->own().upload_chunks, index); + chunks[index].hold(list->own().upload_chunks, base + index); ReleaseSRWLockExclusive(&allocator_lock); return reservation; }; @@ -2724,11 +2734,11 @@ UploadReservation reserve_upload_ring(Wrapper* list, std::size_t bytes) } } - const bool release_at_submit = ring_release_at_submit(); - const u64 ring_bytes = release_at_submit ? max_released_upload_ring_bytes : max_upload_ring_bytes; - const u64 remaining = total_bytes < ring_bytes ? ring_bytes - total_bytes : 0; + const bool grow_released_ring = !snapshot && ring_release_at_submit(); + const u64 budget_bytes = grow_released_ring ? max_released_upload_ring_bytes : max_pool_bytes; + const u64 remaining = total_bytes < budget_bytes ? budget_bytes - total_bytes : 0; if (rounded <= remaining) { - u64 chunk_bytes = chunks.empty() || release_at_submit ? initial_upload_chunk_bytes : chunks.back().capacity * 2; + u64 chunk_bytes = chunks.empty() || grow_released_ring ? initial_upload_chunk_bytes : chunks.back().capacity * 2; if (chunk_bytes < rounded) chunk_bytes = rounded; if (chunk_bytes > remaining) chunk_bytes = remaining; auto* device = the_device ? device_of(the_device) : nullptr; @@ -2751,7 +2761,7 @@ UploadReservation reserve_upload_ring(Wrapper* list, std::size_t bytes) try { chunks.push_back(UploadRingChunk{created, static_cast<unsigned char*>(base), chunk_bytes, 0}); total_bytes += chunk_bytes; - InterlockedAdd64(&upload_ring_capacity_bytes, static_cast<LONG64>(chunk_bytes)); + if (!snapshot) InterlockedAdd64(&upload_ring_capacity_bytes, static_cast<LONG64>(chunk_bytes)); reservation = reserve_upload_chunk(chunks.back(), rounded); note_reserved(rounded); return finish(static_cast<unsigned>(chunks.size() - 1)); @@ -2777,7 +2787,7 @@ UploadReservation reserve_upload_ring(Wrapper* list, std::size_t bytes) } for (unsigned index = 0; index < chunks.size(); ++index) { - reservation = reuse_upload_chunk(chunks[index], index, rounded, queue_submits); + reservation = reuse_upload_chunk(chunks[index], base + index, rounded, queue_submits); if (reservation.mapped) { note_reserved(rounded); return finish(index); @@ -2785,27 +2795,28 @@ UploadReservation reserve_upload_ring(Wrapper* list, std::size_t bytes) } ReleaseSRWLockExclusive(&allocator_lock); - InterlockedIncrement(&upload_ring_refusals); - static LONG refused; - if (first_calls(refused, 8)) - log("x2w-draw upload ring reservation refused: no unused capacity"); + if (!snapshot) InterlockedIncrement(&upload_ring_refusals); + static LONG refused[2]; + if (first_calls(refused[snapshot ? 1 : 0], 8)) + log(snapshot ? "x2w-draw snapshot pool reservation refused: no unused capacity" + : "x2w-draw upload ring reservation refused: no unused capacity"); return reservation; } -unsigned char* reserve_upload_ring(Wrapper* list, std::size_t bytes, u64* offset, ID3D12Resource** resource) +unsigned char* reserve_upload_ring(Wrapper* list, std::size_t bytes, u64* offset, ID3D12Resource** resource, bool snapshot = false) { if (resource) *resource = nullptr; if (offset) *offset = 0; - const UploadReservation reservation = reserve_upload_ring(list, bytes); + const UploadReservation reservation = reserve_upload_ring(list, bytes, snapshot); if (!reservation.mapped) return nullptr; if (offset) *offset = reservation.offset; if (resource) *resource = reservation.resource; return reservation.mapped; } -bool ring_copy(Wrapper* list, u64 title_address, std::size_t bytes, u64* offset, ID3D12Resource** resource = nullptr) +bool ring_copy(Wrapper* list, u64 title_address, std::size_t bytes, u64* offset, ID3D12Resource** resource = nullptr, bool snapshot = false) { - auto* dest = reserve_upload_ring(list, bytes, offset, resource); + auto* dest = reserve_upload_ring(list, bytes, offset, resource, snapshot); if (!dest) return false; std::memcpy(dest, reinterpret_cast<const void*>(title_address), bytes); return true; @@ -2872,6 +2883,7 @@ struct Pass { x2w_startup::ComputeTables compute_tables; // slot 35, read by a Dispatch handler u64 source_view_heap = 0; x2w_startup::ViewTable title_view_heap; // slot 32: the title memory of the list's view heap (heap records) + UINT title_view_heap_entries = 0; // logical descriptor count of title_view_heap (indices 0..count-1) u64 root_address[16] = {}; // title address of each root descriptor std::uint32_t constants[16][8] = {}; unsigned char constant_words_bound[16] = {}; @@ -3373,9 +3385,9 @@ extern "C" __declspec(dllexport) BOOL x2w_d3d12_fixture_compute_root_uav(void* g return TRUE; } -// Query slots 28 to 30, as a hypothesis (command_list_slot_names.h): no fixture here establishes which console -// methods sit there, so they are bound only with X2W_D3D12_QUERY_SLOTS=1. The heap reaches device slot 39 with the -// desktop desc. Only occlusion queries are +// Query slots 28 to 30, confirmed by the GXDK 261000 ID3D12GraphicsCommandList8 function table +// (command_list_slot_names.h): they are bound only with X2W_D3D12_QUERY_SLOTS=1 because the behavior is +// diagnostic. The heap reaches device slot 39 with the desktop desc. Only occlusion queries are // forwarded (shortcut: other heap types are refused until a caller needs them); a call that does not fit the // heap it names is refused and logged with its values instead of reaching the desktop list. enum QueryMethod { begin_query, end_query, resolve_query }; @@ -6651,8 +6663,8 @@ extern "C" __declspec(dllexport) BOOL x2w_d3d12_written_probe(void* address, uns // of its two display render targets the title pushes a bump allocator for allocatorId 0x80 that // serves pageSize 2 (bits 14-15) from a 64 MiB block, then asserts that the block was used up: // the console runtime evidently takes committed-resource memory from XMemAlloc with allocatorId -// 0x80. Hypothesis used here: attributes = pageSize (2 from 4 MiB up, else 1) << 14 | 0x80 << 16 | -// log2(alignment) << 24, memory type 0. The block is bookkeeping only; the desktop resource has its +// 0x80. Hypothesis used here: attributes = pageSize (2, a 2 MiB page, selected from 4 MiB up; else 1) +// << 14 | 0x80 << 16 | log2(alignment) << 24, memory type 0. The block is bookkeeping only; the desktop resource has its // own memory and does not alias it. using XMemAllocHook = void*(__stdcall*)(SIZE_T, ULONGLONG); XMemAllocHook title_alloc_hook() @@ -7436,9 +7448,9 @@ HRESULT __stdcall queue_present(Wrapper* self, UINT planes, const void* plane_pa log("x2w-render upload ring: reserved %llu MiB in %ld reservations, refusals %ld, capacity %llu MiB", static_cast<unsigned long long>(upload_ring_reserved_bytes) >> 20, upload_ring_reservations, upload_ring_refusals, static_cast<unsigned long long>(upload_ring_capacity_bytes) >> 20); - log("x2w-render compute dispatches: translated %ld, refused %ld, no translation %ld, not modelled %ld, builder gate refused %ld", + log("x2w-render compute dispatches: translated %ld, refused %ld, no translation %ld, not modelled %ld, builder gate refused %ld; placed inputs from a GPU copy %ld, from a title snapshot %ld (%ld KiB)", compute_dispatches_translated, compute_dispatches_refused, compute_dispatches_untranslated, compute_dispatches_unmodelled, - compute_builder_gate_refusals); + compute_builder_gate_refusals, compute_inputs_gpu_copied, compute_inputs_snapshot, compute_inputs_snapshot_kib); log_compute_census(); } if (render_mode() && frame % 300 == 0) { @@ -7665,8 +7677,8 @@ void build_tables() list_typed[47] = reinterpret_cast<ListTyped>(&list_index_buffer); list_typed[48] = reinterpret_cast<ListTyped>(&list_vertex_buffers); list_typed[x2w_list_slots::execute_indirect_slot] = reinterpret_cast<ListTyped>(&list_execute_indirect); - // X2W_D3D12_QUERY_SLOTS=1 (diagnostic): which console methods sit at 28 to 30 is a hypothesis, so the query - // bindings are opt-in. Unset, the slots stay no-ops. + // X2W_D3D12_QUERY_SLOTS=1 (diagnostic): the 261000 table confirms BeginQuery, EndQuery and + // ResolveQueryData at 28 to 30, but the bindings stay opt-in. Unset, the slots stay no-ops. if (wchar_t on[4]{}; GetEnvironmentVariableW(L"X2W_D3D12_QUERY_SLOTS", on, 4) && on[0] == L'1') { list_typed[28] = reinterpret_cast<ListTyped>(&list_begin_query); list_typed[29] = reinterpret_cast<ListTyped>(&list_end_query); diff --git a/src/startup_stubs/gfx10_layout.h b/src/startup_stubs/gfx10_layout.h index f07d39f743..38cf1a2f40 100644 --- a/src/startup_stubs/gfx10_layout.h +++ b/src/startup_stubs/gfx10_layout.h @@ -72,12 +72,12 @@ inline UINT block_log2(UINT mode) } // A three-dimensional texture in the 4 KiB standard mode (0x105), which addrlib lays out in thick blocks -// (Gfx10Lib::HwlIsThick: a 3D resource in a standard or display mode): uncompressed texels, with a mip -// chain or without. +// (Gfx10Lib::HwlIsThick: a 3D resource in a standard or display mode), with a mip chain or without. A +// block-compressed element is a 4x4 block of one depth layer. inline bool supports_volume(const D3D12_RESOURCE_DESC& d) { const Element element = element_of(d.Format); - return d.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D && swizzle_mode(d) == 5 && element.bytes && element.texels == 1 && + return d.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D && swizzle_mode(d) == 5 && element.bytes && d.Width && d.Height && d.DepthOrArraySize && d.Width <= 2048 && d.Height <= 2048 && d.DepthOrArraySize <= 2048 && d.MipLevels && d.MipLevels <= max_mips && d.SampleDesc.Count == 1; } @@ -228,7 +228,8 @@ struct Layout { // layer of every mip (Gfx10Lib::ComputeSurfaceInfoMacroTiled and ComputeSurfaceAddrFromCoordMacroTiled // for a thick surface): first the shared tail block when the chain has one, then the mips from the // smallest to the largest, each pitch x height blocks in x, then y. Mip sizes round up at every level - // (GetMipSize). A mip is in the tail when it is at most a block wide and half a block high + // (GetMipSize), in elements: a block-compressed volume is first rounded up to whole 4x4 blocks + // (ElemLib::AdjustSurfaceInfo), and its depth is not divided. A mip is in the tail when it is at most a block wide and half a block high // (GetMipTailDim: a 4 KiB block halves its height) and at most five mips remain (GetMaxNumMipsInTail for // a thick 4 KiB block). Tail mip k from the end sits at byte (k << 8) of the tail block; that offset, // read back as 256-byte micro blocks of Block256_3d, is its origin in x and y. Its z is not moved. @@ -264,17 +265,18 @@ struct Layout { if (bit < zs) z_bits[v] |= 1u << z_at[bit]; } const auto shifted = [](UINT v, UINT mip) { return (std::max)(1u, (v + (1u << mip) - 1) >> mip); }; + const UINT columns0 = (width + texels - 1) / texels, rows0 = (height + texels - 1) / texels; constexpr UINT tail_mips = 5; first_tail = mips; for (UINT mip = 0; mips > 1 && mip < mips; ++mip) - if (shifted(width, mip) <= block_width && shifted(height, mip) <= block_height / 2 && mips - mip <= tail_mips) { + if (shifted(columns0, mip) <= block_width && shifted(rows0, mip) <= block_height / 2 && mips - mip <= tail_mips) { first_tail = mip; break; } std::array<std::uint64_t, max_mips> size{}; for (UINT mip = 0; mip < first_tail; ++mip) { - blocks_wide[mip] = (shifted(width, mip) + block_width - 1) / block_width; - size[mip] = std::uint64_t{blocks_wide[mip]} * ((shifted(height, mip) + block_height - 1) / block_height) * block_bytes; + blocks_wide[mip] = (shifted(columns0, mip) + block_width - 1) / block_width; + size[mip] = std::uint64_t{blocks_wide[mip]} * ((shifted(rows0, mip) + block_height - 1) / block_height) * block_bytes; } std::uint64_t offset = first_tail < mips ? block_bytes : 0; for (UINT mip = first_tail; mip-- > 0;) { diff --git a/src/startup_stubs/local_log.h b/src/startup_stubs/local_log.h index 2a7fdf77d5..e044bd11e1 100644 --- a/src/startup_stubs/local_log.h +++ b/src/startup_stubs/local_log.h @@ -53,6 +53,16 @@ inline bool first_calls(volatile LONG& counter, LONG limit) noexcept return false; } +// Seconds since this process was created: one time base for lines from different stand-in DLLs. +inline double process_seconds() noexcept +{ + FILETIME created{}, exited{}, kernel{}, user{}, now{}; + if (!GetProcessTimes(GetCurrentProcess(), &created, &exited, &kernel, &user)) return 0; + GetSystemTimeAsFileTime(&now); + const auto ticks = [](const FILETIME& t) { return (std::uint64_t{t.dwHighDateTime} << 32) | t.dwLowDateTime; }; + return ticks(now) > ticks(created) ? static_cast<double>(ticks(now) - ticks(created)) / 1e7 : 0.0; +} + // First-chance exceptions stop the whole process while a debugger is attached, so a probe or a copy that is // refused before it touches an unmapped address is worth a query. faults_avoided counts those refusals; the // totals line of the render heartbeat prints it. @@ -76,14 +86,17 @@ inline thread_local MappedCache mapped_cache; inline void forget_mapped_spans() noexcept { mapped_cache = MappedCache{}; } // The pre-check is a debugging aid: it only pays off while a debugger would stop on every first-chance fault. -// It runs when a debugger is attached or X2W_PROBE_PRECHECK is set to anything but 0 (read once, cached); -// otherwise probes and copies keep the plain touch / __try path at no extra cost. +// X2W_PROBE_PRECHECK decides when it is set (0 off, anything else on); unset, the pre-check runs when a debugger is +// attached. Read once, cached. Title runs always start under debug_launch.py, where a VirtualQuery per probe can +// cost far more than the faults it avoids, so X2W_PROBE_PRECHECK=0 turns it off there. Off, probes and copies keep +// the plain touch / __try path at no extra cost. inline bool precheck_enabled() noexcept { static const bool enabled = [] { char value[8] = {}; const DWORD n = GetEnvironmentVariableA("X2W_PROBE_PRECHECK", value, sizeof(value)); - return IsDebuggerPresent() != FALSE || (n != 0 && n < sizeof(value) && value[0] != '0'); + if (n != 0 && n < sizeof(value)) return value[0] != '0'; + return IsDebuggerPresent() != FALSE; }(); return enabled; } diff --git a/src/startup_stubs/translated_sampler_bindings.h b/src/startup_stubs/translated_sampler_bindings.h index 21720a3595..8961082c97 100644 --- a/src/startup_stubs/translated_sampler_bindings.h +++ b/src/startup_stubs/translated_sampler_bindings.h @@ -20,6 +20,8 @@ constexpr UINT translated_sampler_count = D3D12_MAX_SHADER_VISIBLE_SAMPLER_HEAP_ constexpr UINT translated_sampler_space = 1; constexpr UINT translated_sampler_fallback = translated_sampler_count - 1; constexpr UINT title_sampler_stride = sizeof(SamplerWords); +constexpr UINT translated_resheap_space = 2; +constexpr UINT max_translated_resheap = 1024; // comparison: the sampler is read through a SamplerComparisonState (manifest line smpc). SQ_IMG_SAMP_WORD0 bits // 14:12 hold SQ_TEX_DEPTH_COMPARE, which lists NEVER..ALWAYS in the order of D3D12_COMPARISON_FUNC minus one. @@ -115,22 +117,28 @@ inline std::vector<D3D12_STATIC_SAMPLER_DESC> decode_statics(const TranslatedSam // views: the SRVs and UAVs of the view table together. inline UINT sampler_root_parameter(UINT views) { return views ? 2u : 1u; } -// Parameter 1, when there are views, is one table: SRVs t0.. first, then UAVs u0.. right after them. +// Parameter 1, when there are views, is one table: SRVs t0.. first, then UAVs u0.., then bounded resheap SRVs (space 2). inline HRESULT create_translated_root(ID3D12Device* device, UINT constants, UINT srvs, - const TranslatedSamplers& samplers, ID3D12RootSignature** out, UINT uavs = 0) + const TranslatedSamplers& samplers, ID3D12RootSignature** out, UINT uavs = 0, + UINT heap_srvs = 0) { D3D12_ROOT_PARAMETER parameters[3]{}; parameters[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS; parameters[0].Constants.Num32BitValues = constants; - // A compute program's outputs (u0..) follow its resources in the same table. - const D3D12_DESCRIPTOR_RANGE view_ranges[2]{{D3D12_DESCRIPTOR_RANGE_TYPE_SRV, srvs, 0, 0, 0}, - {D3D12_DESCRIPTOR_RANGE_TYPE_UAV, uavs, 0, 0, srvs}}; + // A compute program's outputs (u0..) follow its resources in the same table; bounded heap SRVs follow in space 2. + D3D12_DESCRIPTOR_RANGE view_ranges[3]{}; + UINT range_count = 0; + if (srvs) view_ranges[range_count++] = {D3D12_DESCRIPTOR_RANGE_TYPE_SRV, srvs, 0, 0, 0}; + if (uavs) view_ranges[range_count++] = {D3D12_DESCRIPTOR_RANGE_TYPE_UAV, uavs, 0, 0, srvs}; + if (heap_srvs) { + view_ranges[range_count++] = { + D3D12_DESCRIPTOR_RANGE_TYPE_SRV, heap_srvs, 0, translated_resheap_space, srvs + uavs}; + } parameters[1].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; - // A range of no descriptors does not serialize: a program without resources starts the table at its outputs. - parameters[1].DescriptorTable = {(srvs ? 1u : 0u) + (uavs ? 1u : 0u), srvs ? view_ranges : view_ranges + 1}; + parameters[1].DescriptorTable = {range_count, view_ranges}; const D3D12_DESCRIPTOR_RANGE sampler_range{ D3D12_DESCRIPTOR_RANGE_TYPE_SAMPLER, translated_sampler_count, 0, translated_sampler_space, 0}; - UINT count = sampler_root_parameter(srvs + uavs); + UINT count = sampler_root_parameter(srvs + uavs + heap_srvs); if (samplers.heap) { parameters[count].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; parameters[count].DescriptorTable = {1, &sampler_range}; diff --git a/src/startup_stubs/upload_reservation.h b/src/startup_stubs/upload_reservation.h index eec33a9d33..121bbd6cf3 100644 --- a/src/startup_stubs/upload_reservation.h +++ b/src/startup_stubs/upload_reservation.h @@ -2,6 +2,7 @@ #include <array> #include <cstdint> +#include <limits> struct ID3D12Resource; @@ -11,14 +12,21 @@ inline constexpr std::uint64_t max_upload_ring_bytes = 256ull << 20; inline constexpr std::uint64_t max_released_upload_ring_bytes = 512ull << 20; // Each allocation except possibly the final remainder is at least the initial size. inline constexpr unsigned max_upload_chunks = max_released_upload_ring_bytes / initial_upload_chunk_bytes; -using UploadChunkMask = std::uint32_t; -static_assert(max_upload_chunks <= 32); +// Title input snapshots have a pool of their own, built like the ring (chunks reused once no recording can submit them and every +// queue that used them has finished), so draw and texture uploads cannot starve them and they cannot starve the ring. Its chunks +// are numbered after the ring's in the same recording mask: bit snapshot_chunk_base + i is chunk i of the snapshot pool. +inline constexpr std::uint64_t max_snapshot_pool_bytes = 128ull << 20; +inline constexpr unsigned max_snapshot_chunks = max_snapshot_pool_bytes / initial_upload_chunk_bytes; +inline constexpr unsigned snapshot_chunk_base = max_upload_chunks; +inline constexpr unsigned upload_chunk_bits = max_upload_chunks + max_snapshot_chunks; +using UploadChunkMask = std::uint64_t; +static_assert(upload_chunk_bits <= std::numeric_limits<UploadChunkMask>::digits); template <class Fence> struct UploadQueue { Fence* fence = nullptr; std::uint64_t value = 0; - std::array<std::uint64_t, max_upload_chunks> last_use{}; + std::array<std::uint64_t, upload_chunk_bits> last_use{}; void submitted(UploadChunkMask chunks, bool signaled) { @@ -56,28 +64,35 @@ struct UploadRingChunk { } }; -inline void discard_upload_chunks(UploadChunkMask& recording, UploadRingChunk* chunks) +// Indices below snapshot_chunk_base belong to the upload ring. +template <class Chunk> +inline Chunk& upload_chunk_at(unsigned index, Chunk* chunks, Chunk* snapshot_chunks) +{ + return index < snapshot_chunk_base ? chunks[index] : snapshot_chunks[index - snapshot_chunk_base]; +} +inline void discard_upload_chunks(UploadChunkMask& recording, UploadRingChunk* chunks, UploadRingChunk* snapshot_chunks = nullptr) { for (unsigned i = 0; recording; ++i, recording >>= 1) - if (recording & 1) --chunks[i].recordings; + if (recording & 1) --upload_chunk_at(i, chunks, snapshot_chunks).recordings; } // X2W_D3D12_RING_RELEASE_AT_SUBMIT=1: the chunks a closed list stopped holding when its submit was fenced, and // each chunk's generation at that moment. The queue fence keeps those chunks from reuse until the GPU passes it. struct ReleasedUploadChunks { UploadChunkMask chunks = 0; - std::array<std::uint64_t, max_upload_chunks> generation{}; + std::array<std::uint64_t, upload_chunk_bits> generation{}; }; // Caller holds the lock, after the queue recorded a signalled fence for the recording's chunks. inline void release_upload_chunks_at_submit(UploadChunkMask& recording, UploadRingChunk* chunks, - ReleasedUploadChunks& released) + ReleasedUploadChunks& released, UploadRingChunk* snapshot_chunks = nullptr) { for (unsigned i = 0; recording; ++i, recording >>= 1) { if (!(recording & 1)) continue; released.chunks |= UploadChunkMask{1} << i; - released.generation[i] = chunks[i].generation; - --chunks[i].recordings; + auto& chunk = upload_chunk_at(i, chunks, snapshot_chunks); + released.generation[i] = chunk.generation; + --chunk.recordings; } } @@ -85,14 +100,14 @@ inline void release_upload_chunks_at_submit(UploadChunkMask& recording, UploadRi // the released chunks that were not reused since, which the new submit must fence again, and sets `recycled` to // those that were. inline UploadChunkMask resubmitted_upload_chunks(const ReleasedUploadChunks& released, const UploadRingChunk* chunks, - UploadChunkMask& recycled) + UploadChunkMask& recycled, const UploadRingChunk* snapshot_chunks = nullptr) { UploadChunkMask intact = 0; recycled = 0; - for (unsigned i = 0; i < max_upload_chunks; ++i) { + for (unsigned i = 0; i < upload_chunk_bits; ++i) { const auto bit = UploadChunkMask{1} << i; if (!(released.chunks & bit)) continue; - (chunks[i].generation == released.generation[i] ? intact : recycled) |= bit; + (upload_chunk_at(i, chunks, snapshot_chunks).generation == released.generation[i] ? intact : recycled) |= bit; } return intact; } diff --git a/src/startup_stubs/xapu.cpp b/src/startup_stubs/xapu.cpp index 8648ffe1a1..8232d2bfcb 100644 --- a/src/startup_stubs/xapu.cpp +++ b/src/startup_stubs/xapu.cpp @@ -317,6 +317,77 @@ long decode_packet(Connection& conn, const unsigned char* c, QueueEntry& entry, return hr_ok; } #endif + +// Activity counter (#1145), off unless X2W_AUDIO_ACTIVITY=1: every XApuEnqueueCommand call, counted by command class, +// taken as the first UINT32 of the command (a stand-in convention, like the result type above), with no cap. Classes +// 0..15 are counted one by one and larger ones together; a command that cannot be read and a call with an unknown +// handle are counted apart. commands= in the line is the classes plus the unreadable ones; rejected calls are not in +// it. There is no thread: a counted call (or x2w_xapu_command_counts) at least a second after the previous line (or the +// first such call) writes the next line, with the counts since that line, if a count moved; until then the counts wait +// for a later call. Nothing here runs outside a call into this DLL. Off, nothing here runs: no read of the command, no +// line. +constexpr unsigned command_classes = 16; +struct CommandCounts { + u64 by_class[command_classes + 1]; // the last entry: every larger class + u64 unreadable, rejected; +}; +SRWLOCK count_lock = SRWLOCK_INIT; // guards the four below +CommandCounts command_counts, reported; // the counts now and at the last line +ULONGLONG last_line; // GetTickCount64 of the last line written, or of the first counted call or counter-on export call +bool counting_started; + +bool activity_on() noexcept { return x2w_local::env_on("X2W_AUDIO_ACTIVITY"); } + +// If the last line is at least a second old and a count moved, writes the next line into text and returns true. +// Hold count_lock exclusively; log the text after releasing it. +bool poll_locked(char (&text)[512]) noexcept +{ + const ULONGLONG tick = GetTickCount64(); + if (!counting_started) { + counting_started = true; + last_line = tick; + } + const CommandCounts& now = command_counts; + if (tick - last_line < 1000 || !std::memcmp(&now, &reported, sizeof(now))) return false; + last_line = tick; + char classes[320] = ""; + std::size_t used = 0; + u64 commands = now.unreadable - reported.unreadable; + for (unsigned c = 0; c <= command_classes; ++c) { + const u64 n = now.by_class[c] - reported.by_class[c]; + commands += n; + if (!n || used >= sizeof(classes)) continue; + used += static_cast<std::size_t>(c < command_classes ? std::snprintf(classes + used, sizeof(classes) - used, " %u=%llu", c, n) + : std::snprintf(classes + used, sizeof(classes) - used, " other=%llu", n)); + } + std::snprintf(text, sizeof(text), + "x2w-audio xapu-activity t=%.1f s: commands=%llu by class%s unreadable=%llu; rejected=%llu (not in commands)", + x2w_local::process_seconds(), commands, classes, now.unreadable - reported.unreadable, + now.rejected - reported.rejected); + reported = now; + return true; +} + +// Counts one XApuEnqueueCommand call; the caller's last error is kept. +void count_command(long hr, const void* command) noexcept +{ + if (!activity_on()) return; + const DWORD error = GetLastError(); + const bool readable = hr != hr_handle && x2w_local::readable(command, sizeof(std::uint32_t)); + const std::uint32_t command_class = readable ? *static_cast<const std::uint32_t*>(command) : 0; + char text[512]; + AcquireSRWLockExclusive(&count_lock); + if (hr == hr_handle) + ++command_counts.rejected; + else if (!readable) + ++command_counts.unreadable; + else + ++command_counts.by_class[command_class < command_classes ? command_class : command_classes]; + const bool line = poll_locked(text); + ReleaseSRWLockExclusive(&count_lock); + if (line) x2w_local::logf("%s", text); + SetLastError(error); +} } // namespace extern "C" __declspec(noinline) long XApuConnect(u64 rcx, u64 rdx, u64 r8, u64 r9) @@ -466,6 +537,7 @@ extern "C" __declspec(noinline) long XApuEnqueueCommand(u64 rcx, u64 rdx, u64 r8 static LONG bad_cmd_calls; if (x2w_local::first_calls(bad_cmd_calls, 2)) x2w_local::logf("x2w-audio XApuEnqueueCommand handle=0x%llx -> E_POINTER", rcx); + count_command(hr_pointer, nullptr); // a header this call refuses as unreadable counts as unreadable return hr_pointer; } QueueEntry entry{}; @@ -483,6 +555,7 @@ extern "C" __declspec(noinline) long XApuEnqueueCommand(u64 rcx, u64 rdx, u64 r8 if (decode && !x2w_local::readable(reinterpret_cast<const void*>(rdx), decode_command_size)) { x2w_audio::saturating_add(opus_counts.refused_short_command); x2w_local::logf("x2w-audio XApuEnqueueCommand handle=0x%llx short decode command -> E_POINTER", rcx); + count_command(hr_pointer, reinterpret_cast<const void*>(rdx)); // its header was read: counted as class 3 return hr_pointer; } #endif @@ -556,6 +629,7 @@ extern "C" __declspec(noinline) long XApuEnqueueCommand(u64 rcx, u64 rdx, u64 r8 x2w_audio::saturating_add(opus_counts.refused_out_of_memory); } #endif + count_command(hr, reinterpret_cast<const void*>(rdx)); static LONG calls; if (x2w_local::first_calls(calls, 24)) { char command[3 * 0x60 + 1]; @@ -600,3 +674,26 @@ extern "C" __declspec(noinline) long XApuDisconnect(u64 rcx, u64 rdx, u64 r8, u6 #endif return hr_ok; } + +// Experimental export for the source-built check (tests/startup_acphal_xma_activity.cpp): writes the line if one is +// due, as a counted call does, and the totals since start to out[0..18]: commands of classes 0..15, of larger classes, +// unreadable commands, calls with an unknown handle. With X2W_AUDIO_ACTIVITY off it writes zeros and returns FALSE. +extern "C" BOOL WINAPI x2w_xapu_command_counts(ULONGLONG* out) +{ + if (!out) return FALSE; + const bool on = activity_on(); + CommandCounts now{}; + char text[512]; + bool line = false; + if (on) { + AcquireSRWLockExclusive(&count_lock); + line = poll_locked(text); + now = command_counts; + ReleaseSRWLockExclusive(&count_lock); + } + if (line) x2w_local::logf("%s", text); + for (unsigned c = 0; c <= command_classes; ++c) out[c] = now.by_class[c]; + out[command_classes + 1] = now.unreadable; + out[command_classes + 2] = now.rejected; + return on; +} diff --git a/src/startup_stubs/xapu.def b/src/startup_stubs/xapu.def index 16136a6e78..548adb4c96 100644 --- a/src/startup_stubs/xapu.def +++ b/src/startup_stubs/xapu.def @@ -5,3 +5,4 @@ EXPORTS XApuDisconnect XApuEnqueueCommand XApuGetResultCount + x2w_xapu_command_counts diff --git a/src/startup_stubs/xcrdapi.cpp b/src/startup_stubs/xcrdapi.cpp index 42546d249a..7434b69ec4 100644 --- a/src/startup_stubs/xcrdapi.cpp +++ b/src/startup_stubs/xcrdapi.cpp @@ -886,27 +886,18 @@ void execute_request(Object* self, const unsigned char* request, const ULONG_PTR if (input) { bool bcpack_decoded = false; if (data && bcpack) { - if (bcpack == 7 || bcpack == 1 || bcpack == 4 || bcpack == 5 || bcpack == 3) { - std::vector<unsigned char> decoded(destination_size); - std::size_t produced = 0; - if (x2w_bcpack::decode_bcpack(data, decode_length, bcpack, decoded.data(), decoded.size(), &produced)) { - output = std::move(decoded); - data = output.data(); - decode_length = produced; - outcome = zlib ? "inflated + bcpack decoded" : "bcpack decoded"; - bcpack_decoded = true; - } else { - outcome = "bcpack failed"; - failure = StorageFailure::bcpack; - data = nullptr; - } - } else { - // shortcut for formats not decoded yet: texels are left zero (a blank texture) so the - // title's loading continues. Counted as bcpack_blank. - output.assign(destination_size, 0); + std::vector<unsigned char> decoded(destination_size); + std::size_t produced = 0; + if (x2w_bcpack::decode_bcpack(data, decode_length, bcpack, decoded.data(), decoded.size(), &produced)) { + output = std::move(decoded); data = output.data(); - decode_length = destination_size; - outcome = "BCPack not decoded: zero-filled"; + decode_length = produced; + outcome = zlib ? "inflated + bcpack decoded" : "bcpack decoded"; + bcpack_decoded = true; + } else { + outcome = "bcpack failed"; + failure = StorageFailure::bcpack; + data = nullptr; } } if (data) { diff --git a/src/xmem_mapped_pages.cpp b/src/xmem_mapped_pages.cpp index d38099ce54..c4f202a7d4 100644 --- a/src/xmem_mapped_pages.cpp +++ b/src/xmem_mapped_pages.cpp @@ -124,6 +124,7 @@ void collect_empty_slabs(std::vector<HANDLE>& closed) noexcept void unpin_slot(const Slot& slot, std::vector<HANDLE>* closed = nullptr) { const auto found = memory.pins.find(slot); + if (found == memory.pins.end()) return; // not pinned: nothing to do if (--found->second.references) return; const bool retired = found->second.retired; memory.pins.erase(found); diff --git a/tests/bcpack_format_fixtures.h b/tests/bcpack_format_fixtures.h new file mode 100644 index 0000000000..2dbd7fab74 --- /dev/null +++ b/tests/bcpack_format_fixtures.h @@ -0,0 +1,85 @@ +// Synthetic lane inputs, independent of the decoder's predictor and rank tables. +// SPDX-License-Identifier: MIT +#pragma once +#include "bcpack_encoder.h" +#include <algorithm> + +namespace bcpack_fixture { +inline constexpr uint8_t AB[7][16] = { + {7,7,4,5,4,4,5,4,7,7,7,7}, + {3,3,3,3,3,3,3,3,3,3,4,5,4,7,7}, + {3,3,7,5,5,5,5,4,5,4,7,7}, + {7,7,7,7,5,5,5,5,5,5,5,5}, + {3,3,7,7,5,5,5,5,5,5,5,5}, + {3,3,7,7,7,4,4,4,5,5,5,7,7,7,7,4}, + {3,3,7,7,7,7,7,6,6,4,5,7,7,7,7,4}, +}; +inline size_t lanes(unsigned fmt) { return fmt >= 6 ? 16 : fmt == 2 ? 15 : 12; } +inline size_t per(unsigned fmt) { return fmt == 1 || fmt == 4 ? 1 : 2; } +inline size_t block_bytes(unsigned fmt) { return 8 * per(fmt); } + +inline void byte_symbols(std::vector<uint16_t>& s, size_t at, unsigned value, size_t p) { + if (p == 1) { s[at] = static_cast<uint16_t>(value); return; } + for (unsigned h = 0; h < 2; ++h) { + s[at+h] = 0; + for (unsigned b = 0; b < 4; ++b) s[at+h] |= ((value >> (2*b+h)) & 1) << b; + } +} + +inline std::vector<uint16_t> reference_symbols(unsigned fmt, unsigned er, unsigned xr, unsigned mode) { + const size_t p = per(fmt); + std::vector<uint16_t> s(lanes(fmt)*p, 0); + const int delta = static_cast<int>((er-xr+128)&255)-128; + byte_symbols(s,0,delta >= 0 ? 2*delta : -2*delta-1,p); + byte_symbols(s,p,xr,p); + if (fmt == 6) { s[30] = static_cast<uint16_t>(mode); s[31] = er & 31; } + return s; +} + +inline std::vector<uint16_t> random_symbols(unsigned fmt, size_t blocks, uint64_t seed) { + const size_t target = per(fmt)*blocks; + std::vector<uint16_t> s(lanes(fmt)*target); + bcpack_test::Rng rng{seed}; + for (size_t l = 0; l < lanes(fmt); ++l) + for (size_t i = 0; i < target; ++i) s[l*target+i] = static_cast<uint16_t>(rng.below(1u << (AB[fmt-1][l]+1))); + if (fmt == 6) { + for (size_t i = 0; i < blocks; ++i) { + s[15*target+2*i] = static_cast<uint16_t>(i%14); + s[15*target+2*i+1] = static_cast<uint16_t>(i%32); + } + } else if (fmt == 7) { + // Choose all mapped controls; expected BC7 bytes still come from the oracle. + std::vector<unsigned> codes; + for (unsigned c = 0; c < 512; ++c) + if (x2w_bcpack::BC7_CONTROL_TABLE[c].valid) codes.push_back(c); + for (size_t i = 0; i < blocks; ++i) { + const unsigned code = codes[i%codes.size()]; + s[15*target+2*i] = code & 31; + s[15*target+2*i+1] = code >> 5; + } + } + return s; +} + +inline bool encode(unsigned fmt, const std::vector<uint16_t>& s, size_t blocks, std::vector<uint8_t>& stream) { + const size_t target = blocks*per(fmt), n = lanes(fmt); + if (!target || s.size() != n*target) return false; + std::vector<std::vector<uint8_t>> encoded(n); + for (size_t l = 0; l < n; ++l) { + for (size_t at = 0; at < target;) { + const size_t count = std::min(size_t(128),target-at); + bool ok = false; + for (uint8_t q = 0; q < 16 && !ok; ++q) { + std::vector<uint8_t> fragment; + if (bcpack_test::encode_fragment(AB[fmt-1][l],0,q,s.data()+l*target+at,count,true,fragment)) { + encoded[l].insert(encoded[l].end(),fragment.begin(),fragment.end()); + ok = true; + } + } + if (!ok) return false; + at += count; + } + } + return bcpack_test::interleave(encoded,AB[fmt-1],n,target,stream); +} +} // namespace bcpack_fixture diff --git a/tests/bcpack_formats_check.cpp b/tests/bcpack_formats_check.cpp new file mode 100644 index 0000000000..5f74f9dc71 --- /dev/null +++ b/tests/bcpack_formats_check.cpp @@ -0,0 +1,120 @@ +// Oracle-derived golden hashes of source-built synthetic streams. No SDK at test/run time. +// Optional --oracle ABSOLUTE_DLL_PATH regenerates hashes using an installed developer oracle. +// See docs/experiments/bcpack-standalone.md for provenance and commands. +// SPDX-License-Identifier: MIT +#define WIN32_LEAN_AND_MEAN +#define NOMINMAX +#include <windows.h> +#include "bcpack_format_fixtures.h" +#include "bcpack_formats_goldens.h" +#include <cstdio> +#include <string> + +namespace { +using Oracle = long (__cdecl*)(size_t,void*,size_t,const void*,size_t); +Oracle oracle = nullptr; +bool mutate = false; +size_t cases = 0; + +uint64_t hash(uint64_t h, const std::vector<uint8_t>& bytes) { + for (uint8_t b : bytes) { h ^= b; h *= 1099511628211ull; } + return h; +} + +bool check(unsigned fmt, const std::vector<uint16_t>& s, size_t blocks, uint64_t& h) { + std::vector<uint8_t> packed; + if (!bcpack_fixture::encode(fmt,s,blocks,packed)) return false; + const size_t size = blocks*bcpack_fixture::block_bytes(fmt); + std::vector<uint8_t> expected(size), guarded(size+32,0xa5); + if (oracle) { + if (oracle(fmt,expected.data(),size,packed.data(),packed.size()) < 0) return false; + } else { + bool first = true; + for (int path = 0; path < x2w_bcpack::LANE_PATH_COUNT; ++path) { + if (!x2w_bcpack::lane_path_supported(path)) continue; + x2w_bcpack::lane_path_override = path; + std::fill(guarded.begin(),guarded.end(),0xa5); + size_t produced = 123; + if (!x2w_bcpack::decode_bcpack(packed.data(),packed.size(),fmt,guarded.data()+16,size,&produced) || produced != size) + return false; + for (size_t i = 0; i < 16; ++i) + if (guarded[i] != 0xa5 || guarded[size+16+i] != 0xa5) return false; + if (first) { + std::copy(guarded.begin()+16,guarded.end()-16,expected.begin()); + first = false; + } else if (!std::equal(expected.begin(),expected.end(),guarded.begin()+16)) return false; + } + } + if (mutate && fmt == 2 && cases == 0) expected[0] ^= 1; + h = hash(h,expected); + ++cases; + return true; +} + +bool group(unsigned fmt, int mode, uint64_t expected) { + uint64_t h = 14695981039346656037ull; + cases = 0; + if (mode >= 0) { + for (unsigned r = 0; r < 256; ++r) { + const unsigned ep[] = {r,0,r}, ix[] = {0,r,(r*73+19)&255}; + for (unsigned k = 0; k < 3; ++k) + if (!check(fmt,bcpack_fixture::reference_symbols(fmt,ep[k],ix[k],mode),1,h)) return false; + } + } else { + for (size_t blocks : {size_t(2),size_t(17),size_t(255),size_t(256),size_t(257),size_t(1024)}) + if (!check(fmt,bcpack_fixture::random_symbols(fmt,blocks,0xbc9900+fmt+blocks),blocks,h)) return false; + } + std::printf("BC%u mode %d: %zu cases, %016llx%s\n",fmt,mode,cases, + static_cast<unsigned long long>(h), oracle || h == expected ? "" : " MISMATCH"); + return oracle || h == expected; +} + +bool failures() { + for (unsigned fmt = 1; fmt <= 7; ++fmt) { + auto s = bcpack_fixture::random_symbols(fmt,17,0x1122+fmt); + std::vector<uint8_t> packed; + if (!bcpack_fixture::encode(fmt,s,17,packed)) return false; + const size_t size = 17*bcpack_fixture::block_bytes(fmt); + std::vector<uint8_t> out(size+32,0xa5); + auto reject = [&](size_t input_size, size_t output_size, unsigned format) { + size_t produced = 123; + return !x2w_bcpack::decode_bcpack(packed.data(),input_size,format,out.data()+16,output_size,&produced) && produced == 0 && + std::all_of(out.begin(),out.end(),[](uint8_t b){return b == 0xa5;}); + }; + if (!reject(1,size,fmt) || !reject(packed.size(),size-1,fmt) || + !reject(packed.size(),size,0) || !reject(packed.size(),size,8)) return false; + packed.push_back(0xff); + if (!reject(packed.size(),size,fmt)) return false; + } + // A valid entropy stream can still contain an undefined BC6H mode. + std::vector<uint16_t> s(32,0); + s[30] = 14; + std::vector<uint8_t> packed; + if (!bcpack_fixture::encode(6,s,1,packed)) return false; + uint8_t out[16] = {}; size_t produced = 123; + return !x2w_bcpack::decode_bcpack(packed.data(),packed.size(),6,out,sizeof(out),&produced) && produced == 0; +} +} // namespace + +int main(int argc, char** argv) { + HMODULE library = nullptr; + if (argc == 3 && std::string(argv[1]) == "--oracle") { + library = LoadLibraryExA(argv[2],nullptr,LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR | LOAD_LIBRARY_SEARCH_DEFAULT_DIRS); + if (!library) return 2; + oracle = reinterpret_cast<Oracle>(GetProcAddress(library,"BCPackDecompress")); + if (!oracle) { FreeLibrary(library); return 2; } + } else if (argc == 2 && std::string(argv[1]) == "--mutate") mutate = true; + else if (argc != 1) return 2; + bool ok = true; + for (unsigned fmt : {1u,2u,6u}) { + const unsigned modes = fmt == 6 ? 14 : 1; + for (unsigned mode = 0; mode < modes; ++mode) + ok = group(fmt,mode,BCPACK_REFERENCE_GOLDENS[fmt == 1 ? 0 : fmt == 2 ? 1 : mode+2]) && ok; + } + for (unsigned fmt = 1; fmt <= 7; ++fmt) + ok = group(fmt,-1,BCPACK_RANDOM_GOLDENS[fmt-1]) && ok; + if (!oracle) ok = failures() && ok; + if (library) FreeLibrary(library); + std::puts(ok ? "PASS" : "FAIL"); + return ok ? 0 : 1; +} diff --git a/tests/bcpack_formats_goldens.h b/tests/bcpack_formats_goldens.h new file mode 100644 index 0000000000..dce02eb446 --- /dev/null +++ b/tests/bcpack_formats_goldens.h @@ -0,0 +1,32 @@ +// FNV-1a-64 of GDK 1.2603.3.0 output for source-built synthetic streams. +// Generated by bcpack_formats_check --oracle; see docs/experiments/bcpack-standalone.md. +// SPDX-License-Identifier: MIT +#pragma once +#include <cstdint> +inline constexpr uint64_t BCPACK_REFERENCE_GOLDENS[16] = { + 0x34c5c81aac38ab05ull, + 0x3fbe7d532c8a8ee5ull, + 0x3ad5c83091ad36c8ull, + 0xa166156f9d7c2584ull, + 0xf8dcf5a64a9bc914ull, + 0xc793a6b84f33d1f8ull, + 0x878c19433aad5528ull, + 0x323fe930ab1bbb34ull, + 0x7da68746bab3e824ull, + 0xdb039400e610986cull, + 0x057898faa1d59bf4ull, + 0x840acfcd001e5de0ull, + 0x0f6512b21bceaec9ull, + 0xb8a2e7bdf73cad4dull, + 0x48b0f9f1c4216b49ull, + 0x5dfb4aa715489a1dull, +}; +inline constexpr uint64_t BCPACK_RANDOM_GOLDENS[7] = { + 0x1b0b9d7ad64ed0ebull, + 0x80d855e20ab59f94ull, + 0x0c4a4d67b9bea24full, + 0x736c245fee5efa9aull, + 0xd75651737d36c49aull, + 0x8b25e69129e6d691ull, + 0xc498f7502500346dull, +}; diff --git a/tests/bcpack_oracle_bridge.cpp b/tests/bcpack_oracle_bridge.cpp new file mode 100644 index 0000000000..6683875f2d --- /dev/null +++ b/tests/bcpack_oracle_bridge.cpp @@ -0,0 +1,20 @@ +// Synthetic input bridge for the optional development-only constant recovery tool. +// SPDX-License-Identifier: MIT +#include "bcpack_format_fixtures.h" +#include <cstring> +extern "C" __declspec(dllexport) size_t encode_symbols(unsigned fmt, const uint16_t* symbols, + size_t target, uint8_t* output, size_t capacity) { + if (fmt < 1 || fmt > 7 || !symbols || !output || !target || target%bcpack_fixture::per(fmt)) return 0; + std::vector<uint16_t> s(symbols,symbols+target*bcpack_fixture::lanes(fmt)); + std::vector<uint8_t> packed; + if (!bcpack_fixture::encode(fmt,s,target/bcpack_fixture::per(fmt),packed) || packed.size() > capacity) return 0; + std::memcpy(output,packed.data(),packed.size()); + return packed.size(); +} +extern "C" __declspec(dllexport) size_t storage_symbols(unsigned fmt, uint16_t* output, size_t capacity) { + if ((fmt != 2 && fmt != 6) || !output) return 0; + auto s = bcpack_fixture::random_symbols(fmt,4,0x7700+fmt); + if (capacity < s.size()) return 0; + std::copy(s.begin(),s.end(),output); + return s.size(); +} diff --git a/tests/bcpack_storage_checks.inl b/tests/bcpack_storage_checks.inl new file mode 100644 index 0000000000..9df107ce77 --- /dev/null +++ b/tests/bcpack_storage_checks.inl @@ -0,0 +1,112 @@ +// Included by the source-built startup consumer after its queue/zlib helpers. +// SPDX-License-Identifier: MIT + +bool bcpack_storage_checks() { + _putenv("X2W_XMEM_PERMISSIVE=1"); + const auto library = LoadLibraryW(L"XCRDAPI.dll"); + if (!library) return false; + const auto get_factory = reinterpret_cast<DStorageGetFactoryFn>(GetProcAddress(library,"DStorageGetFactory")); + void* factory_ptr = nullptr; + if (!get_factory || get_factory(nullptr,&factory_ptr) != 0 || !factory_ptr) return false; + auto* factory = static_cast<Object*>(factory_ptr); + for (unsigned fmt : {2u,6u}) { + const auto s = bcpack_fixture::random_symbols(fmt,4,0x7700+fmt); + std::vector<uint8_t> packed; + if (!bcpack_fixture::encode(fmt,s,4,packed)) return false; + const auto zipped = make_stored_zlib(packed.data(),packed.size()); + const auto* expected = fmt == 2 ? BC2_STORAGE_EXPECTED : BC6_STORAGE_EXPECTED; + // Memory/file x raw/zlib, linear/page destinations; then failures followed by valid requests. + for (unsigned scenario = 0; scenario < (fmt == 6 ? 14u : 12u); ++scenario) { + const bool file = (scenario & 1) != 0; + const bool zlib = (scenario & 2) != 0; + const bool page = (scenario >= 4 && scenario < 10) || scenario == 13; + const bool invalid = scenario >= 8; + std::vector<uint8_t> damaged; + if (scenario >= 12) { + auto bad = s; + bad[15*8+6] = 14; // final block's undefined mode, after three valid blocks + if (!bcpack_fixture::encode(fmt,bad,4,damaged)) return false; + } + const auto& input = scenario >= 12 ? damaged : zlib ? zipped : packed; + void *queue_ptr = nullptr, *status_ptr = nullptr; + uint8_t desc[0x20] = {}; *reinterpret_cast<uint16_t*>(desc+8) = 16; + if (reinterpret_cast<CreateQueueFn>(factory->vtable[10])(factory,desc,nullptr,&queue_ptr) != 0 || !queue_ptr || + reinterpret_cast<CreateStatusArrayFn>(factory->vtable[5])(factory,2,"BCPack",nullptr,&status_ptr) != 0 || !status_ptr) + return false; + auto* queue = static_cast<Object*>(queue_ptr); + auto* status = static_cast<Object*>(status_ptr); + std::vector<uint8_t> linear(96,0xa5), following(64,0xa5); + size_t page_count = 2; + u64 pages[2] = {}; + ULONG_PTR tokens[2] = {}; + void* view = nullptr; + if (page) { + if (!XMemAllocatePhysicalPages(0x20400000ull,&page_count,pages) || page_count != 2) return false; + tokens[0] = pages[0]; tokens[1] = pages[1]; + view = XMemVirtualAlloc(nullptr,131072,0x20402000,0x21,PAGE_READWRITE); + if (!view || XMemMapPhysicalPages(view,2,tokens) != view) return false; + std::memset(view,0xa5,131072); + if (scenario == 8 || scenario == 9) tokens[1] = 0; // missing second page: no partial publication + } + wchar_t temp_dir[MAX_PATH], temp_file[MAX_PATH] = {}; + Object* source_file = nullptr; + if (file) { + if (!GetTempPathW(MAX_PATH,temp_dir) || !GetTempFileNameW(temp_dir,L"bcp",0,temp_file)) return false; + const auto h = CreateFileW(temp_file,GENERIC_WRITE,0,nullptr,CREATE_ALWAYS,FILE_ATTRIBUTE_NORMAL,nullptr); + if (h == INVALID_HANDLE_VALUE) return false; + const uint8_t prefix[13] = {}; + DWORD written = 0; + const bool wrote = WriteFile(h,prefix,sizeof(prefix),&written,nullptr) && written == sizeof(prefix) && + WriteFile(h,input.data(),static_cast<DWORD>(input.size()),&written,nullptr) && written == input.size(); + CloseHandle(h); + void* ptr = nullptr; + if (!wrote || reinterpret_cast<OpenFileFn>(factory->vtable[4])(factory,temp_file,nullptr,&ptr) != 0 || !ptr) return false; + source_file = static_cast<Object*>(ptr); + } + uint8_t requests[2][0x48] = {}; + for (unsigned k = 0; k < 2; ++k) { + auto* r = requests[k]; + const bool first = k == 0; + const bool use_file = first && file, use_zlib = first && zlib, use_pages = first && page; + const auto& src = first ? input : packed; + unsigned request_format = first && (scenario == 10 || scenario == 11) ? 8 : fmt; + *reinterpret_cast<u64*>(r) = (request_format << 1) | (use_zlib ? 1 : 0) | + (use_file ? 0 : 0x400000) | (use_pages ? 1ull<<21 : 0); + *reinterpret_cast<void**>(r+0x08) = use_pages ? static_cast<void*>(tokens) : + first ? static_cast<void*>(linear.data()+16) : static_cast<void*>(following.data()); + *reinterpret_cast<u64*>(r+0x10) = use_pages ? 65520 : 0; + *reinterpret_cast<unsigned*>(r+0x18) = 64; + *reinterpret_cast<const void**>(r+0x20) = use_file ? static_cast<const void*>(source_file) : src.data(); + *reinterpret_cast<u64*>(r+0x28) = use_file ? 13 : 0; + *reinterpret_cast<unsigned*>(r+0x30) = static_cast<unsigned>(src.size()); + *reinterpret_cast<unsigned*>(r+0x34) = static_cast<unsigned>(packed.size()); + reinterpret_cast<EnqueueRequestFn>(queue->vtable[3])(queue,r); + reinterpret_cast<EnqueueStatusFn>(queue->vtable[4])(queue,status,k); + } + reinterpret_cast<SubmitFn>(queue->vtable[6])(queue); + for (int i = 0; i < 200 && !reinterpret_cast<IsCompleteFn>(status->vtable[3])(status,1); ++i) Sleep(10); + bool ok = reinterpret_cast<IsCompleteFn>(status->vtable[3])(status,1); + const long hr = reinterpret_cast<GetHResultFn>(status->vtable[4])(status,0); + ok = ok && (invalid ? hr != 0 : hr == 0) && + reinterpret_cast<GetHResultFn>(status->vtable[4])(status,1) == 0 && std::memcmp(following.data(),expected,64) == 0; + const auto* destination = page ? static_cast<const uint8_t*>(view) : linear.data(); + const size_t size = page ? 131072 : linear.size(), offset = page ? 65520 : 16; + for (size_t at = 0; at < size; ++at) { + const uint8_t wanted = !invalid && at >= offset && at < offset+64 ? expected[at-offset] : 0xa5; + if (destination[at] != wanted) ok = false; + } + if (source_file) { + reinterpret_cast<CloseFileFn>(source_file->vtable[3])(source_file); + DeleteFileW(temp_file); + } + if (view) { + XMemMapPhysicalPages(view,2,nullptr); + VirtualFree(view,0,MEM_RELEASE); + XMemFreePhysicalPages(2,pages); + } + std::printf("BC%u storage scenario %u: %s\n",fmt,scenario,ok ? "ok" : "FAIL"); + if (!ok) return false; + } + } + return true; +} diff --git a/tests/bcpack_storage_goldens.h b/tests/bcpack_storage_goldens.h new file mode 100644 index 0000000000..4f2f09b16e --- /dev/null +++ b/tests/bcpack_storage_goldens.h @@ -0,0 +1,15 @@ +// GDK 1.2603.3.0 golden BC blocks from random_symbols(fmt,4,0x7700+fmt). +// Entirely synthetic input, no SDK or title bytes. SPDX-License-Identifier: MIT +#pragma once +inline constexpr unsigned char BC2_STORAGE_EXPECTED[64] = { + 0x0a, 0x5a, 0xf0, 0x97, 0x8d, 0x91, 0x11, 0xbb, 0xff, 0xb9, 0x2f, 0x9e, 0xa6, 0x92, 0x7e, 0x8c, + 0x8f, 0x87, 0x8d, 0xb3, 0x65, 0x45, 0x15, 0x89, 0x44, 0x5f, 0x13, 0x7c, 0x57, 0x45, 0xaa, 0xde, + 0xed, 0x54, 0x81, 0xa6, 0x64, 0xcd, 0xd8, 0xbe, 0x91, 0x96, 0x07, 0x79, 0xf2, 0x16, 0xbd, 0xd0, + 0x12, 0x3c, 0xa4, 0x7c, 0xd7, 0x3a, 0xc8, 0x20, 0x92, 0xdc, 0x96, 0x5b, 0x41, 0x6a, 0x48, 0xc0, +}; +inline constexpr unsigned char BC6_STORAGE_EXPECTED[64] = { + 0x3c, 0xb0, 0x9e, 0x26, 0xae, 0xc9, 0x66, 0xae, 0x35, 0x0e, 0x60, 0xb7, 0xb5, 0x77, 0xc3, 0x32, + 0x49, 0x95, 0xfb, 0xad, 0x62, 0x12, 0xe7, 0x49, 0x02, 0x35, 0x44, 0xe2, 0xb5, 0xd3, 0xd9, 0x8d, + 0x02, 0xf3, 0x80, 0x2a, 0xb8, 0x95, 0xa1, 0x7b, 0x10, 0x5e, 0x64, 0x6d, 0x56, 0x72, 0x71, 0x05, + 0xe6, 0xe9, 0xcd, 0xd4, 0xc6, 0xc7, 0xe0, 0x59, 0xca, 0x7d, 0x30, 0x54, 0x5e, 0x09, 0xbc, 0xfe, +}; diff --git a/tests/bcpack_tables_check.py b/tests/bcpack_tables_check.py index 696d1ce81e..fd9f2a0a39 100644 --- a/tests/bcpack_tables_check.py +++ b/tests/bcpack_tables_check.py @@ -43,9 +43,9 @@ class BCPackTablesCheck(unittest.TestCase): @classmethod def setUpClass(cls): content = HEADER.read_text(encoding="utf-8") - inl = ROOT / "src" / "startup_stubs" / "bcpack_tables_bcn.inl" - if inl.exists() and '#include "bcpack_tables_bcn.inl"' in content: - content = content.replace('#include "bcpack_tables_bcn.inl"', inl.read_text(encoding="utf-8")) + for name in ("bcpack_tables_bcn.inl", "bcpack_tables_extra.inl"): + inl = HEADER.parent / name + content = content.replace(f'#include "{name}"', inl.read_text(encoding="utf-8")) cls.text = strip_comments(content) def test_rans_model_tables(self): @@ -96,22 +96,46 @@ def test_bc7_dictionary_structure(self): for b in row: self.assertIn(b, range(256)) - def test_bc1_window_structure(self): - window = extract_array(self.text, "BC1_WINDOW") - self.assertEqual(len(window), 256) - for row in window: - self.assertEqual(len(row), 6) - for b in row: - self.assertIn(b, range(256)) - - def test_bc1_quad_masks_structure(self): - quad_masks = extract_array(self.text, "BC1_QUAD_MASKS") - self.assertEqual(len(quad_masks), 4) - for row in quad_masks: - self.assertEqual(len(row), 256) - for mask in row: - self.assertGreaterEqual(mask, 0) - self.assertLessEqual(mask, 0xFFFFFFFF) + def test_bc1_bc2_exact_tables_structure(self): + for fmt in (1, 2): + ranks = extract_array(self.text, f"BC{fmt}_POSITION_RANK") + self.assertEqual(len(ranks), 256) + self.assertEqual({tuple(row) for row in ranks}, + {(a, b, c, d) for a in range(4) for b in range(4) + for c in range(4) for d in range(4)}) + dictionary = extract_array(self.text, f"BC{fmt}_FULL_DICTIONARY") + self.assertEqual(len(dictionary), 255) + for row in dictionary: + if fmt == 2: + alpha, ep, ix = row + self.assertEqual(len(alpha), 16) + self.assertTrue(all(v in range(16) for v in alpha)) + else: + ep, ix = row + self.assertEqual(len(ep), 6) + self.assertTrue(all(v in range(64 if i % 3 == 1 else 32) + for i, v in enumerate(ep))) + self.assertEqual(len(ix), 16) + self.assertTrue(all(v in range(4) for v in ix)) + + def test_bc6_tables_structure(self): + dictionary = extract_array(self.text, "BC6_DICTIONARY") + self.assertEqual(len(dictionary), 255) + for ep, ix in dictionary: + self.assertEqual(len(ep), 4) + for endpoint in ep: + self.assertEqual(len(endpoint), 3) + self.assertTrue(all(v in range(65536) for v in endpoint)) + self.assertEqual(len(ix), 16) + self.assertTrue(all(v in range(65536) for v in ix)) + wire = extract_array(self.text, "BC6_WIRE") + self.assertEqual(len(wire), 14) + for mode, row in enumerate(wire): + self.assertEqual(len(row), 82 if mode < 10 else 65) + for field, bit in row: + self.assertIn(field, range(14)) + self.assertIn(bit, range(16)) + self.assertEqual(len(extract_array(self.text, "BC6_ENDPOINT_BITS")), 15) def test_bc4_tables_structure(self): pairs = extract_array(self.text, "RANK_PAIR_BC4") @@ -202,10 +226,6 @@ def test_compare_with_reference_data_if_present(self): expected_dict.append([subsets, [ep[0:8], ep[8:16], ep[16:24]], [ix[0:16], ix[16:32]]]) self.assertEqual(extract_array(self.text, "BC7_DICTIONARY"), expected_dict) - window_json = json.loads((REF_DATA / "bc1_window.json").read_text(encoding="utf-8"))["slots"] - expected_window = [[0] * 6 if e is None else e["value"] for e in window_json] - self.assertEqual(extract_array(self.text, "BC1_WINDOW"), expected_window) - # BC4 checks bc4_json = json.loads((REF_DATA / "bc4.json").read_text(encoding="utf-8")) self.assertEqual(extract_array(self.text, "RANK_PAIR_BC4"), bc4_json["pairs"]) diff --git a/tests/checks/pixel-binary/startup_image_cube.txt b/tests/checks/pixel-binary/startup_image_cube.txt new file mode 100644 index 0000000000..ea2f423737 --- /dev/null +++ b/tests/checks/pixel-binary/startup_image_cube.txt @@ -0,0 +1 @@ +tests/startup_image_cube_check.py binary llvm-mc-15 diff --git a/tests/checks/python-linux/gdk_knowledge_report.txt b/tests/checks/python-linux/gdk_knowledge_report.txt new file mode 100644 index 0000000000..7917575364 --- /dev/null +++ b/tests/checks/python-linux/gdk_knowledge_report.txt @@ -0,0 +1 @@ +tests/gdk_knowledge_report_check.py diff --git a/tests/checks/python-linux/gdk_layouts.txt b/tests/checks/python-linux/gdk_layouts.txt new file mode 100644 index 0000000000..059002a3c5 --- /dev/null +++ b/tests/checks/python-linux/gdk_layouts.txt @@ -0,0 +1 @@ +tests/gdk_layouts_check.py diff --git a/tests/checks/python-linux/gdk_platform_profiles.txt b/tests/checks/python-linux/gdk_platform_profiles.txt new file mode 100644 index 0000000000..f83b228b84 --- /dev/null +++ b/tests/checks/python-linux/gdk_platform_profiles.txt @@ -0,0 +1 @@ +tests/gdk_platform_profiles_check.py diff --git a/tests/checks/python-linux/gdk_runtime_oracle.txt b/tests/checks/python-linux/gdk_runtime_oracle.txt new file mode 100644 index 0000000000..d4fdc274fe --- /dev/null +++ b/tests/checks/python-linux/gdk_runtime_oracle.txt @@ -0,0 +1 @@ +tests/gdk_runtime_oracle_check.py diff --git a/tests/checks/python-linux/gdk_shader_corpus.txt b/tests/checks/python-linux/gdk_shader_corpus.txt new file mode 100644 index 0000000000..2e522eda0a --- /dev/null +++ b/tests/checks/python-linux/gdk_shader_corpus.txt @@ -0,0 +1 @@ +tests/gdk_shader_corpus_check.py diff --git a/tests/checks/python-linux/shader_compile_lds_request_cli.txt b/tests/checks/python-linux/shader_compile_lds_request_cli.txt new file mode 100644 index 0000000000..76a947e366 --- /dev/null +++ b/tests/checks/python-linux/shader_compile_lds_request_cli.txt @@ -0,0 +1 @@ +tests/startup_compile_lds_request_cli_check.py diff --git a/tests/checks/python-linux/startup_compute_waterfall_heap.txt b/tests/checks/python-linux/startup_compute_waterfall_heap.txt new file mode 100644 index 0000000000..decf1dc693 --- /dev/null +++ b/tests/checks/python-linux/startup_compute_waterfall_heap.txt @@ -0,0 +1 @@ +tests/startup_compute_waterfall_heap_check.py diff --git a/tests/checks/python-linux/startup_gfx2hlsl_v_dot2.txt b/tests/checks/python-linux/startup_gfx2hlsl_v_dot2.txt new file mode 100644 index 0000000000..2a9dd9d5ff --- /dev/null +++ b/tests/checks/python-linux/startup_gfx2hlsl_v_dot2.txt @@ -0,0 +1 @@ +tests/startup_gfx2hlsl_v_dot2_check.py diff --git a/tests/checks/python-linux/startup_image_cube.txt b/tests/checks/python-linux/startup_image_cube.txt new file mode 100644 index 0000000000..1ec2d8bd43 --- /dev/null +++ b/tests/checks/python-linux/startup_image_cube.txt @@ -0,0 +1 @@ +tests/startup_image_cube_check.py diff --git a/tests/cmake/bcpack_formats.cmake b/tests/cmake/bcpack_formats.cmake new file mode 100644 index 0000000000..aa1fe16d16 --- /dev/null +++ b/tests/cmake/bcpack_formats.cmake @@ -0,0 +1,15 @@ +add_executable(bcpack_formats_check tests/bcpack_formats_check.cpp) +target_compile_features(bcpack_formats_check PRIVATE cxx_std_17) +target_include_directories(bcpack_formats_check PRIVATE src) +target_compile_definitions(bcpack_formats_check PRIVATE X2W_BCPACK_LANE_TESTS) +add_test(NAME bcpack_all_formats COMMAND bcpack_formats_check) +add_test(NAME bcpack_all_formats_golden_control COMMAND bcpack_formats_check --mutate) +set_tests_properties(bcpack_all_formats bcpack_all_formats_golden_control PROPERTIES TIMEOUT 120) +set_tests_properties(bcpack_all_formats_golden_control PROPERTIES WILL_FAIL TRUE) +add_test(NAME startup_bcpack_storage COMMAND startup_stub_consumer bcpack-storage) +set_tests_properties(startup_bcpack_storage PROPERTIES TIMEOUT 60) + +# Explicit target only: normal builds and all runtime DLLs need no oracle bridge. +add_library(bcpack_oracle_bridge SHARED EXCLUDE_FROM_ALL tests/bcpack_oracle_bridge.cpp) +target_compile_features(bcpack_oracle_bridge PRIVATE cxx_std_17) +target_include_directories(bcpack_oracle_bridge PRIVATE src) diff --git a/tests/cmake/native_bytewin_store.cmake b/tests/cmake/native_bytewin_store.cmake index e1239e016d..f74d743cca 100644 --- a/tests/cmake/native_bytewin_store.cmake +++ b/tests/cmake/native_bytewin_store.cmake @@ -8,4 +8,12 @@ if(TARGET compile_dxil AND TARGET native_store_replay AND "${CMAKE_SOURCE_DIR}/tests/native_bytewin_store_check.py" hardware "$<TARGET_FILE:native_store_replay>" "${DXC_BIN_DIR}") set_tests_properties(native_bytewin_store_hardware PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60) + add_test(NAME native_raw_store_cache_bits_controls COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/native_raw_store_cache_bits_check.py" controls + "$<TARGET_FILE:compile_dxil>" "${DXC_BIN_DIR}") + set_tests_properties(native_raw_store_cache_bits_controls PROPERTIES TIMEOUT 60) + add_test(NAME native_raw_store_cache_bits_hardware COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/native_raw_store_cache_bits_check.py" hardware + "$<TARGET_FILE:native_store_replay>" "${DXC_BIN_DIR}") + set_tests_properties(native_raw_store_cache_bits_hardware PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60) endif() diff --git a/tests/cmake/native_compile_dxil_rekey.cmake b/tests/cmake/native_compile_dxil_rekey.cmake new file mode 100644 index 0000000000..25559ea344 --- /dev/null +++ b/tests/cmake/native_compile_dxil_rekey.cmake @@ -0,0 +1,7 @@ +# Native cache re-keying (--rekey) in compile_dxil (#2935). +if(TARGET compile_dxil) + add_test(NAME native_compile_dxil_rekey COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/native_compile_dxil_rekey_check.py" + "$<TARGET_FILE:compile_dxil>") + set_tests_properties(native_compile_dxil_rekey PROPERTIES TIMEOUT 60) +endif() diff --git a/tests/cmake/native_compute_implicit_lod.cmake b/tests/cmake/native_compute_implicit_lod.cmake new file mode 100644 index 0000000000..2baf329e27 --- /dev/null +++ b/tests/cmake/native_compute_implicit_lod.cmake @@ -0,0 +1,15 @@ +if(TARGET compile_dxil AND EXISTS "${INTAKE_PYTHON}" AND + EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${DXC_BIN_DIR}/dxil.dll") + set(implicit_lod_check "${CMAKE_SOURCE_DIR}/tests/native_compute_implicit_lod_check.py") + add_test(NAME native_compute_implicit_lod_controls COMMAND "${INTAKE_PYTHON}" -B + "${implicit_lod_check}" "$<TARGET_FILE:compile_dxil>" "${DXC_BIN_DIR}") + set_tests_properties(native_compute_implicit_lod_controls PROPERTIES TIMEOUT 330) + if(TARGET offscreen_check) + foreach(adapter IN ITEMS warp hardware) + add_test(NAME native_compute_implicit_lod_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${implicit_lod_check}" "$<TARGET_FILE:compile_dxil>" "${DXC_BIN_DIR}" + "$<TARGET_FILE:offscreen_check>" ${adapter}) + set_tests_properties(native_compute_implicit_lod_${adapter} PROPERTIES TIMEOUT 540 SKIP_RETURN_CODE 77) + endforeach() + endif() +endif() diff --git a/tests/cmake/native_compute_manifest_reasons.cmake b/tests/cmake/native_compute_manifest_reasons.cmake new file mode 100644 index 0000000000..a142534f0b --- /dev/null +++ b/tests/cmake/native_compute_manifest_reasons.cmake @@ -0,0 +1,15 @@ +# Named reasons for compute programs that compile but get no runtime manifest (#3224). +# native_compute_manifest_reasons calls the formatter once per reason; the _requests check runs one reachable +# reason through compile_dxil --requests, --refusals, --watch and triage_run.py. +if(TARGET compile_dxil) + add_executable(native_compute_manifest_reasons tests/native_compute_manifest_reasons.cpp) + target_link_libraries(native_compute_manifest_reasons PRIVATE x2w_shader_compiler) + set_property(TARGET native_compute_manifest_reasons PROPERTY MSVC_RUNTIME_LIBRARY "MultiThreaded$<$<CONFIG:Debug>:Debug>") + add_test(NAME native_compute_manifest_reasons COMMAND native_compute_manifest_reasons) + if(EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${DXC_BIN_DIR}/dxil.dll" AND EXISTS "${INTAKE_PYTHON}") + add_test(NAME native_compute_manifest_reasons_requests COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/native_compute_manifest_reasons_check.py" + "$<TARGET_FILE:compile_dxil>" "${DXC_BIN_DIR}") + set_tests_properties(native_compute_manifest_reasons_requests PROPERTIES TIMEOUT 60) + endif() +endif() diff --git a/tests/cmake/native_cvt_norm_f16.cmake b/tests/cmake/native_cvt_norm_f16.cmake new file mode 100644 index 0000000000..8c1717f4c5 --- /dev/null +++ b/tests/cmake/native_cvt_norm_f16.cmake @@ -0,0 +1,20 @@ +# Direct DXIL VOP1/VOP3 v_cvt_norm_i16_f16 and v_cvt_norm_u16_f16. Compute replay needs SM 6.6 with wave32. +if(TARGET compile_dxil AND TARGET native_store_replay AND TARGET offscreen_check AND + EXISTS "${INTAKE_PYTHON}" AND EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${DXC_BIN_DIR}/dxil.dll") + set(checker "${CMAKE_CURRENT_SOURCE_DIR}/tests/native_cvt_norm_f16_check.py") + add_test(NAME native_cvt_norm_f16_ir COMMAND "${INTAKE_PYTHON}" -B + "${checker}" ir "$<TARGET_FILE:native_compute_ir_dump>") + set_tests_properties(native_cvt_norm_f16_ir PROPERTIES TIMEOUT 60) + add_test(NAME native_cvt_norm_f16_controls COMMAND "${INTAKE_PYTHON}" -B + "${checker}" controls "$<TARGET_FILE:compile_dxil>" "${DXC_BIN_DIR}") + set_tests_properties(native_cvt_norm_f16_controls PROPERTIES TIMEOUT 60) + add_test(NAME native_cvt_norm_f16_compute_hardware COMMAND "${INTAKE_PYTHON}" -B + "${checker}" compute "$<TARGET_FILE:native_store_replay>" "${DXC_BIN_DIR}") + set_tests_properties(native_cvt_norm_f16_compute_hardware PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77) + foreach(adapter IN ITEMS warp hardware) + add_test(NAME native_cvt_norm_f16_pixel_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${checker}" pixel "$<TARGET_FILE:compile_dxil>" "${DXC_BIN_DIR}" "$<TARGET_FILE:offscreen_check>" ${adapter}) + set_tests_properties(native_cvt_norm_f16_pixel_${adapter} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77) + endforeach() + unset(checker) +endif() diff --git a/tests/cmake/native_cvt_pknorm_f32.cmake b/tests/cmake/native_cvt_pknorm_f32.cmake new file mode 100644 index 0000000000..bd0bf75f74 --- /dev/null +++ b/tests/cmake/native_cvt_pknorm_f32.cmake @@ -0,0 +1,20 @@ +# Direct DXIL VOP3 v_cvt_pknorm_i16_f32 and v_cvt_pknorm_u16_f32. Compute replay needs SM 6.6 with wave32. +if(TARGET compile_dxil AND TARGET native_store_replay AND TARGET offscreen_check AND + EXISTS "${INTAKE_PYTHON}" AND EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${DXC_BIN_DIR}/dxil.dll") + set(checker "${CMAKE_CURRENT_SOURCE_DIR}/tests/native_cvt_pknorm_f32_check.py") + add_test(NAME native_cvt_pknorm_f32_ir COMMAND "${INTAKE_PYTHON}" -B + "${checker}" ir "$<TARGET_FILE:native_compute_ir_dump>") + set_tests_properties(native_cvt_pknorm_f32_ir PROPERTIES TIMEOUT 60) + add_test(NAME native_cvt_pknorm_f32_controls COMMAND "${INTAKE_PYTHON}" -B + "${checker}" controls "$<TARGET_FILE:compile_dxil>" "${DXC_BIN_DIR}") + set_tests_properties(native_cvt_pknorm_f32_controls PROPERTIES TIMEOUT 60) + add_test(NAME native_cvt_pknorm_f32_compute_hardware COMMAND "${INTAKE_PYTHON}" -B + "${checker}" compute "$<TARGET_FILE:native_store_replay>" "${DXC_BIN_DIR}") + set_tests_properties(native_cvt_pknorm_f32_compute_hardware PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77) + foreach(adapter IN ITEMS warp hardware) + add_test(NAME native_cvt_pknorm_f32_pixel_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${checker}" pixel "$<TARGET_FILE:compile_dxil>" "${DXC_BIN_DIR}" "$<TARGET_FILE:offscreen_check>" ${adapter}) + set_tests_properties(native_cvt_pknorm_f32_pixel_${adapter} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77) + endforeach() + unset(checker) +endif() diff --git a/tests/cmake/native_dot4c.cmake b/tests/cmake/native_dot4c.cmake new file mode 100644 index 0000000000..fc6c1639f1 --- /dev/null +++ b/tests/cmake/native_dot4c.cmake @@ -0,0 +1,12 @@ +# Direct compute VOP2 signed byte dot-accumulate. +if(TARGET compile_dxil AND TARGET native_store_replay AND + EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${DXC_BIN_DIR}/dxil.dll") + add_test(NAME native_dot4c_ir COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/native_dot4c_check.py" ir + "$<TARGET_FILE:compile_dxil>" "${DXC_BIN_DIR}") + set_tests_properties(native_dot4c_ir PROPERTIES TIMEOUT 60) + add_test(NAME native_dot4c_hardware COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/native_dot4c_check.py" hardware + "$<TARGET_FILE:native_store_replay>" "${DXC_BIN_DIR}") + set_tests_properties(native_dot4c_hardware PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60) +endif() diff --git a/tests/cmake/native_dpp8.cmake b/tests/cmake/native_dpp8.cmake new file mode 100644 index 0000000000..08b341c016 --- /dev/null +++ b/tests/cmake/native_dpp8.cmake @@ -0,0 +1,7 @@ +if(TARGET compile_dxil AND TARGET native_store_replay AND + EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${DXC_BIN_DIR}/dxil.dll") + add_test(NAME native_dpp8_hardware COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/native_dpp8_check.py" + "$<TARGET_FILE:native_store_replay>" "${DXC_BIN_DIR}") + set_tests_properties(native_dpp8_hardware PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60) +endif() diff --git a/tests/cmake/native_exec_symbol_b64.cmake b/tests/cmake/native_exec_symbol_b64.cmake new file mode 100644 index 0000000000..c39593c996 --- /dev/null +++ b/tests/cmake/native_exec_symbol_b64.cmake @@ -0,0 +1,7 @@ +if(TARGET compile_dxil AND EXISTS "${INTAKE_PYTHON}" AND + EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${DXC_BIN_DIR}/dxil.dll") + add_test(NAME native_exec_symbol_b64_controls COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/native_exec_symbol_b64_check.py" + controls "$<TARGET_FILE:compile_dxil>" "${DXC_BIN_DIR}") + set_tests_properties(native_exec_symbol_b64_controls PROPERTIES TIMEOUT 60) +endif() diff --git a/tests/cmake/native_fma_f16_opsel.cmake b/tests/cmake/native_fma_f16_opsel.cmake new file mode 100644 index 0000000000..56692ba2ea --- /dev/null +++ b/tests/cmake/native_fma_f16_opsel.cmake @@ -0,0 +1,14 @@ +# Sorts after native_f16_alu.cmake, which defines native_compute_ir_dump. +if(TARGET native_compute_ir_dump AND EXISTS "${INTAKE_PYTHON}") + add_test(NAME native_fma_f16_opsel_ir COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/native_fma_f16_opsel_check.py" ir + "$<TARGET_FILE:native_compute_ir_dump>") + set_tests_properties(native_fma_f16_opsel_ir PROPERTIES TIMEOUT 60) +endif() +if(TARGET native_store_replay AND EXISTS "${INTAKE_PYTHON}" AND + EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${DXC_BIN_DIR}/dxil.dll") + add_test(NAME native_fma_f16_opsel_hardware COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/native_fma_f16_opsel_check.py" hardware + "$<TARGET_FILE:native_store_replay>" "${DXC_BIN_DIR}") + set_tests_properties(native_fma_f16_opsel_hardware PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60) +endif() diff --git a/tests/cmake/native_fract_f16.cmake b/tests/cmake/native_fract_f16.cmake new file mode 100644 index 0000000000..c0f9c9f869 --- /dev/null +++ b/tests/cmake/native_fract_f16.cmake @@ -0,0 +1,20 @@ +# Direct Compute and Pixel DXIL VOP1/VOP3 v_fract_f16 checks. +if(TARGET native_compute_ir_dump AND TARGET compile_dxil AND TARGET native_store_replay AND TARGET offscreen_check AND + EXISTS "${INTAKE_PYTHON}" AND EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${DXC_BIN_DIR}/dxil.dll") + set(checker "${CMAKE_CURRENT_SOURCE_DIR}/tests/native_fract_f16_check.py") + add_test(NAME native_fract_f16_ir COMMAND "${INTAKE_PYTHON}" -B + "${checker}" ir "$<TARGET_FILE:native_compute_ir_dump>") + set_tests_properties(native_fract_f16_ir PROPERTIES TIMEOUT 60) + add_test(NAME native_fract_f16_controls COMMAND "${INTAKE_PYTHON}" -B + "${checker}" controls "$<TARGET_FILE:compile_dxil>" "${DXC_BIN_DIR}") + set_tests_properties(native_fract_f16_controls PROPERTIES TIMEOUT 60) + add_test(NAME native_fract_f16_compute_hardware COMMAND "${INTAKE_PYTHON}" -B + "${checker}" compute "$<TARGET_FILE:native_store_replay>" "${DXC_BIN_DIR}") + set_tests_properties(native_fract_f16_compute_hardware PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77) + foreach(adapter IN ITEMS warp hardware) + add_test(NAME native_fract_f16_pixel_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${checker}" pixel "$<TARGET_FILE:compile_dxil>" "${DXC_BIN_DIR}" "$<TARGET_FILE:offscreen_check>" ${adapter}) + set_tests_properties(native_fract_f16_pixel_${adapter} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77) + endforeach() + unset(checker) +endif() diff --git a/tests/cmake/native_fract_f32.cmake b/tests/cmake/native_fract_f32.cmake new file mode 100644 index 0000000000..3d24a542c4 --- /dev/null +++ b/tests/cmake/native_fract_f32.cmake @@ -0,0 +1,11 @@ +if(TARGET compile_dxil AND TARGET native_store_replay AND EXISTS "${INTAKE_PYTHON}" AND + EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${DXC_BIN_DIR}/dxil.dll") + add_test(NAME native_fract_f32_controls COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/native_fract_f32_check.py" controls + "$<TARGET_FILE:compile_dxil>" "${DXC_BIN_DIR}") + add_test(NAME native_fract_f32_hardware COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/native_fract_f32_check.py" hardware + "$<TARGET_FILE:native_store_replay>" "${DXC_BIN_DIR}") + set_tests_properties(native_fract_f32_controls PROPERTIES TIMEOUT 60) + set_tests_properties(native_fract_f32_hardware PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60) +endif() diff --git a/tests/cmake/native_global_srv_heap_replay.cmake b/tests/cmake/native_global_srv_heap_replay.cmake index b966866a65..f2dbe64bc9 100644 --- a/tests/cmake/native_global_srv_heap_replay.cmake +++ b/tests/cmake/native_global_srv_heap_replay.cmake @@ -12,4 +12,8 @@ if(TARGET compile_dxil AND EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${ "$<TARGET_FILE:native_global_srv_heap_replay>" "$<TARGET_FILE:compile_dxil>" "${DXC_BIN_DIR}" ${adapter}) set_tests_properties(native_global_srv_heap_replay_${adapter} PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 120) endforeach() + add_test(NAME native_raw_load_cache_bits_hardware COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/native_raw_load_cache_bits_check.py" + "$<TARGET_FILE:native_global_srv_heap_replay>" "$<TARGET_FILE:compile_dxil>" "${DXC_BIN_DIR}") + set_tests_properties(native_raw_load_cache_bits_hardware PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 120) endif() diff --git a/tests/cmake/native_heap_offset_add.cmake b/tests/cmake/native_heap_offset_add.cmake new file mode 100644 index 0000000000..f4ab8ffb76 --- /dev/null +++ b/tests/cmake/native_heap_offset_add.cmake @@ -0,0 +1,7 @@ +# A slot 67 resource-heap descriptor address formed by s_add_u32 with its carry (#3224). +if(TARGET compile_dxil AND EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${DXC_BIN_DIR}/dxil.dll") + add_test(NAME native_heap_offset_add COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/native_heap_offset_add_check.py" + "$<TARGET_FILE:compile_dxil>" "${DXC_BIN_DIR}") + set_tests_properties(native_heap_offset_add PROPERTIES TIMEOUT 60) +endif() diff --git a/tests/cmake/native_image_atomic_binops.cmake b/tests/cmake/native_image_atomic_binops.cmake new file mode 100644 index 0000000000..ee4658b799 --- /dev/null +++ b/tests/cmake/native_image_atomic_binops.cmake @@ -0,0 +1,14 @@ +if(TARGET compile_dxil AND TARGET offscreen_check AND EXISTS "${INTAKE_PYTHON}" AND + EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${DXC_BIN_DIR}/dxil.dll") + set(checker "${CMAKE_CURRENT_SOURCE_DIR}/tests/native_image_atomic_binops_check.py") + add_test(NAME native_image_atomic_binops_controls COMMAND "${INTAKE_PYTHON}" -B + "${checker}" controls "$<TARGET_FILE:compile_dxil>" "${DXC_BIN_DIR}") + set_tests_properties(native_image_atomic_binops_controls PROPERTIES TIMEOUT 120) + foreach(adapter IN ITEMS warp hardware) + add_test(NAME native_image_atomic_binops_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${checker}" hardware "$<TARGET_FILE:compile_dxil>" "${DXC_BIN_DIR}" + "$<TARGET_FILE:offscreen_check>" ${adapter}) + set_tests_properties(native_image_atomic_binops_${adapter} PROPERTIES TIMEOUT 180 SKIP_RETURN_CODE 77) + endforeach() + unset(checker) +endif() diff --git a/tests/cmake/native_image_cache_flags.cmake b/tests/cmake/native_image_cache_flags.cmake new file mode 100644 index 0000000000..003b7ddc2d --- /dev/null +++ b/tests/cmake/native_image_cache_flags.cmake @@ -0,0 +1,15 @@ +if(TARGET compile_dxil AND TARGET offscreen_check AND EXISTS "${INTAKE_PYTHON}" AND + EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${DXC_BIN_DIR}/dxil.dll") + add_test(NAME native_image_cache_flags_controls COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/native_image_cache_flags_check.py" controls + "$<TARGET_FILE:compile_dxil>" "${DXC_BIN_DIR}") + set_tests_properties(native_image_cache_flags_controls PROPERTIES TIMEOUT 60) + foreach(stage IN ITEMS ps cs) + foreach(adapter IN ITEMS warp hardware) + add_test(NAME native_image_cache_flags_${stage}_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/native_image_cache_flags_check.py" ${stage} + "$<TARGET_FILE:compile_dxil>" "${DXC_BIN_DIR}" "$<TARGET_FILE:offscreen_check>" ${adapter}) + set_tests_properties(native_image_cache_flags_${stage}_${adapter} PROPERTIES TIMEOUT 90 SKIP_RETURN_CODE 77) + endforeach() + endforeach() +endif() diff --git a/tests/cmake/native_ldexp_f16.cmake b/tests/cmake/native_ldexp_f16.cmake new file mode 100644 index 0000000000..abd675c284 --- /dev/null +++ b/tests/cmake/native_ldexp_f16.cmake @@ -0,0 +1,12 @@ +if(TARGET compile_dxil AND TARGET native_store_replay AND EXISTS "${INTAKE_PYTHON}") + add_test(NAME native_ldexp_f16_controls + COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/native_ldexp_f16_check.py" + controls "$<TARGET_FILE:compile_dxil>" "${DXC_BIN_DIR}") + set_tests_properties(native_ldexp_f16_controls PROPERTIES TIMEOUT 60) + add_test(NAME native_ldexp_f16_hardware + COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/native_ldexp_f16_check.py" + hardware "$<TARGET_FILE:native_store_replay>" "${DXC_BIN_DIR}") + set_tests_properties(native_ldexp_f16_hardware PROPERTIES + SKIP_RETURN_CODE 77 + TIMEOUT 60) +endif() diff --git a/tests/cmake/native_mad32_k.cmake b/tests/cmake/native_mad32_k.cmake new file mode 100644 index 0000000000..efc50cf87a --- /dev/null +++ b/tests/cmake/native_mad32_k.cmake @@ -0,0 +1,19 @@ +if(TARGET native_compute_ir_dump AND TARGET compile_dxil AND TARGET native_store_replay AND TARGET offscreen_check AND + EXISTS "${INTAKE_PYTHON}" AND EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${DXC_BIN_DIR}/dxil.dll") + set(checker "${CMAKE_CURRENT_SOURCE_DIR}/tests/native_mad32_k_check.py") + add_test(NAME native_mad32_k_ir COMMAND "${INTAKE_PYTHON}" -B + "${checker}" ir "$<TARGET_FILE:native_compute_ir_dump>") + set_tests_properties(native_mad32_k_ir PROPERTIES TIMEOUT 60) + add_test(NAME native_mad32_k_controls COMMAND "${INTAKE_PYTHON}" -B + "${checker}" controls "$<TARGET_FILE:compile_dxil>" "${DXC_BIN_DIR}") + set_tests_properties(native_mad32_k_controls PROPERTIES TIMEOUT 60) + add_test(NAME native_mad32_k_compute_hardware COMMAND "${INTAKE_PYTHON}" -B + "${checker}" compute "$<TARGET_FILE:native_store_replay>" "${DXC_BIN_DIR}") + set_tests_properties(native_mad32_k_compute_hardware PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77) + foreach(adapter IN ITEMS warp hardware) + add_test(NAME native_mad32_k_pixel_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${checker}" pixel "$<TARGET_FILE:compile_dxil>" "${DXC_BIN_DIR}" "$<TARGET_FILE:offscreen_check>" ${adapter}) + set_tests_properties(native_mad32_k_pixel_${adapter} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77) + endforeach() + unset(checker) +endif() diff --git a/tests/cmake/native_or_saveexec.cmake b/tests/cmake/native_or_saveexec.cmake new file mode 100644 index 0000000000..84ae90a645 --- /dev/null +++ b/tests/cmake/native_or_saveexec.cmake @@ -0,0 +1,6 @@ +if(TARGET native_store_replay AND EXISTS "${INTAKE_PYTHON}" AND + EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${DXC_BIN_DIR}/dxil.dll") + add_test(NAME native_or_saveexec_hardware COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/native_or_saveexec_check.py" "$<TARGET_FILE:native_store_replay>" "${DXC_BIN_DIR}") + set_tests_properties(native_or_saveexec_hardware PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 120) +endif() diff --git a/tests/cmake/native_packed_dot2_f16.cmake b/tests/cmake/native_packed_dot2_f16.cmake new file mode 100644 index 0000000000..99f8fb3bbf --- /dev/null +++ b/tests/cmake/native_packed_dot2_f16.cmake @@ -0,0 +1,19 @@ +if(TARGET native_compute_ir_dump AND TARGET compile_dxil AND TARGET native_store_replay AND TARGET offscreen_check AND + EXISTS "${INTAKE_PYTHON}" AND EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${DXC_BIN_DIR}/dxil.dll") + set(checker "${CMAKE_CURRENT_SOURCE_DIR}/tests/native_dot2_f32_f16_check.py") + add_test(NAME native_packed_dot2_f16_ir COMMAND "${INTAKE_PYTHON}" -B + "${checker}" ir "$<TARGET_FILE:native_compute_ir_dump>") + set_tests_properties(native_packed_dot2_f16_ir PROPERTIES TIMEOUT 60) + add_test(NAME native_packed_dot2_f16_controls COMMAND "${INTAKE_PYTHON}" -B + "${checker}" controls "$<TARGET_FILE:compile_dxil>" "${DXC_BIN_DIR}") + set_tests_properties(native_packed_dot2_f16_controls PROPERTIES TIMEOUT 60) + add_test(NAME native_packed_dot2_f16_compute_hardware COMMAND "${INTAKE_PYTHON}" -B + "${checker}" compute "$<TARGET_FILE:native_store_replay>" "${DXC_BIN_DIR}") + set_tests_properties(native_packed_dot2_f16_compute_hardware PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77) + foreach(adapter IN ITEMS warp hardware) + add_test(NAME native_packed_dot2_f16_pixel_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${checker}" pixel "$<TARGET_FILE:compile_dxil>" "${DXC_BIN_DIR}" "$<TARGET_FILE:offscreen_check>" ${adapter}) + set_tests_properties(native_packed_dot2_f16_pixel_${adapter} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77) + endforeach() + unset(checker) +endif() diff --git a/tests/cmake/native_packed_dot2c_f16.cmake b/tests/cmake/native_packed_dot2c_f16.cmake new file mode 100644 index 0000000000..333c902f52 --- /dev/null +++ b/tests/cmake/native_packed_dot2c_f16.cmake @@ -0,0 +1,20 @@ +# Direct Compute and Pixel DXIL v_dot2c_f32_f16 (accumulate-in-place packed f16 dot product) checks. +if(TARGET native_compute_ir_dump AND TARGET compile_dxil AND TARGET native_store_replay AND TARGET offscreen_check AND + EXISTS "${INTAKE_PYTHON}" AND EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${DXC_BIN_DIR}/dxil.dll") + set(checker "${CMAKE_CURRENT_SOURCE_DIR}/tests/native_dot2c_f32_f16_check.py") + add_test(NAME native_packed_dot2c_f16_ir COMMAND "${INTAKE_PYTHON}" -B + "${checker}" ir "$<TARGET_FILE:native_compute_ir_dump>") + set_tests_properties(native_packed_dot2c_f16_ir PROPERTIES TIMEOUT 60) + add_test(NAME native_packed_dot2c_f16_controls COMMAND "${INTAKE_PYTHON}" -B + "${checker}" controls "$<TARGET_FILE:compile_dxil>" "${DXC_BIN_DIR}") + set_tests_properties(native_packed_dot2c_f16_controls PROPERTIES TIMEOUT 60) + add_test(NAME native_packed_dot2c_f16_compute_hardware COMMAND "${INTAKE_PYTHON}" -B + "${checker}" compute "$<TARGET_FILE:native_store_replay>" "${DXC_BIN_DIR}") + set_tests_properties(native_packed_dot2c_f16_compute_hardware PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77) + foreach(adapter IN ITEMS warp hardware) + add_test(NAME native_packed_dot2c_f16_pixel_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${checker}" pixel "$<TARGET_FILE:compile_dxil>" "${DXC_BIN_DIR}" "$<TARGET_FILE:offscreen_check>" ${adapter}) + set_tests_properties(native_packed_dot2c_f16_pixel_${adapter} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77) + endforeach() + unset(checker) +endif() diff --git a/tests/cmake/native_packed_f16_clamp.cmake b/tests/cmake/native_packed_f16_clamp.cmake new file mode 100644 index 0000000000..4e0855a52d --- /dev/null +++ b/tests/cmake/native_packed_f16_clamp.cmake @@ -0,0 +1,20 @@ +# Direct DXIL VOP3P clamp on v_pk_add_f16, v_pk_mul_f16, and v_pk_fma_f16. Compute replay needs SM 6.6 with wave32. +if(TARGET native_compute_ir_dump AND TARGET compile_dxil AND TARGET native_store_replay AND TARGET offscreen_check AND + EXISTS "${INTAKE_PYTHON}" AND EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${DXC_BIN_DIR}/dxil.dll") + set(checker "${CMAKE_CURRENT_SOURCE_DIR}/tests/native_packed_f16_clamp_check.py") + add_test(NAME native_packed_f16_clamp_ir COMMAND "${INTAKE_PYTHON}" -B + "${checker}" ir "$<TARGET_FILE:native_compute_ir_dump>") + set_tests_properties(native_packed_f16_clamp_ir PROPERTIES TIMEOUT 60) + add_test(NAME native_packed_f16_clamp_controls COMMAND "${INTAKE_PYTHON}" -B + "${checker}" controls "$<TARGET_FILE:compile_dxil>" "${DXC_BIN_DIR}") + set_tests_properties(native_packed_f16_clamp_controls PROPERTIES TIMEOUT 60) + add_test(NAME native_packed_f16_clamp_compute_hardware COMMAND "${INTAKE_PYTHON}" -B + "${checker}" compute "$<TARGET_FILE:native_store_replay>" "${DXC_BIN_DIR}") + set_tests_properties(native_packed_f16_clamp_compute_hardware PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77) + foreach(adapter IN ITEMS warp hardware) + add_test(NAME native_packed_f16_clamp_pixel_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${checker}" pixel "$<TARGET_FILE:compile_dxil>" "${DXC_BIN_DIR}" "$<TARGET_FILE:offscreen_check>" ${adapter}) + set_tests_properties(native_packed_f16_clamp_pixel_${adapter} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77) + endforeach() + unset(checker) +endif() diff --git a/tests/cmake/native_packed_f16_inline.cmake b/tests/cmake/native_packed_f16_inline.cmake new file mode 100644 index 0000000000..7920cf2842 --- /dev/null +++ b/tests/cmake/native_packed_f16_inline.cmake @@ -0,0 +1,19 @@ +if(TARGET native_compute_ir_dump AND TARGET compile_dxil AND TARGET native_store_replay AND TARGET offscreen_check AND + EXISTS "${INTAKE_PYTHON}" AND EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${DXC_BIN_DIR}/dxil.dll") + set(checker "${CMAKE_CURRENT_SOURCE_DIR}/tests/native_packed_f16_inline_check.py") + add_test(NAME native_packed_f16_inline_ir COMMAND "${INTAKE_PYTHON}" -B + "${checker}" ir "$<TARGET_FILE:native_compute_ir_dump>") + set_tests_properties(native_packed_f16_inline_ir PROPERTIES TIMEOUT 60) + add_test(NAME native_packed_f16_inline_controls COMMAND "${INTAKE_PYTHON}" -B + "${checker}" controls "$<TARGET_FILE:compile_dxil>" "${DXC_BIN_DIR}") + set_tests_properties(native_packed_f16_inline_controls PROPERTIES TIMEOUT 60) + add_test(NAME native_packed_f16_inline_compute_hardware COMMAND "${INTAKE_PYTHON}" -B + "${checker}" compute "$<TARGET_FILE:native_store_replay>" "${DXC_BIN_DIR}") + set_tests_properties(native_packed_f16_inline_compute_hardware PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77) + foreach(adapter IN ITEMS warp hardware) + add_test(NAME native_packed_f16_inline_pixel_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${checker}" pixel "$<TARGET_FILE:compile_dxil>" "${DXC_BIN_DIR}" "$<TARGET_FILE:offscreen_check>" ${adapter}) + set_tests_properties(native_packed_f16_inline_pixel_${adapter} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77) + endforeach() + unset(checker) +endif() diff --git a/tests/cmake/native_pk_fmac_f16.cmake b/tests/cmake/native_pk_fmac_f16.cmake new file mode 100644 index 0000000000..332ae1eb54 --- /dev/null +++ b/tests/cmake/native_pk_fmac_f16.cmake @@ -0,0 +1,20 @@ +# Direct Compute and Pixel DXIL VOP2 v_pk_fmac_f16 checks. +if(TARGET native_compute_ir_dump AND TARGET compile_dxil AND TARGET native_store_replay AND TARGET offscreen_check AND + EXISTS "${INTAKE_PYTHON}" AND EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${DXC_BIN_DIR}/dxil.dll") + set(checker "${CMAKE_CURRENT_SOURCE_DIR}/tests/native_pk_fmac_f16_check.py") + add_test(NAME native_pk_fmac_f16_ir COMMAND "${INTAKE_PYTHON}" -B + "${checker}" ir "$<TARGET_FILE:native_compute_ir_dump>") + set_tests_properties(native_pk_fmac_f16_ir PROPERTIES TIMEOUT 60) + add_test(NAME native_pk_fmac_f16_controls COMMAND "${INTAKE_PYTHON}" -B + "${checker}" controls "$<TARGET_FILE:compile_dxil>" "${DXC_BIN_DIR}") + set_tests_properties(native_pk_fmac_f16_controls PROPERTIES TIMEOUT 60) + add_test(NAME native_pk_fmac_f16_compute_hardware COMMAND "${INTAKE_PYTHON}" -B + "${checker}" compute "$<TARGET_FILE:native_store_replay>" "${DXC_BIN_DIR}") + set_tests_properties(native_pk_fmac_f16_compute_hardware PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77) + foreach(adapter IN ITEMS warp hardware) + add_test(NAME native_pk_fmac_f16_pixel_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${checker}" pixel "$<TARGET_FILE:compile_dxil>" "${DXC_BIN_DIR}" "$<TARGET_FILE:offscreen_check>" ${adapter}) + set_tests_properties(native_pk_fmac_f16_pixel_${adapter} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77) + endforeach() + unset(checker) +endif() diff --git a/tests/cmake/native_rcp_iflag.cmake b/tests/cmake/native_rcp_iflag.cmake new file mode 100644 index 0000000000..08e8d49151 --- /dev/null +++ b/tests/cmake/native_rcp_iflag.cmake @@ -0,0 +1,16 @@ +if(TARGET compile_dxil AND TARGET native_store_replay AND TARGET offscreen_check AND + EXISTS "${INTAKE_PYTHON}" AND EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${DXC_BIN_DIR}/dxil.dll") + set(checker "${CMAKE_CURRENT_SOURCE_DIR}/tests/native_rcp_iflag_check.py") + add_test(NAME native_rcp_iflag_controls COMMAND "${INTAKE_PYTHON}" -B + "${checker}" controls "$<TARGET_FILE:compile_dxil>" "${DXC_BIN_DIR}") + set_tests_properties(native_rcp_iflag_controls PROPERTIES TIMEOUT 60) + add_test(NAME native_rcp_iflag_compute_hardware COMMAND "${INTAKE_PYTHON}" -B + "${checker}" compute "$<TARGET_FILE:native_store_replay>" "${DXC_BIN_DIR}") + set_tests_properties(native_rcp_iflag_compute_hardware PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77) + foreach(adapter IN ITEMS warp hardware) + add_test(NAME native_rcp_iflag_pixel_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${checker}" pixel "$<TARGET_FILE:compile_dxil>" "${DXC_BIN_DIR}" "$<TARGET_FILE:offscreen_check>" ${adapter}) + set_tests_properties(native_rcp_iflag_pixel_${adapter} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77) + endforeach() + unset(checker) +endif() diff --git a/tests/cmake/native_round_f16.cmake b/tests/cmake/native_round_f16.cmake new file mode 100644 index 0000000000..dcf112f990 --- /dev/null +++ b/tests/cmake/native_round_f16.cmake @@ -0,0 +1,12 @@ +if(X2W_HAVE_DXCAPI AND EXISTS "${INTAKE_PYTHON}") + add_test(NAME native_round_f16_controls + COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/native_round_f16_check.py" + controls "$<TARGET_FILE:compile_dxil>" "${DXC_BIN_DIR}") + set_tests_properties(native_round_f16_controls PROPERTIES TIMEOUT 60) + add_test(NAME native_round_f16_hardware + COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/native_round_f16_check.py" + hardware "$<TARGET_FILE:native_store_replay>" "${DXC_BIN_DIR}") + set_tests_properties(native_round_f16_hardware PROPERTIES + SKIP_RETURN_CODE 77 + TIMEOUT 60) +endif() diff --git a/tests/cmake/native_s_not_b64_exec.cmake b/tests/cmake/native_s_not_b64_exec.cmake new file mode 100644 index 0000000000..21a73092cf --- /dev/null +++ b/tests/cmake/native_s_not_b64_exec.cmake @@ -0,0 +1,12 @@ +if(TARGET compile_dxil AND EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${DXC_BIN_DIR}/dxil.dll") + add_test(NAME native_s_not_b64_exec_controls COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/native_s_not_b64_exec_check.py" controls + "$<TARGET_FILE:compile_dxil>" "${DXC_BIN_DIR}") + set_tests_properties(native_s_not_b64_exec_controls PROPERTIES TIMEOUT 60) + if(TARGET native_store_replay) + add_test(NAME native_s_not_b64_exec_hardware COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/native_s_not_b64_exec_check.py" hardware + "$<TARGET_FILE:native_store_replay>" "${DXC_BIN_DIR}") + set_tests_properties(native_s_not_b64_exec_hardware PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60) + endif() +endif() diff --git a/tests/cmake/native_saveexec_wrexec.cmake b/tests/cmake/native_saveexec_wrexec.cmake new file mode 100644 index 0000000000..9aee2ae897 --- /dev/null +++ b/tests/cmake/native_saveexec_wrexec.cmake @@ -0,0 +1,17 @@ +if(TARGET native_compute_ir_dump AND EXISTS "${INTAKE_PYTHON}") + add_test(NAME native_saveexec_wrexec_ir COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/native_saveexec_wrexec_check.py" ir + "$<TARGET_FILE:native_compute_ir_dump>") + set_tests_properties(native_saveexec_wrexec_ir PROPERTIES TIMEOUT 60) +endif() +if(TARGET compile_dxil AND TARGET native_store_replay AND EXISTS "${INTAKE_PYTHON}" AND + EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${DXC_BIN_DIR}/dxil.dll") + add_test(NAME native_saveexec_wrexec_controls COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/native_saveexec_wrexec_check.py" controls + "$<TARGET_FILE:compile_dxil>" "${DXC_BIN_DIR}") + set_tests_properties(native_saveexec_wrexec_controls PROPERTIES TIMEOUT 60) + add_test(NAME native_saveexec_wrexec_hardware COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/native_saveexec_wrexec_check.py" hardware + "$<TARGET_FILE:native_store_replay>" "${DXC_BIN_DIR}") + set_tests_properties(native_saveexec_wrexec_hardware PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 120) +endif() diff --git a/tests/cmake/native_sdwa_f16_scalar.cmake b/tests/cmake/native_sdwa_f16_scalar.cmake new file mode 100644 index 0000000000..3cece43a8e --- /dev/null +++ b/tests/cmake/native_sdwa_f16_scalar.cmake @@ -0,0 +1,12 @@ +# Scalar sources in direct C++ binary16 SDWA arithmetic. +if(TARGET native_compute_ir_dump) + add_test(NAME native_sdwa_f16_scalar_ir COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/native_sdwa_f16_scalar_check.py" + ir "$<TARGET_FILE:native_compute_ir_dump>") +endif() +if(TARGET native_store_replay) + add_test(NAME native_sdwa_f16_scalar_hardware COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/native_sdwa_f16_scalar_check.py" + gpu "$<TARGET_FILE:native_store_replay>" "${DXC_BIN_DIR}") + set_tests_properties(native_sdwa_f16_scalar_hardware PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60) +endif() diff --git a/tests/cmake/native_slot67_wave_size.cmake b/tests/cmake/native_slot67_wave_size.cmake new file mode 100644 index 0000000000..d9b4773a17 --- /dev/null +++ b/tests/cmake/native_slot67_wave_size.cmake @@ -0,0 +1,7 @@ +if(TARGET compile_dxil AND TARGET native_store_replay AND + EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${DXC_BIN_DIR}/dxil.dll") + add_test(NAME native_slot67_wave_size_hardware COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/native_slot67_wave_size_check.py" + "$<TARGET_FILE:compile_dxil>" "$<TARGET_FILE:native_store_replay>" "${DXC_BIN_DIR}") + set_tests_properties(native_slot67_wave_size_hardware PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60) +endif() diff --git a/tests/cmake/native_smem_vcc_wave64.cmake b/tests/cmake/native_smem_vcc_wave64.cmake new file mode 100644 index 0000000000..35004dffa2 --- /dev/null +++ b/tests/cmake/native_smem_vcc_wave64.cmake @@ -0,0 +1,14 @@ +if(X2W_HAVE_DXCAPI AND EXISTS "${INTAKE_PYTHON}") + add_test(NAME native_smem_vcc_wave64_controls + COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/native_smem_vcc_wave64_check.py" + controls "$<TARGET_FILE:compile_dxil>" "${DXC_BIN_DIR}") + set_tests_properties(native_smem_vcc_wave64_controls PROPERTIES TIMEOUT 60) +endif() + +if(TARGET native_store_replay AND EXISTS "${INTAKE_PYTHON}" AND + EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${DXC_BIN_DIR}/dxil.dll") + add_test(NAME native_smem_vcc_wave64_hardware + COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/native_smem_vcc_wave64_check.py" + hardware "$<TARGET_FILE:native_store_replay>" "${DXC_BIN_DIR}") + set_tests_properties(native_smem_vcc_wave64_hardware PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60) +endif() diff --git a/tests/cmake/native_uav_slots.cmake b/tests/cmake/native_uav_slots.cmake new file mode 100644 index 0000000000..3a0a5d3d73 --- /dev/null +++ b/tests/cmake/native_uav_slots.cmake @@ -0,0 +1,6 @@ +if(TARGET compile_dxil AND EXISTS "${INTAKE_PYTHON}" AND + EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${DXC_BIN_DIR}/dxil.dll") + add_test(NAME native_uav_slots_controls COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/native_uav_slots_check.py" "$<TARGET_FILE:compile_dxil>" "${DXC_BIN_DIR}") + set_tests_properties(native_uav_slots_controls PROPERTIES TIMEOUT 120) +endif() diff --git a/tests/cmake/native_wave64_exec_salu.cmake b/tests/cmake/native_wave64_exec_salu.cmake new file mode 100644 index 0000000000..53d343b15d --- /dev/null +++ b/tests/cmake/native_wave64_exec_salu.cmake @@ -0,0 +1,7 @@ +if(TARGET compile_dxil AND TARGET native_store_replay AND + EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${DXC_BIN_DIR}/dxil.dll") + add_test(NAME native_wave64_exec_salu_hardware COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/native_wave64_exec_salu_check.py" + "$<TARGET_FILE:compile_dxil>" "$<TARGET_FILE:native_store_replay>" "${DXC_BIN_DIR}") + set_tests_properties(native_wave64_exec_salu_hardware PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60) +endif() diff --git a/tests/cmake/native_wave_virtual_derivative.cmake b/tests/cmake/native_wave_virtual_derivative.cmake new file mode 100644 index 0000000000..aa3b68916c --- /dev/null +++ b/tests/cmake/native_wave_virtual_derivative.cmake @@ -0,0 +1,7 @@ +if(TARGET compile_dxil AND EXISTS "${INTAKE_PYTHON}" AND + EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${DXC_BIN_DIR}/dxil.dll") + add_test(NAME native_wave_virtual_derivative_controls COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/native_wave_virtual_derivative_check.py" + "$<TARGET_FILE:compile_dxil>" "${DXC_BIN_DIR}") + set_tests_properties(native_wave_virtual_derivative_controls PROPERTIES TIMEOUT 120) +endif() diff --git a/tests/cmake/native_wrexec64.cmake b/tests/cmake/native_wrexec64.cmake new file mode 100644 index 0000000000..8f0f147d7a --- /dev/null +++ b/tests/cmake/native_wrexec64.cmake @@ -0,0 +1,7 @@ +if(TARGET compile_dxil AND TARGET native_store_replay AND + EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${DXC_BIN_DIR}/dxil.dll") + add_test(NAME native_wrexec64_hardware COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/native_wrexec64_check.py" + "$<TARGET_FILE:compile_dxil>" "$<TARGET_FILE:native_store_replay>" "${DXC_BIN_DIR}") + set_tests_properties(native_wrexec64_hardware PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60) +endif() diff --git a/tests/cmake/shader_compile_lds_request_cli.cmake b/tests/cmake/shader_compile_lds_request_cli.cmake new file mode 100644 index 0000000000..b175d618d6 --- /dev/null +++ b/tests/cmake/shader_compile_lds_request_cli.cmake @@ -0,0 +1,5 @@ +if(EXISTS "${INTAKE_PYTHON}") + add_test(NAME shader_compile_lds_request_cli_check COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_compile_lds_request_cli_check.py") + set_tests_properties(shader_compile_lds_request_cli_check PROPERTIES TIMEOUT 60) +endif() diff --git a/tests/cmake/shader_probe_root_devices_cli.cmake b/tests/cmake/shader_probe_root_devices_cli.cmake new file mode 100644 index 0000000000..27fa4df3de --- /dev/null +++ b/tests/cmake/shader_probe_root_devices_cli.cmake @@ -0,0 +1,6 @@ +# CLI, upfront path/symlink/hardlink guard, atomic output, and temp-copy mutation checks for tools/probe_root_devices.py. +if(EXISTS "${INTAKE_PYTHON}") + add_test(NAME shader_probe_root_devices_cli_check COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/probe_root_devices_cli_check.py") + set_tests_properties(shader_probe_root_devices_cli_check PROPERTIES TIMEOUT 60) +endif() diff --git a/tests/cmake/startup_compute_dispatch_output.cmake b/tests/cmake/startup_compute_dispatch_output.cmake new file mode 100644 index 0000000000..1460af0525 --- /dev/null +++ b/tests/cmake/startup_compute_dispatch_output.cmake @@ -0,0 +1,8 @@ +if(EXISTS "${INTAKE_PYTHON}" AND TARGET startup_stream_consumer) + foreach(adapter IN ITEMS warp hardware) + add_test(NAME startup_compute_dispatch_output_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_compute_dispatch_output_check.py" "$<TARGET_FILE:startup_stream_consumer>" + "${DXC_EXECUTABLE}" ${adapter}) + set_tests_properties(startup_compute_dispatch_output_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) + endforeach() +endif() diff --git a/tests/cmake/startup_compute_dispatch_texture_dims.cmake b/tests/cmake/startup_compute_dispatch_texture_dims.cmake new file mode 100644 index 0000000000..e90a58bce4 --- /dev/null +++ b/tests/cmake/startup_compute_dispatch_texture_dims.cmake @@ -0,0 +1,8 @@ +if(EXISTS "${INTAKE_PYTHON}" AND TARGET startup_stream_consumer) + foreach(adapter IN ITEMS warp hardware) + add_test(NAME startup_compute_dispatch_texture_dims_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_compute_dispatch_texture_dims_check.py" "$<TARGET_FILE:startup_stream_consumer>" + "${DXC_EXECUTABLE}" ${adapter}) + set_tests_properties(startup_compute_dispatch_texture_dims_${adapter} PROPERTIES TIMEOUT 180 SKIP_RETURN_CODE 77) + endforeach() +endif() diff --git a/tests/cmake/startup_compute_half_buffer_uav.cmake b/tests/cmake/startup_compute_half_buffer_uav.cmake new file mode 100644 index 0000000000..591700ac8f --- /dev/null +++ b/tests/cmake/startup_compute_half_buffer_uav.cmake @@ -0,0 +1,17 @@ +if(TARGET compile_dxil AND EXISTS "${INTAKE_PYTHON}" + AND EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${DXC_BIN_DIR}/dxil.dll") + add_test(NAME startup_compute_half_buffer_uav_controls COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_compute_half_buffer_uav_check.py" compile + "$<TARGET_FILE:compile_dxil>" "${DXC_BIN_DIR}") + set_tests_properties(startup_compute_half_buffer_uav_controls PROPERTIES TIMEOUT 60) +endif() +if(TARGET compile_dxil AND TARGET startup_stream_consumer AND TARGET offscreen_check AND EXISTS "${INTAKE_PYTHON}" + AND EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${DXC_BIN_DIR}/dxil.dll") + foreach(adapter IN ITEMS warp hardware) + add_test(NAME startup_compute_half_buffer_uav_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_compute_half_buffer_uav_check.py" + "$<TARGET_FILE:compile_dxil>" "$<TARGET_FILE:startup_stream_consumer>" "$<TARGET_FILE:offscreen_check>" + "${DXC_BIN_DIR}" ${adapter}) + set_tests_properties(startup_compute_half_buffer_uav_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) + endforeach() +endif() diff --git a/tests/cmake/startup_compute_waterfall_heap.cmake b/tests/cmake/startup_compute_waterfall_heap.cmake new file mode 100644 index 0000000000..a0ac246c9a --- /dev/null +++ b/tests/cmake/startup_compute_waterfall_heap.cmake @@ -0,0 +1,12 @@ +if(EXISTS "${INTAKE_PYTHON}" AND TARGET startup_stream_consumer AND TARGET offscreen_check) + foreach(adapter IN ITEMS warp hardware) + add_test(NAME startup_compute_waterfall_heap_oracle_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_compute_waterfall_heap_check.py" + --oracle "${DXC_EXECUTABLE}" "$<TARGET_FILE:offscreen_check>" ${adapter}) + set_tests_properties(startup_compute_waterfall_heap_oracle_${adapter} PROPERTIES TIMEOUT 90 SKIP_RETURN_CODE 77) + add_test(NAME startup_compute_waterfall_heap_dispatch_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_compute_waterfall_heap_check.py" + --dispatch "$<TARGET_FILE:startup_stream_consumer>" "${DXC_EXECUTABLE}" ${adapter}) + set_tests_properties(startup_compute_waterfall_heap_dispatch_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) + endforeach() +endif() diff --git a/tests/cmake/startup_gfx10_volume.cmake b/tests/cmake/startup_gfx10_volume.cmake index d81d067e33..988e462925 100644 --- a/tests/cmake/startup_gfx10_volume.cmake +++ b/tests/cmake/startup_gfx10_volume.cmake @@ -1,10 +1,12 @@ -# Volumes in the 4 KiB standard console layout (0x105, with or without a mip chain; +# Volumes in the 4 KiB standard console layout (0x105, with or without a mip chain, uncompressed or +# block-compressed; # src/startup_stubs/gfx10_layout.h) and the slot-70 descriptions and views that use them # (src/startup_stubs/address_texture.h), without a device: address equations against addrlib's # GFX10_SW_4K_S3 rows (Mesa 25.1.0, src/amd/addrlib, MIT), block order, the mip chain and its tail, -# distinct addresses, round trips and refusals. The thin run lays each volume out as a 2D array of its -# layers and the tail run puts every tail mip at the start of the tail block; both are negative -# controls. The addrlib run compares every element address with addrlib +# block-compressed volumes against the volume of their blocks, distinct addresses, round trips and +# refusals. The thin run lays each volume out as a 2D array of its layers, the tail run puts every tail +# mip at the start of the tail block, and the bc run sizes a block-compressed volume by its texel sides; +# all three are negative controls. The addrlib run compares every element address with addrlib # and skips (77) without it. add_executable(startup_gfx10_volume_check tests/startup_gfx10_volume_check.cpp) target_compile_features(startup_gfx10_volume_check PRIVATE cxx_std_17) @@ -18,5 +20,7 @@ add_test(NAME startup_gfx10_volume_thin_control COMMAND startup_gfx10_volume_che set_tests_properties(startup_gfx10_volume_thin_control PROPERTIES WILL_FAIL TRUE) add_test(NAME startup_gfx10_volume_tail_control COMMAND startup_gfx10_volume_check --mutate tail) set_tests_properties(startup_gfx10_volume_tail_control PROPERTIES WILL_FAIL TRUE) +add_test(NAME startup_gfx10_volume_bc_control COMMAND startup_gfx10_volume_check --mutate bc) +set_tests_properties(startup_gfx10_volume_bc_control PROPERTIES WILL_FAIL TRUE) add_test(NAME startup_gfx10_volume_addrlib COMMAND startup_gfx10_volume_check --addrlib) set_tests_properties(startup_gfx10_volume_addrlib PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) diff --git a/tests/cmake/startup_gfx2hlsl_v_dot2.cmake b/tests/cmake/startup_gfx2hlsl_v_dot2.cmake new file mode 100644 index 0000000000..a7a152f797 --- /dev/null +++ b/tests/cmake/startup_gfx2hlsl_v_dot2.cmake @@ -0,0 +1,11 @@ +# VOP3P 2-halfword integer dot products (v_dot2_i32_i16, v_dot2_u32_u16) in tools/startup/gfx2hlsl.py. +if(EXISTS "${INTAKE_PYTHON}" AND TARGET offscreen_check) + add_test(NAME startup_gfx2hlsl_v_dot2_controls COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_v_dot2_check.py") + foreach(adapter IN ITEMS warp hardware) + add_test(NAME startup_gfx2hlsl_v_dot2_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_v_dot2_check.py" draw "${DXC_EXECUTABLE}" + "$<TARGET_FILE:offscreen_check>" ${adapter} $<$<BOOL:${STARTUP_FXC}>:${STARTUP_FXC}>) + set_tests_properties(startup_gfx2hlsl_v_dot2_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) + endforeach() +endif() diff --git a/tests/cmake/startup_image_cube.cmake b/tests/cmake/startup_image_cube.cmake new file mode 100644 index 0000000000..1c46cfb54d --- /dev/null +++ b/tests/cmake/startup_image_cube.cmake @@ -0,0 +1,12 @@ +# gfx2hlsl cube image sampling (#2943): translation controls, then a six-face TextureCube drawn from literal face +# addresses, translator mutants and the v_cube chain, compared with the address meaning and a desktop TextureCube draw. +if(EXISTS "${INTAKE_PYTHON}" AND TARGET offscreen_check) + add_test(NAME startup_image_cube_controls COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_image_cube_check.py") + foreach(adapter IN ITEMS warp hardware) + add_test(NAME startup_image_cube_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_image_cube_check.py" draw "${DXC_EXECUTABLE}" + "$<TARGET_FILE:offscreen_check>" ${adapter}) + set_tests_properties(startup_image_cube_${adapter} PROPERTIES TIMEOUT 300 SKIP_RETURN_CODE 77) + endforeach() +endif() diff --git a/tests/compute_check.cpp b/tests/compute_check.cpp index ee4fb50d1b..8d8eec6926 100644 --- a/tests/compute_check.cpp +++ b/tests/compute_check.cpp @@ -25,6 +25,9 @@ constexpr UINT uavs = 13, srvs = 21; // The image case header packs the dispatch count and a format/capability selector. The payload // carries raw texels, one word each for RGBA8 and scalar R32, or four for RGBA32. constexpr UINT texture_rgba8_flag = 1u << 24; +// Read-only image case selectors. The dispatch dimensions each fit in three bits. +constexpr UINT texture_mip_zero_sampler_flag = 1u << 22; +constexpr UINT texture_comparison_flag = 1u << 23; constexpr UINT texture_atomic_uint_flag = 1u << 25; constexpr UINT texture_atomic_sint_minmax_flag = 1u << 26; constexpr UINT texture_atomic_uint_minmax_flag = 1u << 27; @@ -460,8 +463,13 @@ void check_compute_texture_file(ID3D12Device* device, const char* path, const ch const bool rgba8 = (store.groups & texture_rgba8_flag) != 0; const bool rgba32_float = (store.groups & texture_rgba32_float_flag) != 0; const bool view_mip1 = (store.groups & texture_view_mip1_flag) != 0; - store.groups &= ~(texture_rgba8_flag | texture_rgba32_float_flag | texture_view_mip1_flag); - const UINT base_words = texture_width * texture_height * (rgba8 ? 1 : texture_channels); + const bool mip_zero = (store.groups & texture_mip_zero_sampler_flag) != 0; + const bool comparison = (store.groups & texture_comparison_flag) != 0; + store.groups &= ~(texture_rgba8_flag | texture_rgba32_float_flag | texture_view_mip1_flag | + texture_mip_zero_sampler_flag | texture_comparison_flag); + const auto format = comparison ? DXGI_FORMAT_R32_FLOAT : rgba8 ? DXGI_FORMAT_R8G8B8A8_UINT + : rgba32_float ? DXGI_FORMAT_R32G32B32A32_FLOAT : DXGI_FORMAT_R32G32B32A32_UINT; + const UINT base_words = texture_width * texture_height * texture_words_per_texel(format); std::vector<UINT> texels(base_words); source.read(reinterpret_cast<char*>(texels.data()), static_cast<std::streamsize>(texels.size() * sizeof(UINT))); // Older cases stop after the base image. A mip case appends levels one and two. @@ -472,11 +480,34 @@ void check_compute_texture_file(ID3D12Device* device, const char* path, const ch } if (!source || source.peek() != std::char_traits<char>::eof() || store.groups >> 24 || !store.axis(0) || store.axis(0) > 5 || store.axis(1) > 5 || store.axis(2) > 5 || (rgba8 && rgba32_float) || + (comparison && (rgba8 || rgba32_float || mip_zero)) || (view_mip1 && texels.size() == base_words)) throw std::runtime_error("Invalid compute image load reference"); - const auto format = rgba8 ? DXGI_FORMAT_R8G8B8A8_UINT - : rgba32_float ? DXGI_FORMAT_R32G32B32A32_FLOAT : DXGI_FORMAT_R32G32B32A32_UINT; - const auto program = create_compute_program(device, shader, {compute_tables, sizeof(compute_tables)}); + D3D12_SHADER_BYTECODE root{compute_tables, sizeof(compute_tables)}; + ComPtr<ID3DBlob> case_root; + if (comparison || mip_zero) { + ComPtr<ID3D12VersionedRootSignatureDeserializer> embedded; + check(D3D12CreateVersionedRootSignatureDeserializer(root.pShaderBytecode, root.BytecodeLength, + IID_PPV_ARGS(&embedded)), "Read embedded compute table signature"); + const D3D12_VERSIONED_ROOT_SIGNATURE_DESC* original = nullptr; + check(embedded->GetRootSignatureDescAtVersion(D3D_ROOT_SIGNATURE_VERSION_1_1, &original), + "Get v1.1 compute table signature"); + auto desc = *original; + if (desc.Desc_1_1.NumStaticSamplers != 1) + throw std::runtime_error("Expected one static sampler in the compute table signature"); + auto sampler = desc.Desc_1_1.pStaticSamplers[0]; + if (comparison) { + sampler.Filter = D3D12_FILTER_COMPARISON_MIN_MAG_MIP_POINT; + sampler.ComparisonFunc = D3D12_COMPARISON_FUNC_LESS; + } else { + sampler.Filter = D3D12_FILTER_MIN_MAG_LINEAR_MIP_POINT; + sampler.MaxLOD = 0; + } + desc.Desc_1_1.pStaticSamplers = &sampler; + check(D3D12SerializeVersionedRootSignature(&desc, &case_root, nullptr), "Serialize compute case signature"); + root = {case_root->GetBufferPointer(), case_root->GetBufferSize()}; + } + const auto program = create_compute_program(device, shader, root); run_compute(device, true, program, false, &store, &texels, format, nullptr, false, false, view_mip1 ? 1 : 0); } @@ -784,3 +815,133 @@ void check_bvh_root_roundtrip(ID3D12Device* device) run_compute(device, false, program); std::puts("normalized_signature=matched_control root_creation=passed pipeline_creation=passed dispatch=passed"); } + +int check_compute_waterfall_oracle(ID3D12Device* device, const char* shader_path) +{ + const auto code = read_compute_shader(shader_path); + ComPtr<ID3D12RootSignature> root; + check(device->CreateRootSignature(0, code.data(), code.size(), IID_PPV_ARGS(&root)), "Create waterfall oracle root"); + D3D12_COMPUTE_PIPELINE_STATE_DESC pso_desc{}; + pso_desc.pRootSignature = root.Get(); + pso_desc.CS = {code.data(), code.size()}; + ComPtr<ID3D12PipelineState> pso; + check(device->CreateComputePipelineState(&pso_desc, IID_PPV_ARGS(&pso)), "Create waterfall oracle pipeline"); + + D3D12_DESCRIPTOR_HEAP_DESC heap_desc{}; + heap_desc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV; + heap_desc.NumDescriptors = 4; + heap_desc.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE; + ComPtr<ID3D12DescriptorHeap> heap; + check(device->CreateDescriptorHeap(&heap_desc, IID_PPV_ARGS(&heap)), "Create oracle descriptor heap"); + const UINT inc = device->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); + + const auto buf_desc = [](UINT64 size, D3D12_RESOURCE_FLAGS flags = D3D12_RESOURCE_FLAG_NONE) { + D3D12_RESOURCE_DESC d{}; + d.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + d.Width = size; + d.Height = 1; + d.DepthOrArraySize = 1; + d.MipLevels = 1; + d.SampleDesc.Count = 1; + d.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + d.Flags = flags; + return d; + }; + const auto write_upload = [](ID3D12Resource* res, const void* data, UINT sz) { + void* mapped = nullptr; + const D3D12_RANGE none{}; + check(res->Map(0, &none, &mapped), "Map upload buffer"); + std::memcpy(mapped, data, sz); + res->Unmap(0, nullptr); + }; + + std::array<ComPtr<ID3D12Resource>, 4> sources; + auto handle = heap->GetCPUDescriptorHandleForHeapStart(); + for (UINT rec = 0; rec < 4; ++rec) { + const std::array<UINT, 4> data{ + 1000u * (rec + 1u), 1000u * (rec + 1u) + 17u, 1000u * (rec + 1u) + 34u, 1000u * (rec + 1u) + 51u}; + sources[rec] = resource(device, buf_desc(16), D3D12_HEAP_TYPE_UPLOAD, D3D12_RESOURCE_STATE_GENERIC_READ); + write_upload(sources[rec].Get(), data.data(), 16); + D3D12_SHADER_RESOURCE_VIEW_DESC srv{}; + srv.Format = DXGI_FORMAT_R32_TYPELESS; + srv.ViewDimension = D3D12_SRV_DIMENSION_BUFFER; + srv.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + srv.Buffer.NumElements = 4; + srv.Buffer.Flags = D3D12_BUFFER_SRV_FLAG_RAW; + device->CreateShaderResourceView(sources[rec].Get(), &srv, handle); + handle.ptr += inc; + } + + auto keys_res = resource(device, buf_desc(16), D3D12_HEAP_TYPE_UPLOAD, D3D12_RESOURCE_STATE_GENERIC_READ); + auto init_res = resource(device, buf_desc(16), D3D12_HEAP_TYPE_UPLOAD, D3D12_RESOURCE_STATE_GENERIC_READ); + auto out_res = resource(device, buf_desc(16, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS), + D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_STATE_COMMON); + auto rb_res = resource(device, buf_desc(16), D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_STATE_COPY_DEST); + constexpr std::array<UINT, 4> sentinels{0xc001cafeu, 0xc001cafeu, 0xc001cafeu, 0xc001cafeu}; + write_upload(init_res.Get(), sentinels.data(), 16); + + D3D12_COMMAND_QUEUE_DESC qdesc{}; + ComPtr<ID3D12CommandQueue> queue; + ComPtr<ID3D12CommandAllocator> alloc; + ComPtr<ID3D12GraphicsCommandList> list; + ComPtr<ID3D12Fence> fence; + check(device->CreateCommandQueue(&qdesc, IID_PPV_ARGS(&queue)), "Create oracle queue"); + check(device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&alloc)), "Create oracle alloc"); + check(device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, alloc.Get(), nullptr, IID_PPV_ARGS(&list)), + "Create oracle list"); + check(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence)), "Create oracle fence"); + check(list->Close(), "Close initial list"); + + const std::array<std::array<UINT, 4>, 5> inputs{{{0, 1, 2, 3}, {3, 2, 1, 0}, {2, 1, 2, 3}, {4, 9, 14, 19}, {7, 7, 7, 7}}}; + UINT matches = 0, mismatches = 0; + UINT64 fence_value = 0; + const auto barrier = [&](D3D12_RESOURCE_STATES before, D3D12_RESOURCE_STATES after) { + D3D12_RESOURCE_BARRIER b{}; + b.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; + b.Transition = {out_res.Get(), D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, before, after}; + list->ResourceBarrier(1, &b); + }; + + for (const auto& row : inputs) { + write_upload(keys_res.Get(), row.data(), 16); + for (UINT active = 0; active <= 4; ++active) { + check(alloc->Reset(), "Reset oracle alloc"); + check(list->Reset(alloc.Get(), pso.Get()), "Reset oracle list"); + barrier(D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_COPY_DEST); + list->CopyBufferRegion(out_res.Get(), 0, init_res.Get(), 0, 16); + barrier(D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); + ID3D12DescriptorHeap* heaps[] = {heap.Get()}; + list->SetDescriptorHeaps(1, heaps); + list->SetComputeRootSignature(root.Get()); + list->SetComputeRootShaderResourceView(0, keys_res->GetGPUVirtualAddress()); + list->SetComputeRootDescriptorTable(1, heap->GetGPUDescriptorHandleForHeapStart()); + list->SetComputeRootUnorderedAccessView(2, out_res->GetGPUVirtualAddress()); + list->SetComputeRoot32BitConstant(3, active, 0); + list->Dispatch(1, 1, 1); + barrier(D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE); + list->CopyBufferRegion(rb_res.Get(), 0, out_res.Get(), 0, 16); + barrier(D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_COMMON); + check(list->Close(), "Close oracle list"); + ID3D12CommandList* cmd = list.Get(); + queue->ExecuteCommandLists(1, &cmd); + check(queue->Signal(fence.Get(), ++fence_value), "Signal oracle fence"); + while (fence->GetCompletedValue() < fence_value) Sleep(1); + + void* mapped = nullptr; + const D3D12_RANGE range{0, 16}; + const D3D12_RANGE no_writes{}; + check(rb_res->Map(0, &range, &mapped), "Map oracle readback"); + std::array<UINT, 4> got{}; + std::memcpy(got.data(), mapped, 16); + rb_res->Unmap(0, &no_writes); + + std::array<UINT, 4> expected{}; + for (UINT lane = 0; lane < 4; ++lane) + expected[lane] = lane < active ? 1000u * ((row[lane] & 3u) + 1u) + 17u * lane : 13u; + if (got == expected) ++matches; + else ++mismatches; + } + } + std::printf("dispatches=25 matches=%u mismatches=%u\n", matches, mismatches); + return 0; +} diff --git a/tests/desktop_gpu.h b/tests/desktop_gpu.h index 977ea73aef..d57366ae69 100644 --- a/tests/desktop_gpu.h +++ b/tests/desktop_gpu.h @@ -26,7 +26,7 @@ float check_startup_sampler_heap(ID3D12Device* device, const char* vertex_path, void check_startup_image_3d(ID3D12Device* device, const char* vertex_path, const char* pixel_path, float z, float color[4], const char* sampler_line, bool array = false, UINT levels = 1, bool one_dimensional = false, bool two_dimensional = false, - UINT first_mip = 0, UINT view_levels = 0, UINT mip_base = 4); + UINT first_mip = 0, UINT view_levels = 0, UINT mip_base = 4, bool cube = false); void check_startup_image_load_d16(ID3D12Device* device, const char* vertex_path, const char* pixel_path, bool depth16, std::uint32_t words[64], bool array = false); int check_startup_image_store(ID3D12Device* device, const char* vertex_path, const char* pixel_path, UINT x, UINT y, @@ -49,6 +49,7 @@ void check_spirv_compare_sampler(ID3D12Device* device, const char* shader_path, const char* reference_path, const char* descriptors = nullptr); void check_compute_file(ID3D12Device* device, const char* path, bool conversion_pair, const char* reference = nullptr, bool dpp_case = false, bool sized_views = false, UINT uav_words = 0); +int check_compute_waterfall_oracle(ID3D12Device* device, const char* shader_path); struct ComputeReadbackProgram { Microsoft::WRL::ComPtr<ID3D12RootSignature> signature; Microsoft::WRL::ComPtr<ID3D12PipelineState> pipeline; diff --git a/tests/era_heap_check.cpp b/tests/era_heap_check.cpp index 79e66e7bc1..20a2e5c961 100644 --- a/tests/era_heap_check.cpp +++ b/tests/era_heap_check.cpp @@ -85,22 +85,27 @@ bool allocation_checks() bool failure_checks() { - // Mix each reserved bit with a valid heap alignment and with the AMD graphics word. - for (unsigned bit = 33; bit < 64; ++bit) { + // Mix each of the 30 reserved bits with a valid heap alignment and with the AMD graphics word. + for (unsigned bit = 34; bit < 64; ++bit) { const auto reserved = std::uint64_t{1} << bit; if (!rejects(257, reserved | (std::uint64_t{6} << 24)) || !rejects(512, reserved | amd_word)) { return false; } } + // The address-below-4-GiB bit is valid but this allocator does not provide such an address. + if (!rejects(257, (std::uint64_t{1} << 33) | (std::uint64_t{6} << 24)) || + !rejects(512, (std::uint64_t{1} << 33) | amd_word)) { + return false; + } // Physical memory types 7-9 are not modeled. Types 10-15 are undefined. for (std::uint64_t type = 7; type < 16; ++type) { if (!rejects(512, (amd_word & ~memory_type_mask) | (type << 29))) return false; } - // Graphics memory with 4 MB pages or a 128 KiB alignment exceeds the desktop + // Graphics memory with 2 MB pages or a 128 KiB alignment exceeds the desktop // allocation granularity. The undefined page size value 3 fails for every type. - const auto four_mb_pages = (amd_word & ~(std::uint64_t{3} << 14)) | (std::uint64_t{2} << 14); + const auto two_mb_pages = (amd_word & ~(std::uint64_t{3} << 14)) | (std::uint64_t{2} << 14); const auto wide_alignment = (amd_word & ~(std::uint64_t{31} << 24)) | (std::uint64_t{17} << 24); - if ((allocation_granularity() < (std::size_t{4} << 20) && !rejects(512, four_mb_pages)) || + if ((allocation_granularity() < (std::size_t{2} << 20) && !rejects(512, two_mb_pages)) || (allocation_granularity() < (std::size_t{1} << 17) && !rejects(512, wide_alignment)) || !rejects(512, amd_word | (std::uint64_t{3} << 14)) || !rejects(64, bink_word | (std::uint64_t{3} << 14))) { @@ -117,9 +122,9 @@ bool observed_word_checks() const auto bink = era_heap::decode(bink_word); const auto amd = era_heap::decode(amd_word); if (bink.object_type != 0 || bink.page_size != 0 || bink.allocator_id != 0xe5 || - bink.alignment != 5 || bink.memory_type != 0 || bink.reserved != 0 || + bink.alignment != 5 || bink.memory_type != 0 || bink.reserved != 0 || bink.address_below_4gib != 0 || amd.object_type != 0 || amd.page_size != 1 || amd.allocator_id != 0 || - amd.alignment != 8 || amd.memory_type != 5 || amd.reserved != 0) { + amd.alignment != 8 || amd.memory_type != 5 || amd.reserved != 0 || amd.address_below_4gib != 0) { return false; } @@ -404,8 +409,9 @@ bool concurrency_checks() return ok.load(); } -// Every field of the ERA attribute layout (objectType:14, pageSize:2, allocatorId:8, alignment:5, memoryType:4, -// reserved:31) at its widest value alone, all at once, and one word with a distinct value in each field. The +// Every field of the XALLOC_ATTRIBUTES layout (objectType:14, pageSize:2, allocatorId:8, alignment:5, memoryType:4, +// address-below-4-GiB:1, reserved:30) at its widest value alone, all at once, and one word with a distinct value +// in each field. The // observed words leave the object type and the reserved bits at 0, so a narrowed mask or a shifted field boundary // would decode them unchanged. narrow_object_type expects a 13-bit object type and is the negative control. bool decode_field_checks(bool narrow_object_type) @@ -416,16 +422,17 @@ bool decode_field_checks(bool narrow_object_type) era_heap::Fields fields; }; constexpr std::uint64_t mixed = 0x2a5cull | 2ull << 14 | 0xb7ull << 16 | 0x13ull << 24 | 9ull << 29 | - 0x5a5a5a5ull << 33; + 1ull << 33 | 0x2a5a5a5ull << 34; const Case cases[] = { - {"object type", 0x3fff, {0x3fff, 0, 0, 0, 0, 0}}, - {"page size", 3ull << 14, {0, 3, 0, 0, 0, 0}}, - {"allocator", 0xffull << 16, {0, 0, 0xff, 0, 0, 0}}, - {"alignment", 0x1full << 24, {0, 0, 0, 0x1f, 0, 0}}, - {"memory type", 0xfull << 29, {0, 0, 0, 0, 0xf, 0}}, - {"reserved", 0x7fffffffull << 33, {0, 0, 0, 0, 0, 0x7fffffff}}, - {"all ones", ~0ull, {0x3fff, 3, 0xff, 0x1f, 0xf, 0x7fffffff}}, - {"mixed", mixed, {0x2a5c, 2, 0xb7, 0x13, 9, 0x5a5a5a5}}, + {"object type", 0x3fff, {0x3fff, 0, 0, 0, 0, 0, 0}}, + {"page size", 3ull << 14, {0, 3, 0, 0, 0, 0, 0}}, + {"allocator", 0xffull << 16, {0, 0, 0xff, 0, 0, 0, 0}}, + {"alignment", 0x1full << 24, {0, 0, 0, 0x1f, 0, 0, 0}}, + {"memory type", 0xfull << 29, {0, 0, 0, 0, 0xf, 0, 0}}, + {"address 32-bit mapping", 1ull << 33, {0, 0, 0, 0, 0, 1, 0}}, + {"reserved", 0x3fffffffull << 34, {0, 0, 0, 0, 0, 0, 0x3fffffff}}, + {"all ones", ~0ull, {0x3fff, 3, 0xff, 0x1f, 0xf, 1, 0x3fffffff}}, + {"mixed", mixed, {0x2a5c, 2, 0xb7, 0x13, 9, 1, 0x2a5a5a5}}, }; bool ok = true; for (const auto& c : cases) { @@ -436,10 +443,11 @@ bool decode_field_checks(bool narrow_object_type) const auto got = era_heap::decode(c.word); if (got.object_type != want.object_type || got.page_size != want.page_size || got.allocator_id != want.allocator_id || got.alignment != want.alignment || - got.memory_type != want.memory_type || got.reserved != want.reserved) { - std::printf("FAIL: decode %s: %x %u %x %u %u %llx\n", c.name, got.object_type, got.page_size, + got.memory_type != want.memory_type || got.reserved != want.reserved || + got.address_below_4gib != want.address_below_4gib) { + std::printf("FAIL: decode %s: %x %u %x %u %u %x %u\n", c.name, got.object_type, got.page_size, got.allocator_id, got.alignment, got.memory_type, - static_cast<unsigned long long>(got.reserved)); + got.reserved, got.address_below_4gib); ok = false; } } diff --git a/tests/f16_exp_midpoints.py b/tests/f16_exp_midpoints.py new file mode 100644 index 0000000000..24eab4f008 --- /dev/null +++ b/tests/f16_exp_midpoints.py @@ -0,0 +1,58 @@ +"""Generate the non-tie binary16 exp2 corrections for an 8 f32 ULP window.""" +import re +import struct +from decimal import Decimal, localcontext +from fractions import Fraction +from functools import cache +from pathlib import Path + + +def floor_log2(value): + exponent = value.numerator.bit_length() - value.denominator.bit_length() + return exponent - (value < Fraction(2) ** exponent) + + +@cache +def exp_f16_midpoints(): + entries = {} + with localcontext() as context: + context.prec = 90 + ln2 = Decimal(2).ln() + for bits in range(0x10000): + if bits & 0x7fff >= 0x7c00: + continue + operand = struct.unpack('<e', struct.pack('<H', bits))[0] + # Beyond these limits the half result is fixed with ample error margin. + if operand < -25 or operand > 16: + continue + power = Fraction(operand) + integer = power.numerator // power.denominator + fractional = power - integer + exponent = Decimal(fractional.numerator) / Decimal(fractional.denominator) + value = Fraction(2) ** integer * Fraction((exponent * ln2).exp()) + binade = floor_log2(value) + half_ulp = Fraction(2) ** (max(binade, -14) - 10) + lower = int(value / half_ulp) * half_ulp + midpoint = lower + half_ulp / 2 + distance = abs(value - midpoint) + if distance == 0: + assert bits == 0xce40 # The emitter handles exp2(-25) explicitly. + elif distance < 8 * Fraction(2) ** (binade - 23): + rounded = lower if value < midpoint else lower + half_ulp + result = struct.unpack('<H', struct.pack('<e', float(rounded)))[0] + entries[bits] = result + return entries + + +def check_cpp_table(): + source = Path(__file__).resolve().parents[1] / 'src' / 'gfx1013_direct_compute.inl' + array = re.search(r'exp_f16_midpoints\[\]\s*\{(.*?)\};', + source.read_text(encoding='utf-8'), re.DOTALL) + assert array, 'missing C++ exp_f16_midpoints array' + pairs = re.findall(r'\{\s*(0x[0-9a-f]+),\s*(0x[0-9a-f]+)\s*\}', array[1]) + parsed = [(int(source, 16), int(result, 16)) for source, result in pairs] + assert len(parsed) == 70 and parsed == list(exp_f16_midpoints().items()), parsed + + +if __name__ == '__main__': + check_cpp_table() diff --git a/tests/f16_packed_model.py b/tests/f16_packed_model.py index f788b40af0..e25ba0866f 100644 --- a/tests/f16_packed_model.py +++ b/tests/f16_packed_model.py @@ -55,8 +55,70 @@ def round_exact(x): return neg | (n if e == -14 and n < 0x400 else ((e + 15) << 10) | (n & 0x3ff)) -def half_op(op, a, b, c=0): - """One binary16 lane: op is 'mul', 'add' or 'fma' (a * b + c).""" +def half_unary_value(op, x): + """Evaluate binary16 unary operations in float64, including special values.""" + if op == 'rcp': + return math.copysign(math.inf, x) if x == 0 else 1.0 / x + if op == 'sqrt': + return math.nan if x < 0 else math.sqrt(x) + if op == 'rsq': + if x == 0: + return math.copysign(math.inf, x) + return math.nan if x < 0 else 1.0 / math.sqrt(x) + assert op == 'exp' + return math.inf if x >= 128 else math.exp2(x) + + +def rsq_rounding(bits): + """Return the exact RNE result and any alternate allowed by the f32 midpoint window.""" + if not 0 < bits < 0x7c00: + value = half_unary_value('rsq', h2f(bits)) + result = 0x7e00 if math.isnan(value) else struct.unpack('<H', struct.pack('<e', value))[0] + return result, None + + source = Fraction(h2f(bits)) + + def below_rsq(value): + return source * value * value < 1 + + # The reciprocal square root of every positive finite half is a normal half + # or falls between two normal half encodings. 0x6c00 is the largest result. + lo, hi = 0x0400, 0x6c01 + while hi - lo > 1: + mid = (lo + hi) // 2 + if below_rsq(Fraction(h2f(mid))): + lo = mid + else: + hi = mid + lower, upper = Fraction(h2f(lo)), Fraction(h2f(hi)) + if source * upper * upper == 1: + return hi, None + midpoint = (lower + upper) / 2 + if source * midpoint * midpoint == 1: + rounded = lo if lo % 2 == 0 else hi + else: + rounded = hi if below_rsq(midpoint) else lo + # The result and midpoint share the lower encoding's binade. Compare + # the exact reciprocal square root to each endpoint by squaring. + radius = Fraction(2) ** ((lo >> 10) - 15 - 20) + near = below_rsq(midpoint - radius) and source * (midpoint + radius) ** 2 > 1 + return rounded, (lo if rounded == hi else hi) if near else None + + +def half_op(op, a, b=0, c=0): + """Round one binary16 operation, including unary rcp, sqrt, rsq and exp2.""" + if op == 'rsq': + return rsq_rounding(a)[0] + if op in ('rcp', 'sqrt', 'exp'): + x = h2f(a) + if op == 'rcp' and math.isfinite(x) and x != 0: + return round_exact(1 / Fraction(x)) + value = half_unary_value(op, x) + if math.isnan(value): + return 0x7e00 + if value == 0 or math.isinf(value): + return struct.unpack('<H', struct.pack('<e', value))[0] + return round_exact(Fraction(value)) words = (a, b, c) if op == 'fma' else (a, b) if any(is_nan(w) for w in words): return 0x7e00 diff --git a/tests/gdk/runtime_families_probe.cpp b/tests/gdk/runtime_families_probe.cpp new file mode 100644 index 0000000000..609766ec4d --- /dev/null +++ b/tests/gdk/runtime_families_probe.cpp @@ -0,0 +1,95 @@ +// Original fixture for tools/gdk_runtime_oracle.py. It prints only public +// observations from the desktop GDK runtime; it never prints package contents. +#ifndef WIN32_LEAN_AND_MEAN +#define WIN32_LEAN_AND_MEAN +#endif +#ifndef NOMINMAX +#define NOMINMAX +#endif +#include <windows.h> +#include <cstddef> +#include <cstdint> +#include <cstdio> +#include <vector> +#include <XGameRuntime.h> + +static void hr(const char* name, HRESULT value) +{ + std::printf("%s=0x%08X\n", name, static_cast<unsigned>(value)); +} + +int main() +{ +#ifndef X2W_SHIM + hr("init", XGameRuntimeInitialize()); +#endif + + std::printf("device=%u\n", static_cast<unsigned>(XSystemGetDeviceType())); + + char console_id[128]{}; + std::size_t console_used = 0; + hr("console_id", XSystemGetConsoleId(sizeof(console_id), console_id, &console_used)); + std::printf("console_used=%zu console_value=%s\n", console_used, console_id); + + std::uint32_t title_id = 0; + hr("title_id", XGameGetXboxTitleId(&title_id)); + std::printf("title_value=0x%08X\n", static_cast<unsigned>(title_id)); + + std::size_t path_size = 0; + hr("pls_path_size", XPersistentLocalStorageGetPathSize(&path_size)); + std::printf("pls_path_size_value=%zu\n", path_size); + if (path_size > 0) + { + std::vector<char> path(path_size + 1, 0); + std::size_t used = 0; + hr("pls_path", XPersistentLocalStorageGetPath(path.size(), path.data(), &used)); + std::printf("pls_path_used=%zu pls_path_value=%s\n", used, path.data()); + } + + XPersistentLocalStorageSpaceInfo space{}; + hr("pls_space", XPersistentLocalStorageGetSpaceInfo(&space)); + std::printf("pls_space_available=%llu total_free=%llu used=%llu total=%llu\n", + static_cast<unsigned long long>(space.availableFreeBytes), + static_cast<unsigned long long>(space.totalFreeBytes), + static_cast<unsigned long long>(space.usedBytes), + static_cast<unsigned long long>(space.totalBytes)); + + XPackageMountHandle mount = nullptr; + hr("xpackage_mount_missing", XPackageMount("x2w-nonexistent-package", &mount)); + std::printf("xpackage_mount_handle=%p\n", static_cast<void*>(mount)); + if (mount) + { + std::size_t mount_size = 0; + hr("xpackage_path_size", XPackageGetMountPathSize(mount, &mount_size)); + std::printf("xpackage_path_size_value=%zu\n", mount_size); + if (mount_size > 0) + { + std::vector<char> path(mount_size + 1, 0); + hr("xpackage_path", XPackageGetMountPath(mount, path.size(), path.data())); + std::printf("xpackage_path_value=%s\n", path.data()); + } + XPackageCloseMountHandle(mount); + std::printf("xpackage_closed=1\n"); + } + + XTaskQueueHandle queue = nullptr; + hr("queue_create", XTaskQueueCreate(XTaskQueueDispatchMode::Manual, + XTaskQueueDispatchMode::Manual, &queue)); + std::printf("queue_handle=%p\n", static_cast<void*>(queue)); + if (queue) + { + std::printf("queue_dispatch=%u\n", + XTaskQueueDispatch(queue, XTaskQueuePort::Completion, 0) ? 1u : 0u); + XTaskQueueCloseHandle(queue); + std::printf("queue_closed=1\n"); + } + +#ifndef X2W_SHIM + char sandbox[64]{}; + std::size_t sandbox_used = 0; + hr("sandbox", XSystemGetXboxLiveSandboxId(sizeof(sandbox), sandbox, &sandbox_used)); + std::printf("sandbox_used=%zu sandbox_value=%s\n", sandbox_used, sandbox); + XGameRuntimeUninitialize(); +#endif + return 0; +} diff --git a/tests/gdk/shaders/cases.json b/tests/gdk/shaders/cases.json new file mode 100644 index 0000000000..1ea3a520b1 --- /dev/null +++ b/tests/gdk/shaders/cases.json @@ -0,0 +1,40 @@ +{ + "cases": [ + { + "name": "wave64_ballot_ps", + "source": "wave64_ballot_ps.hlsl", + "profile": "ps_6_0", + "entry": "main" + }, + { + "name": "root_constants_vs", + "source": "root_constants_vs.hlsl", + "profile": "vs_6_0", + "entry": "main" + }, + { + "name": "image_sample_c_lz_ps", + "source": "image_sample_c_lz_ps.hlsl", + "profile": "ps_6_0", + "entry": "main" + }, + { + "name": "packed_types_cs", + "source": "packed_types_cs.hlsl", + "profile": "cs_6_0", + "entry": "main" + }, + { + "name": "derivatives_ps", + "source": "derivatives_ps.hlsl", + "profile": "ps_6_0", + "entry": "main" + }, + { + "name": "mesh_ngg_ms", + "source": "mesh_ngg_ms.hlsl", + "profile": "ms_6_5", + "entry": "main" + } + ] +} diff --git a/tests/gdk/shaders/derivatives_ps.hlsl b/tests/gdk/shaders/derivatives_ps.hlsl new file mode 100644 index 0000000000..930a7cb0ad --- /dev/null +++ b/tests/gdk/shaders/derivatives_ps.hlsl @@ -0,0 +1,8 @@ +// Original corpus case: implicit derivatives and fwidth in a pixel stage. +float4 main(float2 uv : TEXCOORD0) : SV_Target +{ + float2 dx = ddx(uv); + float2 dy = ddy(uv); + float width = fwidth(uv.x + uv.y); + return float4(dx, dy.x + dy.y, width); +} diff --git a/tests/gdk/shaders/image_sample_c_lz_ps.hlsl b/tests/gdk/shaders/image_sample_c_lz_ps.hlsl new file mode 100644 index 0000000000..f37212cb0d --- /dev/null +++ b/tests/gdk/shaders/image_sample_c_lz_ps.hlsl @@ -0,0 +1,8 @@ +// Original corpus case: comparison sample at an explicit level. +Texture2D<float4> Depth : register(t0); +SamplerComparisonState Shadow : register(s0); + +float4 main(float2 uv : TEXCOORD0) : SV_Target +{ + return Depth.SampleCmpLevelZero(Shadow, uv, 0.5); +} diff --git a/tests/gdk/shaders/mesh_ngg_ms.hlsl b/tests/gdk/shaders/mesh_ngg_ms.hlsl new file mode 100644 index 0000000000..4a24fe7c6a --- /dev/null +++ b/tests/gdk/shaders/mesh_ngg_ms.hlsl @@ -0,0 +1,16 @@ +// Original corpus case: a fixed three-vertex mesh shader. +struct Vertex +{ + float4 position : SV_Position; +}; + +[outputtopology("triangle")] +[numthreads(1, 1, 1)] +void main(out vertices Vertex verts[3], out indices uint3 tris[1]) +{ + SetMeshOutputCounts(3, 1); + verts[0].position = float4(-1.0, -1.0, 0.0, 1.0); + verts[1].position = float4(1.0, -1.0, 0.0, 1.0); + verts[2].position = float4(0.0, 1.0, 0.0, 1.0); + tris[0] = uint3(0, 1, 2); +} diff --git a/tests/gdk/shaders/packed_types_cs.hlsl b/tests/gdk/shaders/packed_types_cs.hlsl new file mode 100644 index 0000000000..959f02b262 --- /dev/null +++ b/tests/gdk/shaders/packed_types_cs.hlsl @@ -0,0 +1,11 @@ +// Original corpus case: packed 16-bit fields in a compute stage. +RWStructuredBuffer<uint> Output : register(u0); + +[numthreads(64, 1, 1)] +void main(uint3 id : SV_DispatchThreadID) +{ + uint packed = (id.x & 0xffffu) | ((id.y & 0xffffu) << 16); + uint low = packed & 0xffffu; + uint high = packed >> 16; + Output[id.x] = low + high + WaveActiveCountBits(low != 0u); +} diff --git a/tests/gdk/shaders/root_constants_vs.hlsl b/tests/gdk/shaders/root_constants_vs.hlsl new file mode 100644 index 0000000000..333e6eca17 --- /dev/null +++ b/tests/gdk/shaders/root_constants_vs.hlsl @@ -0,0 +1,13 @@ +// Original corpus case: a root signature with one constant buffer. +cbuffer Constants : register(b0) +{ + float4x4 Transform; + float4 Tint; +}; + +[RootSignature("RootFlags(0), CBV(b0)")] +float4 main(uint id : SV_VertexID) : SV_Position +{ + float4 position = float4(id & 1u, (id >> 1) & 1u, 0.0, 1.0); + return mul(Transform, position) + Tint; +} diff --git a/tests/gdk/shaders/wave64_ballot_ps.hlsl b/tests/gdk/shaders/wave64_ballot_ps.hlsl new file mode 100644 index 0000000000..6e2ffbbe15 --- /dev/null +++ b/tests/gdk/shaders/wave64_ballot_ps.hlsl @@ -0,0 +1,11 @@ +// Original corpus case: wave ballot and lane index in a pixel stage. +Texture2D<float4> Color : register(t0); +SamplerState Linear : register(s0); + +float4 main(float2 uv : TEXCOORD0) : SV_Target +{ + uint4 ballot = WaveActiveBallot(uv.x > 0.5); + uint count = WaveActiveCountBits(uv.y > 0.5); + float4 color = Color.Sample(Linear, uv); + return color + float4(ballot.x & 1u, count & 1u, WaveGetLaneIndex() & 1u, 0.0); +} diff --git a/tests/gdk_knowledge_report_check.py b/tests/gdk_knowledge_report_check.py new file mode 100644 index 0000000000..0e49b43a51 --- /dev/null +++ b/tests/gdk_knowledge_report_check.py @@ -0,0 +1,467 @@ +"""Synthetic controls for the GDK knowledge merge and coverage report.""" + +import json +from pathlib import Path +import subprocess +import sys +import tempfile + + +ROOT = Path(__file__).resolve().parents[1] +TOOL = ROOT / "tools" / "gdk_knowledge_report.py" +FACT_FIELDS = {"module", "kind", "name", "value", "source", "confidence", "targets"} + + +def write_json(path, data): + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(json.dumps(data, indent=2) + "\n", encoding="utf-8") + + +def write_text(path, text): + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(text, encoding="utf-8") + + +def make_report_tree(root): + write_json( + root / "layouts" / "alpha.json", + { + "module": "alpha", + "classes": [ + {"name": "Shared", "size": 16, "members": [{"offset": 0, "text": "x"}]}, + {"name": "OnlyA", "size": 8, "members": []}, + {"name": "Cross", "size": 8, "members": []}, + ], + }, + ) + write_json( + root / "layouts" / "beta.json", + {"module": "beta", "classes": [{"name": "Cross", "size": 16, "members": []}]}, + ) + write_json( + root / "abi" / "alpha.json", + { + "module": "alpha", + "facts": [ + {"kind": "sizeof", "name": "Shared", "value": 32}, + {"kind": "struct", "name": "AbiOnly", "value": {"size": 4}}, + {"kind": "enum", "name": "Color", "value": 1}, + {"kind": "constant", "name": "Magic", "value": 1}, + ], + }, + ) + write_json( + root / "abi" / "alpha-more.json", + { + "module": "alpha", + "facts": [ + {"kind": "enum", "name": "Color", "value": 2}, + {"kind": "constant", "name": "Magic", "value": 2}, + ], + }, + ) + write_json( + root / "exports" / "alpha-a.json", + { + "module": "alpha", + "exports": [ + {"name": "Foo", "ordinal": 1, "rva": "0x10"}, + {"name": "Bar", "ordinal": 3, "rva": "0x20"}, + ], + }, + ) + write_json( + root / "exports" / "alpha-b.json", + { + "module": "alpha", + "exports": [ + {"name": "Foo", "ordinal": 2, "rva": "0x30"}, + {"name": "Bar", "ordinal": 3, "rva": "0x20"}, + ], + }, + ) + write_json( + root / "behavior" / "alpha.json", + { + "module": "alpha", + "observations": [ + {"kind": "value", "name": "Bar", "value": 42}, + {"kind": "behavior", "name": "OnlyA", "value": "ok"}, + ], + }, + ) + write_json( + root / "platform" / "windows.json", + { + "platform": "windows-x64", + "defines": ["ALPHA=1"], + "includes": ["alpha.h"], + "libs": ["alpha.lib"], + "flags": ["/W4"], + }, + ) + write_json( + root / "shaders" / "corpus.json", + { + "module": "alpha", + "cases": [ + {"name": "ps-case", "stage": "pixel"}, + {"name": "cs-case", "stage": "compute"}, + ], + }, + ) + write_text( + root / "defs" / "alpha.def", + "LIBRARY alpha\n" + "EXPORTS\n" + " Bar @3\n" + " MissingThing @4\n" + " XMemAllocDefault=Bar @5\n" + " x2w_internal_helper @6\n", + ) + write_json( + root / "defs-map.json", + {"alpha": ["Bar", "MappingOnly", "x2w_mapping_internal"]}, + ) + + +def run_report(root, output, *, defs=None, require=None, check=False, markdown=None): + json_path = Path(output) / "coverage.json" + markdown_path = Path(markdown) if markdown else Path(output) / "report.md" + command = [ + sys.executable, + "-B", + str(TOOL), + "report", + "--root", + str(root), + "--json", + str(json_path), + "--markdown", + str(markdown_path), + ] + if defs is not None: + command.extend(["--defs", str(defs)]) + if require is not None: + command.extend(["--require", require]) + if check: + command.append("--check") + process = subprocess.run(command, capture_output=True, text=True) + return process, json_path, markdown_path + + +def check_report(): + with tempfile.TemporaryDirectory() as temporary: + base = Path(temporary) + root = base / "knowledge" + make_report_tree(root) + + process, json_path, markdown_path = run_report( + root, base / "out", defs=root / "defs" + ) + assert process.returncode == 0, process.stderr + report = json.loads(json_path.read_text(encoding="utf-8")) + markdown = markdown_path.read_text(encoding="utf-8") + + assert report["schema"] == "xbox2windows.gdk_knowledge/1" + assert report["generated_by"] == { + "tool": "gdk_knowledge_report", + "version": 1, + } + assert set(report["categories"]) == { + "layouts", + "abi", + "exports", + "behavior", + "platform", + "shaders", + } + assert all(info["present"] for info in report["categories"].values()) + assert report["missing"] == [] + assert report["required"] == [] + assert report["required_missing"] == [] + + summary = report["summary"] + assert summary["modules"] == 3 + assert summary["types"] == 5 + assert summary["classes_types"] == 5 + assert summary["exports"] == 2 + assert summary["export_rows"] == 4 + assert summary["runtime_facts"] == 2 + assert summary["shader_facts"] == 2 + assert summary["platforms"] == 1 + assert summary["facts"] == 19 + assert summary["conflicts"] == 5 + assert summary["shims"] == 3 + assert summary["shims_without_fact"] == 1 + assert report["categories"]["layouts"]["facts"] == 4 + assert report["categories"]["abi"]["facts"] == 6 + assert report["categories"]["exports"]["facts"] == 4 + + assert len(report["facts"]) == 19 + for fact in report["facts"]: + assert set(fact) == FACT_FIELDS + assert fact["module"] + assert fact["kind"] + assert fact["name"] + assert isinstance(fact["confidence"], str) + assert isinstance(fact["targets"], list) + assert not str(fact["source"]).startswith(str(base)) + assert report["facts"] == sorted( + report["facts"], + key=lambda fact: ( + fact["module"].casefold(), + fact["module"], + fact["kind"].casefold(), + fact["kind"], + fact["name"].casefold(), + fact["name"], + json.dumps( + fact["value"], sort_keys=True, ensure_ascii=False, separators=(",", ":") + ), + json.dumps( + fact["source"], sort_keys=True, ensure_ascii=False, separators=(",", ":") + ), + ), + ) + + shared = next( + fact + for fact in report["facts"] + if fact["module"] == "alpha" + and fact["kind"] == "layout" + and fact["name"] == "Shared" + ) + assert shared["value"] == { + "size": 16, + "members": [{"offset": 0, "text": "x"}], + } + assert shared["source"] == "layouts/alpha.json" + assert shared["confidence"] == "header" + + behavior = next( + fact + for fact in report["facts"] + if fact["name"] == "Bar" and fact["kind"] == "behavior" + ) + assert behavior["value"] == 42 + assert behavior["confidence"] == "runtime" + + kinds = [conflict["kind"] for conflict in report["conflicts"]] + assert kinds == ["value", "size", "ordinal", "enum", "type-size"], kinds + by_kind = {conflict["kind"]: conflict for conflict in report["conflicts"]} + assert by_kind["size"]["module"] == "alpha" + assert by_kind["size"]["name"] == "Shared" + assert {item["value"] for item in by_kind["size"]["values"]} == {16, 32} + assert by_kind["ordinal"]["module"] == "alpha" + assert by_kind["ordinal"]["name"] == "Foo" + assert [item["value"] for item in by_kind["ordinal"]["values"]] == [1, 2] + assert by_kind["enum"]["name"] == "Color" + assert {item["value"] for item in by_kind["enum"]["values"]} == {1, 2} + assert by_kind["type-size"]["name"] == "Cross" + assert by_kind["type-size"]["modules"] == ["alpha", "beta"] + assert {item["module"] for item in by_kind["type-size"]["values"]} == {"alpha", "beta"} + assert by_kind["value"]["name"] == "Magic" + for conflict in report["conflicts"]: + assert conflict["message"] + assert conflict["sources"] == sorted(set(conflict["sources"])) + + shims = report["shims"] + assert shims["exports"] == 3 + assert shims["covered"] == 2 + assert shims["internal"] == 1 + assert [ + (item["module"], item["name"], item["alias"]) + for item in shims["without_fact"] + ] == [("alpha", "MissingThing", None)] + + modules = {module["module"]: module for module in report["modules"]} + assert set(modules) == {"alpha", "beta", "windows-x64"} + assert modules["alpha"]["types"] == 4 + assert modules["alpha"]["exports"] == 2 + assert modules["alpha"]["runtime_facts"] == 2 + assert modules["alpha"]["shader_facts"] == 2 + assert modules["windows-x64"]["platform_facts"] == 1 + + assert markdown.startswith("# GDK knowledge coverage\n") + assert "| Modules | 3 |" in markdown + assert "| Classes/types | 5 |" in markdown + assert "| Runtime facts | 2 |" in markdown + assert "| Conflicts | 5 |" in markdown + assert "| ordinal | alpha | Foo |" in markdown + assert "MissingThing" in markdown + assert "A header fact does not prove the runtime." in markdown + assert markdown.endswith("\n") and not markdown.endswith("\n\n") + + second_process, second_json, second_markdown = run_report( + root, base / "out-again", defs=root / "defs" + ) + assert second_process.returncode == 0, second_process.stderr + assert json_path.read_bytes() == second_json.read_bytes() + assert markdown_path.read_bytes() == second_markdown.read_bytes() + + mapping_process, mapping_json, _ = run_report( + root, base / "out-mapping", defs=root / "defs-map.json" + ) + assert mapping_process.returncode == 0, mapping_process.stderr + mapping_report = json.loads(mapping_json.read_text(encoding="utf-8")) + assert mapping_report["summary"]["shims"] == 2 + assert mapping_report["summary"]["shims_without_fact"] == 1 + assert [ + (item["module"], item["name"]) + for item in mapping_report["shims"]["without_fact"] + ] == [("alpha", "MappingOnly")] + assert mapping_report["shims"]["internal"] == 1 + + checked, checked_json, checked_markdown = run_report( + root, base / "out-check", defs=root / "defs", check=True + ) + assert checked.returncode == 1 + assert checked_json.is_file() + assert checked_markdown.is_file() + assert "conflict" in checked.stderr + + +def check_require(): + with tempfile.TemporaryDirectory() as temporary: + base = Path(temporary) + root = base / "clean" + write_json( + root / "layouts" / "one.json", + {"module": "one", "classes": [{"name": "Only", "size": 4, "members": []}]}, + ) + + passed, passed_json, _ = run_report( + root, base / "out-pass", require="layouts", check=True + ) + assert passed.returncode == 0, passed.stderr + passed_report = json.loads(passed_json.read_text(encoding="utf-8")) + assert passed_report["required"] == ["layouts"] + assert passed_report["required_missing"] == [] + assert passed_report["missing"] == ["abi", "exports", "behavior", "platform", "shaders"] + + failed, failed_json, failed_markdown = run_report( + root, base / "out-fail", require="layouts,exports", check=True + ) + assert failed.returncode == 1 + assert "exports" in failed.stderr + failed_report = json.loads(failed_json.read_text(encoding="utf-8")) + assert failed_report["required"] == ["layouts", "exports"] + assert failed_report["required_missing"] == ["exports"] + assert "Required categories missing: exports." in failed_markdown.read_text( + encoding="utf-8" + ) + + warned, warned_json, warned_markdown = run_report( + root, base / "out-warn", require="exports" + ) + assert warned.returncode == 0, warned.stderr + warned_report = json.loads(warned_json.read_text(encoding="utf-8")) + assert warned_report["required_missing"] == ["exports"] + assert "Required categories missing: exports." in warned_markdown.read_text( + encoding="utf-8" + ) + + +def check_module_case(): + with tempfile.TemporaryDirectory() as temporary: + base = Path(temporary) + root = base / "case" + write_json( + root / "layouts" / "one.json", + {"module": "Alpha", "classes": [{"name": "One", "size": 4, "members": []}]}, + ) + write_json( + root / "layouts" / "two.json", + {"module": "alpha", "classes": [{"name": "Two", "size": 8, "members": []}]}, + ) + process, json_path, _ = run_report(root, base / "out") + assert process.returncode == 0, process.stderr + report = json.loads(json_path.read_text(encoding="utf-8")) + assert [module["module"] for module in report["modules"]] == ["alpha"] + assert report["modules"][0]["types"] == 2 + assert report["summary"]["modules"] == 1 + + +def check_errors(): + with tempfile.TemporaryDirectory() as temporary: + base = Path(temporary) + + missing_root, _, _ = run_report(base / "absent", base / "out-absent") + assert missing_root.returncode == 2 + assert "does not exist" in missing_root.stderr + + malformed = base / "malformed" + write_text(malformed / "layouts" / "bad.json", "{") + malformed_process, _, _ = run_report(malformed, base / "out-malformed") + assert malformed_process.returncode == 2 + assert "invalid JSON" in malformed_process.stderr + + wrong_shape = base / "wrong-shape" + write_json(wrong_shape / "layouts" / "bad.json", {"classes": {}}) + wrong_process, _, _ = run_report(wrong_shape, base / "out-wrong") + assert wrong_process.returncode == 2 + assert "classes" in wrong_process.stderr + + valid = base / "valid" + write_json( + valid / "layouts" / "one.json", + {"module": "one", "classes": [{"name": "Only", "size": 4, "members": []}]}, + ) + unknown_require, _, _ = run_report( + valid, base / "out-unknown", require="layouts,unknown" + ) + assert unknown_require.returncode == 2 + assert "unknown category" in unknown_require.stderr + + absent_defs, _, _ = run_report( + valid, base / "out-defs", defs=base / "absent-defs" + ) + assert absent_defs.returncode == 2 + assert "does not exist" in absent_defs.stderr + + bad_mapping = base / "bad-mapping.json" + write_text(bad_mapping, "[") + bad_mapping_process, _, _ = run_report( + valid, base / "out-map", defs=bad_mapping + ) + assert bad_mapping_process.returncode == 2 + assert "invalid JSON" in bad_mapping_process.stderr + + same_path = base / "same.md" + same_process, _, _ = run_report( + valid, base / "out-same", markdown=same_path + ) + assert same_process.returncode == 0, same_process.stderr + + json_path = base / "collision.json" + collision = subprocess.run( + [ + sys.executable, + "-B", + str(TOOL), + "report", + "--root", + str(valid), + "--json", + str(json_path), + "--markdown", + str(json_path), + ], + capture_output=True, + text=True, + ) + assert collision.returncode == 2 + assert "different paths" in collision.stderr + + +def main(): + check_report() + check_require() + check_module_case() + check_errors() + print("gdk_knowledge_report_check: ok") + + +if __name__ == "__main__": + main() diff --git a/tests/gdk_layouts_check.py b/tests/gdk_layouts_check.py new file mode 100644 index 0000000000..3d584e2771 --- /dev/null +++ b/tests/gdk_layouts_check.py @@ -0,0 +1,191 @@ +#!/usr/bin/env python3 +"""Checks for tools/gdk_layouts.py and tools/gdk_abi_probe.py. + +The synthetic log covers the MSVC constructs the knowledge parser needs: +nested classes, a base class, a vftable, bitfields, arrays and an alignment +member. No Windows or GDK is required. +""" + +import json +import sys +import tempfile +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT / "tools")) +import gdk_abi_probe as abi # noqa: E402 +import gdk_layouts as layouts # noqa: E402 + + +SYNTHETIC_LOG = """class Base\tsize(8): +\t+--- + 0\t| {vfptr} +\t+--- + +class Outer\tsize(24): +\t+--- + 0\t| +--- (base class Base) + 0\t| | {vfptr} +\t+--- + 8\t| UINT Width +12\t| UINT Flags : 3 +16\t| UCHAR Data[4] + \t| <alignment member> (size=4) +\t+--- + +class Outer::Inner\tsize(4): +\t+--- + 0\t| UINT Value +\t+--- + +class Single\tsize(4): +\t+--- + 0\t| Value +\t+--- +""" + + +def check(condition, what): + if not condition: + raise AssertionError(what) + + +def check_parser(): + with tempfile.TemporaryDirectory() as directory: + log = Path(directory) / "layout.log" + log.write_text(SYNTHETIC_LOG, encoding="utf-8") + classes = layouts.parse_log(log) + by_name = {item["name"]: item for item in classes} + check(set(by_name) == {"Base", "Outer", "Outer::Inner", "Single"}, f"classes {set(by_name)}") + outer = by_name["Outer"] + check(outer["size"] == 24, f"Outer size {outer['size']}") + check(outer["bases"] == [{"offset": 0, "name": "Base"}], f"bases {outer['bases']}") + check(outer["alignment"] == 4, f"alignment {outer['alignment']}") + members = {item["name"]: item for item in outer["members"] if item["name"]} + check(members["{vfptr}"]["kind"] == "vftable", "vftable kind") + check(members["Width"]["offset"] == 8, "Width offset") + check(members["Width"]["type"] == "UINT", "typed member") + check(members["Flags"]["bits"] == 3, "bitfield width") + check(members["Data"]["array"] == 4, "array count") + check(members["<alignment>"]["kind"] == "alignment", "alignment member") + check(by_name["Outer::Inner"]["nested_in"] == "Outer", "nested_in") + check(by_name["Single"]["members"][0]["type"] == "unknown", "single-token member type") + check(by_name["Single"]["members"][0]["name"] == "Value", "single-token member name") + print("parser: base, vftable, bitfield, array and alignment passed") + + +def write_layouts(path, classes): + path.write_text( + json.dumps({"module": "synthetic", "classes": classes}, indent=2) + "\n", + encoding="utf-8", + ) + + +def check_compare(): + left = [ + {"name": "A", "size": 16, "bases": [], "members": [ + {"offset": 0, "type": "UINT", "name": "X", "bits": None, "kind": "field"}, + {"offset": 8, "type": "UINT", "name": "Y", "bits": None, "kind": "field"}, + ]}, + {"name": "OnlyLeft", "size": 4, "bases": [], "members": []}, + ] + right = [ + {"name": "A", "size": 24, "bases": [], "members": [ + {"offset": 0, "type": "UINT", "name": "X", "bits": None, "kind": "field"}, + {"offset": 12, "type": "UINT", "name": "Y", "bits": None, "kind": "field"}, + {"offset": 20, "type": "UINT", "name": "Z", "bits": None, "kind": "field"}, + ]}, + {"name": "OnlyRight", "size": 8, "bases": [], "members": []}, + ] + with tempfile.TemporaryDirectory() as directory: + directory = Path(directory) + left_path = directory / "left.json" + right_path = directory / "right.json" + write_layouts(left_path, left) + write_layouts(right_path, right) + code = layouts.main(["compare", str(left_path), str(right_path), "--json", str(directory / "diff.json")]) + check(code == 1, f"compare exit {code}") + changes = json.loads((directory / "diff.json").read_text(encoding="utf-8")) + kinds = {(item["class"], item.get("kind")) for item in changes} + check(("A", "size") in kinds, f"size change {kinds}") + check(("A", "offset") in kinds, f"offset change {kinds}") + check(("OnlyLeft", "removed") in kinds and ("OnlyRight", "added") in kinds, f"add/remove {kinds}") + check(layouts.main(["compare", str(left_path), str(left_path)]) == 0, "identical exit") + print("compare: size, offset, add and remove changes passed") + + +def check_probe(): + classes = [ + {"name": "Simple", "size": 12, "bases": [], "members": [ + {"offset": 0, "type": "UINT", "name": "A", "bits": None, "kind": "field"}, + {"offset": 4, "type": "UINT", "name": "Flags", "bits": 3, "kind": "field"}, + {"offset": 8, "type": "UINT", "name": "B", "bits": None, "kind": "field"}, + ]}, + {"name": "Derived", "size": 16, "bases": [{"offset": 0, "name": "Simple"}], "members": [ + {"offset": 0, "type": "void*", "name": "{vfptr}", "bits": None, "kind": "vftable"}, + {"offset": 12, "type": "UINT", "name": "C", "bits": None, "kind": "field"}, + ]}, + ] + with tempfile.TemporaryDirectory() as directory: + directory = Path(directory) + layout_path = directory / "layout.json" + write_layouts(layout_path, classes) + source = directory / "probe.cpp" + code = abi.main([ + "generate", "--layouts", str(layout_path), "--out", str(source), + "--include", "synthetic.h", "--offsetof", "--print", + ]) + check(code == 0, f"generate exit {code}") + text = source.read_text(encoding="utf-8") + check("#include <synthetic.h>" in text, "include") + check('static_assert(sizeof(Simple) == 12, "sizeof(Simple)");' in text, "sizeof Simple") + check('static_assert(offsetof(Simple, A) == 0, "offsetof(Simple, A)");' in text, "offsetof A") + check("offsetof(Simple, Flags)" not in text, "bitfield offset emitted") + check("offsetof(Derived, C)" not in text, "base-class offset emitted") + check('std::printf("offsetof(Simple, B)=%zu\\n", offsetof(Simple, B));' in text, "print B") + + size_only = directory / "size-only.cpp" + private_classes = classes + [ + {"name": "PrivateField", "size": 4, "bases": [], "members": [ + {"offset": 0, "type": "int", "name": "hidden", "bits": None, "kind": "field"}, + ]}, + ] + private_layout = directory / "private.json" + write_layouts(private_layout, private_classes) + code = abi.main([ + "generate", "--layouts", str(private_layout), "--out", str(size_only), + "--include", "synthetic.h", "--print", + ]) + check(code == 0, f"size-only generate exit {code}") + size_text = size_only.read_text(encoding="utf-8") + check('std::printf("sizeof(PrivateField)=%zu\\n"' in size_text, "size-only sizeof") + check("offsetof(PrivateField, hidden)" not in size_text, "print-only emitted offsetof") + check('std::printf("offsetof(Simple, B)=%zu\\n"' not in size_text, "print-only emitted a public offsetof") + + log = directory / "probe.log" + log.write_text("sizeof(Simple)=12\noffsetof(Simple, A)=0\n", encoding="utf-8") + parsed = directory / "parsed.json" + check(abi.main(["parse", str(log), "--json", str(parsed)]) == 0, "parse exit") + facts = json.loads(parsed.read_text(encoding="utf-8"))["facts"] + check(facts == {"sizeof(Simple)": 12, "offsetof(Simple, A)": 0}, f"facts {facts}") + + changed = directory / "changed.json" + changed.write_text( + json.dumps({"facts": {"sizeof(Simple)": 16, "offsetof(Simple, A)": 0}}), + encoding="utf-8", + ) + check(abi.main(["diff", str(parsed), str(changed)]) == 1, "diff exit") + check(abi.main(["diff", str(parsed), str(parsed)]) == 0, "same diff exit") + print("probe: generation, offsetof rules, parse and diff passed") + + +def main(): + check_parser() + check_compare() + check_probe() + print("gdk_layouts_check: all checks passed") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tests/gdk_platform_profiles_check.py b/tests/gdk_platform_profiles_check.py new file mode 100644 index 0000000000..1049b3e3d9 --- /dev/null +++ b/tests/gdk_platform_profiles_check.py @@ -0,0 +1,153 @@ +#!/usr/bin/env python3 +"""Checks for tools/gdk_platform_profiles.py. + +Builds a small MSBuild platform tree in a temporary directory. No GDK or +Windows is required. +""" + +import json +import sys +import tempfile +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT / "tools")) +import gdk_platform_profiles as profiles # noqa: E402 + + +NAMESPACE = 'xmlns="http://schemas.microsoft.com/developer/msbuild/2003"' + + +def write(path, body): + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text( + f"<Project {NAMESPACE}>\n{body}\n</Project>\n", encoding="utf-8" + ) + + +def make_tree(root): + platform = ( + root + / "VS2022" + / "flatDeployment" + / "MSBuild" + / "Microsoft" + / "VC" + / "v170" + / "Platforms" + / "Gaming.Xbox.Scarlett.x64" + ) + write( + platform / "261000" / "Platform.Common.props", + """ <PropertyGroup> + <UseDebugLibraries Condition="'$(Configuration)'=='Debug'">true</UseDebugLibraries> + <CharacterSet>Unicode</CharacterSet> + </PropertyGroup> + <ItemDefinitionGroup> + <ClCompile> + <PreprocessorDefinitions>_GAMING_XBOX;_GAMING_XBOX_SCARLETT;%(PreprocessorDefinitions)</PreprocessorDefinitions> + <AdditionalIncludeDirectories>$(XdkEditionRootVS2022)Include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories> + <AdditionalOptions>/favor:AMD64 %(AdditionalOptions)</AdditionalOptions> + <FloatingPointModel>Fast</FloatingPointModel> + </ClCompile> + <Link> + <AdditionalDependencies>xgameplatform.lib</AdditionalDependencies> + <TargetMachine>MachineX64</TargetMachine> + </Link> + </ItemDefinitionGroup>""", + ) + write( + platform / "Platform.props", + """ <PropertyGroup> + <XdkEditionRootVS2022>D:\\gdk\\</XdkEditionRootVS2022> + </PropertyGroup>""", + ) + write(platform / "Platform.targets", " <PropertyGroup><XdkEdition>261000</XdkEdition></PropertyGroup>") + write( + platform / "PlatformToolsets" / "v143" / "Toolset.props", + """ <ItemDefinitionGroup> + <ClCompile> + <RuntimeLibrary>MultiThreadedDLL</RuntimeLibrary> + </ClCompile> + </ItemDefinitionGroup>""", + ) + write( + platform / "999999" / "Platform.Common.props", + """ <ItemDefinitionGroup> + <ClCompile> + <PreprocessorDefinitions>PROFILE_999999</PreprocessorDefinitions> + </ClCompile> + </ItemDefinitionGroup>""", + ) + return platform + + +def check(condition, what): + if not condition: + raise AssertionError(what) + + +def main(): + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + make_tree(root) + + found = profiles.choose(root, "Gaming.Xbox.Scarlett.x64", "v170", "261000") + check(found is not None, "platform not found") + check(found.name == "Gaming.Xbox.Scarlett.x64", f"platform {found.name}") + + listed = profiles.main(["list", "--root", str(root)]) + check(listed == 0, f"list exit {listed}") + + output = root / "profile.json" + code = profiles.main([ + "scan", "--root", str(root), "--platform", "Gaming.Xbox.Scarlett.x64", + "--json", str(output), + ]) + check(code == 0, f"scan exit {code}") + document = json.loads(output.read_text(encoding="utf-8")) + check(document["platform"] == "Gaming.Xbox.Scarlett.x64", "platform name") + check(document["defines"] == ["_GAMING_XBOX", "_GAMING_XBOX_SCARLETT"], f"defines {document['defines']}") + check(document["includes"] == ["D:\\gdk\\Include"], f"includes {document['includes']}") + check(document["dependencies"] == ["xgameplatform.lib"], f"deps {document['dependencies']}") + check(document["flags"]["floating_point_model"] == "Fast", "floating point") + check(document["flags"]["runtime_library"] == "MultiThreadedDLL", "runtime library") + check(document["flags"]["target_machine"] == "MachineX64", "target machine") + check(document["flags"]["character_set"] == "Unicode", "character set") + conditions = document["properties"]["UseDebugLibraries"] + check(conditions[0]["condition"] == "'$(Configuration)'=='Debug'", f"condition {conditions}") + check(len(document["sources"]) == 4, f"sources {len(document['sources'])}") + + other_output = root / "profile-999999.json" + other = profiles.main([ + "scan", "--root", str(root), "--platform", "Gaming.Xbox.Scarlett.x64", + "--sdk", "999999", "--json", str(other_output), + ]) + check(other == 0, f"999999 scan exit {other}") + other_document = json.loads(other_output.read_text(encoding="utf-8")) + check(other_document["sdk"] == "999999", f"sdk {other_document['sdk']}") + check(other_document["defines"] == ["PROFILE_999999"], f"defines {other_document['defines']}") + source_paths = [item["path"] for item in other_document["sources"]] + check(any("999999" in path and "Platform.Common.props" in path for path in source_paths), + f"999999 source {source_paths}") + check(not any("261000" in path for path in source_paths), f"261000 leaked {source_paths}") + + unsupported_output = root / "profile-unsupported.json" + unsupported = profiles.main([ + "scan", "--root", str(root), "--platform", "Gaming.Xbox.Scarlett.x64", + "--sdk", "888888", "--json", str(unsupported_output), + ]) + check(unsupported == 2, f"unsupported SDK exit {unsupported}") + check(not unsupported_output.exists(), "unsupported SDK wrote output") + + missing = profiles.main([ + "scan", "--root", str(root), "--platform", "Gaming.Desktop.x64", + "--json", str(root / "missing.json"), + ]) + check(missing == 2, f"missing platform exit {missing}") + print("gdk_platform_profiles_check: all checks passed") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tests/gdk_runtime_oracle_check.py b/tests/gdk_runtime_oracle_check.py new file mode 100644 index 0000000000..fb1d70ac3d --- /dev/null +++ b/tests/gdk_runtime_oracle_check.py @@ -0,0 +1,105 @@ +#!/usr/bin/env python3 +"""Checks for tools/gdk_runtime_oracle.py. + +Without a GDK, this covers normalization, the unified diff and the skip path +when cl.exe is absent. It does not claim a desktop runtime was measured. +""" + +import sys +import tempfile +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT / "tools")) +import gdk_runtime_oracle as oracle # noqa: E402 + + +def check(condition, what): + if not condition: + raise AssertionError(what) + + +def check_normalization(): + cases = { + "queue_handle=0000026D29CDFD60": "queue_handle=<handle>", + "xpackage_mount_handle=00007FFFEA53C588": "xpackage_mount_handle=<handle>", + "console_value=58325731.00000000.00000000.00000000.01": "console_value=<console-id>", + "pls_path_value=C:\\Users\\ROLAND~1\\AppData\\Local\\Temp\\xbox-recomp-pls\\x2w-synthetic-title-0001": + "pls_path_value=<localappdata>\\Temp\\xbox-recomp-pls\\x2w-synthetic-title-0001", + "xpackage_path_value=C:\\Users\\ROLAND~1\\AppData\\Local\\Temp\\xbox-recomp-packages\\x2w-nonexistent-package": + "xpackage_path_value=<localappdata>\\Temp\\xbox-recomp-packages\\x2w-nonexistent-package", + "title_id=0x80070490": "title_id=0x80070490", + "queue_dispatch=0": "queue_dispatch=0", + } + for line, expected in cases.items(): + actual = oracle.normalize_line(line) + check(actual == expected, f"{line!r}: {actual!r} != {expected!r}") + print(f"normalization: {len(cases)} cases passed") + + +def check_diff(): + reference = ["init=0x00000000", "device=1", "queue_dispatch=0"] + candidate = ["init=0x00000000", "device=1", "queue_dispatch=1"] + difference = oracle.diff_lines(reference, candidate) + check(difference[0] == "--- reference", f"header {difference[0]!r}") + check(difference[1] == "+++ candidate", f"header {difference[1]!r}") + check("-queue_dispatch=0" in difference, f"removed line {difference}") + check("+queue_dispatch=1" in difference, f"added line {difference}") + check(oracle.diff_lines(reference, reference) == [], "identical logs differ") + + with tempfile.TemporaryDirectory() as directory: + directory = Path(directory) + (directory / "reference.txt").write_text("\n".join(reference) + "\n", encoding="utf-8") + (directory / "candidate.txt").write_text("\n".join(candidate) + "\n", encoding="utf-8") + code = oracle.main(["diff", str(directory / "reference.txt"), str(directory / "candidate.txt")]) + check(code == 1, f"diff exit {code}") + (directory / "candidate.txt").write_text("\n".join(reference) + "\n", encoding="utf-8") + code = oracle.main(["diff", str(directory / "reference.txt"), str(directory / "candidate.txt")]) + check(code == 0, f"identical exit {code}") + print("diff: headers, changed line and exit codes passed") + + +def check_skip(): + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + gdk = root / "grdk" + (gdk / "GameKit" / "Include").mkdir(parents=True) + (gdk / "GameKit" / "Lib" / "amd64").mkdir(parents=True) + shim = root / "shim" + shim.mkdir() + fixture = root / "fixture.cpp" + fixture.write_text("int main() { return 0; }\n", encoding="utf-8") + code = oracle.main([ + "run", + "--gdk-root", str(gdk), + "--shim-dir", str(shim), + "--fixture", str(fixture), + "--out", str(root / "out"), + "--cl", str(root / "missing-cl.exe"), + ]) + check(code == oracle.SKIP, f"missing cl exit {code}") + print("run: missing cl reports 77") + + +def check_version_parser(): + with tempfile.TemporaryDirectory() as directory: + include = Path(directory) + (include / "GRDK.h").write_text( + "#define _GRDKVER_PRODUCTBUILDVER_FULL 10.0.26100.9661\n", encoding="utf-8" + ) + check(oracle.grdk_version(include) == "10.0.26100.9661", "GRDK version") + check(oracle.grdk_version(Path(directory) / "missing") == "unknown", "missing GRDK version") + print("version parser: present and missing headers passed") + + +def main(): + check_normalization() + check_diff() + check_skip() + check_version_parser() + print("gdk_runtime_oracle_check: all checks passed") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tests/gdk_shader_corpus_check.py b/tests/gdk_shader_corpus_check.py new file mode 100644 index 0000000000..632a9bfb2c --- /dev/null +++ b/tests/gdk_shader_corpus_check.py @@ -0,0 +1,135 @@ +#!/usr/bin/env python3 +"""Checks for tools/gdk_shader_corpus.py without the GDK. + +The real compilation is covered by the corpus build in docs/experiments/ +gdk-shader-corpus.md. This check covers case loading, hashing, manifest +verification, triple checks and the missing-dxc skip. +""" + +import json +import sys +import tempfile +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT / "tools")) +import gdk_shader_corpus as corpus # noqa: E402 + + +def check(condition, what): + if not condition: + raise AssertionError(what) + + +def write_corpus(root, duplicate=False): + (root / "case.hlsl").write_text("float4 main() : SV_Target { return 0; }\n", encoding="utf-8") + cases = [{"name": "case", "source": "case.hlsl", "profile": "ps_6_0", "entry": "main"}] + if duplicate: + cases.append(dict(cases[0])) + (root / "cases.json").write_text(json.dumps({"cases": cases}), encoding="utf-8") + + +def check_loading(): + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + write_corpus(root) + cases = corpus.load_cases(root) + check(cases[0]["name"] == "case", f"cases {cases}") + write_corpus(root, duplicate=True) + try: + corpus.load_cases(root) + except ValueError as error: + check("duplicate" in str(error), str(error)) + else: + raise AssertionError("duplicate case accepted") + (root / "case.hlsl").unlink() + try: + corpus.load_cases(root) + except ValueError as error: + check("missing" in str(error), str(error)) + else: + raise AssertionError("missing source accepted") + print("loading: case, duplicate and missing source passed") + + +def check_build_skip(): + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + write_corpus(root) + out = root / "out" + code = corpus.main([ + "build", "--gdk-root", str(root), "--corpus", str(root), "--out", str(out), + "--dxc", str(root / "missing-dxc.exe"), + ]) + check(code == corpus.SKIP, f"missing dxc exit {code}") + code = corpus.main([ + "build", "--gdk-root", str(root), "--corpus", str(root), "--out", str(out), + "--dxc", str(root / "missing-dxc.exe"), "--require", + ]) + check(code == 2, f"required dxc exit {code}") + print("build: missing dxc reports 77 and --require reports 2") + + +def check_verify(): + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + (root / "xbox.cso").write_bytes(b"xbox") + (root / "desktop.cso").write_bytes(b"desktop") + manifest = { + "sdk": "261000", + "cases": [ + { + "name": "case", + "source": "case.hlsl", + "source_sha256": "0" * 64, + "profile": "ps_6_0", + "entry": "main", + "args": [], + "xbox": { + "file": "xbox.cso", + "bytes": 4, + "sha256": corpus.sha256(root / "xbox.cso"), + }, + "desktop": { + "file": "desktop.cso", + "bytes": 7, + "sha256": corpus.sha256(root / "desktop.cso"), + }, + "dxil": { + "original_triple": "dxil-ms-xb2", + "target_triple": "dxil-ms-dx", + "removed_named_metadata": ["xbox.compiler.options"], + }, + } + ], + } + path = root / "corpus.json" + path.write_text(json.dumps(manifest), encoding="utf-8") + check(corpus.main(["verify", "--manifest", str(path)]) == 0, "valid manifest") + + manifest["cases"][0]["xbox"]["sha256"] = "1" * 64 + path.write_text(json.dumps(manifest), encoding="utf-8") + check(corpus.main(["verify", "--manifest", str(path)]) == 1, "hash mismatch") + + manifest["cases"][0]["xbox"]["sha256"] = corpus.sha256(root / "xbox.cso") + manifest["cases"][0]["dxil"]["target_triple"] = "dxil-ms-xb2" + path.write_text(json.dumps(manifest), encoding="utf-8") + check(corpus.main(["verify", "--manifest", str(path)]) == 1, "triple mismatch") + + manifest["cases"][0]["dxil"]["target_triple"] = "dxil-ms-dx" + (root / "xbox.cso").unlink() + path.write_text(json.dumps(manifest), encoding="utf-8") + check(corpus.main(["verify", "--manifest", str(path)]) == 1, "missing file") + print("verify: hashes, sizes, triples and missing files passed") + + +def main(): + check_loading() + check_build_skip() + check_verify() + print("gdk_shader_corpus_check: all checks passed") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tests/native_adjacent_srv_check.py b/tests/native_adjacent_srv_check.py index d2a8ae6dc6..12e1708db3 100644 --- a/tests/native_adjacent_srv_check.py +++ b/tests/native_adjacent_srv_check.py @@ -19,7 +19,7 @@ def main(gpu, sdk): 0xf408040a, 0x16000020, 0xf408080b, 0xfa000000, scalar(0x1e, 12, 6, 130), vmove(8, 12), sop1(3, 126, 129), vmove(3, 130), 0xe0002000, 0x80040103, 0xe0701000, 0x80080108, 0xbf810000] - sa = struct.pack("<7I", 0, 0, 0, 32 | 1 << 16, 1, 0, 0x80 | 6 << 1) + sa = struct.pack("<7I", 0, 0, 0, 32 | 1 << 16, 1 | (1 << 20), 0, 0x80 | 6 << 1) for name, second, reason in ( ("append", "SRV(t18, space=2)", ""), ("null", "SRV(t18, space=2)", ""), diff --git a/tests/native_bytewin_store_check.py b/tests/native_bytewin_store_check.py index d774784c10..79d82b8974 100644 --- a/tests/native_bytewin_store_check.py +++ b/tests/native_bytewin_store_check.py @@ -136,7 +136,7 @@ def hardware(replay, sdk, work, root): return 0 -def main(mode, tool, sdk): +def main(mode, tool, sdk, *, checks=None): with tempfile.TemporaryDirectory() as temp: work = Path(temp) shader = work / "root.hlsl" @@ -144,7 +144,9 @@ def main(mode, tool, sdk): root = work / "root.bin" subprocess.run([Path(sdk) / "dxc.exe", "-T", "rootsig_1_1", "-E", "SIG", "-Fo", root, shader], check=True) - return {"controls": controls, "hardware": hardware}[mode](tool, sdk, work, root.read_bytes()) + if checks is None: + checks = {"controls": controls, "hardware": hardware} + return checks[mode](tool, sdk, work, root.read_bytes()) if __name__ == "__main__": diff --git a/tests/native_compile_dxil_rekey_check.py b/tests/native_compile_dxil_rekey_check.py new file mode 100644 index 0000000000..390540d99d --- /dev/null +++ b/tests/native_compile_dxil_rekey_check.py @@ -0,0 +1,262 @@ +"""Tests for `compile_dxil --rekey` parity with `tools/startup/shader_cache_rekey.py`.""" +import hashlib +import importlib.util +from pathlib import Path +import re +import shutil +import struct +import subprocess +import sys +import tempfile + +ROOT = Path(__file__).resolve().parents[1] +STARTUP = ROOT / 'tools' / 'startup' +REKEY_PY = STARTUP / 'shader_cache_rekey.py' +sys.path.insert(0, str(STARTUP)) +import gfx2hlsl as G # noqa: E402 + +failures = [] + + +def check(name, ok, detail=''): + print('%s: %s%s' % ('ok' if ok else 'FAIL', name, (' (%s)' % detail) if detail and not ok else '')) + if not ok: + failures.append(name) + + +def older_revision_module(): + text = (STARTUP / 'gfx2hlsl.py').read_text(encoding='utf-8') + literal = re.compile(r"b'x2w-startup-shader-([0-9]+)(cs)?'") + found = literal.findall(text) + assert sorted(suffix for _, suffix in found) == ['', 'cs'] and len({n for n, _ in found}) == 1 + number = int(found[0][0]) - 1 + module = importlib.util.module_from_spec(importlib.util.spec_from_loader('gfx2hlsl_%d' % number, loader=None)) + module.__file__ = str(STARTUP / 'gfx2hlsl.py') + exec(compile(literal.sub(lambda m: "b'x2w-startup-shader-%d%s'" % (number, m.group(2) or ''), text), + module.__file__, 'exec'), module.__dict__) + return module + + +def graphics(index, layout=b''): + vs = struct.pack('<4I', 0x7e000280 + index, 0x01020304, index, 0xbf810000) + ps = struct.pack('<3I', 0x7e020281, index * 7, 0xbf810000) + parts = {'.b': ps, '.root': b'RTS0 synthetic root %d' % index, '.a': vs} + if layout: + parts['.ia'] = layout + return parts + + +def gkey(module, parts, ps_inputs=None): + return module.pipeline_key(parts['.a'], parts['.b'], parts['.root'], parts.get('.ia', b''), ps_inputs) + + +COMPUTE = {'.desc': struct.pack('<12Q', *range(12)), '.sa': struct.pack('<7I', *range(7)), '.sb': b'\x05' * 20, + '.data': struct.pack('<2Q', 0x1122334455667788, 0x99), '.root': b'RTS0 synthetic compute root', + '.c67': struct.pack('<2I', 0x7e020280, 0xbf810000)} +MESH_OLD = {'.ps57': b'', '.root': b'RTS0 synthetic mesh root', '.m57': b'synthetic mesh'} +MESH_CURRENT = {'.ps57': b'synthetic pixel stage', '.root': b'RTS0 synthetic mesh root', + '.m57': b'another synthetic mesh'} + + +def write_request(directory, key, parts): + for ext, data in parts.items(): + (directory / ('req_%016x%s' % (key, ext))).write_bytes(data) + + +def write_rtv(directory, base): + text = ('rtv1 %d 28 87' % base).encode('ascii') + key = G.fnv(text) + (directory / ('req_%016x.rtv' % key)).write_bytes(text) + return key + + +def snapshot(directory): + return {p.name: (hashlib.sha256(p.read_bytes()).hexdigest(), p.stat().st_mtime_ns) + for p in sorted(directory.iterdir())} + + +def contents(directory): + return {p.name: p.read_bytes() for p in sorted(directory.iterdir())} + + +def run_cpp(exe, *args): + return subprocess.run([str(exe), '--rekey', *[str(a) for a in args]], + capture_output=True, text=True, timeout=60) + + +def check_revision_strings(): + cpp_req = (ROOT / 'src' / 'shader_compute_request.cpp').read_text(encoding='utf-8') + draw_inl = (ROOT / 'src' / 'startup_stubs' / 'd3d12_draw.inl').read_text(encoding='utf-8') + py_text = (STARTUP / 'gfx2hlsl.py').read_text(encoding='utf-8') + for token in ('x2w-startup-shader-29', 'x2w-startup-shader-29cs', 'x2w-startup-mesh-57-3'): + ok = (token in cpp_req) and (token in draw_inl) and (token in py_text) + check('revision string %s matches across C++ and Python' % token, ok) + + +def main(): + if len(sys.argv) != 2: + print('usage: native_compile_dxil_rekey_check.py <path-to-compile_dxil>', file=sys.stderr) + return 2 + exe = Path(sys.argv[1]) + check('compile_dxil executable exists', exe.is_file(), str(exe)) + check_revision_strings() + + older = older_revision_module() + g1 = graphics(1) + g2 = graphics(2, b'synthetic layout POSITION 0 R32G32B32_FLOAT') + g3 = graphics(3) + psin_masks = (0x0003, 0x000f) + + with tempfile.TemporaryDirectory(prefix='x2w-native-rekey-') as tmp: + tmp = Path(tmp) + src = tmp / 'old_cache' + src.mkdir() + + k1_old = gkey(older, g1) + k2_old = gkey(older, g2) + k3_old = gkey(older, g3, psin_masks) + k1_cur = gkey(G, g1) + k2_cur = gkey(G, g2) + k3_cur = gkey(G, g3, psin_masks) + c_old = older.compute_key(COMPUTE['.c67'], COMPUTE['.data'], COMPUTE['.root'], + COMPUTE['.desc'], COMPUTE['.sa'], COMPUTE['.sb']) + c_cur = G.compute_key(COMPUTE['.c67'], COMPUTE['.data'], COMPUTE['.root'], + COMPUTE['.desc'], COMPUTE['.sa'], COMPUTE['.sb']) + m_old_key = G.mesh57_key(MESH_OLD['.m57'], MESH_OLD['.ps57'], MESH_OLD['.root']) ^ 1 + m_old_cur = G.mesh57_key(MESH_OLD['.m57'], MESH_OLD['.ps57'], MESH_OLD['.root']) + m_cur_key = G.mesh57_key(MESH_CURRENT['.m57'], MESH_CURRENT['.ps57'], MESH_CURRENT['.root']) + + write_request(src, k1_old, g1) + write_request(src, k2_old, g2) + g3_old_parts = dict(g3) + g3_old_parts['.psin'] = ('psin1 %016x ena=0x%04x addr=0x%04x\n' % (k3_old, *psin_masks)).encode('ascii') + write_request(src, k3_old, g3_old_parts) + write_request(src, k1_cur, g1) # duplicate current copy of g1 + write_request(src, c_old, COMPUTE) + write_request(src, m_old_key, MESH_OLD) + write_request(src, m_cur_key, MESH_CURRENT) + old_rtv = write_rtv(src, k1_old) + write_request(src, 0x123456789abcdef0, {'.m86': b'synthetic slot 86'}) + + # Non-request outputs and diagnostics that must never be copied. + (src / ('%016x.txt' % k1_old)).write_bytes(b'synthetic manifest\n') + (src / ('%016x.fail' % k2_old)).write_bytes(b'synthetic refusal\n') + (src / ('%016x.vs.cso' % k1_old)).write_bytes(b'DXBC...') + (src / ('%016x.psdep' % k3_old)).write_bytes(b'psin1 ...\n') + + before_src = snapshot(src) + + dst_cpp = tmp / 'dst_cpp' + dst_py = tmp / 'dst_py' + res_cpp = run_cpp(exe, src, dst_cpp, '--jobs', '2') + res_py = subprocess.run([sys.executable, '-B', str(REKEY_PY), str(src), str(dst_py)], + capture_output=True, text=True, timeout=60) + + check('compile_dxil --rekey exits 0', res_cpp.returncode == 0, res_cpp.stdout + res_cpp.stderr) + check('shader_cache_rekey.py exits 0', res_py.returncode == 0, res_py.stdout + res_py.stderr) + check('byte-for-byte parity with shader_cache_rekey.py', + dst_cpp.is_dir() and contents(dst_cpp) == contents(dst_py)) + check('only req_* files copied (no .txt/.fail/.cso/.psdep)', + all(name.startswith('req_') for name in contents(dst_cpp))) + + rtv_cur = G.fnv(('rtv1 %d 28 87' % k1_cur).encode('ascii')) + check('rewritten .psin names new key with preserved masks', + (dst_cpp / ('req_%016x.psin' % k3_cur)).read_bytes() == + ('psin1 %016x ena=0x%04x addr=0x%04x\n' % (k3_cur, *psin_masks)).encode('ascii')) + check('rewritten .rtv names new base key', + rtv_cur != old_rtv and + (dst_cpp / ('req_%016x.rtv' % rtv_cur)).read_bytes() == ('rtv1 %d 28 87' % k1_cur).encode('ascii')) + + check('summary graphics line', + 'graphics: 4 requests, 1 already current -> 3 keys' in res_cpp.stdout, res_cpp.stdout) + check('summary compute line', + 'compute: 1 requests, 0 already current -> 1 keys' in res_cpp.stdout, res_cpp.stdout) + check('summary m57 line', + 'm57: 2 requests, 1 already current -> 2 keys' in res_cpp.stdout, res_cpp.stdout) + check('summary rtv line', + 'rtv variants: 1 requests -> 1 keys' in res_cpp.stdout, res_cpp.stdout) + check('summary m86 line', + 'not re-keyed (own key strings): m86 1' in res_cpp.stdout, res_cpp.stdout) + + expected_pending = sorted({k1_cur, k2_cur, k3_cur, c_cur, m_old_cur, m_cur_key, rtv_cur}) + check('gfx2hlsl.pending_keys recognizes re-keyed cache', + G.pending_keys(str(dst_cpp), False) == expected_pending, + str(G.pending_keys(str(dst_cpp), False))) + + # --jobs 1 matches --jobs 2 + dst_j1 = tmp / 'dst_j1' + res_j1 = run_cpp(exe, src, dst_j1, '--jobs', '1') + check('--jobs 1 produces identical contents to --jobs 2', + res_j1.returncode == 0 and contents(dst_j1) == contents(dst_cpp), res_j1.stderr) + + # Idempotency (second run writes 0 files and touches nothing) + snap_dst = snapshot(dst_cpp) + second = run_cpp(exe, src, dst_cpp) + total_files = len(snap_dst) + check('second run is idempotent (0 written)', + second.returncode == 0 and ('files: 0 written, %d already present' % total_files) in second.stdout, + second.stdout + second.stderr) + check('second run leaves mtimes and contents unchanged', snapshot(dst_cpp) == snap_dst) + + # Re-keying an already current cache preserves every name and reports all current + dst_again = tmp / 'dst_again' + third = run_cpp(exe, dst_cpp, dst_again) + check('re-keying current cache preserves names and reports all current', + third.returncode == 0 and contents(dst_again) == contents(dst_cpp) + and 'graphics: 3 requests, 3 already current -> 3 keys' in third.stdout + and 'compute: 1 requests, 1 already current -> 1 keys' in third.stdout + and 'm57: 2 requests, 2 already current -> 2 keys' in third.stdout, + third.stdout + third.stderr) + + # Incomplete/malformed negative controls (exit 1, write nothing, dst not created) + bad_cases = [ + ('graphics missing .root', 8, lambda d: (d / ('req_%016x.root' % k2_old)).unlink()), + ('graphics psin wrong key', 8, + lambda d: (d / ('req_%016x.psin' % k3_old)).write_bytes( + ('psin1 %016x ena=0x0003 addr=0x000f\n' % (k3_old ^ 1)).encode('ascii'))), + ('graphics psin contradictory masks', 8, + lambda d: (d / ('req_%016x.psin' % k3_old)).write_bytes( + ('psin1 %016x ena=0x0010 addr=0x0001\n' % k3_old).encode('ascii'))), + ('compute missing .sa', 8, lambda d: (d / ('req_%016x.sa' % c_old)).unlink()), + ('mesh57 missing .ps57', 8, lambda d: (d / ('req_%016x.ps57' % m_old_key)).unlink()), + ('truncated .rtv', 8, + lambda d: (d / ('req_%016x.rtv' % old_rtv)).write_bytes(b'rtv1 123')), + ('missing .rtv base', 7, lambda d: (d / ('req_%016x.a' % k1_old)).unlink()), + ] + for label, expected_total, damage in bad_cases: + bad_src = tmp / ('bad_' + label.replace(' ', '_').replace('.', '')) + bad_dst = tmp / ('out_' + label.replace(' ', '_').replace('.', '')) + shutil.copytree(src, bad_src) + damage(bad_src) + res = run_cpp(exe, bad_src, bad_dst) + check('%s exits 1' % label, res.returncode == 1, '%d %s' % (res.returncode, res.stderr)) + check('%s reports failure count without writing' % label, + ('error: 1 of %d requests are incomplete or unreadable; nothing written' % expected_total) in res.stderr + and not bad_dst.exists(), + res.stderr) + + # CLI negative controls (exit 2) + reg_file = tmp / 'regular_file.txt' + reg_file.write_bytes(b'not a dir') + cli_cases = [ + ('src == dst', [src, src]), + ('missing args', [src]), + ('extra args', [src, tmp / 'x', tmp / 'y']), + ('unknown flag', [src, tmp / 'x', '--bogus']), + ('missing src dir', [tmp / 'does_not_exist', tmp / 'x']), + ('dst is regular file', [src, reg_file]), + ('jobs 0', [src, tmp / 'x', '--jobs', '0']), + ('jobs 65', [src, tmp / 'x', '--jobs', '65']), + ] + for label, cli_args in cli_cases: + res = run_cpp(exe, *cli_args) + check('CLI %s exits 2' % label, res.returncode == 2, '%d %s' % (res.returncode, res.stderr)) + + check('old cache completely unchanged', snapshot(src) == before_src) + + print('%d failed' % len(failures) if failures else 'all checks passed') + return 1 if failures else 0 + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/tests/native_compile_dxil_watch_check.py b/tests/native_compile_dxil_watch_check.py index 44b4b2d43d..a8bbbbb973 100644 --- a/tests/native_compile_dxil_watch_check.py +++ b/tests/native_compile_dxil_watch_check.py @@ -108,6 +108,45 @@ def main(argv: list[str]) -> int: assert (d1 / f"{g_key:016x}.txt").stat().st_mtime_ns == txt_mtime assert (d1 / f"{c_key:016x}.txt").stat().st_mtime_ns == cs_mtime + # Seed outputs that satisfy the old watcher's completeness check. + cs_manifest = d1 / f"{c_key:016x}.txt" + cs_cso = d1 / f"{c_key:016x}.cs.cso" + cs_hlsl = d1 / f"{c_key:016x}.cs.hlsl" + current_manifest = cs_manifest.read_bytes() + old_manifest = b"".join(line for line in current_manifest.splitlines(keepends=True) + if not line.startswith(b"native ")) + assert current_manifest.splitlines().count(b"native 1") == 1 + assert not cs_hlsl.exists() + dummy_cso = b"DXBC" + b"\0" * 20 + struct.pack("<III", 36, 1, 0) + for stale_manifest in (old_manifest, old_manifest + b"native 0\n"): + cs_cso.write_bytes(dummy_cso) + cs_manifest.write_bytes(stale_manifest) + refreshed = run_once(cli, sdk, frontend, d1) + assert refreshed.returncode == 0, (refreshed.stdout, refreshed.stderr) + assert f"{c_key:016x}: compiled compute" in refreshed.stdout, refreshed.stdout + assert cs_manifest.read_bytes() == current_manifest + assert cs_cso.read_bytes().startswith(b"DXBC") and cs_cso.read_bytes() != dummy_cso + assert not cs_hlsl.exists() + + cs_hlsl.write_bytes(b"// Python output\n") + cs_cso.write_bytes(dummy_cso) + cs_manifest.write_bytes(old_manifest) + python_outputs = (cs_hlsl, cs_cso, cs_manifest) + before = [(path.read_bytes(), path.stat().st_mtime_ns) for path in python_outputs] + skipped = run_once(cli, sdk, frontend, d1) + assert skipped.returncode == 0, (skipped.stdout, skipped.stderr) + assert f"{c_key:016x}:" not in skipped.stdout, skipped.stdout + assert [(path.read_bytes(), path.stat().st_mtime_ns) for path in python_outputs] == before + + # A Python output with incomplete bytecode is still pending. The native rebuild removes its sidecar, so + # the stand-in no longer reads the new unmarked-looking pair as a Python output. + cs_cso.write_bytes(dummy_cso[:16]) + rebuilt = run_once(cli, sdk, frontend, d1) + assert rebuilt.returncode == 0, (rebuilt.stdout, rebuilt.stderr) + assert f"{c_key:016x}: compiled compute" in rebuilt.stdout, rebuilt.stdout + assert cs_manifest.read_bytes() == current_manifest + assert not cs_hlsl.exists() + # Corrupting/truncating a stage .cso triggers resume and restores valid DXBC. vs_cso = d1 / f"{g_key:016x}.vs.cso" orig_vs = vs_cso.read_bytes() diff --git a/tests/native_compute_clear_check.py b/tests/native_compute_clear_check.py index e703513b0c..9d1215608d 100644 --- a/tests/native_compute_clear_check.py +++ b/tests/native_compute_clear_check.py @@ -10,7 +10,7 @@ def write_request(work, words, root, sa=None): code = struct.pack(f"<{len(words)}I", *words) data = b"synthetic" if sa is None: - sa = struct.pack("<7I", 0, 0, 0, 32 | (8 << 16), 1, 0, (6 << 1) | (1 << 10)) + sa = struct.pack("<7I", 0, 0, 0, 32 | (8 << 16), 1 | (1 << 20), 0, (6 << 1) | (1 << 10)) desc = struct.pack("<12Q", 0, 0, len(sa), 0, 0, 0, len(code), 0, len(data), 0, 0, 0) parts = {".c67":code, ".data":data, ".root":root, ".desc":desc, ".sa":sa, ".sb":b""} payload = b"x2w-startup-shader-28cs" + b"".join(struct.pack("<Q", len(p))+p for p in parts.values()) @@ -57,6 +57,11 @@ def run(marker, name, expected=0): broken=words[:-3]+[mov(37,128)]+words[-3:] assert "unsupported" in run(write_request(work,broken,root),"partial.cso",1) assert not (work/"partial.cso").exists() + # A correctly keyed request whose state block A is short must fail the shape check with its + # existing diagnostic. The wave-size bit is read only once 28 bytes are proved (#3241). + short=write_request(work,words,root,sa=struct.pack("<6I",0,0,0,32|(8<<16),1|(1<<20),0)) + assert "compute state block A is not 28 bytes" in run(short,"short.cso",1) + assert not (work/"short.cso").exists() print("two-table request, register renaming, store order, cache, tamper and partial descriptor passed") diff --git a/tests/native_compute_implicit_lod_check.py b/tests/native_compute_implicit_lod_check.py new file mode 100644 index 0000000000..441575253c --- /dev/null +++ b/tests/native_compute_implicit_lod_check.py @@ -0,0 +1,247 @@ +"""Check that direct DXIL sampling uses the guest's consecutive-lane quads.""" + +import math +from pathlib import Path +import subprocess +import sys +import tempfile + +from compute_gather4_l_check import FLOAT_TEXTURE_FLAG, HEIGHT, SENTINEL, WIDTH, bits, texels +from native_direct_container_check import compute, words +from native_gather_lod_check import render +from startup_compute_gather_l_check import reference as gather_reference +from startup_image_sample_c_check import LESS, POINT + + +CASES = ( + ((4, 1, 1), True), + ((12, 1, 1), True), + ((32, 1, 1), True), + ((64, 1, 1), False), + ((96, 1, 1), True), + ((128, 1, 1), False), + ((8, 4, 1), True), + ((8, 4, 2), False), +) +MIP_COLORS = tuple(bits(value) for value in (1.0, 2.0, 4.0)) +MIP_ZERO_FLAG = 1 << 22 # tests/compute_check.cpp texture_mip_zero_sampler_flag +DEPTH_FLAG = 1 << 23 # tests/compute_check.cpp texture_comparison_flag +POINT_MIP_SAMPLER = (0x12, 0xFFF000, 0x04500000, 0) + + +def vop2(op, dst, src0, src1): + return (op << 25) | (dst << 17) | (src1 << 9) | src0 + + +def setup(wave32, sampler): + # One group at ID (0,0,0), with guest local IDs in v0/v1/v2. + # The texture descriptor is at table + 0 and output at table + 0x20. + code = [ + 0xBEFE03C1 if wave32 else 0xBEFE04C1, # s_mov_b32 exec_lo, -1 / s_mov_b64 exec, -1 + 0xBE810380, 0xF40C0200, 0xFA000000, + 0xF4080800, 0xFA000020, + ] + for reg, value in enumerate(sampler, start=4): + code += [0xBE8003FF | reg << 16, value] + return code + + +def program(group, wave32, implicit): + code = setup(wave32, POINT_MIP_SAMPLER) + _, y, z = group + if z > 1: + code += [ + vop2(26, 2, 133, 2), # v2 = z << 5 + vop2(28, 0, 258, 0), # v0 |= v2 + ] + if y > 1: + code += [ + vop2(26, 1, 131, 1), # v1 = y << 3 + vop2(28, 0, 257, 0), # v0 |= v1, completing the linear index + ] + code += [ + vop2(26, 5, 130, 0), # v5 = linear index * 4, the output byte offset + ] + if y > 1: + # Use a vertical-only ramp. Consecutive quads step two indices in ddy + # (0.75 texels) and have zero ddx. Spatial 2D quads step eight indices + # in ddy (three texels), so they sample above mip zero. + code += [ + 0x7E0202F0, # v_mov_b32 v1, 0.5 (U) + vop2(27, 2, 142, 0), # v2 = linear index & 14 + 0x7E040D02, # v_cvt_f32_u32 v2, v2 + vop2(8, 2, 255, 2), bits(3 / (8 * HEIGHT)), # V + 0x7E060280, # v_mov_b32 v3, 0 (explicit LOD) + ] + else: + code += [ + vop2(22, 3, 130, 0), # v3 = linear index >> 2 + vop2(27, 3, 131, 3), # v3 &= 3 + vop2(19, 3, 130, 3), # v3 = min(v3, 2), the expected mip + vop2(26, 4, 151, 3), # v4 = mip << 23 + vop2(37, 4, 255, 4), bits(1 / WIDTH), # v4 = bits for (1 / WIDTH) * 2**mip + vop2(27, 1, 129, 0), # v1 = linear index & 1 + 0x7E020D01, # v_cvt_f32_u32 v1, v1 + vop2(8, 1, 260, 1), # v1 = U, giving each quad ddx(U) = 2**mip / WIDTH + vop2(27, 4, 136, 0), # v4 = linear index & 8 + 0x7E080D04, # v_cvt_f32_u32 v4, v4 + vop2(8, 4, 255, 4), bits(0.0625), # v4 = 0.5 when bit 3 of the index is set + vop2(3, 1, 260, 1), # Add an offset constant within each quad. + 0x7E0402F0, # v_mov_b32 v2, 0.5 (V) + 0x7E060D03, # v_cvt_f32_u32 v3, v3 (explicit LOD) + ] + code += [ + 0xBF8CC07F, # s_waitcnt lgkmcnt(0) + 0xF0000108 | ((32 if implicit else 36) << 18), 0x00220401, + 0xBF8C3F70, # s_waitcnt vmcnt(0) + 0xE0701000, 0x80080405, # buffer_store_dword v4, v5, s[32:35], 0 offen + 0xBF810000, + ] + return compute(words(*code), table=True, wave32=wave32, group=group) + + +def compile_shader(cli, sdk, work, group, wave32, implicit): + name = '-'.join(map(str, (*group, int(wave32), int(implicit)))) + return compile_program(cli, sdk, work, name, program(group, wave32, implicit)) + + +def compile_program(cli, sdk, work, name, binary): + source = work / f'{name}.c67' + source.write_bytes(binary) + shader = source.with_suffix('.cso') + run = subprocess.run([cli, sdk, work / 'cache', 'gfx1013-container-cs', source, shader], + capture_output=True, text=True, timeout=30) + return shader, run + + +def compile_pair(cli, sdk, work, group, wave32): + for implicit in (True, False): + shader, run = compile_shader(cli, sdk, work, group, wave32, implicit) + assert run.returncode == 0 and shader.is_file(), (group, wave32, implicit, run.stdout, run.stderr) + yield shader + + +def mip_payload(colors, channels=4): + return [color for mip, color in enumerate(colors) + for _ in range((WIDTH >> mip) * (HEIGHT >> mip) * channels)] + + +def write_case(path, expected, payload, flags=FLOAT_TEXTURE_FLAG): + expected = [*expected, *([SENTINEL] * (320 - len(expected)))] + path.write_bytes(words(flags | 1, *expected, *payload)) + + +def write_reference(path, group): + threads = math.prod(group) + if group[1] > 1: + expected = [MIP_COLORS[0]] * threads + else: + expected = [MIP_COLORS[min((lane // 4) % 4, 2)] for lane in range(threads)] + write_case(path, expected, mip_payload(MIP_COLORS)) + + +def operation_program(op, *, step=2 / WIDTH, operand=0.0, mask=1, components=1, + sampler=POINT_MIP_SAMPLER): + code = setup(True, sampler) + code += [ + vop2(26, 8, {1: 130, 2: 131, 4: 132}[components], 0), # byte offset + vop2(27, 7, 129, 0), # lane & 1 + 0x7E0E0D07, # convert v7 to float + vop2(8, 1, 255, 7), bits(step), + vop2(3, 1, 240, 1), # U = 0.5 + step * (lane & 1) + 0x7E0402F0, # V = 0.5 + 0x7E0002FF, bits(operand), + ] + address = 0 if op in (37, 40) else 1 + if op == 40: + # Comparison reference before U and V, as in startup_image_sample_c_check. + code += [vop2(8, 0, 255, 7), bits(0.25), vop2(3, 0, 240, 0)] + if op in (36, 68): + code += [0x7E060300] # v_mov_b32 v3, v0: explicit LOD after U and V + code += [ + 0xBF8CC07F, + 0xF0000008 | op << 18 | mask << 8, 0x00220400 | address, + 0xBF8C3F70, + {1: 0xE0701000, 2: 0xE0741000, 4: 0xE0781000}[components], 0x80080408, + 0xBF810000, + ] + return compute(words(*code), wave32=True, group=(4, 1, 1), table=True) + + +def operation_cases(): + colors = mip_payload(MIP_COLORS) + yield 'bias-base', operation_program(32), [MIP_COLORS[1]] * 4, colors, FLOAT_TEXTURE_FLAG + yield 'bias-plus-one', operation_program(37, operand=1.0), [MIP_COLORS[2]] * 4, colors, FLOAT_TEXTURE_FLAG + yield 'bias-explicit', operation_program(36, operand=2.0), [MIP_COLORS[2]] * 4, colors, FLOAT_TEXTURE_FLAG + + comparison = (POINT | LESS, 0xFFF000, 0x04000000, 0) + depth = mip_payload(tuple(map(bits, (0.25, 0.625, 1.0))), channels=1) + yield 'compare', operation_program(40, sampler=comparison), [bits(1.0), bits(0.0)] * 2, depth, DEPTH_FLAG + + mip_zero = (0x12, 0, 0x04500000, 0) + query = operation_program(96, step=4 / WIDTH, mask=3, components=2, sampler=mip_zero) + yield 'get-lod', query, [bits(0.0), bits(2.0)] * 4, colors, FLOAT_TEXTURE_FLAG | MIP_ZERO_FLAG + + step = 1 / (4 * WIDTH) + taps = gather_reference(0, 0, (0.5, 0.5))[:4] + assert taps == gather_reference(0, 0, (0.5 + step, 0.5))[:4] + for name, op in (('gather', 64), ('gather-explicit', 68)): + binary = operation_program(op, step=step, components=4, sampler=mip_zero) + yield name, binary, taps * 4, texels(), FLOAT_TEXTURE_FLAG | MIP_ZERO_FLAG + + +def check_readback(renderer, adapter, shader, reference): + result = render(renderer, adapter, '--compute-texture-case', shader, reference) + assert result.returncode == 0 and 'compared_words=320 mismatches=0' in result.stdout, ( + shader.name, result.stdout, result.stderr) + + +def main(cli, sdk, *render_args): + with tempfile.TemporaryDirectory() as tmp: + work = Path(tmp) + if not render_args: + dxc = Path(sdk) / 'dxc.exe' + for group, wave32 in CASES: + shaders = compile_pair(cli, sdk, work, group, wave32) + for shader, dimensions in zip(shaders, ((math.prod(group), 1, 1), group)): + dump = subprocess.check_output([dxc, '-dumpbin', shader], text=True, timeout=30) + expected = '; NumThreads=(' + ','.join(map(str, dimensions)) + ')' + actual = next((line for line in dump.splitlines() if line.startswith('; NumThreads=')), '') + assert actual == expected, (shader.name, expected, actual) + for group, reason in ( + ((36, 1, 1), 'partial final wave in multi-wave group'), + ((6, 1, 1), 'implicit derivatives require a pixel stage'), + ): + _, run = compile_shader(cli, sdk, work, group, True, True) + assert run.returncode != 0 and reason in run.stderr, (group, run.stdout, run.stderr) + _, run = compile_program(cli, sdk, work, 'gather-unsupported-sampler', + operation_program(64, components=4)) + assert run.returncode != 0 and 'implicit gather requires a sampler fixed to mip zero' in run.stderr, ( + run.stdout, run.stderr) + group = (6, 1, 1) + shader, run = compile_shader(cli, sdk, work, group, True, False) + assert run.returncode == 0 and shader.is_file(), run.stdout + run.stderr + for name, binary, _, _, _ in operation_cases(): + shader, run = compile_program(cli, sdk, work, name, binary) + assert run.returncode == 0 and shader.is_file(), (name, run.stdout, run.stderr) + return + + renderer, adapter = render_args + wave = render(renderer, adapter, '--shader-wave32') + assert wave.returncode == 0, wave.stdout + wave.stderr + reference = work / 'expected.bin' + for group, wave32 in CASES: + write_reference(reference, group) + for shader in compile_pair(cli, sdk, work, group, wave32): + check_readback(renderer, adapter, shader, reference) + print(f'{group} wave{32 if wave32 else 64}: implicit and explicit LOD matched guest readback') + for name, binary, expected, payload, flags in operation_cases(): + shader, run = compile_program(cli, sdk, work, name, binary) + assert run.returncode == 0 and shader.is_file(), (name, run.stdout, run.stderr) + write_case(reference, expected, payload, flags) + check_readback(renderer, adapter, shader, reference) + print(f'{name}: exact readback') + + +if __name__ == '__main__': + main(*sys.argv[1:]) diff --git a/tests/native_compute_manifest_reasons.cpp b/tests/native_compute_manifest_reasons.cpp new file mode 100644 index 0000000000..92d7147f14 --- /dev/null +++ b/tests/native_compute_manifest_reasons.cpp @@ -0,0 +1,122 @@ +// Every refusal of format_compute_runtime_manifest names its reason, and an accepted program's manifest is unchanged. +#include "direct_compute_cache.h" +#include "native_compute_output.h" + +#include <cstdio> +#include <cstring> +#include <functional> +#include <string> + +using namespace x2w; + +static ComputeViewBinding view(ComputeViewKind kind, unsigned reg, unsigned root = 1, unsigned offset = 0) { + ComputeViewBinding b{}; + b.kind = kind; + b.root_parameter = root; + b.byte_offset = offset; + b.shader_register = reg; + return b; +} + +static NativeComputeShader base() { + NativeComputeShader p{}; + p.group = {8, 4, 1}; + p.constants.push_back({0, 0, 2}); + p.bindings.push_back(view(ComputeViewKind::buffer_srv, 0, 1, 64)); + p.bindings.push_back(view(ComputeViewKind::raw_buffer_uav, 0, 1, 32)); + return p; +} + +int main() { + int failures = 0; + std::string reason = "unset"; + const auto accepted = format_compute_runtime_manifest(base(), &reason); + const std::string expected = "x2w-manifest 2\nstage cs\ngroup 8 4 1\nud 2\nudsrc 0 rootconst 0 0\n" + "udsrc 1 rootconst 0 1\nsrv 0 buf table 1 64\nuav 0 table 1 32\nnative " + + std::to_string(native_compute_output_revision) + "\n"; + if (!accepted || *accepted != expected || reason != "unset") { + std::printf("FAIL accepted program: manifest %s, reason \"%s\"\n", accepted ? accepted->c_str() : "(none)", + reason.c_str()); + ++failures; + } + + using K = ComputeViewKind; + const struct { + const char *expected; + std::function<void(NativeComputeShader &)> change; + } cases[] = { + {"group size has a zero dimension", [](auto &p) { p.group[2] = 0; }}, + {"root constants above root parameter 15", [](auto &p) { p.constants[0].root_parameter = 16; }}, + {"more than 8 root constants in one root parameter", [](auto &p) { p.constants[0].count = 9; }}, + {"more than 32 user data words", [](auto &p) { + p.constants.assign(4, {0, 0, 8}); + p.bindings[0].kind = K::raw_vector_srv; + p.stride_srvs = {0}; + }}, + {"resource heap view", [](auto &p) { p.bindings.push_back(view(K::heap_buffer_srv, 1, compute_resource_heap)); }}, + {"sampler heap", [](auto &p) { p.bindings.push_back(view(K::heap_sampler, 1, compute_sampler_heap)); }}, + {"view above root parameter 15", [](auto &p) { p.bindings[1].root_parameter = 16; }}, + {"SRV registers not contiguous", [](auto &p) { p.bindings[0].shader_register = 1; }}, + {"UAV registers not contiguous", [](auto &p) { p.bindings[1].shader_register = 1; }}, + {"SRV kind root_buffer_srv", [](auto &p) { p.bindings[0].kind = K::root_buffer_srv; }}, + {"SRV kind texture_srv cube", [](auto &p) { + p.bindings[0].kind = K::texture_srv; + p.bindings[0].image_dimension = 3; + }}, + {"SRV kind texture_srv 2d array", [](auto &p) { + p.bindings[0].kind = K::texture_srv; + p.bindings[0].array_count = 4; + }}, + {"UAV kind typed_buffer_uav", [](auto &p) { p.bindings[1].kind = K::typed_buffer_uav; }}, + {"UAV kind texture_uav cube", [](auto &p) { + p.bindings[1].kind = K::texture_uav; + p.bindings[1].image_dimension = 3; + }}, + {"more than 32 SRVs", [](auto &p) { + for (unsigned r = 1; r < 33; ++r) + p.bindings.push_back(view(K::buffer_srv, r, 1, 64 + 32 * r)); + }}, + {"more than 8 UAVs", [](auto &p) { + for (unsigned r = 1; r < 9; ++r) + p.bindings.push_back(view(K::raw_buffer_uav, r, 2, 32 * r)); + }}, + {"comparison sampler", [](auto &p) { p.samplers.push_back({{0, 0, 0, 0}, true, true}); }}, + {"stride words from a view that is not one raw vector SRV", [](auto &p) { p.stride_srvs = {0}; }}, + }; + for (const auto &c : cases) { + auto program = base(); + c.change(program); + reason.clear(); + const auto manifest = format_compute_runtime_manifest(program, &reason); + const bool ok = !manifest && reason == c.expected; + std::printf("%s %s%s%s\n", ok ? "ok " : "FAIL", c.expected, ok ? "" : " | got: ", + ok ? "" : manifest ? "a manifest" : reason.c_str()); + failures += !ok; + } + // A texture SRV is published under the name of its dimension: the line the runtime's reader takes. + const struct { + unsigned image_dimension; + const char *line; + } published[] = { + {0, "srv 0 tex1d table 1 64\n"}, + {1, "srv 0 tex2d table 1 64\n"}, + {2, "srv 0 tex3d table 1 64\n"}, + {5, "srv 0 tex2da table 1 64\n"}, + }; + for (const auto &c : published) { + auto program = base(); + program.bindings[0].kind = K::texture_srv; + program.bindings[0].image_dimension = c.image_dimension; + reason = "unset"; + const auto manifest = format_compute_runtime_manifest(program, &reason); + std::string wanted = expected; + wanted.replace(wanted.find("srv 0 buf table 1 64\n"), std::strlen("srv 0 buf table 1 64\n"), c.line); + const bool ok = manifest && *manifest == wanted && reason == "unset"; + std::printf("%s publishes %s", ok ? "ok " : "FAIL", c.line); + if (!ok) + std::printf(" | got: %s\n", manifest ? manifest->c_str() : reason.c_str()); + failures += !ok; + } + std::printf("%d of %zu manifest reasons wrong\n", failures, std::size(cases) + std::size(published) + 1); + return failures ? 1 : 0; +} diff --git a/tests/native_compute_manifest_reasons_check.py b/tests/native_compute_manifest_reasons_check.py new file mode 100644 index 0000000000..201d0c6bac --- /dev/null +++ b/tests/native_compute_manifest_reasons_check.py @@ -0,0 +1,104 @@ +"""A compute program that compiles but gets no runtime manifest names the reason (#3224). + +The program reads a root CBV and a root SRV (the raw-root fixture), so it translates to DXIL but the +compute manifest has no line for a root descriptor. A table-bound control still publishes its manifest. +--requests reports the reason on stdout and leaves no .fail, so watchers keep retrying the key; --watch, +which refuses the key, writes the reason to its .fail. + +usage: + native_compute_manifest_reasons_check.py <compile_dxil> <sdk> +""" +import json +from pathlib import Path +import shutil +import struct +import subprocess +import sys +import tempfile + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE)) +sys.path.insert(0, str(HERE.parent / "tools" / "startup")) + +import gfx2hlsl as G # noqa: E402 +import triage_run # noqa: E402 +from native_compute_clear_check import write_request # noqa: E402 +from native_startup_request_cache_check import ( # noqa: E402 + COMPUTE_GROUP, + COMPUTE_RSRC2, + compile_compute_root, + compute_program_words, + put_compute_request, +) +from startup_compute_translate_check import state_a # noqa: E402 + +# s_load_dwordx4 from the root CBV at s[6:7]; copy the root SRV address s[8:9] to s[2:3]; load from it; s_endpgm. +ROOT_CODE = [0xF40C0403, 0xFA000010, 0xBE820408, 0xF40C0601, 0xFA000030, 0xBF810000] +ROOT_SA = struct.pack("<7I", 0, 0, 0, 32 | (1 << 16), 1 | (1 << 20), 0, 10 << 1) +REASON = "unsupported startup runtime manifest bindings: SRV kind root_buffer_srv" + + +def main(argv: list[str]) -> int: + if len(argv) != 2: + raise SystemExit(__doc__) + cli, sdk = Path(argv[0]).resolve(), Path(argv[1]) + with tempfile.TemporaryDirectory() as tmp: + work = Path(tmp) + src = work / "root.hlsl" + src.write_text('#define RS "RootConstants(num32BitConstants=2,b1),CBV(b0),SRV(t0)"', encoding="ascii") + subprocess.run([sdk / "dxc.exe", "-T", "rootsig_1_1", "-E", "RS", "-Fo", work / "root.bin", src], check=True) + requests = work / "requests" + requests.mkdir() + key = write_request(requests, ROOT_CODE, (work / "root.bin").read_bytes(), ROOT_SA).stem[4:] + control = "%016x" % put_compute_request( + requests, compute_program_words(), compile_compute_root(sdk, work), state_a(COMPUTE_GROUP, COMPUTE_RSRC2)) + watched = work / "watched" + shutil.copytree(requests, watched) + + # 1. --requests in a live cache: the DXIL is published, the reason goes to stdout, and no .fail is left. + # A genuine refusal beside it keeps its .fail. The Python watcher's two selections tell them apart. + live = work / "live" + shutil.copytree(requests, live) + broken = compute_program_words()[:-4] + struct.pack("<2I", 0xFFFFFFFF, 0xBF810000) + refused = "%016x" % put_compute_request( + live, broken, compile_compute_root(sdk, work), state_a(COMPUTE_GROUP, COMPUTE_RSRC2)) + (live / f"{key}.fail").write_text("stale failure\n", encoding="ascii") + run = subprocess.run([cli, sdk, work / "frontend", "--jobs", "2", "gfx1013-direct-cs@0", "--requests", + live, live], capture_output=True, text=True) + assert run.returncode == 1 and "requests=3 compiled=2 refused=1" in run.stdout, (run.stdout, run.stderr) + retry_all = sorted(int(k, 16) for k in (key, refused)) + assert G.pending_keys(str(live), False) == retry_all, G.pending_keys(str(live), False) + assert G.pending_keys(str(live), True) == [int(key, 16)], G.pending_keys(str(live), True) + assert f"no_manifest input=req_{key}.c67 {REASON}\n" in run.stdout, run.stdout + assert run.stdout.count("no_manifest ") == 1, run.stdout + assert (live / f"{key}.cs.cso").read_bytes().startswith(b"DXBC") + assert not (live / f"{key}.txt").exists() and not (live / f"{key}.fail").exists() + assert (live / f"{control}.txt").is_file() and not (live / f"{control}.fail").exists() + assert (live / f"{refused}.fail").is_file() and not (live / f"{refused}.cs.cso").exists() + + # 2. --refusals counts it with the same text. + summary = json.loads(subprocess.run([cli, "--refusals", requests, "--json"], capture_output=True, + text=True, check=True).stdout)["compute"] + assert summary["examined"] == 2 and summary["no_refusal"] == 1 and summary["refused"] == 1, summary + assert summary["reasons"] == [{"reason": REASON, "count": 1}], summary + + # 3. --watch writes the same line, and triage_run.py reports it as a fixed category without the key. + watch = subprocess.run([cli, "--watch", sdk, work / "watch_cache", watched, "--once"], + capture_output=True, text=True) + assert watch.returncode == 0 and f"{key}: refused: {REASON}" in watch.stdout, (watch.stdout, watch.stderr) + assert f"{control}: compiled compute" in watch.stdout, watch.stdout + assert (watched / f"{key}.fail").read_text(encoding="ascii") == REASON + "\n" + # A watcher refusal is a genuine failure: skipped by the repeated pass, retried by the first. + assert G.pending_keys(str(watched), True) == [] and G.pending_keys(str(watched), False) == [int(key, 16)] + logs = work / "logs" + logs.mkdir() + (logs / "stderr.txt").write_text("", encoding="utf-8") + report = triage_run.triage_run(logs, shader_cache=watched) + assert "| 1 | `compute: runtime manifest: SRV kind root_buffer_srv` |" in report, report + assert key not in report and control not in report + print("compute manifest reasons: ok") + return 0 + + +if __name__ == "__main__": + sys.exit(main(sys.argv[1:])) diff --git a/tests/native_compute_raw_root_check.py b/tests/native_compute_raw_root_check.py index ad2355bb95..d7809b2885 100644 --- a/tests/native_compute_raw_root_check.py +++ b/tests/native_compute_raw_root_check.py @@ -22,7 +22,7 @@ def signature(text): return binary.read_bytes() def compile_case(code, root, user=10, error=None): - sa = struct.pack("<7I", 0, 0, 0, 32 | (1 << 16), 1, 0, user << 1) + sa = struct.pack("<7I", 0, 0, 0, 32 | (1 << 16), 1 | (1 << 20), 0, user << 1) marker = write_request(work, code, root, sa) result = subprocess.run([exe, sdk, work / "cache", "gfx1013-direct-cs@0", marker, marker.with_suffix(".cso")], text=True, capture_output=True) diff --git a/tests/native_cvt_norm_f16_check.py b/tests/native_cvt_norm_f16_check.py new file mode 100644 index 0000000000..d468aafcfe --- /dev/null +++ b/tests/native_cvt_norm_f16_check.py @@ -0,0 +1,317 @@ +"""Direct DXIL VOP1/VOP3 v_cvt_norm_i16_f16 and v_cvt_norm_u16_f16 lowering in Compute and Pixel shaders.""" +from dataclasses import dataclass +from pathlib import Path +import struct +import subprocess +import sys +import tempfile + +from native_direct_container_check import patched_pixel +from native_dpp_mirror_check import vop2 +from native_dpp_quad_check import request +import native_f16_alu_check as F +from native_packed_f16_inline_check import PROLOGUE, inline_word +from native_scalar_lds_check import sop1 +from startup_image_3d_check import FULLSCREEN_VS, compile_hlsl + +VOP1_OPS = {'i16': 0x63, 'u16': 0x64} +VOP3_OPS = {'i16': 0x1E3, 'u16': 0x1E4} +ALL_EXEC = 0xFFFFFFFF +DST_INIT = 0xDEADCAFE + + +def vop1_cvt_norm(kind, dst, src0): + return [0x7E000000 | ((dst & 0xFF) << 17) | (VOP1_OPS[kind] << 9) | (src0 & 0x1FF)] + + +def vop3_cvt_norm(kind, dst, src0, *, abs_=0, neg=0, op_sel=0, clamp=0, omod=0, s1=0, s2=0): + w0 = (0xD4000000 | (VOP3_OPS[kind] << 16) | ((clamp & 1) << 15) | ((op_sel & 15) << 11) | + ((abs_ & 7) << 8) | (dst & 0xFF)) + w1 = ((neg & 7) << 29) | ((omod & 3) << 27) | ((s2 & 0x1FF) << 18) | ((s1 & 0x1FF) << 9) | (src0 & 0x1FF) + return [w0, w1] + + +def eval_cvt_norm(kind, raw_word, *, abs_=0, neg=0, op_sel=0, dst_init=DST_INIT): + signed = kind == 'i16' + bits = (raw_word >> (16 if (op_sel & 1) else 0)) & 0xFFFF + if abs_ & 1: + bits &= 0x7FFF + if neg & 1: + bits ^= 0x8000 + sign = bits & 0x8000 + mag = bits & 0x7FFF + if mag > 0x7C00 or mag == 0: + res = 0 + elif not signed: + if sign: + res = 0 + elif mag >= 0x3C00: + res = 0xFFFF + else: + exp = mag >> 10 + mant = mag if exp == 0 else (0x400 | (mag & 0x3FF)) + shift = 24 if exp == 0 else (25 - exp) + prod = mant * 65535 + q = prod >> shift + mid = 1 << (shift - 1) + rem = prod & ((1 << shift) - 1) + if rem > mid or (rem == mid and (q & 1)): + q += 1 + res = q + else: + if mag >= 0x3C00: + q = 32767 + else: + exp = mag >> 10 + mant = mag if exp == 0 else (0x400 | (mag & 0x3FF)) + shift = 24 if exp == 0 else (25 - exp) + prod = mant * 32767 + q = prod >> shift + mid = 1 << (shift - 1) + rem = prod & ((1 << shift) - 1) + if rem > mid or (rem == mid and (q & 1)): + q += 1 + res = ((-q) & 0xFFFF) if sign else q + if op_sel & 8: + return ((res & 0xFFFF) << 16) | (dst_init & 0xFFFF) + return (dst_init & 0xFFFF0000) | (res & 0xFFFF) + + +@dataclass(frozen=True) +class Case: + name: str + kind: str + src0: int + val0: int + wide: bool = False + abs_: int = 0 + neg: int = 0 + op_sel: int = 0 + exec_mask: int = ALL_EXEC + + def expected(self, lane=0): + if ((self.exec_mask >> lane) & 1) == 0: + return DST_INIT + raw = self.val0 & 0xFFFFFFFF if (self.src0 < 128 or self.src0 >= 255) else inline_word(self.src0) + return eval_cvt_norm(self.kind, raw, abs_=self.abs_, neg=self.neg, op_sel=self.op_sel) + + +def all_cases(): + return [ + # 1. Signed zero, unity, saturation (>1 / <-1 / +/-Inf), and NaN -> 0 for i16 & u16. + Case('i16_neg_zero', 'i16', 257, 0x8000), + Case('u16_neg_zero', 'u16', 257, 0x8000), + Case('i16_pos_one_and_over', 'i16', 257, 0x7BFF3C00), # 1.0 -> 32767 (hi=65504 ignored) + Case('i16_neg_two_sat', 'i16', 257, 0xC000), # -2.0 -> -32767 (0x8001) + Case('u16_neg_clamp_zero', 'u16', 257, 0xBC00), # -1.0 -> 0 + Case('u16_pos_inf_sat', 'u16', 257, 0x7C00), # +Inf -> 65535 (0xffff) + Case('i16_neg_inf_sat', 'i16', 257, 0xFC00), # -Inf -> -32767 (0x8001) + Case('u16_neg_inf_zero', 'u16', 257, 0xFC00), # -Inf -> 0 + Case('i16_nan_zero', 'i16', 257, 0x7E01), # NaN -> 0 + Case('u16_neg_nan_zero', 'u16', 257, 0xFC01), # -NaN -> 0 + # 2. Exact halfway ties and binary32 double-rounding / subnormal discriminators. + Case('i16_half_tie_even', 'i16', 257, 0x3800), # 0.5 * 32767 = 16383.5 -> 16384 (even) + Case('u16_half_tie_even', 'u16', 257, 0x3800), # 0.5 * 65535 = 32767.5 -> 32768 (even) + Case('i16_neg_half_tie_even', 'i16', 257, 0xB800), # -0.5 -> -16384 (0xc000) + Case('i16_dbl_round_3801', 'i16', 257, 0x3801), # 1025/2048 * 32767 = 16399.4997 -> 16399 + Case('u16_dbl_round_3801', 'u16', 257, 0x3801), # 1025/2048 * 65535 = 32799.4995 -> 32799 + Case('i16_dbl_round_b802', 'i16', 257, 0xB802), # -1026/2048 * 32767 -> -16415 + Case('u16_max_subnormal', 'u16', 257, 0x03FF), # 0x03ff * 65535 / 2^24 -> 4 + Case('i16_neg_max_subnormal', 'i16', 257, 0x83FF), # -0x03ff * 32767 / 2^24 -> -2 (0xfffe) + Case('u16_lt_one_3bff', 'u16', 257, 0x3BFF), # (1 - 2^-11) * 65535 = 65503.0005 -> 65503 + # 3. VOP3 modifiers: separate abs, neg, and high-half op_sel[0]/op_sel[3]. + Case('i16_vop3_abs', 'i16', 257, 0x7BFFB800, wide=True, abs_=1), + Case('u16_vop3_neg', 'u16', 257, 0x7BFFB800, wide=True, neg=1), + Case('i16_vop3_opsel_hi_src', 'i16', 257, 0x38000000, wide=True, op_sel=0b0001), + Case('u16_vop3_opsel_hi_dst', 'u16', 257, 0x00003800, wide=True, op_sel=0b1000), + Case('i16_vop3_opsel_hi_rw', 'i16', 257, 0xB800BEEF, wide=True, op_sel=0b1001), + # 4. SGPR, literal (255), inline f16 float (240/248), inline int (129/193), and partial EXEC_LO. + Case('u16_sgpr_src0', 'u16', 10, 0x3800), + Case('i16_literal_src0', 'i16', 255, 0x3802), + Case('u16_inline_f16_248', 'u16', 248, 0), + Case('i16_inline_int_129', 'i16', 129, 0), + Case('i16_inline_int_193_nan', 'i16', 193, 0), + Case('u16_partial_exec', 'u16', 257, 0x7BFF3800, exec_mask=0xAAAAAAAA), + ] + + +def emit_case(c: Case): + code = F.mov(4, DST_INIT) + if c.exec_mask != ALL_EXEC: + code += [sop1(3, 126, 255), c.exec_mask] + lit_tail = [] + if c.src0 >= 256: + code += F.mov(c.src0 - 256, c.val0) + elif c.src0 <= 105: + code += F.smov(c.src0, c.val0) + elif c.src0 == 255: + lit_tail = [c.val0] + if c.wide: + code += vop3_cvt_norm(c.kind, 4, c.src0, abs_=c.abs_, neg=c.neg, op_sel=c.op_sel) + else: + code += vop1_cvt_norm(c.kind, 4, c.src0) + code += lit_tail + if c.exec_mask != ALL_EXEC: + code += [sop1(3, 126, 193)] + return code + + +def compute_program(cases): + assert len(cases) <= 32, len(cases) + code = list(PROLOGUE) + for slot, c in enumerate(cases): + code += emit_case(c) + F.store(slot * 4, 4) + return code + [0xBF810000] + + +def refusal_programs(): + cond_mode = [0xBF840001, 0xBFA5000F] # s_cbranch_scc0 +1; s_denorm_mode 15 + plain = vop1_cvt_norm('i16', 4, 257) + [0xBF810000] + return [ + # Clamp and omod refused on both forms. + (vop3_cvt_norm('i16', 4, 257, clamp=1) + [0xBF810000], 'unsupported v_cvt_norm_i16_f16 clamp or omod'), + (vop3_cvt_norm('u16', 4, 257, omod=1) + [0xBF810000], 'unsupported v_cvt_norm_u16_f16 clamp or omod'), + # Unused VOP3 operand modifier / op_sel bits. + (vop3_cvt_norm('u16', 4, 257, op_sel=0b0010) + [0xBF810000], 'unsupported v_cvt_norm_u16_f16 operand modifiers'), + (vop3_cvt_norm('i16', 4, 257, s1=258) + [0xBF810000], 'unsupported v_cvt_norm_i16_f16 operand modifiers'), + # High-half op_sel on non-VGPR source. + (vop3_cvt_norm('u16', 4, 10, op_sel=0b0001) + [0xBF810000], + 'unsupported v_cvt_norm_u16_f16 high-half op_sel on non-VGPR source'), + # DPP16 and SDWA forms. + (vop1_cvt_norm('i16', 4, 250) + [0xFF00E401, 0xBF810000], 'unsupported DPP arithmetic'), + (vop1_cvt_norm('u16', 4, 249) + [0x06060601, 0xBF810000], 'unimplemented direct SDWA operand profile'), + # Special scalar source (vcc_lo). + (vop1_cvt_norm('i16', 4, 106) + [0xBF810000], 'unsupported v_cvt_norm_i16_f16 source'), + # Unsupported binary16 rounding/denorm modes and dynamic conditional MODE write. + ([0xBFA40004] + plain, 'unsupported binary16 rounding or denormal mode'), + ([0xBFA50003] + plain, 'unsupported binary16 rounding or denormal mode'), + (cond_mode + plain, 'unsupported binary16 rounding or denormal mode'), + ] + + +def ir(dumper): + items = all_cases() + code = compute_program(items) + want = [c.expected(lane=0) for c in items] + refusals = refusal_programs() + with tempfile.TemporaryDirectory() as tmp: + work = Path(tmp) + run = F.dump(dumper, work, code, 'cvt-norm-f16') + assert run.returncode == 0, run.stderr + stores = sorted(F.interpret(run.stdout)) + assert [addr for addr, _ in stores] == [4 * i for i in range(len(want))], stores[:4] + bad = [(i, items[i].name, hex(got), hex(exp)) + for i, ((_, got), exp) in enumerate(zip(stores, want)) if got != exp] + assert not bad, bad[:8] + for idx, (refused, why) in enumerate(refusals): + r = F.dump(dumper, work, refused, f'refused-{idx}') + assert r.returncode != 0 and why in r.stderr, (idx, why, r.returncode, r.stderr) + print(f'native_cvt_norm_f16 IR: {len(want)} cases matched exact model; {len(refusals)} refusals matched') + return 0 + + +def controls(cli, sdk, work, root): + items = all_cases() + code = compute_program(items) + marker = request(work, root, code) + output = marker.with_suffix('.cso') + result = subprocess.run([cli, sdk, work / 'cache', 'gfx1013-direct-cs@0', marker, output], + capture_output=True, text=True) + assert result.returncode == 0 and output.is_file(), (result.stdout, result.stderr) + dump = subprocess.run([Path(sdk) / 'dxc.exe', '-dumpbin', output], capture_output=True, text=True, check=True).stdout + assert '32767' in dump and '65535' in dump and 'lshr i32' in dump, dump + + refusals = refusal_programs() + for idx, (prog, why) in enumerate(refusals): + m = request(work, root, prog) + o = m.with_suffix(f'.refused{idx}.cso') + r = subprocess.run([cli, sdk, work / 'cache', 'gfx1013-direct-cs@0', m, o], capture_output=True, text=True) + assert r.returncode != 0 and why in r.stderr, (idx, why, r.stdout, r.stderr) + assert not o.exists(), o + + print(f'native_cvt_norm_f16 controls: compiled {len(items)} cases to DXIL; verified {len(refusals)} refusals') + return 0 + + +def hardware(replay, sdk, work, root): + items = all_cases() + code = compute_program(items) + marker = request(work, root, code) + output = work / 'out.bin' + run = subprocess.run([replay, sdk, marker, work / 'cache', '0', output, '--direct']) + if run.returncode == 77: + return 77 + run.check_returncode() + words_out = list(struct.unpack(f'<{F.WORDS}I', output.read_bytes())) + expected = {} + for group in range(F.GROUPS): + for lane in range(32): + head = F.BASE + group * 1024 + lane * 32 + for idx, c in enumerate(items): + expected[head + idx] = c.expected(lane=lane) + bad = [] + for i, got in enumerate(words_out): + if i in expected: + if got != expected[i]: + bad.append((i, hex(got), hex(expected[i]))) + elif got != F.SENTINEL: + bad.append((i, hex(got), hex(F.SENTINEL))) + assert not bad, bad[:10] + print(f'native_cvt_norm_f16 compute hardware: {len(items)} cases matched across {F.GROUPS}x32 lanes and guards') + return 0 + + +def pixel_program(pair): + code = [] + for idx, c in enumerate(pair): + code += emit_case(c) + lo_reg, hi_reg = 8 + 2 * idx, 9 + 2 * idx + code += [vop2(0x1B, lo_reg, 255, 4), 65535, vop2(0x16, hi_reg, 144, 4)] + # Each 16-bit half is exactly representable in binary32 as an integer in 0..65535. + code += [0x7E000C00 | reg << 17 | (256 + reg) for reg in (lo_reg, hi_reg)] + return patched_pixel(len(code), code, export=(0xF800180F, 0x0B0A0908)) + + +def pixel(cli, sdk, renderer, adapter, work): + items = [c for c in all_cases() if c.exec_mask == ALL_EXEC] + if len(items) % 2: + items.append(items[-1]) + vs = compile_hlsl(str(Path(sdk) / 'dxc.exe'), 'dxc', FULLSCREEN_VS, 'fullscreen', 'vs_6_0', work) + pairs = [items[i:i + 2] for i in range(0, len(items), 2)] + for idx, pair in enumerate(pairs): + shader = work / f'cvt-norm-f16-{idx}.ps' + shader.write_bytes(pixel_program(pair)) + cso = shader.with_suffix('.cso') + build = subprocess.run([cli, sdk, work / 'cache', 'gfx1013-container-ps', shader, cso], + capture_output=True, text=True, timeout=30) + assert build.returncode == 0, ([c.name for c in pair], build.stdout, build.stderr) + w0, w1 = pair[0].expected(), pair[1].expected() + ref = work / 'expected.bin' + ref.write_bytes(struct.pack('<4f', w0 & 0xFFFF, w0 >> 16, w1 & 0xFFFF, w1 >> 16)) + run = subprocess.run([renderer, adapter, '--startup-pixel-words', vs, cso, '1', '1', ref], + capture_output=True, text=True, timeout=30) + if run.returncode == 77: + return 77 + assert run.returncode == 0, (idx, [c.name for c in pair], run.stdout, run.stderr) + if 'debug_layer=enabled' in run.stdout: + assert 'debug_errors=0 debug_warnings=0' in run.stdout, run.stdout + print(f'native_cvt_norm_f16 pixel ({adapter}): {len(pairs)} pixel draws ({len(items)} cases) matched') + return 0 + + +def main(mode, tool, sdk=None, *args): + if mode == 'ir': + return ir(tool) + with tempfile.TemporaryDirectory() as tmp: + work = Path(tmp) + if mode == 'pixel': + return pixel(tool, sdk, args[0], args[1], work) + shader = work / 'root.hlsl' + shader.write_text('#define SIG "DescriptorTable(UAV(u0,numDescriptors=8))"') + root = work / 'root.bin' + subprocess.run([Path(sdk) / 'dxc.exe', '-T', 'rootsig_1_1', '-E', 'SIG', '-Fo', root, shader], check=True) + return {'controls': controls, 'compute': hardware}[mode](tool, sdk, work, root.read_bytes()) + + +if __name__ == '__main__': + sys.exit(main(*sys.argv[1:])) diff --git a/tests/native_cvt_pknorm_f32_check.py b/tests/native_cvt_pknorm_f32_check.py new file mode 100644 index 0000000000..ab4788e317 --- /dev/null +++ b/tests/native_cvt_pknorm_f32_check.py @@ -0,0 +1,350 @@ +"""Direct DXIL VOP3 v_cvt_pknorm_i16_f32 and v_cvt_pknorm_u16_f32 lowering in Compute and Pixel shaders.""" +from dataclasses import dataclass +from fractions import Fraction +import math +from pathlib import Path +import struct +import subprocess +import sys +import tempfile + +from native_direct_container_check import patched_pixel +from native_dpp_mirror_check import vop2 +from native_dpp_quad_check import request +import native_f16_alu_check as F +from native_packed_f16_inline_check import PROLOGUE +from native_scalar_lds_check import sop1 +from startup_image_3d_check import FULLSCREEN_VS, compile_hlsl + +OPS = {'i16': 0x368, 'u16': 0x369} +ALL_EXEC = 0xFFFFFFFF +DST_INIT = 0xDEADCAFE + +INLINE_F32_WORDS = { + 240: 0x3F000000, 241: 0xBF000000, 242: 0x3F800000, 243: 0xBF800000, + 244: 0x40000000, 245: 0xC0000000, 246: 0x40800000, 247: 0xC0800000, + 248: 0x3E22F983, +} + + +def inline_f32_word(enc): + if enc in INLINE_F32_WORDS: + return INLINE_F32_WORDS[enc] + if 128 <= enc <= 192: + return enc - 128 + if 193 <= enc <= 208: + return (192 - enc) & 0xFFFFFFFF + raise ValueError(enc) + + +def vop3_pknorm(kind, dst, srcs, *, abs_=0, neg=0, op_sel=0, clamp=0, omod=0, s2=0): + s0, s1 = srcs + w0 = (0xD4000000 | (OPS[kind] << 16) | ((clamp & 1) << 15) | ((op_sel & 15) << 11) | + ((abs_ & 7) << 8) | (dst & 0xFF)) + w1 = ((neg & 7) << 29) | ((omod & 3) << 27) | ((s2 & 0x1FF) << 18) | ((s1 & 0x1FF) << 9) | (s0 & 0x1FF) + return [w0, w1] + + +def cvt_norm_f32_half(kind, bits): + bits &= 0xFFFFFFFF + if (bits & 0x7FFFFFFF) > 0x7F800000: + return 0 + val = struct.unpack('<f', struct.pack('<I', bits))[0] + if kind == 'u16': + if math.isnan(val) or val <= 0.0: + return 0 + if val >= 1.0: + return 0xFFFF + scaled = Fraction(val) * 65535 + else: + if val == 0.0: + return 0 + if val >= 1.0: + return 32767 + if val <= -1.0: + return (-32767) & 0xFFFF + scaled = Fraction(val) * 32767 + neg_sign = scaled < 0 + mag = abs(scaled) + q = int(mag) + rem = mag - q + if rem > Fraction(1, 2) or (rem == Fraction(1, 2) and (q & 1)): + q += 1 + return ((-q) & 0xFFFF) if neg_sign else (q & 0xFFFF) + + +def eval_pknorm(kind, raw0, raw1, *, abs_=0, neg=0): + words = [] + for j, w in enumerate((raw0, raw1)): + bits = w & 0xFFFFFFFF + if (abs_ >> j) & 1: + bits &= 0x7FFFFFFF + if (neg >> j) & 1: + bits ^= 0x80000000 + words.append(cvt_norm_f32_half(kind, bits)) + return words[0] | (words[1] << 16) + + +@dataclass(frozen=True) +class Case: + name: str + kind: str + srcs: tuple + vals: tuple + abs_: int = 0 + neg: int = 0 + exec_mask: int = ALL_EXEC + + def expected(self, lane=0): + if ((self.exec_mask >> lane) & 1) == 0: + return DST_INIT + raw = [v & 0xFFFFFFFF if (s < 128 or s >= 255) else inline_f32_word(s) + for s, v in zip(self.srcs, self.vals)] + return eval_pknorm(self.kind, raw[0], raw[1], abs_=self.abs_, neg=self.neg) + + +def all_cases(): + return [ + # 1. Zeros, subnormals, 2^-17 boundary, unity, saturation (>1, <-1, +/-Inf), and NaNs. + Case('i16_signed_zeros', 'i16', (257, 258), (0x00000000, 0x80000000)), + Case('u16_neg_and_pos_zero', 'u16', (257, 258), (0x80000000, 0x00000000)), + Case('i16_subnormals', 'i16', (257, 258), (0x00000001, 0x807FFFFF)), + Case('u16_2m17_boundary', 'u16', (257, 258), (0x37000000, 0x37000100)), # 0.5-eps -> 0, 0.5+eps -> 1 + Case('i16_2m17_neg_subone', 'i16', (257, 258), (0xB7000000, 0x3F7FFFFF)), # -> 0, 32767 + Case('u16_tiny_and_almost_one', 'u16', (257, 258), (0x34000000, 0x3F7FFFFF)), # -> 0, 65535 + Case('i16_unity_sat', 'i16', (257, 258), (0x3F800000, 0xBF800000)), # -> +32767, -32767 + Case('u16_unity_neg_sat', 'u16', (257, 258), (0x3F800000, 0xBF800000)), # -> 65535, 0 + Case('i16_over_under_sat', 'i16', (257, 258), (0x40000000, 0xC0000000)), # 2.0, -2.0 -> 32767, -32767 + Case('u16_over_under_sat', 'u16', (257, 258), (0x60000000, 0xC0000000)), # large, -2.0 -> 65535, 0 + Case('i16_infs', 'i16', (257, 258), (0x7F800000, 0xFF800000)), + Case('u16_infs', 'u16', (257, 258), (0x7F800000, 0xFF800000)), + Case('i16_nans', 'i16', (257, 258), (0x7FC00001, 0xFF800001)), + Case('u16_nans', 'u16', (257, 258), (0x7F800001, 0xFFC00001)), + # 2. Exact halfway RNE ties and p_lo != 0 carry-over tie-break witnesses. + Case('i16_half_ties', 'i16', (257, 258), (0x3F000000, 0xBF000000)), # 0.5 -> 16384, -0.5 -> -16384 + Case('u16_half_and_quarter', 'u16', (257, 258), (0x3F000000, 0x3E800000)), # 0.5 -> 32768, 0.25 -> 16384 + Case('i16_neg_quarter', 'i16', (257, 258), (0xBE800000, 0x3E800000)), # -0.25 -> -8192, 0.25 -> 8192 + Case('u16_p_lo_tie_witness', 'u16', (257, 258), (0x3F000101, 0xBF000101)), # 32768.50389 -> 32769 (kills drop p_lo) + Case('i16_p_lo_tie_witness', 'i16', (257, 258), (0x3F000201, 0xBF000201)), # +-16384.50192 -> +-16385 + # Single-rounding exact product vs binary32-multiply-then-RNE witnesses: + Case('i16_single_round_sep', 'i16', (257, 258), (0x3F000400, 0x38400180)), # 16385 vs 16386, 1 vs 2 + Case('u16_single_round_sep', 'u16', (257, 258), (0x3F000200, 0x37C000C0)), # 32769 vs 32770, 1 vs 2 + # 3. VOP3 abs[1:0] and neg[1:0] across both operands. + Case('i16_abs_both', 'i16', (257, 258), (0xBF000000, 0xBE800000), abs_=0b11), + Case('i16_neg_both', 'i16', (257, 258), (0x3F000000, 0x3F800000), neg=0b11), + Case('u16_abs_neg_mix', 'u16', (257, 258), (0xBF000000, 0xBF000000), abs_=0b01, neg=0b10), + # 4. SGPR, literal (255), inline f32 (240/241/242/248), inline int (128), and partial EXEC_LO. + Case('u16_sgpr_literal', 'u16', (10, 255), (0x3F000000, 0x3F000101)), + Case('i16_inline_f32', 'i16', (240, 243), (0, 0)), + Case('u16_inline_248_128', 'u16', (248, 128), (0, 0)), + Case('i16_partial_exec', 'i16', (257, 258), (0x3F800000, 0xBF000000), exec_mask=0xAAAAAAAA), + ] + + +def emit_case(c: Case): + code = F.mov(4, DST_INIT) + if c.exec_mask != ALL_EXEC: + code += [sop1(3, 126, 255), c.exec_mask] + lit_tail = [] + for s, v in zip(c.srcs, c.vals): + if s >= 256: + code += F.mov(s - 256, v) + elif s <= 105: + code += F.smov(s, v) + elif s == 255: + lit_tail = [v] + code += vop3_pknorm(c.kind, 4, c.srcs, abs_=c.abs_, neg=c.neg) + code += lit_tail + if c.exec_mask != ALL_EXEC: + code += [sop1(3, 126, 193)] + return code + + +def compute_program(cases): + assert len(cases) <= 32, len(cases) + code = list(PROLOGUE) + for slot, c in enumerate(cases): + code += emit_case(c) + F.store(slot * 4, 4) + return code + [0xBF810000] + + +def refusal_programs(): + return [ + # clamp and omod refused. + (vop3_pknorm('i16', 4, (257, 258), clamp=1) + [0xBF810000], 'unsupported v_cvt_pknorm_i16_f32 clamp or omod'), + (vop3_pknorm('u16', 4, (257, 258), omod=1) + [0xBF810000], 'unsupported v_cvt_pknorm_u16_f32 clamp or omod'), + # op_sel, third-operand abs/neg, and nonzero src2 refused. + (vop3_pknorm('u16', 4, (257, 258), op_sel=1) + [0xBF810000], 'unsupported v_cvt_pknorm_u16_f32 operand modifiers'), + (vop3_pknorm('i16', 4, (257, 258), op_sel=8) + [0xBF810000], 'unsupported v_cvt_pknorm_i16_f32 operand modifiers'), + (vop3_pknorm('i16', 4, (257, 258), abs_=4) + [0xBF810000], 'unsupported v_cvt_pknorm_i16_f32 operand modifiers'), + (vop3_pknorm('u16', 4, (257, 258), neg=4) + [0xBF810000], 'unsupported v_cvt_pknorm_u16_f32 operand modifiers'), + (vop3_pknorm('u16', 4, (257, 258), s2=259) + [0xBF810000], 'unsupported v_cvt_pknorm_u16_f32 operand modifiers'), + # Unsupported special operand encoding (e.g. 254). + (vop3_pknorm('i16', 4, (254, 258)) + [0xBF810000], 'direct DXIL operand encoding'), + ] + + +def cvt_norm_f32_half_mul_f32_oracle(kind, bits): + """Alternative binary32-multiply-then-RNE oracle (separated by *_single_round_sep).""" + bits &= 0xFFFFFFFF + if (bits & 0x7FFFFFFF) > 0x7F800000: + return 0 + val = struct.unpack('<f', struct.pack('<I', bits))[0] + if kind == 'u16': + if math.isnan(val) or val <= 0.0: + return 0 + if val >= 1.0: + return 0xFFFF + scaled = Fraction(struct.unpack('<f', struct.pack('<f', val * 65535.0))[0]) + else: + if val == 0.0: + return 0 + if val >= 1.0: + return 32767 + if val <= -1.0: + return (-32767) & 0xFFFF + scaled = Fraction(struct.unpack('<f', struct.pack('<f', val * 32767.0))[0]) + neg_sign = scaled < 0 + mag = abs(scaled) + q = int(mag) + rem = mag - q + if rem > Fraction(1, 2) or (rem == Fraction(1, 2) and (q & 1)): + q += 1 + return ((-q) & 0xFFFF) if neg_sign else (q & 0xFFFF) + + +def check_oracle_separation(): + assert cvt_norm_f32_half('i16', 0x3F000400) == 16385 and cvt_norm_f32_half_mul_f32_oracle('i16', 0x3F000400) == 16386 + assert cvt_norm_f32_half('i16', 0x38400180) == 1 and cvt_norm_f32_half_mul_f32_oracle('i16', 0x38400180) == 2 + assert cvt_norm_f32_half('u16', 0x3F000200) == 32769 and cvt_norm_f32_half_mul_f32_oracle('u16', 0x3F000200) == 32770 + assert cvt_norm_f32_half('u16', 0x37C000C0) == 1 and cvt_norm_f32_half_mul_f32_oracle('u16', 0x37C000C0) == 2 + + +def ir(dumper): + check_oracle_separation() + items = all_cases() + code = compute_program(items) + want = [c.expected(lane=0) for c in items] + refusals = refusal_programs() + with tempfile.TemporaryDirectory() as tmp: + work = Path(tmp) + run = F.dump(dumper, work, code, 'cvt-pknorm-f32') + assert run.returncode == 0, run.stderr + stores = sorted(F.interpret(run.stdout)) + assert [addr for addr, _ in stores] == [4 * i for i in range(len(want))], stores[:4] + bad = [(i, items[i].name, hex(got), hex(exp)) + for i, ((_, got), exp) in enumerate(zip(stores, want)) if got != exp] + assert not bad, bad[:8] + for idx, (refused, why) in enumerate(refusals): + r = F.dump(dumper, work, refused, f'refused-{idx}') + assert r.returncode != 0 and why in r.stderr, (idx, why, r.returncode, r.stderr) + print(f'native_cvt_pknorm_f32 IR: {len(want)} cases matched exact model; {len(refusals)} refusals matched') + return 0 + + +def controls(cli, sdk, work, root): + check_oracle_separation() + items = all_cases() + code = compute_program(items) + marker = request(work, root, code) + output = marker.with_suffix('.cso') + result = subprocess.run([cli, sdk, work / 'cache', 'gfx1013-direct-cs@0', marker, output], + capture_output=True, text=True) + assert result.returncode == 0 and output.is_file(), (result.stdout, result.stderr) + dump = subprocess.run([Path(sdk) / 'dxc.exe', '-dumpbin', output], capture_output=True, text=True, check=True).stdout + assert '32767' in dump and '65535' in dump and 'lshr i32' in dump, dump + + refusals = refusal_programs() + for idx, (prog, why) in enumerate(refusals): + m = request(work, root, prog) + o = m.with_suffix(f'.refused{idx}.cso') + r = subprocess.run([cli, sdk, work / 'cache', 'gfx1013-direct-cs@0', m, o], capture_output=True, text=True) + assert r.returncode != 0 and why in r.stderr, (idx, why, r.stdout, r.stderr) + assert not o.exists(), o + + print(f'native_cvt_pknorm_f32 controls: compiled {len(items)} cases to DXIL; verified {len(refusals)} refusals') + return 0 + + +def hardware(replay, sdk, work, root): + items = all_cases() + code = compute_program(items) + marker = request(work, root, code) + output = work / 'out.bin' + run = subprocess.run([replay, sdk, marker, work / 'cache', '0', output, '--direct']) + if run.returncode == 77: + return 77 + run.check_returncode() + words_out = list(struct.unpack(f'<{F.WORDS}I', output.read_bytes())) + expected = {} + for group in range(F.GROUPS): + for lane in range(32): + head = F.BASE + group * 1024 + lane * 32 + for idx, c in enumerate(items): + expected[head + idx] = c.expected(lane=lane) + bad = [] + for i, got in enumerate(words_out): + if i in expected: + if got != expected[i]: + bad.append((i, hex(got), hex(expected[i]))) + elif got != F.SENTINEL: + bad.append((i, hex(got), hex(F.SENTINEL))) + assert not bad, bad[:10] + print(f'native_cvt_pknorm_f32 compute hardware: {len(items)} cases matched across {F.GROUPS}x32 lanes and guards') + return 0 + + +def pixel_program(pair): + code = [] + for idx, c in enumerate(pair): + code += emit_case(c) + lo_reg, hi_reg = 8 + 2 * idx, 9 + 2 * idx + code += [vop2(0x1B, lo_reg, 255, 4), 65535, vop2(0x16, hi_reg, 144, 4)] + # Each 16-bit half is exactly representable in binary32 as an integer in 0..65535. + code += [0x7E000C00 | reg << 17 | (256 + reg) for reg in (lo_reg, hi_reg)] + return patched_pixel(len(code), code, export=(0xF800180F, 0x0B0A0908)) + + +def pixel(cli, sdk, renderer, adapter, work): + items = [c for c in all_cases() if c.exec_mask == ALL_EXEC] + if len(items) % 2: + items.append(items[-1]) + vs = compile_hlsl(str(Path(sdk) / 'dxc.exe'), 'dxc', FULLSCREEN_VS, 'fullscreen', 'vs_6_0', work) + pairs = [items[i:i + 2] for i in range(0, len(items), 2)] + for idx, pair in enumerate(pairs): + shader = work / f'cvt-pknorm-f32-{idx}.ps' + shader.write_bytes(pixel_program(pair)) + cso = shader.with_suffix('.cso') + build = subprocess.run([cli, sdk, work / 'cache', 'gfx1013-container-ps', shader, cso], + capture_output=True, text=True, timeout=30) + assert build.returncode == 0, ([c.name for c in pair], build.stdout, build.stderr) + w0, w1 = pair[0].expected(), pair[1].expected() + ref = work / 'expected.bin' + ref.write_bytes(struct.pack('<4f', w0 & 0xFFFF, w0 >> 16, w1 & 0xFFFF, w1 >> 16)) + run = subprocess.run([renderer, adapter, '--startup-pixel-words', vs, cso, '1', '1', ref], + capture_output=True, text=True, timeout=30) + if run.returncode == 77: + return 77 + assert run.returncode == 0, (idx, [c.name for c in pair], run.stdout, run.stderr) + if 'debug_layer=enabled' in run.stdout: + assert 'debug_errors=0 debug_warnings=0' in run.stdout, run.stdout + print(f'native_cvt_pknorm_f32 pixel ({adapter}): {len(pairs)} pixel draws ({len(items)} cases) matched') + return 0 + + +def main(mode, tool, sdk=None, *args): + if mode == 'ir': + return ir(tool) + with tempfile.TemporaryDirectory() as tmp: + work = Path(tmp) + if mode == 'pixel': + return pixel(tool, sdk, args[0], args[1], work) + shader = work / 'root.hlsl' + shader.write_text('#define SIG "DescriptorTable(UAV(u0,numDescriptors=8))"') + root = work / 'root.bin' + subprocess.run([Path(sdk) / 'dxc.exe', '-T', 'rootsig_1_1', '-E', 'SIG', '-Fo', root, shader], check=True) + return {'controls': controls, 'compute': hardware}[mode](tool, sdk, work, root.read_bytes()) + + +if __name__ == '__main__': + sys.exit(main(*sys.argv[1:])) diff --git a/tests/native_descriptor_scc_check.py b/tests/native_descriptor_scc_check.py new file mode 100644 index 0000000000..8ee3457143 --- /dev/null +++ b/tests/native_descriptor_scc_check.py @@ -0,0 +1,154 @@ +"""Observe the SCC of a buffer stride extraction and both MAX operand orders.""" + +from pathlib import Path +import struct +import subprocess +import sys +from tempfile import TemporaryDirectory + +from native_compute_clear_check import write_request +from native_scalar_lds_check import scalar, sop1, vmove +from startup_compute_dispatch_check import dispatch, lines, prepare_case +from startup_compute_translate_check import state_a +from startup_gfx2hlsl_compute_check import KEY, SENTINEL, TGID_X, TGID_Y, TGID_Z, USER7, WORDS + + +def program(*, runtime=False): + offset = 0 if runtime else 32 + table, constant = (6, 4) if runtime else (4, 5) + words = [sop1(3, 20, table), sop1(3, 21, 128), + 0xf408040a, 0xfa000000 | offset, # input SRV in s[16:19] + 0xf408080a, 0xfa000000 | (offset + 32), # output UAV in s[32:35] + 0xbf8cc07f, + scalar(0x27, 25, 17, 255), 0xe0010, # s_bfe_u32: 14-bit stride + sop1(3, 26, 253), + scalar(9, 27, 25, 129), sop1(3, 28, 253), + scalar(9, 29, 129, 25), sop1(3, 30, 253)] + if runtime: + # Flatten the 3x2x2 Dispatch so each group owns four output words. + words += [scalar(0x26, 8, 8, 131), scalar(0x26, 9, 9, 134), + scalar(0, 6, 7, 8), scalar(0, 6, 6, 9)] + words += [scalar(0x1e, 7, 6, 132), vmove(8, 7), sop1(3, 126, 129)] + for i, reg in enumerate((26, 28, 30, constant)): + words += [vmove(10, reg), 0xe0701000 | (4 * i), 0x80080a08] + return words + [0xbf810000] + + +def main(compile_dxil, replay, sdk, backend): + with TemporaryDirectory() as directory: + work = Path(directory) + dxc = Path(sdk) / "dxc.exe" + source, root = work / "root.hlsl", work / "root.bin" + requests = work / "requests" + requests.mkdir() + # s5 is one root constant and s6 is the X group ID. Exercise b0 with + # the descriptor metadata appended to a regular root constant. + sa = struct.pack("<7I", 0, 0, 0, 32 | 1 << 16, 1, 0, 0x80 | 6 << 1) + + def root_bytes(srv_count): + source.write_text(f'#define RS "DescriptorTable(SRV(t0,numDescriptors={srv_count}),' + f'UAV(u0,numDescriptors={3 - srv_count},offset={srv_count})),' + 'RootConstants(num32BitConstants=1,b0)"\n', encoding="ascii") + subprocess.run([dxc, "-T", "rootsig_1_1", "-E", "RS", source, "-Fo", root], check=True) + return root.read_bytes() + + marker = write_request(requests, program(), root_bytes(2), sa) + prefix = [compile_dxil, sdk, work / "cache", "gfx1013-direct-cs@0"] + for hit in (0, 1): + published = work / f"published-{hit}" + result = subprocess.run([*prefix, "--requests", requests, published], + capture_output=True, text=True) + assert result.returncode == 0 and f"frontend_cache_hit={hit}" in result.stdout, result.stdout + result.stderr + [manifest] = published.glob("*.txt") + # The native output revision line (#3006) is checked separately; the binding lines stay exact. + lines = manifest.read_text().splitlines() + assert sum(line.startswith("native ") for line in lines) == 1, manifest.read_text() + assert [line for line in lines if not line.startswith("native ")] == [ + "x2w-manifest 2", "stage cs", "group 32 1 1", "ud 2", + "udsrc 0 rootconst 1 0", "udsrc 1 stride 0", + "srv 0 buf table 0 32", "uav 0 table 0 64", + ], manifest.read_text() + print("cold and warm manifests both bind the stride of SRV 0 after the root constant") + + negative = work / "negative" + negative.mkdir() + bad = write_request(negative, program(), root_bytes(1), sa) + result = subprocess.run([*prefix, bad, work / "bad.cso"], capture_output=True, text=True) + assert result.returncode and "numeric SCC from a symbolic descriptor field" in result.stderr, result.stderr + print("the same descriptor load from a UAV range is refused") + + mode = "--direct-warp" if backend == "warp" else "--direct" + readback, metadata = work / "readback.bin", work / "stride.txt" + for value in (0, 1, 4, 16, 0x4000, 0x7fff): + metadata.write_text(str(value), encoding="ascii") + result = subprocess.run([replay, sdk, marker, work / "cache", "0", readback, mode, metadata], + capture_output=True, text=True) + if result.returncode == 77: + print(result.stderr.strip()) + return 77 + assert result.returncode == 0, result.stdout + result.stderr + stride = value & 0x3fff + expected = [0x69696969] * 2064 + for group in range(2): + start = 8 + group * 4 + expected[start:start + 4] = [int(stride != 0), int(stride > 1), int(1 > stride), 3] + actual = list(struct.unpack("<2064I", readback.read_bytes())) + assert actual == expected, next((i, a, b) for i, (a, b) in enumerate(zip(actual, expected)) if a != b) + print(f"stride word {value}: two groups match {expected[8:12]} and all guards") + result = subprocess.run([replay, sdk, marker, work / "cache", "0", readback, mode], + capture_output=True, text=True) + assert result.returncode == 1 and "compute descriptor stride metadata missing" in result.stderr, result.stderr + print("missing stride metadata is rejected before dispatch") + return 0 + + +def runtime_main(compile_dxil, consumer, sdk, backend): + with TemporaryDirectory() as directory: + work = Path(directory) + cache, env = prepare_case(work, backend) + env.pop("X2W_NATIVE_SHADERS", None) + env.pop("X2W_NATIVE_SHADERS_ONLY", None) + env["X2W_TEST_DISPATCH_FIELDS"] = str(work / "descriptor.bin") + fields = Path(env["X2W_TEST_DISPATCH_FIELDS"]) + fields.write_bytes(struct.pack("<6I", 4, 64, 0, 4, WORDS, 0)) + code = program(runtime=True) + (work / "program").write_bytes(struct.pack(f"<{len(code)}I", *code)) + (work / "state").write_bytes(state_a((32, 1, 1), USER7 | TGID_X | TGID_Y | TGID_Z)) + got, result = dispatch(work, consumer, env, "dispatch-records32", probe=True) + assert got == [SENTINEL] * WORDS and lines(result, "refused: no translation"), result.stderr + [marker] = cache.glob("req_*.c67") + + for route in ("native", "published"): + selected = dict(env) + if route == "native": + selected["X2W_NATIVE_SHADERS"] = sdk + else: + subprocess.run([compile_dxil, sdk, work / "frontend", "gfx1013-direct-cs@0", + "--requests", cache, cache], check=True) + manifest = cache / (marker.stem.removeprefix("req_") + ".txt") + assert "udsrc 2 stride 0\n" in manifest.read_text(), manifest.read_text() + for stride in (0, 1, 4, 16): + fields.write_bytes(struct.pack("<6I", stride, 64, 0, 4, WORDS, 0)) + got, result = dispatch(work, consumer, selected, "dispatch-records32") + if lines(result, "the adapter has no 32-lane waves"): + assert got == [SENTINEL] * WORDS + print("skip: runtime adapter has no wave32") + return 77 + expected = [int(stride != 0), int(stride > 1), int(1 > stride), KEY] * 12 + expected += [SENTINEL] * (WORDS - len(expected)) + assert got == expected, ( + next((i, a, b) for i, (a, b) in enumerate(zip(got, expected)) if a != b), result.stderr[-3000:] + ) + assert bool(lines(result, "translated natively: 3 entry values, 1 inputs, 1 outputs")) == ( + route == "native" + ), result.stderr[-3000:] + assert lines(result, "Dispatch(3, 2, 2) translated") and not lines(result, "refused: "), result.stderr + assert not [line for line in lines(result, "x2w-d3d12-debug ") if " sev=0 " in line or " sev=1 " in line] + print(f"{route}: stride {stride}, 12 groups match {expected[:4]} and all guards") + return 0 + + +if __name__ == "__main__": + if sys.argv[1] == "runtime": + sys.exit(runtime_main(*sys.argv[2:])) + sys.exit(main(*sys.argv[1:])) diff --git a/tests/native_direct_container_check.py b/tests/native_direct_container_check.py index a2d0a2a888..22b41cf886 100644 --- a/tests/native_direct_container_check.py +++ b/tests/native_direct_container_check.py @@ -13,7 +13,7 @@ def words(*values): return struct.pack(f"<{len(values)}I", *values) -def compute(code, threads=32, table=False, root_descriptor=False, wave32=True, uses=()): +def compute(code, threads=32, table=False, root_descriptor=False, wave32=True, uses=(), *, group=None): body = bytearray(256) struct.pack_into("<Q", body, 0, 6) for offset in (8, 16, 24, 32, 40, 48, 72): @@ -33,7 +33,8 @@ def compute(code, threads=32, table=False, root_descriptor=False, wave32=True, u struct.pack_into("<I", body, record+20, 32 if wave32 else 0) struct.pack_into("<II", body, record+76, 512, 4) user_flags = 4 if root_descriptor else (0x1002 if table else 0) - struct.pack_into("<IIII", body, record+120, 0x8400 | user_flags, threads, 1, 1) + group = (threads, 1, 1) if group is None else group + struct.pack_into("<IIII", body, record+120, 0x8400 | user_flags, *group) body.extend(code) return pack(body) @@ -196,7 +197,78 @@ def comparison_program(op=47, dim=1, sampler=0x08001012): return [*setup, 0xf0000100 | (dim << 3) | op << 18, 0x00220400] +# Scalar ops whose direct lowering writes SCC. The byte-window field refuses when +# the next instruction still looks like an SCC reader, so these have to sit in +# uses_scc_after's overwrite list next to s_max_u32. +SCC_WRITERS = ("s_absdiff_i32", "s_min_u32", "s_min_i32", "s_max_i32") + + +def scc_overwrite_names(source): + start = source.index("const bool overwrites = ") + end = source.index("const bool preserves_pair", start) + return set(re.findall(r'n == "([^"]+)"', source[start:end])) + + +def symbolic_field_scc_live(program, writers): + """Same backward walk as uses_scc_after, for a straight-line program. + + Returns whether SCC is live at the instruction after program[0]. + """ + preserves = {"s_mov_b32", "s_mov_b64", "s_ff1_i32_b64", "s_brev_b32"} + readers = {"s_cselect_b32"} + live = [False] * len(program) + previous = [[] for _ in program] + pending = [] + for index, name in enumerate(program): + scalar = name.startswith("s_") and name != "s_endpgm" + reads = name in readers + uncertain = scalar and not reads and name not in writers and name not in preserves + if reads or uncertain: + live[index] = True + pending.append(index) + continue + if name in writers or name == "s_endpgm": + continue + previous[index + 1].append(index) + while pending: + index = pending.pop() + for pred in previous[index]: + if live[pred]: + continue + live[pred] = True + pending.append(pred) + return live[1] + + +def check_scc_writer_mutant(): + source = pathlib.Path(__file__).resolve().parents[1].joinpath( + "src", "gfx1013_direct_compute.inl").read_text(encoding="utf-8") + start = source.index("const bool overwrites = ") + end = source.index("const bool preserves_pair", start) + block = source[start:end] + writers = scc_overwrite_names(source) + assert "s_and_b32" in writers and "s_max_u32" in writers + for name in SCC_WRITERS: + assert block.count(f'n == "{name}"') == 1, name + killed = ["s_and_b32", "s_mov_b32", "s_mov_b32", "s_absdiff_i32", "s_cselect_b32", + "v_mov_b32", "s_endpgm"] + select = ["s_and_b32", "s_mov_b32", "s_mov_b32", "s_ff1_i32_b64", "s_cselect_b32", "s_endpgm"] + assert symbolic_field_scc_live(select, writers) + assert not symbolic_field_scc_live(killed, writers) + mutant = block + for name in SCC_WRITERS: + mutant = mutant.replace(f'n == "{name}"', 'n == "s_endpgm"', 1) + dropped = set(re.findall(r'n == "([^"]+)"', mutant)) - {"s_endpgm"} + for name in SCC_WRITERS: + program = ["s_and_b32", "s_mov_b32", "s_mov_b32", name, "v_mov_b32", "s_endpgm"] + assert not symbolic_field_scc_live(program, writers), name + assert symbolic_field_scc_live(program, dropped), name + assert symbolic_field_scc_live(killed, dropped) + print("scc writer mutant: each new case is live once its overwrite entry is removed") + + def main(): + check_scc_writer_mutant() if len(sys.argv) == 4 and sys.argv[1] in ("--sampler-pso", "--graphics-sampler-pso"): sdk, probe = sys.argv[2:] with tempfile.TemporaryDirectory() as tmp: @@ -354,6 +426,25 @@ def check(name, profile, data, expected=""): check("descriptor-sop1-before-scc-read", cs, compute(words(*address_field, *pair_zero, ff1_pair, select_scc, end), table=True), "numeric SCC from a symbolic descriptor field") + # s_min_i32 / s_min_u32 / s_max_i32 / s_absdiff_i32 write SCC, same as s_max_u32. + # After the address-field rewrite they kill that symbolic SCC. s_cselect with + # no such writer in between stays refused above. The source mutant in + # check_scc_writer_mutant drops each overwrite entry and the same shape is live. + use_diff = 0x7e00021a # v_mov_b32 v0, s26 + for name, word in ( + ("s_min_i32", 0x831a1716), # s_min_i32 s26, s22, s23 + ("s_min_u32", 0x839a1716), + ("s_max_i32", 0x841a1716), + ("s_absdiff_i32", 0x961a1716)): + check("descriptor-" + name + "-kills-scc", cs, + compute(words(*address_field, *pair_zero, word, use_diff, end), table=True)) + check("descriptor-absdiff-then-cselect", cs, + compute(words(*address_field, *pair_zero, 0x961a1716, 0x85191716, use_diff, end), + table=True)) + or_saveexec = 0xbe983dc1 # s_or_saveexec_b32 s24, -1 + check("descriptor-or-saveexec-kill", cs, compute(words(*address_field, or_saveexec, read_scc, end), table=True)) + check("or-saveexec-exec-destination", cs, compute(words(0xbefe3dc1, end)), + "unsupported wave32 SAVEEXEC destination") # The previous symbolic SCC is dead at WQM. Reading it before WQM # must still refuse. The nonzero high word supplies the new SCC. numeric_wqm = [0xbe9a0380, 0xbe9b0381, 0xbe980a1a] # s[24:25] = WQM(s[26:27]) @@ -456,13 +547,10 @@ def atomic_program(instructions): root_vs = vertex(constants=(0,2,1), program=[*root_load, 0x7e00020f, 0xf80008cf, 0, end]) check("address-vs", "gfx1013-container-vs", root_vs) check("address-cs", cs, compute(words(*root_load, end), root_descriptor=True)) - for offset in (106, 107): - check(f"wave64-smem-offset-{offset}", cs, - compute(words(0xf4000200, offset << 25, end), threads=64, - root_descriptor=True, wave32=False), "unsupported scalar memory addressing") - check("wave64-smem-vcc-dst", cs, - compute(words(0xf4000000 | 107 << 6, 125 << 25, end), threads=64, - root_descriptor=True, wave32=False), "unsupported scalar memory destination range") + check("wave64-smem-symbolic-vcc-dst", cs, + compute(words(0xbe810380, 0xf4080000 | 104 << 6, 125 << 25, end), + threads=64, table=True, wave32=False), + "symbolic scalar memory destination overlaps wave64 VCC") check("wave32-smem-cross-vcc", cs, compute(words(0xf40c0000 | 104 << 6, 125 << 25, end), root_descriptor=True), "unsupported scalar memory destination range") @@ -873,7 +961,8 @@ def waterfall_pixel(byte_key=False,modifier=None): 0xbe840380, 0xbe8503ff, 0x00fff000, 0xbe8603ff, 0x04000000, 0xbe870380, 0x7e0002f0, 0x7e0202f2, 0x7e0402f4, 0xf0000108 | op << 18, 0x00220000] check(f"sample{op}", "gfx1013-container-ps", patched_pixel(len(prefix), prefix, True)) - check(f"derivative{op}", cs, compute(words(*prefix, end), table=True), + # Six threads do not form complete compute quads, so implicit derivatives stay refused. + check(f"derivative{op}", cs, compute(words(*prefix, end), threads=6, table=True), "implicit derivatives require a pixel stage") image_setup = prefix[:-2] # Reread v0 as the input record index before the instruction overwrites it. diff --git a/tests/native_dot2_f32_f16_check.py b/tests/native_dot2_f32_f16_check.py new file mode 100644 index 0000000000..2c4847f517 --- /dev/null +++ b/tests/native_dot2_f32_f16_check.py @@ -0,0 +1,350 @@ +"""Direct DXIL v_dot2_f32_f16 lowering in Compute and Pixel shaders.""" +from dataclasses import dataclass +import math +from pathlib import Path +import struct +import subprocess +import sys +import tempfile + +from native_direct_container_check import patched_pixel +from native_dpp_quad_check import request +import native_f16_alu_check as F +from native_packed_f16_inline_check import INLINE_F16_WORDS, PROLOGUE, inline_word +from native_scalar_lds_check import vmove +from startup_image_3d_check import FULLSCREEN_VS, compile_hlsl + +OP_DOT2_F32_F16 = 0x13 + + +def vop3p_dot2(dst, srcs, *, op_sel=0, op_sel_hi=0, neg_lo=0, neg_hi=0, clamp=0, op_sel_hi2=0): + s0, s1, s2 = srcs + w0 = (0xCC000000 | (OP_DOT2_F32_F16 << 16) | ((clamp & 1) << 15) | ((op_sel_hi2 & 1) << 14) | + ((op_sel & 7) << 11) | ((neg_hi & 7) << 8) | (dst & 0xFF)) + w1 = ((neg_lo & 7) << 29) | ((op_sel_hi & 3) << 27) | ((s2 & 0x1FF) << 18) | ((s1 & 0x1FF) << 9) | (s0 & 0x1FF) + return [w0, w1] + + +def f32_to_bits(val): + return struct.unpack('<I', struct.pack('<f', val))[0] + + +def bits_to_f32(bits): + return struct.unpack('<f', struct.pack('<I', bits & 0xFFFFFFFF))[0] + + +def widen_f16(half_bits): + return struct.unpack('<e', struct.pack('<H', half_bits & 0xFFFF))[0] + + +def f32_inline_bits(enc): + f32_inline = { + 240: 0x3F000000, 241: 0xBF000000, 242: 0x3F800000, 243: 0xBF800000, + 244: 0x40000000, 245: 0xC0000000, 246: 0x40800000, 247: 0xC0800000, + 248: 0x3E22F983, + } + if enc in f32_inline: + return f32_inline[enc] + if 128 <= enc <= 192: + return enc - 128 + if 193 <= enc <= 208: + return (192 - enc) & 0xFFFFFFFF + raise ValueError(enc) + + +def is_nan_f32(bits): + return (bits & 0x7FFFFFFF) > 0x7F800000 + + +def same_f32(got, want): + if is_nan_f32(want): + return is_nan_f32(got) + return got == want + + +def eval_dot2(raw_words, *, op_sel=0, op_sel_hi=0, neg_lo=0, neg_hi=0, clamp=0): + def term(word, selector, neg): + half = (word >> 16) if selector else (word & 0xFFFF) + if neg: + half ^= 0x8000 + return widen_f16(half) + + a0 = term(raw_words[0], op_sel & 1, bool(neg_lo & 1)) + b0 = term(raw_words[1], (op_sel >> 1) & 1, bool(neg_lo & 2)) + a1 = term(raw_words[0], op_sel_hi & 1, bool(neg_hi & 1)) + b1 = term(raw_words[1], (op_sel_hi >> 1) & 1, bool(neg_hi & 2)) + c_bits = raw_words[2] ^ (0x80000000 if (neg_lo & 4) else 0) + c = bits_to_f32(c_bits) + + p0 = bits_to_f32(f32_to_bits(a0 * b0)) + p1 = bits_to_f32(f32_to_bits(a1 * b1)) + s01 = bits_to_f32(f32_to_bits(p0 + p1)) + res = bits_to_f32(f32_to_bits(s01 + c)) + if clamp: + res = 0.0 if (math.isnan(res) or res <= 0.0) else (1.0 if res >= 1.0 else res) + return f32_to_bits(res) + + +@dataclass(frozen=True) +class Case: + name: str + srcs: tuple + vals: tuple + op_sel: int = 0 + op_sel_hi: int = 3 + neg_lo: int = 0 + neg_hi: int = 0 + clamp: int = 0 + op_sel_hi2: int = 0 + pixel_safe: bool = True + + def raw_words(self): + words = [] + for idx, (s, v) in enumerate(zip(self.srcs, self.vals)): + if s < 128 or s >= 255: + words.append(v & 0xFFFFFFFF) + elif idx < 2: + words.append(inline_word(s)) + else: + words.append(f32_inline_bits(s)) + return tuple(words) + + def expected(self): + return eval_dot2(self.raw_words(), op_sel=self.op_sel, op_sel_hi=self.op_sel_hi, + neg_lo=self.neg_lo, neg_hi=self.neg_hi, clamp=self.clamp) + + +def p16(lo, hi): + return ((hi & 0xFFFF) << 16) | (lo & 0xFFFF) + + +def all_cases(): + return [ + # 1. Basic VGPR dot product with packed halves and binary32 accumulator. + Case('basic_vgpr', (257, 258, 259), (p16(0x3C00, 0x4000), p16(0x4200, 0x4400), f32_to_bits(0.5))), + # 2. All op_sel / op_sel_hi cross-lane combinations + LLVM-style op_sel_hi[2]=1. + Case('opsel_swap', (257, 258, 259), (p16(0x3C00, 0x4000), p16(0x4200, 0x4400), f32_to_bits(1.25)), + op_sel=0b10, op_sel_hi=0b01, op_sel_hi2=1), + Case('opsel_broadcast_lo', (257, 258, 259), (p16(0x3C00, 0x7E00), p16(0x4200, 0x7E00), f32_to_bits(2.0)), + op_sel=0b00, op_sel_hi=0b00), + Case('opsel_broadcast_hi', (257, 258, 259), (p16(0x7E00, 0x3C00), p16(0x7E00, 0x4000), f32_to_bits(-0.5)), + op_sel=0b11, op_sel_hi=0b11), + # 3. Negate modifiers: neg_lo[0], neg_lo[1], neg_lo[2] (f32 src2), neg_hi[0], neg_hi[1]. + Case('neg_pair0', (257, 258, 259), (p16(0x3C00, 0x4000), p16(0x4200, 0x4400), f32_to_bits(10.0)), + neg_lo=0b001), + Case('neg_pair0_both_and_c', (257, 258, 259), (p16(0x3C00, 0x4000), p16(0x4200, 0x4400), f32_to_bits(10.0)), + neg_lo=0b111), + Case('neg_pair1_hi0_hi1', (257, 258, 259), (p16(0x3C00, 0x4000), p16(0x4200, 0x4400), f32_to_bits(1.0)), + neg_hi=0b10), + Case('neg_all_five', (257, 258, 259), (p16(0x3C00, 0x4000), p16(0x4200, 0x4400), f32_to_bits(3.0)), + neg_lo=0b111, neg_hi=0b11), + # 4. Clamp / saturate: < 0 -> +0.0, interior (0, 1), > 1 -> 1.0, exact boundary 0.0 / 1.0. + Case('clamp_negative', (257, 258, 259), (p16(0xBC00, 0x3C00), p16(0x4000, 0x3800), f32_to_bits(-2.0)), + clamp=1), + Case('clamp_above_one', (257, 258, 259), (p16(0x4000, 0x4000), p16(0x4000, 0x4000), f32_to_bits(0.5)), + clamp=1), + Case('clamp_interior', (257, 258, 259), (p16(0x3800, 0x3400), p16(0x3800, 0x3C00), f32_to_bits(0.125)), + clamp=1), + Case('clamp_nan_to_zero', (257, 258, 259), (p16(0x7E00, 0x3C00), p16(0x3C00, 0x3C00), f32_to_bits(0.5)), + clamp=1, pixel_safe=False), + # 5. Inline binary16 float constants on src0/src1 (including zero high half 242, 245, 248) and f32 src2 inline. + Case('inline_f16_lo_242_hi_zero', (242, 258, 240), (0, p16(0x4000, 0x4400), 0)), + Case('inline_f16_245_248', (245, 248, 259), (0, 0, f32_to_bits(1.0)), op_sel=0b00, op_sel_hi=0b11), + Case('inline_src2_243_neg_c', (257, 258, 243), (p16(0x3C00, 0x3C00), p16(0x3C00, 0x4000), 0), neg_lo=0b100), + # 6. Inline integer constants on src0/src1 (129=subnormal 2^-24, 192=64 subnormal) & src2 (128=+0, 129=2^-149). + Case('inline_int_129_192_128', (129, 192, 128), (0, 0, 0)), + Case('inline_int_src2_128_zero', (257, 258, 128), (p16(0x3C00, 0x3C00), p16(0x4000, 0x3800), 0)), + Case('inline_int_src2_129', (257, 258, 129), (p16(0x0000, 0x0000), p16(0x0000, 0x0000), 0)), + Case('vgpr_src2_subnormal_pos', (257, 258, 259), (p16(0x0000, 0x0000), p16(0x0000, 0x0000), 0x00000001)), + Case('vgpr_src2_subnormal_neg', (257, 258, 259), (p16(0x0000, 0x0000), p16(0x0000, 0x0000), 0x80400000)), + Case('vgpr_src2_subnormal_clamp_pos', (257, 258, 259), (p16(0x0000, 0x0000), p16(0x0000, 0x0000), 0x00000001), clamp=1), + Case('vgpr_src2_subnormal_clamp_neg', (257, 258, 259), (p16(0x0000, 0x0000), p16(0x0000, 0x0000), 0x80400000), clamp=1), + # 7. SGPR and 32-bit literal sources. + Case('sgpr_sources', (10, 11, 12), (p16(0x3C00, 0xC000), p16(0x4200, 0x3800), f32_to_bits(0.75))), + Case('literal_src0', (255, 258, 259), (p16(0x4000, 0x3C00), p16(0x3800, 0x4200), f32_to_bits(-1.0))), + Case('literal_src2', (257, 258, 255), (p16(0x3C00, 0x3800), p16(0x3C00, 0x4000), f32_to_bits(3.25))), + # 8. Binary16 subnormals, signed zeros, infinity, max finite, and NaN propagation. + Case('subnormal_f16_exact', (257, 258, 259), (p16(0x0001, 0x03FF), p16(0x0001, 0x7BFF), f32_to_bits(0.0))), + Case('signed_zero_keep', (257, 258, 259), (p16(0x8000, 0x8000), p16(0x3C00, 0x3C00), f32_to_bits(-0.0)), + pixel_safe=False), + Case('signed_zero_cancel_pos', (257, 258, 259), (p16(0x3C00, 0x3C00), p16(0xBC00, 0x3C00), f32_to_bits(-0.0)), + pixel_safe=False), + Case('inf_propagation', (257, 258, 259), (p16(0x7C00, 0x3C00), p16(0x3C00, 0x3C00), f32_to_bits(-4.0)), + pixel_safe=False), + Case('nan_propagation', (257, 258, 259), (p16(0x7E01, 0x3C00), p16(0x3C00, 0x3C00), f32_to_bits(1.0)), + pixel_safe=False), + ] + + +def emit_case(c: Case): + code = [] + lit_tail = [] + for idx, (s, v) in enumerate(zip(c.srcs, c.vals)): + if s >= 256: + code += F.mov(s - 256, v) + elif s <= 105: + code += F.smov(s, v) + elif s == 255: + lit_tail = [v] + code += vop3p_dot2(4, c.srcs, op_sel=c.op_sel, op_sel_hi=c.op_sel_hi, + neg_lo=c.neg_lo, neg_hi=c.neg_hi, clamp=c.clamp, op_sel_hi2=c.op_sel_hi2) + code += lit_tail + return code + + +def compute_program(cases): + code = list(PROLOGUE) + want = [] + for slot, c in enumerate(cases): + code += emit_case(c) + F.store(slot * 4, 4) + want.append(c.expected()) + return code + [0xBF810000], want + + +def refusal_programs(): + # Conditional branch + s_denorm_mode makes half_mode_known == false for v_dot2_f32_f16. + cond_mode = [0xBF840001, 0xBFA5000F, 0xBF810000] # s_cbranch_scc0 +1; s_denorm_mode 15 + return [ + # Reserved OP_SEL[2] and NEG_HI[2] bits on v_dot2_f32_f16. + (vop3p_dot2(4, (257, 258, 259), op_sel=0b100) + [0xBF810000], 'unsupported v_dot2_f32_f16 encoding'), + (vop3p_dot2(4, (257, 258, 259), neg_hi=0b100) + [0xBF810000], 'unsupported v_dot2_f32_f16 encoding'), + # Special scalar sources refused on src0, src1, src2. + (vop3p_dot2(4, (106, 258, 259)) + [0xBF810000], 'unsupported v_dot2_f32_f16 source'), + (vop3p_dot2(4, (257, 124, 259)) + [0xBF810000], 'unsupported v_dot2_f32_f16 source'), + (vop3p_dot2(4, (257, 258, 126)) + [0xBF810000], 'unsupported v_dot2_f32_f16 source'), + (vop3p_dot2(4, (257, 258, 253)) + [0xBF810000], 'unsupported v_dot2_f32_f16 source'), + # Unsupported binary16 denormal flush (s_denorm_mode 3) or rounding mode (s_round_mode 4). + ([0xBFA50003] + vop3p_dot2(4, (257, 258, 259)) + [0xBF810000], + 'unsupported binary16 rounding or denormal mode'), + ([0xBFA40004] + vop3p_dot2(4, (257, 258, 259)) + [0xBF810000], + 'unsupported binary16 rounding or denormal mode'), + # Unsupported binary32 denormal flush (s_denorm_mode 0xC) refused via mode gate. + ([0xBFA5000C] + vop3p_dot2(4, (257, 258, 259)) + [0xBF810000], + 'unsupported compute control instruction s_denorm_mode'), + # Dynamic conditional mode change makes half_mode_known false via half_binary tracking. + (cond_mode[:-1] + vop3p_dot2(4, (257, 258, 259)) + [0xBF810000], + 'unsupported binary16 rounding or denormal mode'), + ] + + +def ir(dumper): + items = all_cases() + code, want = compute_program(items) + refusals = refusal_programs() + with tempfile.TemporaryDirectory() as tmp: + work = Path(tmp) + run = F.dump(dumper, work, code, 'dot2-f32-f16') + assert run.returncode == 0, run.stderr + stores = sorted(F.interpret(run.stdout)) + assert [addr for addr, _ in stores] == [4 * i for i in range(len(want))], stores[:4] + bad = [(i, items[i].name, hex(got), hex(exp)) + for i, ((_, got), exp) in enumerate(zip(stores, want)) if not same_f32(got, exp)] + assert not bad, bad[:8] + for idx, (refused, why) in enumerate(refusals): + r = F.dump(dumper, work, refused, f'refused-{idx}') + assert r.returncode != 0 and why in r.stderr, (idx, why, r.returncode, r.stderr) + print(f'native_dot2_f32_f16 IR: {len(want)} cases matched exact model; {len(refusals)} refusals matched') + return 0 + + +def controls(cli, sdk, work, root): + items = all_cases() + code, want = compute_program(items) + marker = request(work, root, code) + output = marker.with_suffix('.cso') + result = subprocess.run([cli, sdk, work / 'cache', 'gfx1013-direct-cs@0', marker, output], + capture_output=True, text=True) + assert result.returncode == 0 and output.is_file(), (result.stdout, result.stderr) + dump = subprocess.run([Path(sdk) / 'dxc.exe', '-dumpbin', output], capture_output=True, text=True, check=True).stdout + assert 'legacyF16ToF32' in dump and 'fmul float' in dump and 'fadd float' in dump and 'unary.f32(i32 7,' in dump, dump + + refusals = refusal_programs() + for idx, (prog, why) in enumerate(refusals): + m = request(work, root, prog) + o = m.with_suffix(f'.refused{idx}.cso') + r = subprocess.run([cli, sdk, work / 'cache', 'gfx1013-direct-cs@0', m, o], capture_output=True, text=True) + assert r.returncode != 0 and why in r.stderr, (idx, why, r.stdout, r.stderr) + assert not o.exists(), o + + print(f'native_dot2_f32_f16 controls: compiled {len(want)} cases to DXIL; verified {len(refusals)} refusals') + return 0 + + +def hardware(replay, sdk, work, root): + items = all_cases() + code, want = compute_program(items) + marker = request(work, root, code) + output = work / 'out.bin' + run = subprocess.run([replay, sdk, marker, work / 'cache', '0', output, '--direct']) + if run.returncode == 77: + return 77 + run.check_returncode() + words_out = list(struct.unpack(f'<{F.WORDS}I', output.read_bytes())) + expected = {} + for group in range(F.GROUPS): + for lane in range(32): + head = F.BASE + group * 1024 + lane * 32 + for idx, w in enumerate(want): + expected[head + idx] = w + bad = [] + for i, got in enumerate(words_out): + if i in expected: + if not same_f32(got, expected[i]): + bad.append((i, hex(got), hex(expected[i]))) + elif got != F.SENTINEL: + bad.append((i, hex(got), hex(F.SENTINEL))) + assert not bad, bad[:10] + print(f'native_dot2_f32_f16 compute hardware: {len(want)} cases matched across {F.GROUPS}x32 lanes and guards') + return 0 + + +def pixel_program(quad): + code = [] + for idx, c in enumerate(quad): + code += emit_case(c) + code.append(vmove(8 + idx, 256 + 4)) + return patched_pixel(len(code), code, export=(0xF800180F, 0x0B0A0908)) + + +def pixel(cli, sdk, renderer, adapter, work): + items = [c for c in all_cases() if c.pixel_safe] + while len(items) % 4: + items.append(items[-1]) + vs = compile_hlsl(str(Path(sdk) / 'dxc.exe'), 'dxc', FULLSCREEN_VS, 'fullscreen', 'vs_6_0', work) + quads = [items[i:i + 4] for i in range(0, len(items), 4)] + for idx, quad in enumerate(quads): + shader = work / f'dot2-{idx}.ps' + shader.write_bytes(pixel_program(quad)) + cso = shader.with_suffix('.cso') + build = subprocess.run([cli, sdk, work / 'cache', 'gfx1013-container-ps', shader, cso], + capture_output=True, text=True, timeout=30) + assert build.returncode == 0, ([c.name for c in quad], build.stdout, build.stderr) + ref = work / 'expected.bin' + ref.write_bytes(struct.pack('<4I', *(c.expected() for c in quad))) + run = subprocess.run([renderer, adapter, '--startup-pixel-words', vs, cso, '1', '1', ref], + capture_output=True, text=True, timeout=30) + if run.returncode == 77: + return 77 + assert run.returncode == 0, (idx, [c.name for c in quad], run.stdout, run.stderr) + if 'debug_layer=enabled' in run.stdout: + assert 'debug_errors=0 debug_warnings=0' in run.stdout, run.stdout + print(f'native_dot2_f32_f16 pixel ({adapter}): {len(quads)} quad draws matched') + return 0 + + +def main(mode, tool, sdk=None, *args): + if mode == 'ir': + return ir(tool) + with tempfile.TemporaryDirectory() as tmp: + work = Path(tmp) + if mode == 'pixel': + return pixel(tool, sdk, args[0], args[1], work) + shader = work / 'root.hlsl' + shader.write_text('#define SIG "DescriptorTable(UAV(u0,numDescriptors=8))"') + root = work / 'root.bin' + subprocess.run([Path(sdk) / 'dxc.exe', '-T', 'rootsig_1_1', '-E', 'SIG', '-Fo', root, shader], check=True) + return {'controls': controls, 'compute': hardware}[mode](tool, sdk, work, root.read_bytes()) + + +if __name__ == '__main__': + sys.exit(main(*sys.argv[1:])) diff --git a/tests/native_dot2c_f32_f16_check.py b/tests/native_dot2c_f32_f16_check.py new file mode 100644 index 0000000000..3c0160a2f5 --- /dev/null +++ b/tests/native_dot2c_f32_f16_check.py @@ -0,0 +1,283 @@ +"""Direct DXIL VOP2 v_dot2c_f32_f16 lowering in Compute and Pixel shaders.""" +from dataclasses import dataclass +from pathlib import Path +import struct +import subprocess +import sys +import tempfile + +from native_direct_container_check import patched_pixel +from native_dot2_f32_f16_check import bits_to_f32, f32_to_bits, p16, same_f32, widen_f16 +from native_dpp_quad_check import request +import native_f16_alu_check as F +from native_packed_f16_inline_check import PROLOGUE, inline_word +from native_scalar_lds_check import sop1, vmove +from startup_image_3d_check import FULLSCREEN_VS, compile_hlsl + +OP_DOT2C_F32_F16 = 0x02 +ALL_EXEC = 0xFFFFFFFF + + +def vop2_dot2c(dst, src0, vsrc1): + assert 256 <= vsrc1 < 512, vsrc1 + return ((OP_DOT2C_F32_F16 << 25) | ((dst & 0xFF) << 17) | (((vsrc1 - 256) & 0xFF) << 9) | (src0 & 0x1FF)) + + +def vop3_dot2c_e64(dst, src0, vsrc1, *, clamp=0): + return [ + 0xD5020000 | ((clamp & 1) << 15) | (dst & 0xFF), + ((vsrc1 & 0x1FF) << 9) | (src0 & 0x1FF), + ] + + +def eval_dot2c(s0_word, s1_word, acc_bits): + a0 = widen_f16(s0_word & 0xFFFF) + b0 = widen_f16(s1_word & 0xFFFF) + a1 = widen_f16((s0_word >> 16) & 0xFFFF) + b1 = widen_f16((s1_word >> 16) & 0xFFFF) + p0 = bits_to_f32(f32_to_bits(a0 * b0)) + p1 = bits_to_f32(f32_to_bits(a1 * b1)) + s01 = bits_to_f32(f32_to_bits(p0 + p1)) + c = bits_to_f32(acc_bits) + return f32_to_bits(s01 + c) + + +@dataclass(frozen=True) +class Case: + name: str + steps: tuple + acc: int + exec_mask: int = ALL_EXEC + alias: str = 'none' + pixel_safe: bool = True + + def expected(self, lane=0): + if ((self.exec_mask >> lane) & 1) == 0: + return self.acc & 0xFFFFFFFF + cur = self.acc & 0xFFFFFFFF + for s0, v0, v1 in self.steps: + if self.alias == 'src0': + w0 = cur + elif s0 < 128 or s0 >= 255: + w0 = v0 & 0xFFFFFFFF + else: + w0 = inline_word(s0) + w1 = cur if self.alias == 'src1' else (v1 & 0xFFFFFFFF) + cur = eval_dot2c(w0, w1, cur) + return cur + + +def all_cases(): + return [ + # 1. Basic VGPR accumulate with distinct low/high products. + Case('vgpr_basic', ((262, p16(0x3C00, 0x4000), p16(0x4200, 0x4400)),), f32_to_bits(0.5)), + # 2. Opposite products cancel to +0.0, preserving binary32 accumulator. + Case('vgpr_cancel_to_acc', ((262, p16(0x3C00, 0x4000), p16(0xC000, 0x3C00)),), f32_to_bits(1.25)), + # 3. Back-to-back accumulation in the same destination VGPR. + Case('multi_accumulate', + ((262, p16(0x3C00, 0x3800), p16(0x4000, 0x4000)), + (262, p16(0xBC00, 0x4000), p16(0x3C00, 0x4200))), + f32_to_bits(0.25)), + # 4. Destination VGPR aliased with src0 or vsrc1 (read both as f16x2 input and f32 acc). + Case('vgpr_dst_alias_src0', ((260, 0, p16(0x4000, 0x4200)),), p16(0x0000, 0x3C00), alias='src0'), + Case('vgpr_dst_alias_src1', ((262, p16(0x4200, 0x3C00), 0),), p16(0x3800, 0x4000), alias='src1'), + # 5. SGPR and 32-bit literal src0 encodings. + Case('sgpr_src0', ((10, p16(0x3C00, 0xC000), p16(0x4200, 0x3800)),), f32_to_bits(0.75)), + Case('literal_src0', ((255, p16(0x4000, 0x3C00), p16(0x3800, 0x4200)),), f32_to_bits(-1.0)), + # 6. Inline binary16 float constants (0.5, 1.0, -1.0) and inline integer 0. + Case('inline_f16_240', ((240, 0, p16(0x4000, 0x4400)),), f32_to_bits(1.5)), + Case('inline_f16_242', ((242, 0, p16(0x4000, 0x4400)),), f32_to_bits(2.0)), + Case('inline_f16_243', ((243, 0, p16(0x3C00, 0x4000)),), f32_to_bits(3.0)), + Case('inline_int_128', ((128, 0, p16(0x4000, 0x4400)),), f32_to_bits(-2.5)), + # 7. Binary16 subnormal operands (2^-24 and max subnormal). + Case('half_subnormal_src0', ((262, p16(0x0001, 0x03FF), p16(0x0001, 0x7BFF)),), f32_to_bits(0.0)), + # 8. Binary32 subnormal accumulators: preserved when sum == 0, flushed/rounded under nonzero sum. + Case('f32_subnormal_acc_pos', ((262, p16(0x0000, 0x0000), p16(0x0000, 0x0000)),), 0x00000001), + Case('f32_subnormal_acc_neg', ((262, p16(0x0000, 0x0000), p16(0x0000, 0x0000)),), 0x80400000), + Case('f32_subnormal_acc_nonzero_dot', ((262, p16(0x3C00, 0x0000), p16(0x3C00, 0x0000)),), 0x00000001), + # 9. Partial EXEC mask: odd lanes update vdst, even lanes preserve pre-existing vdst accumulator. + Case('partial_exec_odd', ((262, p16(0x3C00, 0x4000), p16(0x4000, 0x4200)),), + 0x40A00000, exec_mask=0xAAAAAAAA, pixel_safe=False), + # 10. Signed zero, infinity, and NaN propagation. + Case('signed_zero_keep', ((262, p16(0x8000, 0x8000), p16(0x3C00, 0x3C00)),), + f32_to_bits(-0.0), pixel_safe=False), + Case('inf_propagation', ((262, p16(0x7C00, 0x3C00), p16(0x3C00, 0x3C00)),), + f32_to_bits(-4.0), pixel_safe=False), + Case('nan_propagation', ((262, p16(0x7E01, 0x3C00), p16(0x3C00, 0x3C00)),), + f32_to_bits(1.0), pixel_safe=False), + ] + + +def emit_case(c: Case): + code = F.mov(4, c.acc) + if c.exec_mask != ALL_EXEC: + code += [sop1(3, 126, 255), c.exec_mask] + for s0, v0, v1 in c.steps: + lit_tail = [] + vsrc1 = 260 if c.alias == 'src1' else 261 + if c.alias != 'src1': + code += F.mov(vsrc1 - 256, v1) + src0 = 260 if c.alias == 'src0' else s0 + if c.alias != 'src0': + if src0 >= 256: + code += F.mov(src0 - 256, v0) + elif src0 <= 105: + code += F.smov(src0, v0) + elif src0 == 255: + lit_tail = [v0] + code.append(vop2_dot2c(4, src0, vsrc1)) + code += lit_tail + if c.exec_mask != ALL_EXEC: + code += [sop1(3, 126, 193)] + return code + + +def compute_program(cases): + code = list(PROLOGUE) + for slot, c in enumerate(cases): + code += emit_case(c) + F.store(slot * 4, 4) + return code + [0xBF810000] + + +def refusal_programs(): + cond_mode = [0xBF840001, 0xBFA5000F] # s_cbranch_scc0 +1; s_denorm_mode 15 + plain = [vop2_dot2c(4, 262, 261), 0xBF810000] + return [ + # VOP3 _e64 form of v_dot2c_f32_f16. + (vop3_dot2c_e64(4, 262, 261) + [0xBF810000], 'unsupported v_dot2c_f32_f16 encoding'), + # DPP16, DPP8, and SDWA forms. + ([vop2_dot2c(4, 250, 261), 0xFF00E406, 0xBF810000], 'unsupported DPP arithmetic'), + ([vop2_dot2c(4, 233, 261), 0xC6886806, 0xBF810000], 'unsupported DPP arithmetic'), + ([vop2_dot2c(4, 249, 261), 0x06060606, 0xBF810000], 'unimplemented direct SDWA operand profile'), + # Special scalar sources refused on src0 (vcc_lo). + ([vop2_dot2c(4, 106, 261), 0xBF810000], 'unsupported v_dot2c_f32_f16 source'), + # Unsupported binary16 rounding/denorm, binary32 denorm flush, and conditional MODE write. + ([0xBFA40004] + plain, 'unsupported binary16 rounding or denormal mode'), + ([0xBFA50003] + plain, 'unsupported binary16 rounding or denormal mode'), + ([0xBFA5000C] + plain, 'unsupported compute control instruction s_denorm_mode'), + (cond_mode + plain, 'unsupported binary16 rounding or denormal mode'), + ] + + +def ir(dumper): + items = all_cases() + code = compute_program(items) + want = [c.expected(lane=0) for c in items] + refusals = refusal_programs() + with tempfile.TemporaryDirectory() as tmp: + work = Path(tmp) + run = F.dump(dumper, work, code, 'dot2c-f32-f16') + assert run.returncode == 0, run.stderr + stores = sorted(F.interpret(run.stdout)) + assert [addr for addr, _ in stores] == [4 * i for i in range(len(want))], stores[:4] + bad = [(i, items[i].name, hex(got), hex(exp)) + for i, ((_, got), exp) in enumerate(zip(stores, want)) if not same_f32(got, exp)] + assert not bad, bad[:8] + for idx, (refused, why) in enumerate(refusals): + r = F.dump(dumper, work, refused, f'refused-{idx}') + assert r.returncode != 0 and why in r.stderr, (idx, why, r.returncode, r.stderr) + print(f'native_dot2c_f32_f16 IR: {len(want)} cases matched exact model; {len(refusals)} refusals matched') + return 0 + + +def controls(cli, sdk, work, root): + items = all_cases() + code = compute_program(items) + marker = request(work, root, code) + output = marker.with_suffix('.cso') + result = subprocess.run([cli, sdk, work / 'cache', 'gfx1013-direct-cs@0', marker, output], + capture_output=True, text=True) + assert result.returncode == 0 and output.is_file(), (result.stdout, result.stderr) + dump = subprocess.run([Path(sdk) / 'dxc.exe', '-dumpbin', output], capture_output=True, text=True, check=True).stdout + assert 'legacyF16ToF32' in dump and 'fmul float' in dump and 'fadd float' in dump, dump + + refusals = refusal_programs() + for idx, (prog, why) in enumerate(refusals): + m = request(work, root, prog) + o = m.with_suffix(f'.refused{idx}.cso') + r = subprocess.run([cli, sdk, work / 'cache', 'gfx1013-direct-cs@0', m, o], capture_output=True, text=True) + assert r.returncode != 0 and why in r.stderr, (idx, why, r.stdout, r.stderr) + assert not o.exists(), o + + print(f'native_dot2c_f32_f16 controls: compiled {len(items)} cases to DXIL; verified {len(refusals)} refusals') + return 0 + + +def hardware(replay, sdk, work, root): + items = all_cases() + code = compute_program(items) + marker = request(work, root, code) + output = work / 'out.bin' + run = subprocess.run([replay, sdk, marker, work / 'cache', '0', output, '--direct']) + if run.returncode == 77: + return 77 + run.check_returncode() + words_out = list(struct.unpack(f'<{F.WORDS}I', output.read_bytes())) + expected = {} + for group in range(F.GROUPS): + for lane in range(32): + head = F.BASE + group * 1024 + lane * 32 + for idx, c in enumerate(items): + expected[head + idx] = c.expected(lane=lane) + bad = [] + for i, got in enumerate(words_out): + if i in expected: + if not same_f32(got, expected[i]): + bad.append((i, hex(got), hex(expected[i]))) + elif got != F.SENTINEL: + bad.append((i, hex(got), hex(F.SENTINEL))) + assert not bad, bad[:10] + print(f'native_dot2c_f32_f16 compute hardware: {len(items)} cases matched across {F.GROUPS}x32 lanes and guards') + return 0 + + +def pixel_program(quad): + code = [] + for idx, c in enumerate(quad): + code += emit_case(c) + code.append(vmove(8 + idx, 256 + 4)) + return patched_pixel(len(code), code, export=(0xF800180F, 0x0B0A0908)) + + +def pixel(cli, sdk, renderer, adapter, work): + items = [c for c in all_cases() if c.pixel_safe] + while len(items) % 4: + items.append(items[-1]) + vs = compile_hlsl(str(Path(sdk) / 'dxc.exe'), 'dxc', FULLSCREEN_VS, 'fullscreen', 'vs_6_0', work) + quads = [items[i:i + 4] for i in range(0, len(items), 4)] + for idx, quad in enumerate(quads): + shader = work / f'dot2c-{idx}.ps' + shader.write_bytes(pixel_program(quad)) + cso = shader.with_suffix('.cso') + build = subprocess.run([cli, sdk, work / 'cache', 'gfx1013-container-ps', shader, cso], + capture_output=True, text=True, timeout=30) + assert build.returncode == 0, ([c.name for c in quad], build.stdout, build.stderr) + ref = work / 'expected.bin' + ref.write_bytes(struct.pack('<4I', *(c.expected(lane=0) for c in quad))) + run = subprocess.run([renderer, adapter, '--startup-pixel-words', vs, cso, '1', '1', ref], + capture_output=True, text=True, timeout=30) + if run.returncode == 77: + return 77 + assert run.returncode == 0, (idx, [c.name for c in quad], run.stdout, run.stderr) + if 'debug_layer=enabled' in run.stdout: + assert 'debug_errors=0 debug_warnings=0' in run.stdout, run.stdout + print(f'native_dot2c_f32_f16 pixel ({adapter}): {len(quads)} quad draws matched') + return 0 + + +def main(mode, tool, sdk=None, *args): + if mode == 'ir': + return ir(tool) + with tempfile.TemporaryDirectory() as tmp: + work = Path(tmp) + if mode == 'pixel': + return pixel(tool, sdk, args[0], args[1], work) + shader = work / 'root.hlsl' + shader.write_text('#define SIG "DescriptorTable(UAV(u0,numDescriptors=8))"') + root = work / 'root.bin' + subprocess.run([Path(sdk) / 'dxc.exe', '-T', 'rootsig_1_1', '-E', 'SIG', '-Fo', root, shader], check=True) + return {'controls': controls, 'compute': hardware}[mode](tool, sdk, work, root.read_bytes()) + + +if __name__ == '__main__': + sys.exit(main(*sys.argv[1:])) diff --git a/tests/native_dot4c_check.py b/tests/native_dot4c_check.py new file mode 100644 index 0000000000..da68910efa --- /dev/null +++ b/tests/native_dot4c_check.py @@ -0,0 +1,109 @@ +"""Direct compute VOP2 signed byte dot-accumulate lowering and replay.""" +from pathlib import Path +import struct +import subprocess +import sys +import tempfile + +from native_dpp_mirror_check import vop2 +from native_dpp_quad_check import request +from native_scalar_lds_check import scalar, sop1, vmove + + +DOT4C = 0x0D +ALL = 0xFFFFFFFF +EVEN = 0x55555555 +SENTINEL = 0x69696969 +CASES = ( + # Name, encoded src0, extension words, packed src1, accumulator base, dot, EXEC + ("literal", 255, (0xFBF201F7,), 0x04030201, 100, -69, ALL), + ("sgpr", 10, (), 0x80808080, 0x7FFFFFF0, 65536, EVEN), + ("inline", 193, (), 0x01020304, 64, -10, ALL), + ("vgpr_dst_alias", 259, (), 0x7F000000, 0x80000000, -16256, ALL), +) + + +def program(case, *, modifier=None): + name, src0, extension, b, base, _, active = case + # Group IDs (0,0,0) and (1,0,0), 32 lanes each. UAV u0 starts with + # eight guard words, then one consecutive 32-word row per group. + code = [ + sop1(3, 126, 193), # EXEC_LO = all lanes + sop1(3, 20, 4), sop1(3, 21, 128), # s[20:21] = resource table base + 0xF408080A, 0xFA000020, # load s[32:35] for u0 + scalar(0x1E, 7, 5, 135), # s7 = group_id.x * 128 bytes + vop2(0x1A, 8, 130, 0), # v8 = local lane * 4 bytes + vop2(0x25, 8, 7, 8), # v8 += s7 + vmove(2, 255), b, + vop2(0x25, 3, 255, 0), base, # v3 = accumulator base + local lane + 0xBF8CC07F, # wait for descriptor load + ] + if name == "sgpr": + code += [sop1(3, 10, 255), 0x80808080] + code += [sop1(3, 126, 255), active] + if modifier == "dpp": + src0, extension = 250, (0xFF00E403,) # v3, identity quad_perm, full masks + elif modifier == "sdwa": + src0, extension = 249, (0x06060603,) # v3, DWORD selectors + return code + [ + vop2(DOT4C, 3, src0, 2), *extension, + sop1(3, 126, 193), # restore EXEC before readback + 0xE0701000, 0x80080308, # buffer_store_dword v3, v8, s[32:35], 0 offen + 0xBF810000, + ] + + +def ir(cli, sdk, work, root): + for case, modifier, error in ( + *((case, None, None) for case in CASES), + (CASES[-1], "dpp", "unsupported DPP arithmetic"), + (CASES[-1], "sdwa", "unimplemented direct SDWA operand profile"), + ): + marker = request(work, root, program(case, modifier=modifier)) + output = marker.with_suffix(".cso") + result = subprocess.run([cli, sdk, work / "cache", "gfx1013-direct-cs@0", marker, output], + capture_output=True, text=True) + if error: + assert result.returncode and error in result.stderr, (modifier, result.stdout, result.stderr) + assert not output.exists(), output + else: + assert result.returncode == 0 and output.is_file(), (case[0], result.stdout, result.stderr) + dump = subprocess.run([Path(sdk) / "dxc.exe", "-dumpbin", output], capture_output=True, + text=True, check=True).stdout + assert dump.count("@dx.op.dot4AddPacked.i32(i32 163,") == 1, (case[0], dump) + print("signed VOP2 dot-accumulate DXIL verified for four source encodings; DPP and SDWA refused") + return 0 + + +def hardware(replay, sdk, work, root): + for case in CASES: + name, _, _, _, base, dot, active = case + marker = request(work, root, program(case)) + output = work / "out.bin" + result = subprocess.run([replay, sdk, marker, work / "cache", "0", output, "--direct"]) + if result.returncode == 77: + return 77 + result.check_returncode() + row = tuple((base + lane + (dot if (active >> lane) & 1 else 0)) & ALL + for lane in range(32)) + expected = (SENTINEL,) * 8 + row * 2 + (SENTINEL,) * (2064 - 72) + actual = struct.unpack("<2064I", output.read_bytes()) + for index, (got, want) in enumerate(zip(actual, expected)): + assert got == want, f"{name} word {index}: got {got:08x}, expected {want:08x}" + print(f"{name}: 64 results and all guards matched") + return 0 + + +def main(mode, executable, sdk): + with tempfile.TemporaryDirectory() as temp: + work = Path(temp) + shader = work / "root.hlsl" + shader.write_text('#define SIG "DescriptorTable(UAV(u0,numDescriptors=8))"') + root = work / "root.bin" + subprocess.run([Path(sdk) / "dxc.exe", "-T", "rootsig_1_1", "-E", "SIG", + "-Fo", root, shader], check=True) + return {"ir": ir, "hardware": hardware}[mode](executable, sdk, work, root.read_bytes()) + + +if __name__ == "__main__": + sys.exit(main(*sys.argv[1:])) diff --git a/tests/native_dpp8_check.py b/tests/native_dpp8_check.py new file mode 100644 index 0000000000..d3679ab26c --- /dev/null +++ b/tests/native_dpp8_check.py @@ -0,0 +1,97 @@ +"""Wave32 hardware readback for direct compute DPP8.""" +from pathlib import Path +import struct +import subprocess +import sys +import tempfile + +from native_compute_clear_check import write_request +from native_dpp_mirror_check import vop2 +from native_scalar_lds_check import scalar, sop1, vmove + + +ADD, MIN, MAX = 0x03, 0x0F, 0x10 +SWAP = (4, 5, 6, 7, 0, 1, 2, 3) +ASYMMETRIC = (7, 0, 3, 1, 6, 2, 5, 4) +ALL = 0xFFFFFFFF +SPARSE = 0x55555555 +SENTINEL = 0x69696969 + + +def program(op, selectors, active, fi): + # Each workgroup writes 32 words, starting after eight guard words. + words = [sop1(3, 20, 4), sop1(3, 21, 128), 0xF408080A, 0xFA000020, + scalar(0x1E, 7, 5, 135), vop2(0x1A, 8, 130, 0), vop2(0x25, 8, 7, 8), + vop2(0x25, 9, 145, 0), 0x7E000000 | 9 << 17 | 6 << 9 | 265] + # Seed v9 under full EXEC and alias both inputs with the destination. + # Restore full EXEC before storing so disabled destinations are visible. + src0 = 234 if fi else 233 + instruction = vmove(9, src0) if op is None else vop2(op, 9, src0, 9) + control = 9 | sum(peer << (8 + 3 * lane) for lane, peer in enumerate(selectors)) + return words + [sop1(3, 126, 255), active, instruction, control, + sop1(3, 126, 193), 0xE0701000, 0x80080908, 0xBF810000] + + +def reference(op, selectors, active, fi): + initial = list(range(17, 49)) + result = initial.copy() + for start in range(0, 32, 8): + for offset, selection in enumerate(selectors): + lane, peer = start + offset, start + selection + if not active & (1 << lane): + continue + source = initial[peer] if fi or active & (1 << peer) else 0 + if op == ADD: + result[lane] = source + initial[lane] + elif op == MIN: + result[lane] = min(source, initial[lane]) + elif op == MAX: + result[lane] = max(source, initial[lane]) + else: + result[lane] = source + return struct.unpack("<32I", struct.pack("<32f", *result)) + + +def hardware(replay, sdk, work, root): + # Unique values in all four octets expose a wrong group base. In each + # sparse case lane 0 selects disabled lane 7, exposing ignored FI. + cases = ( + ("min swap", MIN, SWAP, ALL, False), + ("add swap", ADD, SWAP, ALL, False), + ("max swap", MAX, SWAP, ALL, False), + ("mov asymmetric", None, ASYMMETRIC, ALL, False), + ("add sparse without FI", ADD, ASYMMETRIC, SPARSE, False), + # min(0, x) differs from the old destination, so it separates "zero" from "keep". + ("min sparse without FI", MIN, ASYMMETRIC, SPARSE, False), + ("add sparse with FI", ADD, ASYMMETRIC, SPARSE, True), + ) + sa = struct.pack("<7I", 0, 0, 0, 32 | (1 << 16), 1 | (1 << 20), 0, 0x8A) + for name, op, selectors, active, fi in cases: + marker = write_request(work, program(op, selectors, active, fi), root, sa) + output = work / "out.bin" + run = subprocess.run([replay, sdk, marker, work / "cache", "0", output, "--direct"]) + if run.returncode == 77: + return 77 + run.check_returncode() + lanes = reference(op, selectors, active, fi) + expected = (SENTINEL,) * 8 + lanes * 2 + (SENTINEL,) * (2064 - 72) + actual = struct.unpack("<2064I", output.read_bytes()) + for index, (observed, wanted) in enumerate(zip(actual, expected)): + assert observed == wanted, (name, index, hex(observed), hex(wanted)) + print(f"{name}: 64 results and guards matched") + return 0 + + +def main(replay, sdk): + with tempfile.TemporaryDirectory() as temp: + work = Path(temp) + shader = work / "root.hlsl" + shader.write_text('#define SIG "DescriptorTable(UAV(u0,numDescriptors=8))"') + root = work / "root.bin" + subprocess.run([Path(sdk) / "dxc.exe", "-T", "rootsig_1_1", "-E", "SIG", + "-Fo", root, shader], check=True) + return hardware(replay, sdk, work, root.read_bytes()) + + +if __name__ == "__main__": + sys.exit(main(*sys.argv[1:])) diff --git a/tests/native_dpp_mirror_check.py b/tests/native_dpp_mirror_check.py index 9a3ac0c0ef..f009c67489 100644 --- a/tests/native_dpp_mirror_check.py +++ b/tests/native_dpp_mirror_check.py @@ -89,7 +89,7 @@ def main(cli, replay, raster, sdk): root, vs = work/"root", work/"vs.cso" subprocess.run([dxc,"-T","rootsig_1_1","-E","SIG","-Fo",root,shader],check=True) subprocess.run([dxc,"-T","vs_6_6","-E","vs","-Fo",vs,shader],check=True) - sa = struct.pack("<7I",0,0,0,32 | 1 << 16,1,0,0x8a) + sa = struct.pack("<7I",0,0,0,32 | 1 << 16,1 | (1 << 20),0,0x8a) sparse = 0x955ad3b6 for mask, active, fi, zero in ((7,0xffffffff,1,0), (15,0xffffffff,1,0), (7,sparse,1,0), (7,sparse,0,0), (7,sparse,0,1)): diff --git a/tests/native_dpp_quad_check.py b/tests/native_dpp_quad_check.py index 522401a540..8f5ec48551 100644 --- a/tests/native_dpp_quad_check.py +++ b/tests/native_dpp_quad_check.py @@ -65,7 +65,7 @@ def reference(op, selection, active, fi, bound_zero): def request(work, root, program, threads=32): - sa = struct.pack("<7I", 0, 0, 0, threads | 1 << 16, 1, 0, 0x8A) + sa = struct.pack("<7I", 0, 0, 0, threads | 1 << 16, 1 | (1 << 20), 0, 0x8A) return write_request(work, program, root, sa) diff --git a/tests/native_dpp_row_check.py b/tests/native_dpp_row_check.py index 4cd35f70ae..ac8084ef71 100644 --- a/tests/native_dpp_row_check.py +++ b/tests/native_dpp_row_check.py @@ -84,7 +84,7 @@ def reference(op, direction, amount, fi, bound_zero): def request(work, root, op, instruction, control, threads=64): - sa = struct.pack("<7I", 0, 0, 0, threads | (1 << 16), 1, 0, 0x8A) + sa = struct.pack("<7I", 0, 0, 0, threads | (1 << 16), 1 | (1 << 20), 0, 0x8A) return write_request(work, program(op, instruction, control), root, sa) diff --git a/tests/native_exec_symbol_b64_check.py b/tests/native_exec_symbol_b64_check.py new file mode 100644 index 0000000000..a6349abdad --- /dev/null +++ b/tests/native_exec_symbol_b64_check.py @@ -0,0 +1,47 @@ +"""Reject a sampler word copied from EXEC after a 64-bit implicit write.""" +from pathlib import Path +import subprocess +import sys +import tempfile + +from native_direct_container_check import comparison_program, compute, words + + +def program(exec_op=None): + code = comparison_program(dim=5) + sampler_address = code[4] + code[3:5] = [ + 0x7e2c0500, # v_readfirstlane_b32 s22, v0 + 0xbe970380, # s_mov_b32 s23, 0 + 0xbefe04ff, sampler_address, # s_mov_b64 exec, comparison sampler word + *(() if exec_op is None else (exec_op,)), + 0xbe84037e, # s_mov_b32 s4, exec_lo + ] + return compute(words(*code, 0xbf810000), threads=64, table=True, wave32=False) + + +def controls(cli, sdk): + with tempfile.TemporaryDirectory() as temp: + work = Path(temp) + for name, exec_op in ( + ("constant-exec", None), + ("saveexec", 0xbe982416), # s_and_saveexec_b64 s[24:25], s[22:23] + ("wrexec", 0xbe983a16), # s_andn2_wrexec_b64 s[24:25], s[22:23] + ): + source = work / (name + ".cdx") + output = source.with_suffix(".cso") + source.write_bytes(program(exec_op)) + result = subprocess.run( + [cli, sdk, work / "cache", "gfx1013-container-cs", source, output], + capture_output=True, text=True, + ) + if exec_op is None: + assert result.returncode == 0 and output.read_bytes().startswith(b"DXBC"), (name, result.stderr) + else: + assert result.returncode != 0 and "nonconstant sampler" in result.stderr, (name, result.stderr) + assert not output.exists(), output + + +if __name__ == "__main__": + mode, cli, sdk = sys.argv[1:] + {"controls": controls}[mode](cli, sdk) diff --git a/tests/native_f16_alu_check.py b/tests/native_f16_alu_check.py index e511fc7e02..c04181fc34 100644 --- a/tests/native_f16_alu_check.py +++ b/tests/native_f16_alu_check.py @@ -1,11 +1,13 @@ -"""v_add_f16, v_sub_f16, v_subrev_f16 and v_mul_f16 in the direct C++ compute path. +"""Binary16 binary and unary ALU in the direct C++ compute path. Each source contributes its low 16 bits. abs clears bit 15 of that half, then neg toggles it. The operation runs in f32 and rounds to binary16 the way v_cvt_f16_f32 does. The result is the low 16 bits and the destination's high half keeps its value (LLVM GCNSubtarget::zeroesHigh16BitsOfDest: "On gfx10, all 16-bit instructions preserve the high bits"). Every destination holds HI_A in its high half before the operation, so each stored word is HI_A | result. The reference is half_op in f16_packed_model.py (sub is an add of -the negated second source, subrev swaps the sources). NaN payloads are compared by class. +the negated second source, subrev swaps the sources). Exp2 matches exact bits. +Rsq permits the other encoding only within 8 f32 ULP of a binary16 midpoint. +For the other operations NaNs match by class. native_f16_alu_check.py model no dumper and no GPU: the case table, the f32 rounding cross-check, and the two mutants @@ -14,6 +16,7 @@ native_f16_alu_check.py gpu STORE_REPLAY SDK compute readback of the same words and the DPP16 cases (exit 77 without wave32) """ +import math import re import struct import subprocess @@ -22,6 +25,7 @@ from pathlib import Path import f16_packed_model as M +from f16_exp_midpoints import check_cpp_table, exp_f16_midpoints from native_compute_clear_check import write_request from native_direct_container_check import pack, words from native_scalar_lds_check import scalar, sop1, vmove @@ -30,12 +34,15 @@ WORDS = 2064 SENTINEL = 0x69696969 # native_store_replay fills untouched words with 0x69 BASE = 8 -STRIDE = 128 -SHIFT = 9 +STRIDE = 512 +SHIFT = 11 assert 4 * STRIDE == 1 << SHIFT OPS = ('add', 'sub', 'subrev', 'mul') OP_CODE = {'add': 0x32, 'sub': 0x33, 'subrev': 0x34, 'mul': 0x35} +UNARY_CODE = {'rcp': 0x54, 'sqrt': 0x55, 'exp': 0x58, 'rsq': 0x56} +UNARY_INPUTS = M.GRID + [0x8001, 0x0400, 0x3800, 0x4000, 0x4400, 0x3555, + 0x4bff, 0x4c00, 0x4c40, 0xce00, 0xce40, 0xce80] # Binary16 rounding of the nine inline float encodings, in encoding order. INLINE_F16 = { 240: 0x3800, 241: 0xb800, 242: 0x3c00, 243: 0xbc00, 244: 0x4000, @@ -67,6 +74,8 @@ def binary16(op, a, b): return M.half_op('add', a, b ^ 0x8000) if op == 'subrev': return M.half_op('add', b, a ^ 0x8000) + if op == 'exp' and a in exp_f16_midpoints(): + return exp_f16_midpoints()[a] return M.half_op(op, a, b) @@ -78,14 +87,6 @@ def modified(bits, abs_mask, neg, index): return bits & 0xffff -def same_half(got, want): - """Bit equality of two stored words: the high half must be the kept HI_A, the low halves equal. Any NaN - matches any NaN.""" - if got >> 16 != HI_A >> 16 or want >> 16 not in (0, HI_A >> 16): - return False - return same_binary16(got & 0xffff, want & 0xffff) - - def same_binary16(got, want): """Bit equality of two binary16 values (16 bits each). Any NaN matches any NaN.""" if got >> 16 or want >> 16: @@ -95,6 +96,20 @@ def same_binary16(got, want): return got == want +def same_alu_result(got, want, op, alternate): + if op == 'exp': + return got == want + return same_binary16(got, want) or got == alternate + + +def same_half(got, want, case=None): + """Check the preserved HI_A and compare the low half with the reference.""" + if got >> 16 != HI_A >> 16 or want >> 16 not in (0, HI_A >> 16): + return False + return same_alu_result(got & 0xffff, want & 0xffff, + case.op if case else None, case.alternate if case else None) + + def _u32(value): return value & 0xffffffff @@ -129,9 +144,19 @@ def round_shift(value, shift, half): def f32_half(op, a, b): - """f32 operation of two exact f16 values, then the integer binary16 round.""" + """f32 operation on exact f16 inputs, then the integer binary16 round.""" left, right = M.h2f(a), M.h2f(b) - value = {'add': left + right, 'sub': left - right, 'subrev': right - left, 'mul': left * right}[op] + if op in UNARY_CODE: + value = M.half_unary_value(op, left) + else: + value = {'add': left + right, 'sub': left - right, 'subrev': right - left, 'mul': left * right}[op] + if op == 'exp': + if M.is_nan(a): + return 0x7e00 + if a == 0xce40: + return 0 + if a in exp_f16_midpoints(): + return exp_f16_midpoints()[a] bits = struct.unpack('<I', struct.pack('<f', value))[0] return packed_half_rne(bits) @@ -140,8 +165,13 @@ def vop2(op, dst, src0, src1): return [(op << 25) | ((dst & 255) << 17) | ((src1 & 255) << 9) | (src0 & 511)] -def vop3(op, dst, src0, src1, abs_mask=0, neg=0, clamp=0, omod=0, opsel=0): - word = (0xd4000000 | ((0x100 + op) << 16) | ((abs_mask & 7) << 8) | ((opsel & 15) << 11) | +def vop1(op, dst, src0): + return [0x7e000000 | ((dst & 255) << 17) | (op << 9) | (src0 & 511)] + + +def vop3(op, dst, src0, src1, abs_mask=0, neg=0, clamp=0, omod=0, opsel=0, unary=False): + base = 0x180 if unary else 0x100 + word = (0xd4000000 | ((base + op) << 16) | ((abs_mask & 7) << 8) | ((opsel & 15) << 11) | ((clamp & 1) << 15) | (dst & 255)) other = (src0 & 511) | ((src1 & 511) << 9) | ((omod & 3) << 27) | ((neg & 7) << 29) return [word, other] @@ -173,10 +203,20 @@ def __init__(self, op, a, b, kind='vop2', abs_mask=0, neg=0, inline_src=242): a = (192 - 193) & 0xffff self.a = a & 0xffff self.b = b & 0xffff - self.want = binary16(op, modified(self.a, abs_mask, neg, 0), modified(self.b, abs_mask, neg, 1)) + left = modified(self.a, abs_mask, neg, 0) + if op == 'rsq': + self.want, self.alternate = M.rsq_rounding(left) + else: + self.want = binary16(op, left, modified(self.b, abs_mask, neg, 1)) + self.alternate = None def emit(self): a_word, b_word = HI_A | self.a, HI_B | self.b + if self.op in UNARY_CODE: + op = UNARY_CODE[self.op] + instruction = (vop3(op, 3, 257, 0, self.abs_mask, self.neg, unary=True) + if self.kind == 'vop3' else vop1(op, 3, 257)) + return mov(1, a_word) + mov(3, HI_A) + instruction op = OP_CODE[self.op] if self.kind == 'overlap': self.dest = 1 @@ -213,6 +253,18 @@ def all_cases(): items.append(Case('add', 0x3c00, 0x4000, 'overlap')) items.append(Case('subrev', 0x3c00, 0x4000, 'overlap')) items.append(Case('add', 0x3c00, 0x4000, 'issue')) + for op in UNARY_CODE: + items.extend(Case(op, a, 0, kind) for kind in ('vop1', 'vop3') for a in UNARY_INPUTS) + items.append(Case(op, 0xc000, 0, 'vop3', abs_mask=1)) + items.append(Case(op, 0x4000, 0, 'vop3', neg=1)) + for kind in ('vop1', 'vop3'): + items.extend(Case('exp', a, 0, kind) for a in exp_f16_midpoints()) + items.append(Case('rsq', 0x3bfe, 0, kind)) + items += [ + Case('exp', 0x91c5, 0, 'vop3', abs_mask=1), + Case('exp', 0x11c5, 0, 'vop3', neg=1), + Case('exp', 0x91c5, 0, 'vop3', neg=1), + ] assert len(items) < STRIDE return items @@ -236,7 +288,7 @@ def program(items): def dpp_program(): - assert STRIDE == 32 * len(DPP_CASES) + assert 32 * len(DPP_CASES) <= STRIDE # 4 words per lane, inside one group code = preamble() code += [sop1(3, 126, 193)] # the preamble leaves EXEC at lane 0; set up every lane code += vop2(0x1A, 8, 132, 0) + vop2(0x25, 8, 7, 8) # 16 * lane + group byte base @@ -267,6 +319,8 @@ def dpp_reference(): def swapped_want(case): + if case.op in UNARY_CODE: + return case.want op = {'sub': 'subrev', 'subrev': 'sub'}.get(case.op, case.op) return binary16(op, modified(case.a, case.abs_mask, case.neg, 0), modified(case.b, case.abs_mask, case.neg, 1)) @@ -281,6 +335,7 @@ def reject_mutants(items): def check_model(items): + check_cpp_table() assert binary16('add', 0x3c00, 0x1000) == 0x3c00 assert binary16('add', 0x3c01, 0x1000) == 0x3c02 assert binary16('add', 0x7bff, 0x7bff) == 0x7c00 @@ -291,11 +346,29 @@ def check_model(items): assert binary16('sub', 0x4200, 0x3c00) == 0x4000 assert binary16('subrev', 0x3c00, 0x4200) == 0x4000 assert binary16('sub', 0x3c00, 0x4000) != binary16('subrev', 0x3c00, 0x4000) + assert M.half_op('rcp', 0x8000) == 0xfc00 + assert M.half_op('rcp', 0xfc00) == 0x8000 + assert M.half_op('sqrt', 0x8000) == 0x8000 + assert M.half_op('sqrt', 0x4400) == 0x4000 + assert M.is_nan(M.half_op('sqrt', 0xbc00)) + assert M.half_op('exp', 0x8000) == 0x3c00 + assert M.half_op('exp', 0x4c00) == 0x7c00 # 2**16 overflows binary16. + assert M.half_op('exp', 0xce00) == 0x0001 # 2**-24 is the least subnormal. + assert M.half_op('exp', 0xce40) == 0x0000 # 2**-25 ties to zero. + for source, rsq in ((0x0000, 0x7c00), (0x8000, 0xfc00), (0x7c00, 0x0000), + (0x3c00, 0x3c00), (0x0001, 0x6c00), (0x4400, 0x3800)): + assert M.half_op('rsq', source) == rsq + for source in (0xbc00, 0x8001, 0xfc00, 0x7e01): + assert M.is_nan(M.half_op('rsq', source)) + assert M.rsq_rounding(0x3bfe) == (0x3c01, 0x3c00) + assert M.rsq_rounding(0x3c00) == (0x3c00, None) + assert not same_alu_result(0x3c00, 0x3c01, 'exp', None) + assert not same_alu_result(0x7e01, 0x7e00, 'exp', None) for case in items: left = modified(case.a, case.abs_mask, case.neg, 0) right = modified(case.b, case.abs_mask, case.neg, 1) got = f32_half(case.op, left, right) - assert same_half(HI_A | got, case.want), (case.op, case.kind, hex(left), hex(right), hex(got), hex(case.want)) + assert same_half(HI_A | got, case.want, case), (case.op, case.kind, hex(left), hex(right), hex(got), hex(case.want)) wants = [case.want for case in items] assert 0x8000 in wants and 0x0000 in wants and 0x7c00 in wants and 0x3c00 in wants and 0x3c02 in wants assert any(M.is_nan(value) for value in wants) @@ -306,7 +379,7 @@ def check_model(items): def refusal_programs(): add = vop2(0x32, 3, 257, 2) programs = [] - programs.append((vop2(0x32, 3, 233, 2) + [0xfac68801, 0xbf810000], 'SDWA or DPP vector operands')) + programs.append((vop2(0x32, 3, 233, 2) + [0xfac68801, 0xbf810000], 'unsupported v_add_f16 DPP form')) # DPP8 stays refused on binary16 # Clamp needs a wide encoding. A VOP3 with clamp and the DPP16 source selector is invalid. programs.append((vop3(0x32, 3, 250, 258, clamp=1) + [0xbf810000], 'unsupported v_add_f16 clamp or omod')) programs.append((vop3(0x35, 3, 257, 258, clamp=1) + [0xbf810000], 'unsupported v_mul_f16 clamp or omod')) @@ -319,8 +392,20 @@ def refusal_programs(): programs.append(([0xb98005c1] + add + [0xbf810000], 'unsupported binary16 rounding or denormal mode')) programs.append(([0xbfa40001] + add + [0xbf810000], 'unsupported compute control instruction s_round_mode')) programs.append(([0xbfa5000c] + add + [0xbf810000], 'unsupported compute control instruction s_denorm_mode')) - programs.append((vop2(0x3c, 3, 257, 2) + [0xbf810000], 'direct DXIL lowering for v_pk_fmac_f16')) programs.append((vop2(0x3a, 3, 257, 2) + [0xbf810000], 'direct DXIL lowering for v_min_f16')) + for name, op in UNARY_CODE.items(): + programs.append((vop1(op, 3, 250) + [0, 0xbf810000], 'unsupported v_%s_f16 DPP form' % name)) + programs.append((vop3(op, 3, 257, 0, clamp=1, unary=True) + [0xbf810000], + 'unsupported v_%s_f16 clamp or omod' % name)) + programs.append((vop3(op, 3, 257, 0, omod=1, unary=True) + [0xbf810000], + 'unsupported v_%s_f16 clamp or omod' % name)) + programs.append((vop3(op, 3, 257, 0, opsel=1, unary=True) + [0xbf810000], + 'unsupported v_%s_f16 high-half op_sel' % name)) + for mode in (0xbfa4000c, 0xbfa50000): + programs.append(([mode] + vop1(op, 3, 257) + [0xbf810000], + 'unsupported binary16 rounding or denormal mode')) + for instruction in (vop1(0x57, 3, 257), vop3(0x57, 3, 257, 0, unary=True)): + programs.append((instruction + [0xbf810000], 'direct DXIL lowering for v_log_f16')) return programs @@ -383,8 +468,12 @@ def _f32(bits): def _fbin(op, left, right): - value = {'fadd': _f32(left) + _f32(right), 'fsub': _f32(left) - _f32(right), - 'fmul': _f32(left) * _f32(right)}[op] + if op == 'fdiv': + assert left == 0x3f800000 + value = M.half_unary_value('rcp', _f32(right)) + else: + value = {'fadd': _f32(left) + _f32(right), 'fsub': _f32(left) - _f32(right), + 'fmul': _f32(left) * _f32(right)}[op] return struct.unpack('<I', struct.pack('<f', value))[0] @@ -477,7 +566,7 @@ def _exec(line, values, memory, stores): raise AssertionError(rhs) values[name] = ('i32', bits) return - floated = re.fullmatch(r'(fadd|fsub|fmul) float (\S+), (\S+)', rhs) + floated = re.fullmatch(r'(fadd|fsub|fmul|fdiv) float (\S+), (\S+)', rhs) if floated: def bits_of(token): if token.startswith('%'): @@ -507,6 +596,27 @@ def bits_of(token): argument = re.search(r'i32 33,\s*i32 ([^,\s\)]+)\)', rhs) x = _i32(argument.group(1), values) & 0xffffffff values[name] = ('i32', (32 - x.bit_length()) if x else 0xffffffff) + elif 'unary.f32(i32 7,' in rhs: + argument = re.search(r'i32 7,\s*float ([^,\s\)]+)\)', rhs) + token = argument.group(1) + if token.startswith('%'): + kind, bits = values[token] + if kind != 'float': + raise AssertionError(rhs) + else: + bits = struct.unpack('<I', struct.pack('<f', float(token)))[0] + val = _f32(bits) + clamped = 0.0 if (math.isnan(val) or val <= 0.0) else (1.0 if val >= 1.0 else val) + values[name] = ('float', struct.unpack('<I', struct.pack('<f', clamped))[0]) + elif 'unary.f32' in rhs: + call = re.fullmatch(r'call float @dx\.op\.unary\.f32\(i32 (21|24|25), float (%\w+)\)', rhs) + assert call, rhs + op = {'21': 'exp', '24': 'sqrt', '25': 'rsq'}[call.group(1)] + kind, bits = values[call.group(2)] + assert kind == 'float', rhs + # Exercise the guest sign fix even with a host Rsqrt that treats -0 as +0. + value = M.half_unary_value(op, 0.0 if op == 'rsq' and bits == 0x80000000 else _f32(bits)) + values[name] = ('float', struct.unpack('<I', struct.pack('<f', value))[0]) elif 'createHandleFromBinding' in rhs or 'annotateHandle' in rhs: values[name] = ('handle', 0) else: @@ -578,11 +688,12 @@ def run_ir(dumper): text = run.stdout assert 'legacyF16ToF32' in text and 'legacyF32ToF16' not in text, 'rounding opcode' assert 'fadd float' in text and 'fsub float' in text and 'fmul float' in text + assert 'fdiv float' in text and all(f'@dx.op.unary.f32(i32 {op},' in text for op in (21, 24, 25)) assert '939524096' in text, 'integer nearest-even rounding' stores = sorted(interpret(text)) assert [addr for addr, _ in stores] == [4 * i for i in range(len(want))], stores[:4] bad = [(i, hex(got), hex(expected)) for i, ((_, got), expected) in enumerate(zip(stores, want)) - if not same_half(got, expected)] + if not same_half(got, expected, items[i])] assert not bad, bad[:8] run = dump(dumper, work, dpp_program(), 'dpp') assert run.returncode == 0 and 'waveReadLaneAt.i32' in run.stdout, (run.stdout, run.stderr) @@ -602,28 +713,29 @@ def group_offsets(count): def run_gpu(gpu, sdk): - code, want = program(all_cases()) + items = all_cases() + code, want = program(items) with tempfile.TemporaryDirectory() as tmp: work = Path(tmp) src, root = work / 'root.hlsl', work / 'root.bin' src.write_text('#define SIG "DescriptorTable(UAV(u0,numDescriptors=8))"') subprocess.run([str(Path(sdk) / 'dxc.exe'), '-T', 'rootsig_1_1', '-E', 'SIG', '-Fo', root, src], check=True) sa = struct.pack('<7I', 0, 0, 0, 32 | (1 << 16), 1 | (1 << 20), 0, 0x80 | (5 << 1)) - for name, instructions, reference in (('alu', code, want), ('dpp', dpp_program(), dpp_reference())): + for name, instructions, reference, cases in (('alu', code, want, items), + ('dpp', dpp_program(), dpp_reference(), None)): marker = write_request(work, instructions, root.read_bytes(), sa) dest = work / (name + '-readback.bin') run = subprocess.run([gpu, sdk, str(marker), str(work / 'cache'), '0', str(dest), '--direct']) if run.returncode == 77: sys.exit(77) run.check_returncode() - results = {slot: value for offsets in group_offsets(len(reference)) - for slot, value in zip(offsets, reference)} + results = {slot: (value, cases[n] if cases else None) for offsets in group_offsets(len(reference)) + for n, (slot, value) in enumerate(zip(offsets, reference))} actual = struct.unpack('<2064I', dest.read_bytes()) bad = [] for index, got in enumerate(actual): - model = results.get(index, SENTINEL) - # Compare NaNs by class, keep the destination high half, and check the guard words. - ok = same_half(got, model) if index in results else got == model + model, case = results.get(index, (SENTINEL, None)) + ok = same_half(got, model, case) if index in results else got == model if not ok: bad.append((index, hex(got), hex(model))) assert not bad, (name, bad[:10]) diff --git a/tests/native_fma_f16_check.py b/tests/native_fma_f16_check.py index afb4d8e704..7eb4c24b53 100644 --- a/tests/native_fma_f16_check.py +++ b/tests/native_fma_f16_check.py @@ -206,7 +206,7 @@ def refusal_programs(): (F.vop2(OP_FMAC, 3, 249, 2) + [0x06060601, 0xBF810000], 'unimplemented direct SDWA operand profile'), (vop3_tern(OP_FMA_VOP3, 3, 257, 258, 260, omod=1) + [0xBF810000], 'unsupported v_fma_f16 omod'), (vop3_tern(OP_FMAC_VOP3, 3, 257, 258, 0, omod=1) + [0xBF810000], 'unsupported v_fmac_f16 omod'), - (vop3_tern(OP_FMA_VOP3, 3, 257, 258, 260, op_sel=1) + [0xBF810000], 'unsupported v_fma_f16 high-half op_sel'), + (vop3_tern(OP_FMA_VOP3, 3, 244, 258, 260, op_sel=1) + [0xBF810000], 'unsupported v_fma_f16 high-half op_sel on non-VGPR source'), (vop3_tern(OP_FMAC_VOP3, 3, 257, 258, 0, op_sel=8) + [0xBF810000], 'unsupported v_fmac_f16 high-half op_sel'), (vop3_tern(OP_FMAC_VOP3, 3, 257, 258, 0, neg=4) + [0xBF810000], 'unsupported v_fmac_f16 third-source modifier'), (vop3_tern(OP_FMAC_VOP3, 3, 257, 258, 260) + [0xBF810000], 'unsupported v_fmac_f16 third-source modifier'), diff --git a/tests/native_fma_f16_opsel_check.py b/tests/native_fma_f16_opsel_check.py new file mode 100644 index 0000000000..83e9b5f4ba --- /dev/null +++ b/tests/native_fma_f16_opsel_check.py @@ -0,0 +1,98 @@ +"""Direct VOP3 v_fma_f16 source and destination half selection.""" +from pathlib import Path +import struct +import subprocess +import sys +import tempfile + +import f16_packed_model as model +from native_compute_clear_check import write_request +import native_f16_alu_check as F +from native_fma_f16_check import OP_FMA_VOP3, OP_FMAC, vop3_tern + + +SOURCES = (0x40003C00, 0x44004200, 0x4C004500) # (high, low): (2, 1), (4, 3), (16, 5) +DST = 0xABCD1234 +END = 0xBF810000 + + +def fma(srcs, op_sel, *, clamp=0): + return vop3_tern(OP_FMA_VOP3, 3, *srcs, op_sel=op_sel, clamp=clamp) + + +def program(): + # s5 supplies the group X ID (0 or 1). Lane 0 alone writes each dword. + # Case i in group g stores at byte 512*g + 4*i relative to the UAV window, + # which starts at readback word 8, so the file word index is 8 + 128*g + i. + # The preamble sets EXEC to 1 before the per-lane VGPR initialization. + code = F.preamble() + F.mov(1, SOURCES[0]) + F.mov(2, SOURCES[1]) + F.mov(4, SOURCES[2]) + want = [] + for op_sel in (1, 2, 3, 15, 14, 12, 8): + srcs = (257, 258, 260) + words = SOURCES + if op_sel == 8: + srcs = (244, 258, 243) # inline binary16 2.0 and -1.0 + words = (0x4000, SOURCES[1], 0xBC00) + halves = [model.pick(word, op_sel & (1 << j)) for j, word in enumerate(words)] + result = model.half_op('fma', *halves) + code += F.mov(3, DST) + fma(srcs, op_sel) + F.store(4 * len(want), 3) + want.append(((result << 16) | (DST & 0xFFFF)) if op_sel & 8 else ((DST & 0xFFFF0000) | result)) + assert want == [0xABCD4980, 0xABCD4880, 0xABCD4A80, 0x4E001234, 0x4D001234, 0x4CC01234, 0x45001234] + return code + [END], want + + +def refusals(): + return ( + (F.smov(10, SOURCES[0]) + fma((10, 258, 260), 1), + 'unsupported v_fma_f16 high-half op_sel on non-VGPR source'), + (F.vop2(OP_FMAC, 3, 250, 2) + [0xFF00B101], 'unsupported DPP arithmetic'), + (fma((257, 258, 260), 8, clamp=1), 'unsupported v_fma_f16 high-half op_sel'), + ) + + +def ir(dumper, work, code, want): + run = F.dump(dumper, work, code, 'fma-f16-opsel') + assert run.returncode == 0, run.stderr + stores = sorted(F.interpret(run.stdout)) + assert stores == [(4 * i, word) for i, word in enumerate(want)], stores + for i, (snippet, why) in enumerate(refusals()): + run = F.dump(dumper, work, F.preamble() + snippet + [END], f'refused-{i}') + assert run.returncode != 0 and why in run.stderr, (why, run.returncode, run.stderr) + print(f'native_fma_f16_opsel IR matched {len(want)} cases and {len(refusals())} refusals') + return 0 + + +def hardware(replay, sdk, work, code, want): + shader, root = work / 'root.hlsl', work / 'root.bin' + shader.write_text('#define SIG "DescriptorTable(UAV(u0,numDescriptors=8))"') + subprocess.run([Path(sdk) / 'dxc.exe', '-T', 'rootsig_1_1', '-E', 'SIG', '-Fo', root, shader], check=True) + # .sa dword 4, bit 20 requests wave32. + sa = struct.pack('<7I', 0, 0, 0, 32 | (1 << 16), 1 | (1 << 20), 0, 0x8A) + marker = write_request(work, code, root.read_bytes(), sa) + output = work / 'out.bin' + run = subprocess.run([replay, sdk, marker, work / 'cache', '0', output, '--direct']) + if run.returncode == 77: + return 77 + run.check_returncode() + got = struct.unpack(f'<{F.WORDS}I', output.read_bytes()) + expected = {slot: value for slots in F.group_offsets(len(want)) + for slot, value in zip(slots, want)} + bad = [(i, hex(word), hex(expected.get(i, F.SENTINEL))) + for i, word in enumerate(got) if word != expected.get(i, F.SENTINEL)] + assert not bad, bad[:8] + print(f'native_fma_f16_opsel hardware matched {len(want)} cases across {F.GROUPS} groups') + return 0 + + +def main(mode, tool, sdk=None): + code, want = program() + with tempfile.TemporaryDirectory() as tmp: + work = Path(tmp) + if mode == 'ir': + return ir(tool, work, code, want) + assert mode == 'hardware' and sdk is not None + return hardware(tool, sdk, work, code, want) + + +if __name__ == '__main__': + sys.exit(main(*sys.argv[1:])) diff --git a/tests/native_fract_f16_check.py b/tests/native_fract_f16_check.py new file mode 100644 index 0000000000..1fe6fa96e5 --- /dev/null +++ b/tests/native_fract_f16_check.py @@ -0,0 +1,318 @@ +"""Direct DXIL VOP1/VOP3 v_fract_f16 lowering in Compute and Pixel shaders.""" +from dataclasses import dataclass +from fractions import Fraction +import math +from pathlib import Path +import re +import struct +import subprocess +import sys +import tempfile +from unittest import mock + +from f16_packed_model import h2f, round_exact +from native_direct_container_check import patched_pixel +from native_dpp_mirror_check import vop2 +from native_dpp_quad_check import request +import native_f16_alu_check as F +from native_packed_f16_inline_check import PROLOGUE, inline_word +from native_scalar_lds_check import sop1 +from startup_image_3d_check import FULLSCREEN_VS, compile_hlsl + +OP_VOP1_FRACT_F16 = 0x5F +OP_VOP3_FRACT_F16 = 0x1DF +ALL_EXEC = 0xFFFFFFFF +DST_INIT = 0xDEADCAFE + + +def vop1_fract_f16(dst, src0): + return [0x7E000000 | ((dst & 0xFF) << 17) | (OP_VOP1_FRACT_F16 << 9) | (src0 & 0x1FF)] + + +def vop3_fract_f16(dst, src0, *, abs_=0, neg=0, op_sel=0, clamp=0, omod=0, s1=0, s2=0): + w0 = (0xD4000000 | (OP_VOP3_FRACT_F16 << 16) | ((clamp & 1) << 15) | ((op_sel & 15) << 11) | + ((abs_ & 7) << 8) | (dst & 0xFF)) + w1 = ((neg & 7) << 29) | ((omod & 3) << 27) | ((s2 & 0x1FF) << 18) | ((s1 & 0x1FF) << 9) | (src0 & 0x1FF) + return [w0, w1] + + +def eval_fract_f16(raw_word, *, abs_=0, neg=0, op_sel=0, clamp=0, dst_init=DST_INIT): + bits = (raw_word >> (16 if (op_sel & 1) else 0)) & 0xFFFF + if abs_ & 1: + bits &= 0x7FFF + if neg & 1: + bits ^= 0x8000 + if (bits & 0x7FFF) >= 0x7C00: + res = 0x0000 if clamp else 0x7E00 + else: + x = Fraction(h2f(bits)) + diff = x - math.floor(x) + res = 0x0000 if diff == 0 else min(round_exact(diff), 0x3BFF) + if op_sel & 8: + return ((res & 0xFFFF) << 16) | (dst_init & 0xFFFF) + return (dst_init & 0xFFFF0000) | (res & 0xFFFF) + + +@dataclass(frozen=True) +class Case: + name: str + src0: int + val0: int + wide: bool = False + abs_: int = 0 + neg: int = 0 + op_sel: int = 0 + clamp: int = 0 + exec_mask: int = ALL_EXEC + + def expected(self, lane=0): + if ((self.exec_mask >> lane) & 1) == 0: + return DST_INIT + raw = self.val0 & 0xFFFFFFFF if (self.src0 < 128 or self.src0 >= 255) else inline_word(self.src0) + return eval_fract_f16(raw, abs_=self.abs_, neg=self.neg, op_sel=self.op_sel, clamp=self.clamp) + + +def all_cases(): + return [ + # 1. Positive fractions and exact positive integers (with nonzero unused high halves on op_sel[0]=0 VGPR reads). + Case('pos_zero', 257, 0x0000), + Case('pos_frac_mixed', 257, 0x7BFF3D00), # 1.25 -> 0.25 (hi=65504 ignored) + Case('pos_exact_one', 257, 0x3C00), # 1.0 -> +0.0 + Case('pos_exact_max', 257, 0x7BFF), # 65504 -> +0.0 + # 2. Negative fractions and exact negative integers (-0.0, -1.0, -65504). + Case('neg_zero', 257, 0x8000), # -0.0 -> +0.0 + Case('neg_quarter', 257, 0x7BFFB400), # -0.25 -> 0.75 (hi=65504 ignored) + Case('neg_1_75', 257, 0xBF00), # -1.75 -> 0.25 + Case('neg_exact_one', 257, 0xBC00), # -1.0 -> +0.0 + Case('neg_exact_max', 257, 0xFBFF), # -65504 -> +0.0 + # 3. Tiny negatives: x - floor(x) near 1.0 (0x3bff clamp + RNE-vs-truncation discriminators). + Case('tiny_neg_2_m11', 257, 0x9000), # -2^-11 -> 0x3bff exact + Case('tiny_neg_2_m12', 257, 0x8C00), # -2^-12 (rounds to 1.0 without clamp) -> 0x3bff + Case('tiny_neg_5_m12', 257, 0x9500), # -5*2^-12 (halfway tie -> 0x3bfe under RNE vs 0x3bfd trunc) + Case('tiny_neg_9_m13', 257, 0x9480), # -9*2^-13 (rounds to 0x3bfe under RNE vs 0x3bfd trunc) + Case('tiny_neg_min_subnormal', 257, 0x8001), # -2^-24 -> 0x3bff + # 4. Positive binary16 subnormal preserved as exact fraction. + Case('pos_min_subnormal', 257, 0x0001), + # 5. Non-finite inputs (+Inf, -Inf, NaN -> 0x7e00 or +0.0 with clamp) and finite clamp=1 preservation. + Case('pos_inf', 257, 0x7C00), + Case('neg_inf', 257, 0xFC00), + Case('nan_payload', 257, 0x7E01), + Case('vop3_clamp_inf_and_neg', 257, 0xFC00, wide=True, clamp=1), + Case('vop3_clamp_nan', 257, 0x7E01, wide=True, clamp=1), + Case('vop3_clamp_pos', 257, 0x7BFF3D00, wide=True, clamp=1), + Case('vop3_clamp_neg', 257, 0x7BFFB400, wide=True, clamp=1), + # 6. VOP3 modifiers: separate abs, neg, and high-half op_sel[0]/op_sel[3] preserving D[15:0]. + Case('vop3_abs', 257, 0x7BFFB400, wide=True, abs_=1), # abs(-0.25) = 0.25 -> 0.25 + Case('vop3_neg', 257, 0x7BFF3400, wide=True, neg=1), # neg(0.25) = -0.25 -> 0.75 + Case('vop3_opsel_hi_src', 257, 0x3D003C00, wide=True, op_sel=0b0001), + Case('vop3_opsel_hi_dst', 257, 0x3C003D00, wide=True, op_sel=0b1000), + Case('vop3_opsel_hi_rw', 257, 0x3D00BEEF, wide=True, op_sel=0b1001), + # 7. SGPR, literal (255), inline binary16 float (248=0x3118) and inline integer subnormal (129=0x0001). + Case('sgpr_src0', 10, 0xB400), + Case('literal_src0', 255, 0x8C00), + Case('inline_f16_248', 248, 0), + Case('inline_int_129', 129, 0), + # 8. Partial EXEC_LO mask: inactive lanes keep DST_INIT. + Case('partial_exec', 257, 0x7BFF3D00, exec_mask=0xAAAAAAAA), + ] + + +def emit_case(c: Case): + code = F.mov(4, DST_INIT) + if c.exec_mask != ALL_EXEC: + code += [sop1(3, 126, 255), c.exec_mask] + lit_tail = [] + if c.src0 >= 256: + code += F.mov(c.src0 - 256, c.val0) + elif c.src0 <= 105: + code += F.smov(c.src0, c.val0) + elif c.src0 == 255: + lit_tail = [c.val0] + if c.wide: + code += vop3_fract_f16(4, c.src0, abs_=c.abs_, neg=c.neg, op_sel=c.op_sel, clamp=c.clamp) + else: + code += vop1_fract_f16(4, c.src0) + code += lit_tail + if c.exec_mask != ALL_EXEC: + code += [sop1(3, 126, 193)] + return code + + +def compute_program(cases): + assert len(cases) <= 32, len(cases) + code = list(PROLOGUE) + for slot, c in enumerate(cases): + code += emit_case(c) + F.store(slot * 4, 4) + return code + [0xBF810000] + + +def refusal_programs(): + cond_mode = [0xBF840001, 0xBFA5000F] # s_cbranch_scc0 +1; s_denorm_mode 15 + plain = vop1_fract_f16(4, 257) + [0xBF810000] + return [ + # VOP3 output modifier omod != 0. + (vop3_fract_f16(4, 257, omod=1) + [0xBF810000], 'unsupported v_fract_f16 omod'), + # Unused VOP3 operand modifier/op_sel bits. + (vop3_fract_f16(4, 257, op_sel=0b0010) + [0xBF810000], 'unsupported v_fract_f16 operand modifiers'), + (vop3_fract_f16(4, 257, s1=258) + [0xBF810000], 'unsupported v_fract_f16 operand modifiers'), + # High-half op_sel on non-VGPR source. + (vop3_fract_f16(4, 10, op_sel=0b0001) + [0xBF810000], + 'unsupported v_fract_f16 high-half op_sel on non-VGPR source'), + # DPP16 and SDWA forms. + (vop1_fract_f16(4, 250) + [0xFF00E401, 0xBF810000], 'unsupported DPP arithmetic'), + (vop1_fract_f16(4, 249) + [0x06060601, 0xBF810000], 'unimplemented direct SDWA operand profile'), + # Special scalar source (vcc_lo). + (vop1_fract_f16(4, 106) + [0xBF810000], 'unsupported v_fract_f16 source'), + # Unsupported binary16 rounding/denorm modes and dynamic conditional MODE write. + ([0xBFA40004] + plain, 'unsupported binary16 rounding or denormal mode'), + ([0xBFA50003] + plain, 'unsupported binary16 rounding or denormal mode'), + (cond_mode + plain, 'unsupported binary16 rounding or denormal mode'), + ] + + +def _exec_with_floor(orig_exec): + def wrapped(line, values, memory, stores): + if 'unary.f32(i32 27,' in line: + name, rhs = [part.strip() for part in line.split('=', 1)] + token = re.search(r'i32 27,\s*float ([^,\s\)]+)\)', rhs).group(1) + if token.startswith('%'): + kind, bits = values[token] + assert kind == 'float', line + else: + bits = struct.unpack('<I', struct.pack('<f', float(token)))[0] + val = struct.unpack('<f', struct.pack('<I', bits))[0] + if not (math.isnan(val) or math.isinf(val) or val == 0.0): + bits = struct.unpack('<I', struct.pack('<f', float(math.floor(val))))[0] + values[name] = ('float', bits) + return + orig_exec(line, values, memory, stores) + return wrapped + + +def ir(dumper): + items = all_cases() + code = compute_program(items) + want = [c.expected(lane=0) for c in items] + refusals = refusal_programs() + with tempfile.TemporaryDirectory() as tmp: + work = Path(tmp) + run = F.dump(dumper, work, code, 'fract-f16') + assert run.returncode == 0, run.stderr + with mock.patch.object(F, '_exec', _exec_with_floor(F._exec)): + stores = sorted(F.interpret(run.stdout)) + assert [addr for addr, _ in stores] == [4 * i for i in range(len(want))], stores[:4] + bad = [(i, items[i].name, hex(got), hex(exp)) + for i, ((_, got), exp) in enumerate(zip(stores, want)) if got != exp] + assert not bad, bad[:8] + for idx, (refused, why) in enumerate(refusals): + r = F.dump(dumper, work, refused, f'refused-{idx}') + assert r.returncode != 0 and why in r.stderr, (idx, why, r.returncode, r.stderr) + print(f'native_fract_f16 IR: {len(want)} cases matched exact model; {len(refusals)} refusals matched') + return 0 + + +def controls(cli, sdk, work, root): + items = all_cases() + code = compute_program(items) + marker = request(work, root, code) + output = marker.with_suffix('.cso') + result = subprocess.run([cli, sdk, work / 'cache', 'gfx1013-direct-cs@0', marker, output], + capture_output=True, text=True) + assert result.returncode == 0 and output.is_file(), (result.stdout, result.stderr) + dump = subprocess.run([Path(sdk) / 'dxc.exe', '-dumpbin', output], capture_output=True, text=True, check=True).stdout + assert 'legacyF16ToF32' in dump and 'fsub float' in dump and 'unary.f32(i32 27,' in dump, dump + + refusals = refusal_programs() + for idx, (prog, why) in enumerate(refusals): + m = request(work, root, prog) + o = m.with_suffix(f'.refused{idx}.cso') + r = subprocess.run([cli, sdk, work / 'cache', 'gfx1013-direct-cs@0', m, o], capture_output=True, text=True) + assert r.returncode != 0 and why in r.stderr, (idx, why, r.stdout, r.stderr) + assert not o.exists(), o + + print(f'native_fract_f16 controls: compiled {len(items)} cases to DXIL; verified {len(refusals)} refusals') + return 0 + + +def hardware(replay, sdk, work, root): + items = all_cases() + code = compute_program(items) + marker = request(work, root, code) + output = work / 'out.bin' + run = subprocess.run([replay, sdk, marker, work / 'cache', '0', output, '--direct']) + if run.returncode == 77: + return 77 + run.check_returncode() + words_out = list(struct.unpack(f'<{F.WORDS}I', output.read_bytes())) + expected = {} + for group in range(F.GROUPS): + for lane in range(32): + head = F.BASE + group * 1024 + lane * 32 + for idx, c in enumerate(items): + expected[head + idx] = c.expected(lane=lane) + bad = [] + for i, got in enumerate(words_out): + if i in expected: + if got != expected[i]: + bad.append((i, hex(got), hex(expected[i]))) + elif got != F.SENTINEL: + bad.append((i, hex(got), hex(F.SENTINEL))) + assert not bad, bad[:10] + print(f'native_fract_f16 compute hardware: {len(items)} cases matched across {F.GROUPS}x32 lanes and guards') + return 0 + + +def pixel_program(pair): + code = [] + for idx, c in enumerate(pair): + code += emit_case(c) + lo_reg, hi_reg = 8 + 2 * idx, 9 + 2 * idx + code += [vop2(0x1B, lo_reg, 255, 4), 65535, vop2(0x16, hi_reg, 144, 4)] + # Each 16-bit half is exactly representable in binary32 as an integer in 0..65535. + code += [0x7E000C00 | reg << 17 | (256 + reg) for reg in (lo_reg, hi_reg)] + return patched_pixel(len(code), code, export=(0xF800180F, 0x0B0A0908)) + + +def pixel(cli, sdk, renderer, adapter, work): + items = [c for c in all_cases() if c.exec_mask == ALL_EXEC] + if len(items) % 2: + items.append(items[-1]) + vs = compile_hlsl(str(Path(sdk) / 'dxc.exe'), 'dxc', FULLSCREEN_VS, 'fullscreen', 'vs_6_0', work) + pairs = [items[i:i + 2] for i in range(0, len(items), 2)] + for idx, pair in enumerate(pairs): + shader = work / f'fract-f16-{idx}.ps' + shader.write_bytes(pixel_program(pair)) + cso = shader.with_suffix('.cso') + build = subprocess.run([cli, sdk, work / 'cache', 'gfx1013-container-ps', shader, cso], + capture_output=True, text=True, timeout=30) + assert build.returncode == 0, ([c.name for c in pair], build.stdout, build.stderr) + w0, w1 = pair[0].expected(), pair[1].expected() + ref = work / 'expected.bin' + ref.write_bytes(struct.pack('<4f', w0 & 0xFFFF, w0 >> 16, w1 & 0xFFFF, w1 >> 16)) + run = subprocess.run([renderer, adapter, '--startup-pixel-words', vs, cso, '1', '1', ref], + capture_output=True, text=True, timeout=30) + if run.returncode == 77: + return 77 + assert run.returncode == 0, (idx, [c.name for c in pair], run.stdout, run.stderr) + if 'debug_layer=enabled' in run.stdout: + assert 'debug_errors=0 debug_warnings=0' in run.stdout, run.stdout + print(f'native_fract_f16 pixel ({adapter}): {len(pairs)} pixel draws ({len(items)} cases) matched') + return 0 + + +def main(mode, tool, sdk=None, *args): + if mode == 'ir': + return ir(tool) + with tempfile.TemporaryDirectory() as tmp: + work = Path(tmp) + if mode == 'pixel': + return pixel(tool, sdk, args[0], args[1], work) + shader = work / 'root.hlsl' + shader.write_text('#define SIG "DescriptorTable(UAV(u0,numDescriptors=8))"') + root = work / 'root.bin' + subprocess.run([Path(sdk) / 'dxc.exe', '-T', 'rootsig_1_1', '-E', 'SIG', '-Fo', root, shader], check=True) + return {'controls': controls, 'compute': hardware}[mode](tool, sdk, work, root.read_bytes()) + + +if __name__ == '__main__': + sys.exit(main(*sys.argv[1:])) diff --git a/tests/native_fract_f32_check.py b/tests/native_fract_f32_check.py new file mode 100644 index 0000000000..305f41afd0 --- /dev/null +++ b/tests/native_fract_f32_check.py @@ -0,0 +1,124 @@ +"""Direct DXIL fract's strict upper bound, NaNs and output modifier order. + +The source-built VOP1 and VOP3 instructions write 32 words per lane in two +wave32 groups. Tiny negative values make a host Frc round to 1.0; gfx1013 +instead returns the greatest binary32 below 1.0. A NaN must stay a NaN. +""" +import math +import struct +import subprocess +import sys +import tempfile +from pathlib import Path + +from native_dpp_quad_check import request +from native_frexp_f32_check import v_mov_lit, vop1, vop3_unary +from native_mad32_check import PROLOGUE + +INPUTS = (0xb0800000, 0xb1800000, 0x3e800000, 0xbe800000, + 0, 0x80000000, 0x7fc12345, 0xc0400000) +CAP = 0x3f7fffff +SENTINEL = 0x69696969 +WORDS = 2064 + + +def bits(value): + return struct.unpack('<I', struct.pack('<f', value))[0] + + +def value(word): + return struct.unpack('<f', struct.pack('<I', word))[0] + + +def fract(word, *, cap=True, nan_to_cap=False): + x = value(word) + if math.isnan(x): + return CAP if nan_to_cap else 0x7fc00000 + result = bits(x - math.floor(x)) + if not result & 0x7fffffff: + result = 0 # floor retains -0, so subtracting that same zero yields +0. + return CAP if cap and value(result) >= 1.0 else result + + +def expected_row(word, **mutation): + plain = fract(word, **mutation) + negated = fract(word ^ 0x80000000, **mutation) + clamped = bits(0.0 if math.isnan(value(plain)) else value(plain)) + scaled = bits(value(plain) * 2.0) + return plain, negated, clamped, scaled + + +def reference(**mutation): + row = [v for word in INPUTS for v in expected_row(word, **mutation)] + return [SENTINEL] * 8 + row * 64 + [SENTINEL] * 8 + + +def program(): + code = list(PROLOGUE) + for ci, word in enumerate(INPUTS): + code += v_mov_lit(1, word) + forms = ([vop1(0x20, 3, 257)], + vop3_unary(0x1a0, 3, 257, neg0=1), + vop3_unary(0x1a0, 3, 257, clamp=1), + vop3_unary(0x1a0, 3, 257, omod=1)) + for fi, form in enumerate(forms): + code += form + [0xe0701000 | (4 * (4 * ci + fi)), 0x80080308] + return code + [0xbf810000] + + +def is_nan(word): + return (word & 0x7fffffff) > 0x7f800000 + + +def matches(actual, expected): + return len(actual) == len(expected) and all( + a == e or (is_nan(a) and is_nan(e)) for a, e in zip(actual, expected)) + + +def controls(cli, sdk, work, root): + marker = request(work, root, program()) + output = work / 'fract.cso' + subprocess.run([cli, sdk, work / 'cache', 'gfx1013-direct-cs@0', marker, output], check=True) + dump = subprocess.run([Path(sdk) / 'dxc.exe', '-dumpbin', output], + capture_output=True, text=True, check=True).stdout + assert 'Frc(value)' in dump, dump + # Ordered comparison preserves NaN. The cap precedes the output scale + # and clamp, which the hardware mode checks through the stored words. + assert 'fcmp oge float' in dump and '1065353215 to float' in dump, 'missing ordered upper bound' + expected = reference() + assert not matches(reference(cap=False), expected), 'uncapped Frc escaped' + assert not matches(reference(nan_to_cap=True), expected), 'NaN-losing minimum escaped' + print('fract DXIL validates; uncapped and NaN-losing references differ') + return 0 + + +def hardware(replay, sdk, work, root): + marker = request(work, root, program()) + output = work / 'readback.bin' + result = subprocess.run([replay, sdk, marker, work / 'cache', '0', output, '--direct']) + if result.returncode == 77: + return 77 + result.check_returncode() + actual = struct.unpack(f'<{WORDS}I', output.read_bytes()) + expected = reference() + if not matches(actual, expected): + bad = [(i, f'{a:08x}', f'{e:08x}') for i, (a, e) in enumerate(zip(actual, expected)) + if a != e and not (is_nan(a) and is_nan(e))] + raise AssertionError(f'{len(bad)}/{WORDS} words differ: {bad[:12]}') + print('fract e32/e64: 2048 words and 16 guards matched (NaN by class)') + return 0 + + +def main(mode, executable, sdk): + with tempfile.TemporaryDirectory(prefix='x2w_native_fract_f32_') as temp: + work = Path(temp) + source = work / 'root.hlsl' + source.write_text('#define SIG "DescriptorTable(UAV(u0,numDescriptors=8))"') + root = work / 'root.bin' + subprocess.run([Path(sdk) / 'dxc.exe', '-T', 'rootsig_1_1', '-E', 'SIG', + '-Fo', root, source], check=True) + return {'controls': controls, 'hardware': hardware}[mode](executable, sdk, work, root.read_bytes()) + + +if __name__ == '__main__': + raise SystemExit(main(*sys.argv[1:])) diff --git a/tests/native_global_load_check.py b/tests/native_global_load_check.py index f0b3203494..2c989f023e 100644 --- a/tests/native_global_load_check.py +++ b/tests/native_global_load_check.py @@ -38,7 +38,7 @@ def words(hexes): ROOT = 'SRV(t0),DescriptorTable(UAV(u0,numDescriptors=8))' -SA = struct.pack('<7I', 0, 0, 0, 32 | 1 << 16, 1, 0, 0x80 | 7 << 1) +SA = struct.pack('<7I', 0, 0, 0, 32 | 1 << 16, 1 | (1 << 20), 0, 0x80 | 7 << 1) # s_mov_b32 s20, s6 / s_mov_b32 s21, 0 / s_load_dwordx4 s[40:43], s[20:21], 0x20 / s_load_dword s30, s[4:5], 0xfc / # s_lshl_b32 s12, s7, 10 / v_lshlrev_b32 v8, 5, v0 / v_add_nc_u32 v8, s12, v8 / v_lshlrev_b32 v1, 2, v0 / # v_and_b32 v2, 3, v0 / v_lshlrev_b32 v2, 2, v2 / v_or_b32 v2, -16, v2 / v_add_nc_u32 v3, 1, v1 diff --git a/tests/native_global_srv_heap_replay_check.py b/tests/native_global_srv_heap_replay_check.py index ad16834a7f..fba18e6179 100644 --- a/tests/native_global_srv_heap_replay_check.py +++ b/tests/native_global_srv_heap_replay_check.py @@ -6,7 +6,9 @@ ResourceDescriptorHeap[slot] and stores them to u0. Slots 0 and 1 are raw buffers with different data, slot 2 is a texture, slot 3 a typed buffer. The fixture's `record` mode captures the GPU selector and the slot view types into a req_<key>.views file and refuses the incompatible slots before the dispatch; `compile_dxil` and the fixture's `replay` -mode consume the same file offline. Exit 77 when the fixture reports a capability skip. +mode consume the same file offline. Section 11 forms the heap descriptor address by adding the byte offset to the heap +base (s_add_u32, carry into the high word) instead of the SGPR offset of the load. Exit 77 when the fixture reports a +capability skip. """ import pathlib import shutil @@ -384,8 +386,6 @@ def raw_load_request(name, width=1, *, offen=False, soffset=18, imm=0, flags=0, modifiers = "raw buffer load needs a linear byte offset and no modifiers" for name, diagnostic, addressing in ( - ("raw_glc", modifiers, {"flags": 1 << 14}), - ("raw_slc", modifiers, {"flags2": 1 << 22}), ("raw_idxen", modifiers, {"flags": 1 << 13}), ("raw_descriptor_soffset", "unbound numeric SGPR s20", {"soffset": 20}), ("raw_literal_soffset", "raw buffer load scalar offset needs an SGPR or inline integer", {"soffset": 255}), @@ -393,4 +393,65 @@ def raw_load_request(name, width=1, *, offen=False, soffset=18, imm=0, flags=0, (code, out, err), _, _, _, cso = raw_load_request(name, **addressing) require(code == 1 and diagnostic in err and not cso.exists(), f"{name}: refused with '{diagnostic}'") + # 11. The heap descriptor address formed by adding the byte offset to the heap base, as a waterfall loop over a + # lane-selected slot does, instead of the SGPR offset of the load (encodings checked with tools/disasm_rdna2.py): + # s_add_u32 s24, s2, s17 ; s_add_u32 s25, 0, src_scc ; s_load_dwordx4 s[20:23], s[24:25], 0x0 + # It reads the same slot: recorded, compiled offline and replayed like PROGRAM. + ADD_LO, ADD_HI, ADDED_LOAD = 0x80181102, 0x8019fd80, [0xf408050c, 0xfa000000] + + def added(lo=ADD_LO, between=(), hi=ADD_HI, load_words=ADDED_LOAD): + return words_list[:heap_load] + [lo, *between, hi, *load_words] + words_list[heap_load + 2:] + + ADDED = added() + directory, added_stem = shader_request("added_nometa", ADDED) + out_dir = base / "added_nometa_out" + code, out, err = run([compile_dxil, sdk, cache, "gfx1013-container-cs", "--requests", directory, out_dir]) + require(code == 1 and HEAP_REFUSAL in err and not any(out_dir.glob("*.cso")), + "compile_dxil added address without .views refuses the heap read with the slot/type text") + added_outputs = {} + for n in (0, 1): + directory, added_stem = shader_request(f"added{n}", ADDED) + code, out, err = run([fixture, "record", sdk, cache, directory / (added_stem + ".cdx"), adapter, n, "ok"]) + require(code == 0 and "output matches slot %d data" % n in out, + f"record added select {n}: u0 equals the slot {n} data read through the added address") + out_dir = base / f"added{n}_out" + code, out, err = run([compile_dxil, sdk, cache, "gfx1013-container-cs", "--requests", directory, out_dir]) + cso = out_dir / (added_stem[len("req_"):] + ".cs.cso") + require(code == 0 and "requests=1 compiled=1 refused=0" in out and cso.exists(), + f"compile_dxil added select {n}: compiled and published a .cso") + added_outputs[n] = (directory, cso) + code, out, err = run([fixture, "replay", sdk, cache, directory / (added_stem + ".cdx"), cso, + directory / (added_stem + ".views"), adapter, "ok", n]) + require(code == 0 and "output matches slot %d data" % n in out, f"replay added select {n}: output equals slot {n} data") + directory, cso = added_outputs[0] + code, out, err = run([fixture, "replay", sdk, cache, directory / (added_stem + ".cdx"), cso, + directory / (added_stem + ".views"), adapter, "ok", 1]) + require(code == 1 and "mismatch word 0" in out, "replay added select 0 compared with slot 1 data reports a mismatch") + + high_word = "heap descriptor address high word is not the carry of its offset add" + added_shapes = { + # s_add_u32 s24, s17, s2 and s_addc_u32 s25, 0, 0: the other operand order and carry form + "added_swapped_addc": (added(lo=0x80180211, hi=0x82198080), None), + # s_add_u32 s24, s2, 0x40: a constant offset names a slot that is not the captured GPU selection + "added_constant": (added(lo=0x8018ff02, between=(0x00000040,)), "unbound numeric SGPR s2"), + # s_mov_b32 s25, 0: the high word drops the carry of the offset add + "added_mov_high": (added(hi=0xbe990380), high_word), + # s_cmp_lg_u32 s16, s16 between the adds: SCC is no longer the carry + "added_scc_clobbered": (added(between=(0xbf071010,)), high_word), + # s_load_dwordx4 s[20:23], s[24:25], 0x20 + "added_immediate": (added(load_words=[0xf408050c, 0xfa000020]), + "heap descriptor load with an immediate offset addresses another slot than the captured selection"), + } + for name, (program, expected) in added_shapes.items(): + directory, shape_stem = shader_request("shape_" + name, program) + (directory / (shape_stem + ".views")).write_text(good, newline="\n") + out_dir = base / ("shape_" + name + "_out") + code, out, err = run([compile_dxil, sdk, cache, "gfx1013-container-cs", "--requests", directory, out_dir]) + if expected is None: + require(code == 0 and "requests=1 compiled=1 refused=0" in out and any(out_dir.glob("*.cso")), + f"compile_dxil shape '{name}': compiled") + else: + require(code == 1 and expected in err and not any(out_dir.glob("*.cso")), + f"compile_dxil shape '{name}': refused with '{expected}'") + print("native_global_srv_heap_replay: all checks passed") diff --git a/tests/native_heap_offset_add_check.py b/tests/native_heap_offset_add_check.py new file mode 100644 index 0000000000..4d5f8978b2 --- /dev/null +++ b/tests/native_heap_offset_add_check.py @@ -0,0 +1,84 @@ +"""A slot 67 request that forms its resource-heap descriptor address by adding a byte offset (issue #3224). + +usage: native_heap_offset_add_check.py COMPILE_DXIL SDK + +A waterfall loop over a lane-selected heap slot adds the slot's byte offset to the heap base and carries into the high +word instead of passing the offset as the SGPR offset of the load: + + s_add_u32 s10, s5, s8 ; s_add_u32 s11, 0, src_scc ; s_load_dwordx4 s[12:15], s[10:11], 0x0 + +The requests are written from source with the entry layout of the start-up shaders that do this: user SGPRs s4 (a +descriptor table), s5 (the resource heap) and s6 (the sampler heap) under both directly indexed heap flags, wave32. Such a +load is the same GPU-selected heap read as the SGPR-offset form, so both now stop at the heap view contract, which a +.c67 request has no metadata for. Before this change the add was refused as a numeric use of the heap table. The +controls keep their refusals: a high word that is not the carry of the add, SCC clobbered between the adds, and a +constant offset. The GPU readback of the same address form is in native_global_srv_heap_replay_check.py (section 11). +Encodings were checked with tools/disasm_rdna2.py; the test needs no LLVM. +""" +import pathlib +import struct +import subprocess +import sys +import tempfile + +from native_compute_clear_check import write_request + +ROOT = "RootFlags(CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED | SAMPLER_HEAP_DIRECTLY_INDEXED), DescriptorTable(SRV(t0), UAV(u0))" +HEAP_CONTRACT = "direct resource-heap load requires the selected GPU slot and its view type" +HIGH_WORD = "heap descriptor address high word is not the carry of its offset add" +SELECT = [0x7E100500, 0x8F088508] # v_readfirstlane_b32 s8, v0 ; s_lshl_b32 s8, s8, 5 +ADD_LO, ADD_HI = 0x800A0805, 0x800BFD80 # s_add_u32 s10, s5, s8 ; s_add_u32 s11, 0, src_scc +LOAD = [0xF4080305, 0xFA000000] # s_load_dwordx4 s[12:15], s[10:11], 0x0 +END = [0xBF8CC07F, 0xBF810000] # s_waitcnt lgkmcnt(0) ; s_endpgm +PROGRAMS = { + "added": (SELECT + [ADD_LO, ADD_HI] + LOAD + END, HEAP_CONTRACT), + # s_mov_b32 s10, s5 ; s_mov_b32 s11, 0 ; s_load_dwordx4 s[12:15], s[10:11], s8: the SGPR-offset form + "sgpr_offset": (SELECT + [0xBE8A0305, 0xBE8B0380, 0xF4080305, 0x10000000] + END, HEAP_CONTRACT), + # s_mov_b32 s11, 0 instead of the carry + "mov_high": (SELECT + [ADD_LO, 0xBE8B0380] + LOAD + END, HIGH_WORD), + # s_cmp_lg_u32 s8, s8 between the adds + "scc_clobbered": (SELECT + [ADD_LO, 0xBF070808, ADD_HI] + LOAD + END, HIGH_WORD), + # s_add_u32 s10, s5, 0x40: a constant offset is not a GPU selection; the heap table is used as a number + "constant": (SELECT + [0x800AFF05, 0x40, ADD_HI] + LOAD + END, "unbound numeric SGPR s5"), + # Wave64, s_load_dwordx4 s[104:107], s[10:11], 0x0: the slot index would be written into VCC, which the wave64 + # model keeps as mask data, so the overlap refusal comes before the heap contract. + "wave64_vcc_dst": (SELECT + [ADD_LO, ADD_HI, 0xF4081A05, 0xFA000000] + END, + "symbolic scalar memory destination overlaps wave64 VCC", 64), +} + + +def main(compile_dxil, sdk): + failures = 0 + with tempfile.TemporaryDirectory(prefix="x2w_heap_offset_add_") as scratch: + base = pathlib.Path(scratch) + source = base / "root.hlsl" + source.write_text(f'#define RS "{ROOT}"') + binary = base / "root.bin" + subprocess.run([pathlib.Path(sdk) / "dxc.exe", "-T", "rootsig_1_1", "-E", "RS", "-Fo", binary, source], + check=True, capture_output=True) + root = binary.read_bytes() + for name, (program, expected, *wave) in PROGRAMS.items(): + # Group 32x1x1 in wave32 (bit 20 of dword 4), or 64x1x1 in wave64, 7 user SGPRs. + threads = wave[0] if wave else 32 + sa = struct.pack("<7I", 0, 0, 0, threads | (1 << 16), 1 | (0 if wave else 1 << 20), 0, 7 << 1) + folder = base / name + folder.mkdir() + marker = write_request(folder, program, root, sa) + output = marker.with_suffix(".cso") + result = subprocess.run([compile_dxil, sdk, base / "cache", "gfx1013-direct-cs@0", marker, output], + capture_output=True, text=True, timeout=60) + ok = result.returncode != 0 and expected in result.stderr and not output.exists() + print(("ok: " if ok else "FAIL: ") + f"{name}: refused with '{expected}' and no .cso") + if not ok: + print(result.stdout + result.stderr) + failures += 1 + if failures: + return 1 + print("native_heap_offset_add: all checks passed") + return 0 + + +if __name__ == "__main__": + if len(sys.argv) != 3: + raise SystemExit(__doc__) + sys.exit(main(*sys.argv[1:])) diff --git a/tests/native_image_atomic_binops_check.py b/tests/native_image_atomic_binops_check.py new file mode 100644 index 0000000000..f8ce9f287b --- /dev/null +++ b/tests/native_image_atomic_binops_check.py @@ -0,0 +1,110 @@ +"""Check new direct DXIL integer atomics on the typed 2D uint UAV.""" +from pathlib import Path +import operator +import re +import subprocess +import sys +import tempfile + +from native_direct_container_check import compute, words +from native_image_atomic_check import ( + OPERAND, TEXELS, UINT_MASK, WIDTH, image_atomic, program_words, reference, render, +) + + +OPS = { + 'swap': (0x0f, 8, 1 << 28, lambda old, operand: operand), + 'umin': (0x15, 6, 1 << 27, min), + 'and': (0x18, 1, 1 << 25, operator.and_), + 'or': (0x19, 2, 1 << 25, operator.or_), + 'xor': (0x1a, 3, 1 << 25, operator.xor), +} +REFUSED = {'sub': 0x12, 'smin': 0x14, 'smax': 0x16, 'inc': 0x1b, 'dec': 0x1c, + 'fcmpswap': 0x1d, 'fmin': 0x1e, 'fmax': 0x1f} +OPERAND_DIAGNOSTIC = 'unsupported typed 2D image atomic operands' + + +def compile_shader(cli, sdk, work, opcode, *, glc=True, sparse=False, contend=False, **encoding): + # Retain the fixture's coordinates, EXEC mask, wait, and old-value probe. + # With GLC clear the probe observes the original data VGPR instead. + code = program_words('add', returning=True, drop_glc=not glc, sparse=sparse, + contend=contend, **encoding) + flags = encoding.get('flags', 0) | (0x2000 if glc else 0) + atomic_word, _ = image_atomic('add', flags=flags, mask=encoding.get('mask'), dim=encoding.get('dim', 1)) + index = code.index(atomic_word) + code[index] = (atomic_word & ~(0x7f << 18)) | (opcode << 18) + if contend: + # The original fixture uses 1 for contended add. Exercise the same + # high-bit operand as the distinct-texel case here. + code[code.index(0x7e1c02ff) + 1] = OPERAND + source = work / 'binop.cs' + shader = source.with_suffix('.cso') + shader.unlink(missing_ok=True) + source.write_bytes(compute(words(*code), table=True)) + result = subprocess.run([cli, sdk, work / 'cache', 'gfx1013-container-cs', source, shader], + capture_output=True, text=True, timeout=30) + return shader, result + + +def controls(cli, sdk, work): + for name, (opcode, dxil, _, _) in OPS.items(): + shader, run = compile_shader(cli, sdk, work, opcode) + assert run.returncode == 0, ( + f'{name}: valid typed image atomic refused (operand diagnostic: {OPERAND_DIAGNOSTIC})', + run.stdout, run.stderr, + ) + dump = subprocess.run([Path(sdk) / 'dxc.exe', '-dumpbin', shader], + capture_output=True, text=True, timeout=30, check=True).stdout + # The second atomic is the existing add probe and must have code 0. + codes = re.findall(r'@dx\.op\.atomicBinOp\.i32\(i32 78, %dx\.types\.Handle [^,]+, i32 (\d+),', dump) + assert codes == [str(dxil), '0'] and '2d' in dump, (name, dump) + for encoding in ({'dim': 5}, {'mask': 15}, {'coord': 255}, {'flags': 0x80}, + {'addr_flags': 0x40000000}, {'addr_flags': 0x200000}): + _, run = compile_shader(cli, sdk, work, opcode, **encoding) + assert run.returncode and OPERAND_DIAGNOSTIC in run.stderr, (name, encoding, run.stdout, run.stderr) + for name, opcode in REFUSED.items(): + _, run = compile_shader(cli, sdk, work, opcode) + assert run.returncode and 'direct image opcode or descriptor modifiers' in run.stderr, ( + name, run.stdout, run.stderr, + ) + print('Typed image binary atomic DXIL codes and refusal diagnostics matched') + + +def expected_texels(update, *, glc, contend): + initial, _ = reference('add') + expected = initial.copy() + for lane in range(0, 32, 2): + x, y = (5, 6) if contend else (2 + lane % 8, 1 + lane // 8) + index = y * WIDTH + x + previous = expected[index] + expected[index] = update(previous, OPERAND) + # Contending lanes use the same operand, so the aggregate of returned + # values depends only on the number of updates, regardless of order. + probe = index + 12 + expected[probe] = (expected[probe] + (previous if glc else OPERAND)) & UINT_MASK + return initial, expected + + +def hardware(cli, sdk, work, renderer, adapter): + wave = render(renderer, adapter, '--shader-wave32') + assert wave.returncode == 0, (wave.stdout, wave.stderr) + print(wave.stdout, end='') + for name, (opcode, _, format_selector, update) in OPS.items(): + for contend in (False, True): + for glc in (False, True): + shader, run = compile_shader(cli, sdk, work, opcode, glc=glc, sparse=True, contend=contend) + assert run.returncode == 0, (name, glc, contend, run.stdout, run.stderr) + initial, expected = expected_texels(update, glc=glc, contend=contend) + payload = work / 'texture.bin' + payload.write_bytes(words(1 | format_selector, 0, *initial, *expected)) + run = render(renderer, adapter, '--compute-texture-store-case', shader, payload) + assert run.returncode == 0, (name, glc, contend, run.stdout, run.stderr) + if 'debug_layer=enabled' in run.stdout: + assert 'debug_errors=0 debug_warnings=0' in run.stdout, run.stdout + print(f'{name} GLC={glc} contended={contend}: {TEXELS} texture words matched') + + +if __name__ == '__main__': + mode, cli, sdk, *args = sys.argv[1:] + with tempfile.TemporaryDirectory() as temp: + {'controls': controls, 'hardware': hardware}[mode](cli, sdk, Path(temp), *args) diff --git a/tests/native_image_cache_flags_check.py b/tests/native_image_cache_flags_check.py new file mode 100644 index 0000000000..4fd7df93c9 --- /dev/null +++ b/tests/native_image_cache_flags_check.py @@ -0,0 +1,136 @@ +"""Verify GLC and DLC cache-policy flags on direct read-only image ops (#3242).""" +from pathlib import Path +import struct +import subprocess +import sys +import tempfile + +from native_direct_container_check import compute, patched_pixel, words +import native_gather_lod_check as G + +GLC = 0x2000 +DLC = 0x0080 +SLC = 0x02000000 +ALL_CACHE = GLC | DLC | SLC +REFUSED = 'direct image opcode or descriptor modifiers' + + +def ro_program(op, stage, *, flags=0, w1_flags=0): + code = [0xBE810380, 0xF40C0200, 0xFA000000] # s[8:15] texture descriptor + if stage == 'cs': + code += [0xF4080800, 0xFA000020, 0x7E060280] # s[32:35] UAV, v3 = 0 + for reg, value in enumerate((0x12, 512 << 12, 0x04500000, 0), start=4): + code += [0xBE8003FF | (reg << 16), value] + coords = (0.5, 0.5, 0.0) if op >= 32 else (0, 0, 0) + for reg, value in enumerate(coords): + encoded = struct.unpack('<I', struct.pack('<f', value))[0] if op >= 32 else value + code += [0x7E0002FF | (reg << 17), encoded] + sampler_field = (1 << 21) if op >= 32 else 0 + dmask = 1 if op in (68, 71) else 0xF + code += [0xBF8CC07F, 0xF0000008 | (op << 18) | (dmask << 8) | flags, 0x00020400 | sampler_field | w1_flags, 0xBF8C3F70] + if stage == 'cs': + return compute(words(*code, 0xE0781000, 0x80080403, 0xBF810000), threads=1, table=True) + return patched_pixel(len(code), code, table=True, export=(0xF800180F, 0x07060504)) + + +def store_program(stage, *, flags=0): + code = [0xBE810380, 0xF40C0200, 0xFA000000, 0xBF8CC07F, + 0x7E000280, 0x7E020280, + 0xF0000F08 | (8 << 18) | flags, 0x00020400, 0xBF810000] + if stage == 'cs': + return compute(words(*code), threads=1, table=True) + return patched_pixel(len(code), code, table=True, export=(0xF800180F, 0x07060504)) + + +def compile_bytes(cli, sdk, work, label, stage, blob): + src = work / f'{label}.{stage}' + src.write_bytes(blob) + cso = src.with_suffix('.cso') + run = subprocess.run([cli, sdk, work / 'cache', f'gfx1013-container-{stage}', src, cso], + capture_output=True, text=True, timeout=30) + return cso, run + + +def controls(cli, sdk, work): + ops = ( + ('image_load', 0, '@dx.op.textureLoad.f32'), + ('image_load_mip', 1, '@dx.op.textureLoad.f32'), + ('image_getresinfo', 14, '@dx.op.getDimensions'), + ('image_sample_lz', 39, '@dx.op.sampleLevel.f32'), + ('image_gather4_lz', 71, '@dx.op.textureGather.f32'), + ('image_gather4_l', 68, '@dx.op.textureLoad.f32'), + ) + accepted = 0 + for stage in ('cs', 'ps'): + for name, op, expected_dxil in ops: + base_cso, base_run = compile_bytes(cli, sdk, work, f'{name}-base', stage, ro_program(op, stage)) + assert base_run.returncode == 0 and base_cso.is_file(), (stage, name, base_run.stdout, base_run.stderr) + base_dump = subprocess.run([Path(sdk) / 'dxc.exe', '-dumpbin', base_cso], + capture_output=True, text=True, check=True).stdout + assert expected_dxil in base_dump, (stage, name, expected_dxil, base_dump) + for tag, fl in (('glc', GLC), ('dlc', DLC), ('slc', SLC), ('all', ALL_CACHE)): + cso, run = compile_bytes(cli, sdk, work, f'{name}-{tag}', stage, ro_program(op, stage, flags=fl)) + assert run.returncode == 0 and cso.is_file(), (stage, name, tag, run.stdout, run.stderr) + dump = subprocess.run([Path(sdk) / 'dxc.exe', '-dumpbin', cso], + capture_output=True, text=True, check=True).stdout + assert dump == base_dump, (stage, name, tag) + accepted += 1 + + refusals = ( + ('store_glc', lambda st: store_program(st, flags=GLC)), + ('store_dlc', lambda st: store_program(st, flags=DLC)), + ('sample_r128', lambda st: ro_program(39, st, flags=0x8000)), + ('sample_tfe', lambda st: ro_program(39, st, flags=0x10000)), + ('sample_lwe', lambda st: ro_program(39, st, flags=0x20000)), + ('sample_res_bit6', lambda st: ro_program(39, st, flags=0x0040)), + ('sample_res_bit14', lambda st: ro_program(39, st, flags=0x4000)), + ('sample_res_w1_bit26', lambda st: ro_program(39, st, w1_flags=1 << 26)), + ) + refused = 0 + for stage in ('cs', 'ps'): + for rname, builder in refusals: + _, run = compile_bytes(cli, sdk, work, f'ref-{rname}', stage, builder(stage)) + assert run.returncode != 0 and REFUSED in run.stderr, (stage, rname, run.returncode, run.stderr) + refused += 1 + + print(f'native_image_cache_flags controls: {accepted} flagged DXIL modules matched plain baselines; {refused} refusals matched') + return 0 + + +def execute(cli, sdk, renderer, adapter, stage, work): + if stage == 'cs': + wave = G.render(renderer, adapter, '--shader-wave32') + assert wave.returncode == 0, wave.stdout + wave.stderr + cases = (G.CASES[0], G.CASES[1], G.CASES[3], G.CASES[7]) + flag_sets = (('glc', GLC), ('dlc', DLC), ('glc_dlc_slc', ALL_CACHE)) + for case in cases: + for tag, flags in flag_sets: + cso, run = G.compile_shader(cli, sdk, work, case, stage, flags=flags) + assert run.returncode == 0, (stage, case.name, tag, run.stdout, run.stderr) + reference = work / 'expected.bin' + if stage == 'ps': + G.write_case(reference, 3 - case.first, case.first, [G.taps(case)] * (G.SIDE ** 2)) + res = G.render(renderer, adapter, '--check-pixel-gather', cso, reference) + assert res.returncode == 0 and 'pixels=64 channels=256 max_absolute_error=0' in res.stdout, ( + stage, case.name, tag, res.stdout, res.stderr) + else: + expected = G.compute_reference(case.first + case.relative, case.channel, case.uv) + res = G.render_compute(renderer, adapter, cso, reference, case.first, expected) + assert res.returncode == 0 and 'compared_words=320 mismatches=0' in res.stdout, ( + stage, case.name, tag, res.stdout, res.stderr) + if 'debug_layer=enabled' in res.stdout: + assert 'debug_errors=0 debug_warnings=0' in res.stdout, res.stdout + print(f'native_image_cache_flags {stage} ({adapter}): {len(cases) * len(flag_sets)} cached-flag cases matched') + return 0 + + +def main(mode, cli, sdk, *args): + with tempfile.TemporaryDirectory() as tmp: + work = Path(tmp) + if mode == 'controls': + return controls(cli, sdk, work) + return execute(cli, sdk, args[0], args[1], mode, work) + + +if __name__ == '__main__': + sys.exit(main(*sys.argv[1:])) diff --git a/tests/native_image_store_exact_width_check.py b/tests/native_image_store_exact_width_check.py new file mode 100644 index 0000000000..b5b4ba620c --- /dev/null +++ b/tests/native_image_store_exact_width_check.py @@ -0,0 +1,116 @@ +"""Compile source-built gfx1013 image stores and exercise the startup Dispatch binder.""" +from pathlib import Path +import subprocess +import sys +import tempfile + +from native_direct_container_check import words +from startup_compute_dispatch_check import lines +from startup_compute_dispatch_texture_check import clean, run +from startup_compute_image_store_check import ARRAY_END, ARRAY_PROLOGUE, ARRAY_SLICE, RSRC2 +from startup_compute_request_check import DATA, prepare +from startup_compute_translate_check import state_a +from startup_gfx2hlsl_compute_check import root_blob + + +CASES = { + "r": (1, 1, "tex2d", 1), + "rg": (3, 1, "tex2d", 2), + "rgb": (7, 1, "tex2d", 1), + "array": (7, 5, "tex2da", 1), + "volume": (7, 2, "tex3d", 1), + "rgba": (7, 1, "tex2d", 1), + "sparse": (9, 1, "tex2d", 1), +} +OPCODE_REFUSAL = "direct image opcode or descriptor modifiers" +CHANNEL_REFUSAL = "an exact-width image store requires a matching output texture channel count" + + +def program(mask, dimension): + # ARRAY_PROLOGUE loads the image descriptor from table 1 + 64 into s[24:31]. + # v8 = 4 * group_id.x + local_id.x, v9 = 2 * group_id.y + local_id.y. + # v10 = 1 for array/volume. EXEC explicitly selects the even lanes of each 4x2 group. + values = (0x3F800000, 0x40000000, 0x40800000) + data = [] + for i in range(mask.bit_count()): + data.extend((0x7E1C02FF + (i << 17), values[i])) # v_mov_b32 v14+i, literal + store = words(0xF0201000 | (mask << 8) | (dimension << 3), 0x00060E08) + return (ARRAY_PROLOGUE + ARRAY_SLICE[1] + words(0xBF8CC07F) + words(*data) + + words(0xBEFE03FF, 0x55) + store + ARRAY_END) + + +def check(directory, cli, sdk, consumer, adapter, case): + mask, dimension, view, texel_words = CASES[case] + cache, env = prepare(directory) + env.update(X2W_D3D12_LIST_NOOP="1", X2W_D3D12_DEBUG="1", + X2W_TEST_COMPUTE_ROOT=str(directory / "compute_root")) + env.pop("X2W_NATIVE_SHADERS", None) + env.pop("X2W_TEST_DISPATCH_HARDWARE", None) + if adapter == "hardware": + env["X2W_TEST_DISPATCH_HARDWARE"] = "1" + (directory / "compute_root").write_bytes(root_blob(3, table_range=True)) + (directory / "program").write_bytes(program(mask, dimension)) + (directory / "data").write_bytes(DATA) + (directory / "state").write_bytes(state_a((4, 2, 1), RSRC2)) + + # Each mip under test is 32x8. Array/volume use six slices and a view starting + # at slice 1, so the shader's relative coordinate 1 writes physical slice 2. + layers = 6 if dimension != 1 else 1 + initial = [0x30000000 + i for i in range(layers * 32 * 8 * texel_words)] + mode = "texture-exact-" + ("rgba" if case == "sparse" else case) + layout = f"<{len(initial)}I" + got, result = run(directory, consumer, env, mode, layout) + assert got == initial and lines(result, "Dispatch(2, 1, 1) refused: no translation"), result.stderr + key = lines(result, "x2w-draw compute request")[0].split()[3] + compiled = subprocess.run([cli, sdk, directory / "compiler-cache", "gfx1013-direct-cs@0", + "--requests", cache, cache], capture_output=True, text=True, timeout=30) + diagnostic = compiled.stdout + compiled.stderr + manifest = cache / f"{key}.txt" + if case == "sparse": + assert compiled.returncode and OPCODE_REFUSAL in diagnostic and not manifest.exists(), diagnostic + print(diagnostic, end="") + return 0 + assert compiled.returncode == 0 and manifest.is_file(), diagnostic + assert f"uav 0 {view} float table 1 64 channels {mask.bit_count()}" in manifest.read_text().splitlines() + + expected = initial.copy() + if case != "rgba": + # Packed unsigned floats for (1, 2, 4), with 6/6/5 mantissa bits. + packed = 0x3C0 | (0x400 << 11) | (0x220 << 22) + values = {"r": [0x3F800000], "rg": [0x3F800000, 0x40000000]}.get(case, [packed]) + for y in range(2): + for x in (0, 2, 4, 6): # two X groups, local lanes 0, 2, 4 and 6 in each group + i = (((2 if layers > 1 else 0) * 8 + y) * 32 + x) * texel_words + expected[i:i + texel_words] = values + + # Native translation first with the published manifest removed (no fallback), so an + # adapter without 32-lane waves reports the capability skip before any PSO is made; + # then bind solely from the restored manifest. + published = manifest.read_bytes() + for native in (True, False): + if native: + manifest.unlink() + env["X2W_NATIVE_SHADERS"] = sdk + else: + manifest.write_bytes(published) + env.pop("X2W_NATIVE_SHADERS", None) + got, result = run(directory, consumer, env, mode, layout) + if native and lines(result, "not translated natively: the adapter has no 32-lane waves"): + assert got == initial, result.stderr + return 77 + assert got == expected, (case, native, result.stderr, + next(i for i, (actual, want) in enumerate(zip(got, expected)) if actual != want)) + if native: + assert lines(result, "translated natively:"), result.stderr + if case == "rgba": + assert lines(result, f"Dispatch(2, 1, 1) refused: {CHANNEL_REFUSAL}"), result.stderr + else: + assert lines(result, "Dispatch(2, 1, 1) translated"), result.stderr + clean(result) + print(f"{adapter} {case}: checked all {len(initial)} words through both binders") + return 0 + + +if __name__ == "__main__": + with tempfile.TemporaryDirectory() as temp: + sys.exit(check(Path(temp), *sys.argv[1:])) diff --git a/tests/native_indexed_atomic_check.py b/tests/native_indexed_atomic_check.py index 2efea33e7e..a1bcdf3061 100644 --- a/tests/native_indexed_atomic_check.py +++ b/tests/native_indexed_atomic_check.py @@ -69,7 +69,7 @@ def main(cli, gpu, sdk): src, root = work/"root.hlsl", work/"root.bin" src.write_text('#define SIG "DescriptorTable(UAV(u0,numDescriptors=8))"') subprocess.run([Path(sdk)/"dxc.exe", "-T", "rootsig_1_1", "-E", "SIG", "-Fo", root, src], check=True) - sa = struct.pack("<7I",0,0,0,32 | 1<<16,1,0,0x8a) + sa = struct.pack("<7I",0,0,0,32 | 1<<16,1 | (1 << 20),0,0x8a) previous = None for mutant in (False, True): words = program(mutant) diff --git a/tests/native_lane_access_check.py b/tests/native_lane_access_check.py index eb468c842a..eaf974be0d 100644 --- a/tests/native_lane_access_check.py +++ b/tests/native_lane_access_check.py @@ -26,7 +26,7 @@ def readfirstlane(dst, vgpr): def launch(threads): - return struct.pack("<7I", 0, 0, 0, threads | 1 << 16, 1, 0, 0x8a) + return struct.pack("<7I", 0, 0, 0, threads | 1 << 16, 1 | (1 << 20), 0, 0x8a) def program(): diff --git a/tests/native_ldexp_f16_check.py b/tests/native_ldexp_f16_check.py new file mode 100644 index 0000000000..ea5416ef0f --- /dev/null +++ b/tests/native_ldexp_f16_check.py @@ -0,0 +1,216 @@ +"""Direct compute v_ldexp_f16 (VOP2 and VOP3A, exact integer binary16 scaling, high-half preserving).""" +from pathlib import Path +import struct +import subprocess +import sys +import tempfile + +from native_dpp_quad_check import request + +MASK = 0xFFFFFFFF +SENTINEL = 0x69696969 +HIGH_SEED = 0xBEEF0000 + +# Two 8-case batches covering normals, denormals, subnormal ties, ±0, ±Inf, qNaN, and large/min deltas. +BATCHES = ( + ( + (0xCAFE3C00, 0x00000002), # 1.0h * 2^2 = 4.0h + (0x1234C200, 0xABCDFFFE), # -3.0h * 2^-2 = -0.75h (delta = -2) + (0x00000001, 0x0000000A), # smallest subnormal 2^-24 * 2^10 = smallest normal 2^-14 + (0x00000400, 0x0000FFFF), # smallest normal 2^-14 * 2^-1 = largest subnormal 2^-15 + (0x00000403, 0x0000FFFE), # subnormal round-up (rest > half) + (0x00000402, 0x0000FFFE), # subnormal tie-to-even (even q stays) + (0x00000406, 0x0000FFFE), # subnormal tie-to-even (odd q rounds up) + (0x00007BFF, 0x00000001), # max finite overflow -> +Inf (clamped to 1.0h) + ), + ( + (0x00000000, 0x00000005), # +0.0h pass-through + (0x00008000, 0x0000FFFB), # -0.0h pass-through + (0x00007C00, 0x0000FFF0), # +Inf pass-through (clamped to 1.0h) + (0x0000FC00, 0x00000010), # -Inf pass-through (clamped to 0.0h) + (0x00007E01, 0x00000003), # qNaN pass-through (clamped to 0.0h) + (0x00003C00, 0x00000064), # 1.0h * 2^100 -> +Inf (clamped delta +100 -> +64) + (0x00003C00, 0x0000FF9C), # 1.0h * 2^-100 -> +0.0h (clamped delta -100 -> -64) + (0x00003C00, 0x00008000), # 1.0h * 2^-32768 -> +0.0h (INT16_MIN delta) + ), +) + + +def v_mov_lit(vdst, lit): + return [0x7E0002FF | ((vdst & 0xFF) << 17), lit & MASK] + + +def vop2(op, vdst, src0, vsrc1): + return ((op & 0x3F) << 25) | ((vdst & 0xFF) << 17) | ((vsrc1 & 0xFF) << 9) | (src0 & 0x1FF) + + +def vop3_binary(op, vdst, src0, src1, *, abs_m=0, neg_m=0, clamp=0, omod=0): + w0 = 0xD4000000 | ((op & 0x3FF) << 16) | ((clamp & 1) << 15) | ((abs_m & 7) << 8) | (vdst & 0xFF) + w1 = ((neg_m & 7) << 29) | ((omod & 3) << 27) | ((src1 & 0x1FF) << 9) | (src0 & 0x1FF) + return [w0, w1] + + +def program(batch_idx): + code = [0xBE940304, 0xBE950380, 0xF408080A, 0xFA000020, + 0x8F078C05, 0x34100087, 0x4A101007, 0xBF8CC07F] + for ci, (s0, s1) in enumerate(BATCHES[batch_idx]): + code += v_mov_lit(2, s0) + v_mov_lit(3, s1) + # 0: VOP2 v_ldexp_f16 v4, v2, v3 + code += v_mov_lit(4, HIGH_SEED | 0x1111) + [vop2(0x3B, 4, 258, 3), 0xE0701000 | (4 * (ci * 4 + 0)), 0x80080408] + # 1: batch 0 -> VOP3A v_ldexp_f16 v4, v2, v3; batch 1 -> VOP2 inline float constant 1.0 (src0=242 -> 0x3C00) + if batch_idx == 0: + code += v_mov_lit(4, HIGH_SEED | 0x2222) + vop3_binary(0x13B, 4, 258, 259) + [ + 0xE0701000 | (4 * (ci * 4 + 1)), 0x80080408] + else: + code += v_mov_lit(4, HIGH_SEED | 0x2222) + [vop2(0x3B, 4, 242, 3), + 0xE0701000 | (4 * (ci * 4 + 1)), 0x80080408] + # 2: VOP3A v_ldexp_f16 v4, -v2, v3 + code += v_mov_lit(4, HIGH_SEED | 0x3333) + vop3_binary(0x13B, 4, 258, 259, neg_m=1) + [ + 0xE0701000 | (4 * (ci * 4 + 2)), 0x80080408] + # 3: VOP3A v_ldexp_f16 v4, |v2|, v3 clamp + code += v_mov_lit(4, HIGH_SEED | 0x4444) + vop3_binary(0x13B, 4, 258, 259, abs_m=1, clamp=1) + [ + 0xE0701000 | (4 * (ci * 4 + 3)), 0x80080408] + return code + [0xBF810000] + + +def sext16(v): + v &= 0xFFFF + return v - 0x10000 if (v & 0x8000) else v + + +def ldexp_f16(bits, delta_raw, *, flush_denormals=False, truncate_subnormal=False, drop_keep=False, clamp=False): + bits &= 0xFFFF + delta = max(-64, min(64, sext16(delta_raw))) + sign = bits & 0x8000 + exp = (bits >> 10) & 0x1F + mant = bits & 0x3FF + if not drop_keep and (exp == 0x1F or (bits & 0x7FFF) == 0): + res = bits + else: + if exp == 0: + if flush_denormals: + res = sign + exp = None + else: + steps = 0 + x = mant + while x and (x & 0x400) == 0: + x <<= 1 + steps += 1 + mant = x & 0x3FF + e = 1 - steps + delta + else: + e = exp + delta + if exp is not None: + if e > 30: + res = sign | 0x7C00 + elif e > 0: + res = sign | (e << 10) | mant + elif e < -10: + res = sign + else: + full = 0x400 | mant + amt = 1 - e + half = 1 << (amt - 1) + rest = full & ((1 << amt) - 1) + q = full >> amt + up = 0 if truncate_subnormal else int(rest > half or (rest == half and (q & 1) != 0)) + res = sign | (q + up) + if clamp: + abs_r = res & 0x7FFF + if abs_r > 0x7C00 or (res & 0x8000): + res = 0 + elif res > 0x3BFF: + res = 0x3C00 + return res & 0xFFFF + + +def reference(batch_idx, *, flush_denormals=False, truncate_subnormal=False, drop_keep=False, + inline_as_zero=False, no_clamp=False, zero_high=False): + hi = 0 if zero_high else HIGH_SEED + words = [SENTINEL] * 8 + for _lane in range(64): + for s0, s1 in BATCHES[batch_idx]: + r0 = ldexp_f16(s0, s1, flush_denormals=flush_denormals, truncate_subnormal=truncate_subnormal, + drop_keep=drop_keep) + if batch_idx == 0: + r1 = r0 + else: + r1 = ldexp_f16(0x0000 if inline_as_zero else 0x3C00, s1, + flush_denormals=flush_denormals, truncate_subnormal=truncate_subnormal, + drop_keep=drop_keep) + r_neg = ldexp_f16((s0 & 0xFFFF) ^ 0x8000, s1, flush_denormals=flush_denormals, + truncate_subnormal=truncate_subnormal, drop_keep=drop_keep) + r_abs_clamp = ldexp_f16(s0 & 0x7FFF, s1, flush_denormals=flush_denormals, + truncate_subnormal=truncate_subnormal, drop_keep=drop_keep, clamp=not no_clamp) + words.extend((hi | r0, hi | r1, hi | r_neg, hi | r_abs_clamp)) + return words + [SENTINEL] * 8 + + +def controls(cli, sdk, work, root): + for bi in range(len(BATCHES)): + sub = work / f'b{bi}' + sub.mkdir(exist_ok=True) + marker = request(sub, root, program(bi)) + output = marker.with_suffix('.cso') + result = subprocess.run([cli, sdk, work / 'cache', 'gfx1013-direct-cs@0', marker, output], + capture_output=True, text=True) + assert result.returncode == 0 and output.is_file(), (bi, result.stdout, result.stderr) + dump = subprocess.run([Path(sdk) / 'dxc.exe', '-dumpbin', output], capture_output=True, + text=True, check=True).stdout + assert 'shl i32 ' in dump and 'lshr i32 ' in dump, dump + if bi == 1: + assert '15360' in dump, 'inline float 1.0 must lower to 0x3c00 (15360)' + for tag, bad, msg in ( + ('omod', vop3_binary(0x13B, 4, 258, 259, omod=1) + [0xBF810000], 'unsupported v_ldexp_f16 operand modifiers'), + ('neg_src1', vop3_binary(0x13B, 4, 258, 259, neg_m=2) + [0xBF810000], 'unsupported v_ldexp_f16 operand modifiers'), + ('bad_mode', [0xBFA4000C, vop2(0x3B, 4, 258, 3), 0xBF810000], 'unsupported binary16 rounding or denormal mode'), + ): + sub = work / tag + sub.mkdir(exist_ok=True) + bad_marker = request(sub, root, bad) + bad_res = subprocess.run([cli, sdk, work / 'cache', 'gfx1013-direct-cs@0', bad_marker, + bad_marker.with_suffix('.cso')], capture_output=True, text=True) + assert bad_res.returncode != 0 and msg in (bad_res.stdout + bad_res.stderr), ( + tag, bad_res.stdout, bad_res.stderr) + assert reference(0) != reference(0, flush_denormals=True) + assert reference(0) != reference(0, truncate_subnormal=True) + assert reference(0) != reference(0, no_clamp=True) + assert reference(0) != reference(0, zero_high=True) + assert reference(1) != reference(1, drop_keep=True) + assert reference(1) != reference(1, inline_as_zero=True) + print('v_ldexp_f16 DXIL verified; invalid modifiers/mode refused; all negative controls differ') + return 0 + + +def hardware(replay, sdk, work, root): + for bi in range(len(BATCHES)): + sub = work / f'hw{bi}' + sub.mkdir(exist_ok=True) + marker = request(sub, root, program(bi)) + output = work / f'out_{bi}.bin' + result = subprocess.run([replay, sdk, marker, work / 'cache', '0', output, '--direct']) + if result.returncode == 77: + return 77 + result.check_returncode() + expected = reference(bi) + actual = struct.unpack(f'<{len(expected)}I', output.read_bytes()) + mismatch = next((i for i, (a, e) in enumerate(zip(actual, expected)) if a != e), None) + if mismatch is not None: + raise AssertionError(f'batch={bi} word {mismatch}: got {actual[mismatch]:08x}, expected {expected[mismatch]:08x}') + print(f'batch={bi}: 2048 result words (high halves kept) and 16 guards matched') + return 0 + + +def main(mode, executable, sdk): + with tempfile.TemporaryDirectory(prefix='x2w_native_ldexp_f16_') as temp: + work = Path(temp) + shader = work / 'root.hlsl' + shader.write_text('#define SIG "DescriptorTable(UAV(u0,numDescriptors=8))"') + root = work / 'root.bin' + subprocess.run([Path(sdk) / 'dxc.exe', '-T', 'rootsig_1_1', '-E', 'SIG', '-Fo', root, shader], check=True) + return (controls if mode == 'controls' else hardware)(executable, sdk, work, root.read_bytes()) + + +if __name__ == '__main__': + raise SystemExit(main(sys.argv[1], sys.argv[2], sys.argv[3])) diff --git a/tests/native_mad32_k_check.py b/tests/native_mad32_k_check.py new file mode 100644 index 0000000000..68dfc0849a --- /dev/null +++ b/tests/native_mad32_k_check.py @@ -0,0 +1,289 @@ +"""v_madmk_f32 and v_madak_f32 in the direct C++ Compute and Pixel DXIL paths.""" +from dataclasses import dataclass +import math +from pathlib import Path +import struct +import subprocess +import sys +import tempfile + +from native_direct_container_check import patched_pixel +from native_dpp_quad_check import request +import native_f16_alu_check as F +from native_packed_f16_inline_check import PROLOGUE +from native_scalar_lds_check import vmove +from startup_image_3d_check import FULLSCREEN_VS, compile_hlsl + +OP_CODE = {'madmk': 0x20, 'madak': 0x21} + + +def fbits(x): + return struct.unpack('<I', struct.pack('<f', x))[0] + + +def fval(b): + return struct.unpack('<f', struct.pack('<I', b & 0xFFFFFFFF))[0] + + +def ftz(b): + b &= 0xFFFFFFFF + return b & 0x80000000 if (b & 0x7FFFFFFF) < 0x00800000 else b + + +def mad_ftz(a, b, c, *, fused=False, flush=True): + if flush: + a, b, c = ftz(a), ftz(b), ftz(c) + x, y, z = fval(a), fval(b), fval(c) + if (math.isinf(x) and y == 0.0) or (math.isinf(y) and x == 0.0) or math.isnan(x) or math.isnan(y): + product = math.nan + else: + product = x * y + if fused: + total = product + z if not math.isnan(product) else math.nan + out = 0x7FC00000 if math.isnan(total) else fbits(total) + else: + p = 0x7FC00000 if math.isnan(product) else (ftz(fbits(product)) if flush else fbits(product)) + q = fval(p) + total = q + z if not math.isnan(q) else math.nan + out = 0x7FC00000 if math.isnan(total) else fbits(total) + return ftz(out) if flush else out + + +def is_nan_f32(b): + return (b & 0x7F800000) == 0x7F800000 and (b & 0x007FFFFF) != 0 + + +def same_f32(got, want): + if is_nan_f32(want): + return is_nan_f32(got) + return got == want + + +def vop2_k(op, dst, src0, vsrc1, lit): + w0 = (OP_CODE[op] << 25) | ((dst & 0xFF) << 17) | ((vsrc1 & 0xFF) << 9) | (src0 & 0x1FF) + return [w0, lit & 0xFFFFFFFF] + + +def f32_inline(enc): + inline_f = { + 240: 0x3F000000, 241: 0xBF000000, 242: 0x3F800000, 243: 0xBF800000, + 244: 0x40000000, 245: 0xC0000000, 246: 0x40800000, 247: 0xC0800000, + } + if enc in inline_f: + return inline_f[enc] + if 128 <= enc <= 192: + return enc - 128 + raise ValueError(enc) + + +@dataclass(frozen=True) +class Case: + name: str + op: str + src0_enc: int + src0_val: int + vsrc1_val: int + k_val: int + pixel_safe: bool = True + + def operands(self): + a = f32_inline(self.src0_enc) if 128 <= self.src0_enc < 255 else self.src0_val + if self.op == 'madmk': + return a, self.k_val, self.vsrc1_val + return a, self.vsrc1_val, self.k_val + + def expected(self, **mutation): + return mad_ftz(*self.operands(), **mutation) + + +def all_cases(): + return [ + # 1. Distinct K vs S1 argument positions. + Case('madmk_asymmetric', 'madmk', 257, fbits(3.0), fbits(1.25), fbits(-2.5)), + Case('madak_asymmetric', 'madak', 257, fbits(3.0), fbits(-2.5), fbits(1.25)), + # 2. Unfused product rounding ties: fused FMA differs by 1 ULP. + Case('madmk_unfused_tie_sub', 'madmk', 257, 0x3F800800, fbits(-1.0), 0x3F800800), + Case('madak_unfused_tie_add', 'madak', 257, 0x3F800001, 0x3F800001, 0x3F800003), + # 3. Denormal input flushes (src0, literal K multiplier in madmk, literal K addend in madak). + Case('madmk_ftz_src0', 'madmk', 257, 0x00000001, fbits(1.0), 0x7E800000), + Case('madmk_ftz_lit_k', 'madmk', 257, 0x7E800000, fbits(2.0), 0x80400000), + Case('madak_ftz_lit_k', 'madak', 257, 0x00800000, fbits(1.0), 0x00400000), + # 4. Denormal product flush and denormal sum flush. + Case('madmk_ftz_product', 'madmk', 257, 0x00800000, 0x00800000, fbits(0.5)), + Case('madak_ftz_sum', 'madak', 257, fbits(1.5 * 2.0 ** -63), fbits(2.0 ** -63), 0x80800000, pixel_safe=False), + # 5. SGPR src0 and inline float src0 (242=1.0, 240=0.5). + Case('madmk_sgpr_src0', 'madmk', 10, fbits(2.5), fbits(-0.75), fbits(4.0)), + Case('madak_inline_242', 'madak', 242, 0, fbits(3.5), fbits(-1.5)), + Case('madmk_inline_240', 'madmk', 240, 0, fbits(0.25), fbits(5.0)), + # 6. Inf/zero -> NaN and negative-zero preservation. + Case('madmk_zero_inf_nan', 'madmk', 257, fbits(0.0), fbits(2.0), 0x7F800000, pixel_safe=False), + Case('madak_neg_zero', 'madak', 257, 0x80000000, fbits(1.0), 0x80000000, pixel_safe=False), + ] + + +def emit_case(c: Case): + code = [] + if c.src0_enc >= 256: + code += F.mov(c.src0_enc - 256, c.src0_val) + elif c.src0_enc <= 105: + code += F.smov(c.src0_enc, c.src0_val) + code += F.mov(2, c.vsrc1_val) + code += vop2_k(c.op, 4, c.src0_enc, 2, c.k_val) + return code + + +def compute_program(cases): + code = list(PROLOGUE) + want = [] + for slot, c in enumerate(cases): + code += emit_case(c) + F.store(slot * 4, 4) + want.append(c.expected()) + return code + [0xBF810000], want + + +def refusal_programs(): + return [ + # Non-VOP2 (VOP3 e64) forms of v_madmk_f32 / v_madak_f32 refused. + ([0xD5200004, 0x00020501, 0xBF810000], 'unsupported v_madmk_f32 encoding'), + ([0xD5210004, 0x00020501, 0xBF810000], 'unsupported v_madak_f32 encoding'), + # SDWA and DPP forms remain refused. + ([0x400804F9, 0x06060601, 0xBF810000], 'unimplemented direct SDWA operand profile'), + ([0x420804FA, 0xFF001B01, 0xBF810000], 'SDWA or DPP vector operands'), + ] + + +def check_reference_mutations(items): + baseline = [c.expected() for c in items] + for label, mutation in (('fused', {'fused': True}), ('no_flush', {'flush': False})): + mutated = [c.expected(**mutation) for c in items] + assert mutated != baseline, label + swapped = [mad_ftz(c.operands()[0], c.operands()[2], c.operands()[1]) for c in items] + assert swapped != baseline, 'swapped_k_s1' + + +def ir(dumper): + items = all_cases() + check_reference_mutations(items) + code, want = compute_program(items) + refusals = refusal_programs() + with tempfile.TemporaryDirectory() as tmp: + work = Path(tmp) + run = F.dump(dumper, work, code, 'mad32-k') + assert run.returncode == 0, run.stderr + assert '@dx.op.tertiary.f32(i32 46,' not in run.stdout, run.stdout + stores = sorted(F.interpret(run.stdout)) + assert [addr for addr, _ in stores] == [4 * i for i in range(len(want))], stores[:4] + bad = [(i, items[i].name, hex(got), hex(exp)) + for i, ((_, got), exp) in enumerate(zip(stores, want)) if not same_f32(got, exp)] + assert not bad, bad[:8] + for idx, (prog, why) in enumerate(refusals): + r = F.dump(dumper, work, prog, f'refused-{idx}') + assert r.returncode != 0 and why in r.stderr, (idx, why, r.returncode, r.stderr) + print(f'native_mad32_k IR: {len(want)} cases matched unfused FTZ model; {len(refusals)} refusals matched') + return 0 + + +def controls(cli, sdk, work, root): + items = all_cases() + check_reference_mutations(items) + code, want = compute_program(items) + marker = request(work, root, code) + output = marker.with_suffix('.cso') + result = subprocess.run([cli, sdk, work / 'cache', 'gfx1013-direct-cs@0', marker, output], + capture_output=True, text=True) + assert result.returncode == 0 and output.is_file(), (result.stdout, result.stderr) + dump = subprocess.run([Path(sdk) / 'dxc.exe', '-dumpbin', output], capture_output=True, text=True, check=True).stdout + assert dump.count('fmul') >= len(items) and dump.count('fadd') >= len(items), dump + assert '@dx.op.tertiary.f32(i32 46,' not in dump, dump + assert ' fast ' not in dump and 'contract' not in dump, dump + + refusals = refusal_programs() + for idx, (prog, why) in enumerate(refusals): + m = request(work, root, prog) + o = m.with_suffix(f'.refused{idx}.cso') + r = subprocess.run([cli, sdk, work / 'cache', 'gfx1013-direct-cs@0', m, o], capture_output=True, text=True) + assert r.returncode != 0 and why in r.stderr, (idx, why, r.stdout, r.stderr) + assert not o.exists(), o + + print(f'native_mad32_k controls: compiled {len(want)} cases with separate fmul/fadd; verified {len(refusals)} refusals') + return 0 + + +def hardware(replay, sdk, work, root): + items = all_cases() + code, want = compute_program(items) + marker = request(work, root, code) + output = work / 'out.bin' + run = subprocess.run([replay, sdk, marker, work / 'cache', '0', output, '--direct']) + if run.returncode == 77: + return 77 + run.check_returncode() + words_out = list(struct.unpack(f'<{F.WORDS}I', output.read_bytes())) + expected = {} + for group in range(F.GROUPS): + for lane in range(32): + head = F.BASE + group * 1024 + lane * 32 + for idx, w in enumerate(want): + expected[head + idx] = w + bad = [] + for i, got in enumerate(words_out): + if i in expected: + if not same_f32(got, expected[i]): + bad.append((i, hex(got), hex(expected[i]))) + elif got != F.SENTINEL: + bad.append((i, hex(got), hex(F.SENTINEL))) + assert not bad, bad[:10] + print(f'native_mad32_k compute hardware: {len(want)} cases matched across {F.GROUPS}x32 lanes and guards') + return 0 + + +def pixel_program(quad): + code = [] + for idx, c in enumerate(quad): + code += emit_case(c) + code.append(vmove(8 + idx, 256 + 4)) + return patched_pixel(len(code), code, export=(0xF800180F, 0x0B0A0908)) + + +def pixel(cli, sdk, renderer, adapter, work): + items = [c for c in all_cases() if c.pixel_safe] + while len(items) % 4: + items.append(items[-1]) + vs = compile_hlsl(str(Path(sdk) / 'dxc.exe'), 'dxc', FULLSCREEN_VS, 'fullscreen', 'vs_6_0', work) + quads = [items[i:i + 4] for i in range(0, len(items), 4)] + for idx, quad in enumerate(quads): + shader = work / f'madk-{idx}.ps' + shader.write_bytes(pixel_program(quad)) + cso = shader.with_suffix('.cso') + build = subprocess.run([cli, sdk, work / 'cache', 'gfx1013-container-ps', shader, cso], + capture_output=True, text=True, timeout=30) + assert build.returncode == 0, ([c.name for c in quad], build.stdout, build.stderr) + ref = work / 'expected.bin' + ref.write_bytes(struct.pack('<4I', *(c.expected() for c in quad))) + run = subprocess.run([renderer, adapter, '--startup-pixel-words', vs, cso, '1', '1', ref], + capture_output=True, text=True, timeout=30) + if run.returncode == 77: + return 77 + assert run.returncode == 0, (idx, [c.name for c in quad], run.stdout, run.stderr) + if 'debug_layer=enabled' in run.stdout: + assert 'debug_errors=0 debug_warnings=0' in run.stdout, run.stdout + print(f'native_mad32_k pixel ({adapter}): {len(quads)} quad draws matched') + return 0 + + +def main(mode, tool, sdk=None, *args): + if mode == 'ir': + return ir(tool) + with tempfile.TemporaryDirectory() as tmp: + work = Path(tmp) + if mode == 'pixel': + return pixel(tool, sdk, args[0], args[1], work) + shader = work / 'root.hlsl' + shader.write_text('#define SIG "DescriptorTable(UAV(u0,numDescriptors=8))"') + root = work / 'root.bin' + subprocess.run([Path(sdk) / 'dxc.exe', '-T', 'rootsig_1_1', '-E', 'SIG', '-Fo', root, shader], check=True) + return {'controls': controls, 'compute': hardware}[mode](tool, sdk, work, root.read_bytes()) + + +if __name__ == '__main__': + sys.exit(main(*sys.argv[1:])) diff --git a/tests/native_mtbuf_check.py b/tests/native_mtbuf_check.py index 0753d9f042..fe3a740291 100644 --- a/tests/native_mtbuf_check.py +++ b/tests/native_mtbuf_check.py @@ -88,7 +88,7 @@ def main(cli, gpu, sdk): src, root = work / "root.hlsl", work / "root.bin" src.write_text('#define SIG "DescriptorTable(SRV(t0,numDescriptors=8)),DescriptorTable(UAV(u0,numDescriptors=8))"') subprocess.run([Path(sdk)/"dxc.exe", "-T", "rootsig_1_1", "-E", "SIG", "-Fo", root, src], check=True) - sa = struct.pack("<7I", 0, 0, 0, 32 | 1 << 16, 1, 0, 0x8c) + sa = struct.pack("<7I", 0, 0, 0, 32 | 1 << 16, 1 | (1 << 20), 0, 0x8c) reference = [0x69696969] * 2064 for group in range(2): start = 8 + 128 * group diff --git a/tests/native_or_saveexec_check.py b/tests/native_or_saveexec_check.py new file mode 100644 index 0000000000..8f9b4cd133 --- /dev/null +++ b/tests/native_or_saveexec_check.py @@ -0,0 +1,79 @@ +"""Direct wave32 s_or_saveexec_b32: saved EXEC, the OR result, SCC and a restore, in full and partial waves.""" +from pathlib import Path +import struct +import subprocess +import sys +import tempfile + +from native_compute_clear_check import write_request +from native_scalar_lds_check import scalar, sop1, vmove + + +def or_saveexec_readback(work, gpu, sdk): + full = 0xffffffff + root = (work / "root.bin").read_bytes() + for width in (8, 32): + entry = (1 << width) - 1 + sa = struct.pack("<7I", 0, 0, 0, width | 1 << 16, 1, 0, 0x80 | 5 << 1) + for name, old, src, mask in ( + ("all", 0x25, 193, full), + ("sgpr", 0x25, 10, 0x80000092), # Source aliases the saved EXEC destination. + ("literal", 0x25, 255, 0x80000018), + ("vcc", 0x25, 106, 0x80000042), + ("empty", 0, 128, 0), + ("past-end", 0, 255, 0x80000000), + ): + updated = old | mask # EXEC is stored as computed, including bits past the group + words = [sop1(3, 20, 4), sop1(3, 21, 128), 0xf408080a, 0xfa000020, + scalar(0x1e, 7, 5, 137), 0x34000000 | 8 << 17 | 132, + 0x4a000000 | 8 << 17 | 8 << 9 | 7, + sop1(0x3c, 24, 255), old] + if src in (10, 106): + words += [sop1(3, src, 255), mask] + if name == "all": + words.append(sop1(3, 10, 32)) # Replace symbolic descriptor provenance with numeric EXEC. + if name == "vcc": + # Derive the same partial EXEC through S_ANDN2_WREXEC_B32. + words += [sop1(3, 126, 255), entry ^ old, sop1(0x47, 25, 24)] + # Set the incoming SCC opposite to the expected new SCC. + words += [0xbf068180 if updated else 0xbf068080, sop1(0x3d, 10, src)] + if src == 255: + words.append(mask) + words += [scalar(0xa, 11, 129, 128), vmove(9, 10), vmove(10, 126), + 0xe0701000, 0x80080908, 0xe0701004, 0x80080a08, + sop1(3, 126, 10), vmove(9, 177), 0xe0701008, 0x80080908, + sop1(3, 126, 24), vmove(9, 11), 0xe070100c, 0x80080908, + 0xbf810000] + expected = [0x69696969] * 2064 + for group in range(2): + for lane in range(width): + pos = 8 + group * 128 + lane * 4 + if updated & (1 << lane): + expected[pos:pos + 2] = [old, updated] + if old & (1 << lane): + expected[pos + 2] = 49 + expected[pos + 3] = int(bool(updated)) + marker = write_request(work, words, root, sa) + dest = work / "or-saveexec.bin" + result = subprocess.run([gpu, sdk, marker, work / "cache", "0", dest, "--direct"]) + if result.returncode == 77: + sys.exit(77) + result.check_returncode() + actual = struct.unpack("<2064I", dest.read_bytes()) + assert list(actual) == expected, (width, name, [ + (i, a, b) for i, (a, b) in enumerate(zip(actual, expected)) if a != b + ][:10]) + + +def main(gpu, sdk): + with tempfile.TemporaryDirectory() as temp: + work = Path(temp) + src, root = work / "root.hlsl", work / "root.bin" + src.write_text('#define SIG "DescriptorTable(UAV(u0,numDescriptors=8))"') + subprocess.run([Path(sdk) / "dxc.exe", "-T", "rootsig_1_1", "-E", "SIG", "-Fo", root, src], check=True) + or_saveexec_readback(work, gpu, sdk) + print("s_or_saveexec_b32 matched six sources in 8- and 32-thread groups, with SCC, restore and guards.") + + +if __name__ == "__main__": + main(*sys.argv[1:]) diff --git a/tests/native_pack_b32_f16_check.py b/tests/native_pack_b32_f16_check.py index efa2e4f8a3..679c5be908 100644 --- a/tests/native_pack_b32_f16_check.py +++ b/tests/native_pack_b32_f16_check.py @@ -164,7 +164,7 @@ def run_gpu(gpu, sdk): src, root = work / 'root.hlsl', work / 'root.bin' src.write_text('#define SIG "DescriptorTable(UAV(u0,numDescriptors=8))"') subprocess.run([Path(sdk) / 'dxc.exe', '-T', 'rootsig_1_1', '-E', 'SIG', '-Fo', root, src], check=True) - sa = struct.pack('<7I', 0, 0, 0, 32 | 1 << 16, 1, 0, 0x80 | 5 << 1) + sa = struct.pack('<7I', 0, 0, 0, 32 | 1 << 16, 1 | (1 << 20), 0, 0x80 | 5 << 1) checked = 0 for a, b in PAIRS: # Same preamble as half_mad_readback in native_scalar_lds_check.py: s20:21 table, v8 = group * 512 bytes (STRIDE words). diff --git a/tests/native_packed_f16_check.py b/tests/native_packed_f16_check.py index aea34cac6a..4bfd8e1a7d 100644 --- a/tests/native_packed_f16_check.py +++ b/tests/native_packed_f16_check.py @@ -103,8 +103,11 @@ def controls(cli, sdk, work): dump = subprocess.run([Path(sdk) / 'dxc.exe', '-dumpbin', output], check=True, capture_output=True, text=True).stdout assert 'fadd float' in dump and 'fmul float' in dump and '@dx.op.unaryBits.i32(i32 33,' in dump, dump + clamped_source = request(work, root, compute_program(CASES[:1], bad=0x8000)) + clamped_output, clamped_run = compile_shader(cli, sdk, work, 'gfx1013-direct-cs@0', clamped_source) + assert clamped_run.returncode == 0 and clamped_output.is_file(), clamped_run.stdout + clamped_run.stderr for options, message in ( - ({'bad': 0x8000}, 'packed binary16 arithmetic encoding'), + ({'bad': 0x0400}, 'packed binary16 arithmetic encoding'), ({'bad': 0x2000}, 'packed binary16 arithmetic encoding'), ({'mode': (0xBFA50003,)}, 'binary16 rounding or denormal mode'), ({'mode': (0xBFA40004,)}, 'binary16 rounding or denormal mode'), @@ -112,7 +115,7 @@ def controls(cli, sdk, work): source = request(work, root, compute_program(CASES[:1], **options)) _, run = compile_shader(cli, sdk, work, 'gfx1013-direct-cs@0', source) assert run.returncode and message in run.stderr, (options, run.stderr) - print('ADD/MUL and integer FMA compiled; unsupported modifiers and modes were refused') + print('ADD/MUL and integer FMA compiled (including clamp); unsupported modifiers and modes were refused') def operands(case, high): diff --git a/tests/native_packed_f16_clamp_check.py b/tests/native_packed_f16_clamp_check.py new file mode 100644 index 0000000000..70663247cc --- /dev/null +++ b/tests/native_packed_f16_clamp_check.py @@ -0,0 +1,292 @@ +"""Direct DXIL VOP3P clamp on v_pk_add_f16, v_pk_mul_f16, and v_pk_fma_f16 in Compute and Pixel shaders.""" +from dataclasses import dataclass +from pathlib import Path +import struct +import subprocess +import sys +import tempfile + +from f16_packed_model import half_op +from native_direct_container_check import patched_pixel +from native_dpp_mirror_check import vop2 +from native_dpp_quad_check import request +import native_f16_alu_check as F +from native_packed_f16_inline_check import PROLOGUE, inline_word, vop3p +from native_scalar_lds_check import sop1 +from startup_image_3d_check import FULLSCREEN_VS, compile_hlsl + +ALL_EXEC = 0xFFFFFFFF +DST_INIT = 0xDEADCAFE + + +def clamp_f16(bits): + bits &= 0xFFFF + if (bits & 0x7FFF) > 0x7C00 or (bits & 0x8000): + return 0x0000 + return 0x3C00 if bits > 0x3BFF else bits + + +def eval_clamp_case(op_name, raw_words, op_sel, op_sel_hi, neg_lo, neg_hi, clamp): + arity = 3 if op_name == 'fma' else 2 + + def lane_eval(high): + sel = op_sel_hi if high else op_sel + neg = neg_hi if high else neg_lo + ops = [] + for j in range(arity): + half = (raw_words[j] >> (16 if ((sel >> j) & 1) else 0)) & 0xFFFF + if (neg >> j) & 1: + half ^= 0x8000 + ops.append(half) + res = half_op(op_name, *ops) + return clamp_f16(res) if clamp else res + + return lane_eval(False) | (lane_eval(True) << 16) + + +@dataclass(frozen=True) +class Case: + name: str + op: str + srcs: tuple + vals: tuple + op_sel: int = 0 + op_sel_hi: int = 7 + neg_lo: int = 0 + neg_hi: int = 0 + clamp: int = 1 + exec_mask: int = ALL_EXEC + + def raw_words(self): + return tuple(v & 0xFFFFFFFF if (s < 128 or s >= 255) else inline_word(s) + for s, v in zip(self.srcs, self.vals)) + + def expected(self, lane=0): + if ((self.exec_mask >> lane) & 1) == 0: + return DST_INIT + return eval_clamp_case(self.op, self.raw_words(), self.op_sel, self.op_sel_hi, + self.neg_lo, self.neg_hi, self.clamp) + + +def all_cases(): + return [ + # 1. v_pk_add_f16: negative finite, -0.0, subnormals, interior (0,1), >= 1.0, +/-Inf, NaN, and unclamped contrast. + Case('add_neg_and_over_one', 'add', (257, 258), ((0x4000 << 16) | 0xBC00, (0x3800 << 16) | 0xB800)), + Case('add_neg_zero_and_lt_one', 'add', (257, 258), ((0x3BFF << 16) | 0x8000, (0x0000 << 16) | 0x8000)), + Case('add_subnormals_exact_one', 'add', (257, 258), ((0x3800 << 16) | 0x0001, (0x3800 << 16) | 0x0000)), + Case('add_pos_inf_and_nan', 'add', (257, 258), ((0x7C00 << 16) | 0x7E01, (0x3C00 << 16) | 0x3C00)), + Case('add_neg_inf_and_inf_minus_inf', 'add', (257, 258), ((0xFC00 << 16) | 0x7C00, (0x3C00 << 16) | 0xFC00)), + Case('add_unclamped_contrast', 'add', (257, 258), ((0x7C00 << 16) | 0xBC00, (0x3C00 << 16) | 0xB800), clamp=0), + # 2. v_pk_mul_f16: subnormal normal-product, -0.0, interior, overflow/+Inf -> 1.0, -Inf/Inf*0 NaN -> +0.0. + Case('mul_subnormal_and_neg_zero', 'mul', (257, 258), ((0x0400 << 16) | 0x8000, (0x3800 << 16) | 0x3C00)), + Case('mul_overflow_and_interior', 'mul', (257, 258), ((0x7BFF << 16) | 0x3800, (0x4000 << 16) | 0x3800)), + Case('mul_neg_inf_and_inf_times_zero', 'mul', (257, 258), ((0xFC00 << 16) | 0x7C00, (0x3C00 << 16) | 0x0000)), + Case('mul_neg_finite_and_max_subnormal', 'mul', (257, 258), ((0xBC00 << 16) | 0x03FF, (0x3800 << 16) | 0x3C00)), + # 3. v_pk_fma_f16: negative/-0, subnormals, exact 1.0, 0x3BFF edge, overflow avoidance, +/-Inf, Inf*0 NaN. + Case('fma_neg_and_over_one', 'fma', (257, 258, 259), + ((0x4000 << 16) | 0xBC00, (0x4000 << 16) | 0x3C00, (0x0000 << 16) | 0x3800)), + Case('fma_subnormal_and_exact_one', 'fma', (257, 258, 259), + ((0x3800 << 16) | 0x3800, (0x0400 << 16) | 0x3800, (0x0001 << 16) | 0x3A00)), + Case('fma_near_one_and_overflow_avoid', 'fma', (257, 258, 259), + ((0x7BFF << 16) | 0x3800, (0x4000 << 16) | 0x4000, (0xFBFF << 16) | 0x9000)), + Case('fma_nan_and_inf_zero', 'fma', (257, 258, 259), + ((0x7E01 << 16) | 0x7C00, (0x3C00 << 16) | 0x0000, (0x3C00 << 16) | 0x3C00)), + Case('fma_neg_zero_and_neg_inf', 'fma', (257, 258, 259), + ((0x8000 << 16) | 0xFC00, (0x3C00 << 16) | 0x3C00, (0x8000 << 16) | 0x0000)), + # 4. VOP3P selectors (op_sel / op_sel_hi) + neg_lo / neg_hi combined with clamp. + Case('add_opsel_neg_clamp', 'add', (257, 258), + ((0x3800 << 16) | 0x4000, (0x3C00 << 16) | 0xBC00), op_sel=0b01, op_sel_hi=0b10, neg_lo=0b10, neg_hi=0b01), + Case('mul_opsel_neg_clamp', 'mul', (257, 258), + ((0x3800 << 16) | 0xC000, (0x4000 << 16) | 0x3C00), op_sel=0b10, op_sel_hi=0b01, neg_lo=0b01, neg_hi=0b10), + Case('fma_opsel_neg_clamp', 'fma', (257, 258, 259), + ((0x3800 << 16) | 0x4000, (0x4000 << 16) | 0x3800, (0xBC00 << 16) | 0x3400), + op_sel=0b101, op_sel_hi=0b010, neg_lo=0b100, neg_hi=0b011), + # 5. SGPR, literal (255), inline f16 float (242/243/240), inline int (193 NaN -> +0.0 under clamp). + Case('add_sgpr_literal_clamp', 'add', (10, 255), ((0x4000 << 16) | 0xBC00, (0x3800 << 16) | 0x3800)), + Case('mul_inline_242_243_clamp', 'mul', (257, 243), ((0x3800 << 16) | 0xBC00, 0), + op_sel=0, op_sel_hi=0b101, neg_lo=0b10), + Case('fma_inline_int_193_nan_clamp', 'fma', (257, 240, 193), ((0x4000 << 16) | 0x3C00, 0, 0), + op_sel=0, op_sel_hi=0b101), + # 6. Partial EXEC_LO mask: inactive lanes keep DST_INIT. + Case('fma_partial_exec_clamp', 'fma', (257, 258, 259), + ((0x4000 << 16) | 0xBC00, (0x3C00 << 16) | 0x3C00, (0x0000 << 16) | 0x0000), + exec_mask=0xAAAAAAAA), + ] + + +def emit_case(c: Case): + code = F.mov(4, DST_INIT) + if c.exec_mask != ALL_EXEC: + code += [sop1(3, 126, 255), c.exec_mask] + lit_tail = [] + for s, v in zip(c.srcs, c.vals): + if s >= 256: + code += F.mov(s - 256, v) + elif s <= 105: + code += F.smov(s, v) + elif s == 255: + lit_tail = [v] + code += vop3p(c.op, 4, c.srcs, op_sel=c.op_sel, op_sel_hi=c.op_sel_hi, + neg_lo=c.neg_lo, neg_hi=c.neg_hi, clamp=c.clamp) + code += lit_tail + if c.exec_mask != ALL_EXEC: + code += [sop1(3, 126, 193)] + return code + + +def compute_program(cases): + assert len(cases) <= 32, len(cases) + code = list(PROLOGUE) + for slot, c in enumerate(cases): + code += emit_case(c) + F.store(slot * 4, 4) + return code + [0xBF810000] + + +def refusal_programs(): + cond_mode = [0xBF840001, 0xBFA5000F] # s_cbranch_scc0 +1; s_denorm_mode 15 + clamped_add = vop3p('add', 4, (257, 258), clamp=1) + [0xBF810000] + add_bad_src2 = vop3p('add', 4, (257, 258), clamp=1) + add_bad_src2[1] |= 259 << 18 + fmac_e64_clamp = [0xD53C8004, (258 << 9) | 257] # VOP3 e64 v_pk_fmac_f16 with clamp=1 + return [ + # Unused third-operand fields and VOP3 e64 v_pk_fmac_f16 clamp refused. + (add_bad_src2 + [0xBF810000], 'unsupported packed binary16 arithmetic encoding'), + (fmac_e64_clamp + [0xBF810000], 'unsupported packed binary16 arithmetic encoding'), + (vop3p('mul', 4, (257, 258), op_sel=4, clamp=1) + [0xBF810000], 'unsupported packed binary16 arithmetic encoding'), + (vop3p('add', 4, (257, 258), neg_lo=4, clamp=1) + [0xBF810000], 'unsupported packed binary16 arithmetic encoding'), + (vop3p('mul', 4, (257, 258), neg_hi=4, clamp=1) + [0xBF810000], 'unsupported packed binary16 arithmetic encoding'), + # Special scalar source refused. + (vop3p('fma', 4, (257, 106, 259), clamp=1) + [0xBF810000], 'unsupported packed binary16 arithmetic source'), + # Unsupported binary16 rounding/denormal modes and dynamic conditional MODE write. + ([0xBFA40004] + clamped_add, 'unsupported binary16 rounding or denormal mode'), + ([0xBFA50003] + clamped_add, 'unsupported binary16 rounding or denormal mode'), + (cond_mode + clamped_add, 'unsupported binary16 rounding or denormal mode'), + ] + + +def ir(dumper): + items = all_cases() + code = compute_program(items) + want = [c.expected(lane=0) for c in items] + refusals = refusal_programs() + with tempfile.TemporaryDirectory() as tmp: + work = Path(tmp) + run = F.dump(dumper, work, code, 'packed-f16-clamp') + assert run.returncode == 0, run.stderr + stores = sorted(F.interpret(run.stdout)) + assert [addr for addr, _ in stores] == [4 * i for i in range(len(want))], stores[:4] + bad = [(i, items[i].name, hex(got), hex(exp)) + for i, ((_, got), exp) in enumerate(zip(stores, want)) if got != exp] + assert not bad, bad[:8] + for idx, (refused, why) in enumerate(refusals): + r = F.dump(dumper, work, refused, f'refused-{idx}') + assert r.returncode != 0 and why in r.stderr, (idx, why, r.returncode, r.stderr) + print(f'native_packed_f16_clamp IR: {len(want)} cases matched exact model; {len(refusals)} refusals matched') + return 0 + + +def controls(cli, sdk, work, root): + items = all_cases() + code = compute_program(items) + marker = request(work, root, code) + output = marker.with_suffix('.cso') + result = subprocess.run([cli, sdk, work / 'cache', 'gfx1013-direct-cs@0', marker, output], + capture_output=True, text=True) + assert result.returncode == 0 and output.is_file(), (result.stdout, result.stderr) + dump = subprocess.run([Path(sdk) / 'dxc.exe', '-dumpbin', output], capture_output=True, text=True, check=True).stdout + assert 'fadd float' in dump and 'fmul float' in dump and '@dx.op.unaryBits.i32(i32 33,' in dump, dump + + refusals = refusal_programs() + for idx, (prog, why) in enumerate(refusals): + m = request(work, root, prog) + o = m.with_suffix(f'.refused{idx}.cso') + r = subprocess.run([cli, sdk, work / 'cache', 'gfx1013-direct-cs@0', m, o], capture_output=True, text=True) + assert r.returncode != 0 and why in r.stderr, (idx, why, r.stdout, r.stderr) + assert not o.exists(), o + + print(f'native_packed_f16_clamp controls: compiled {len(items)} cases to DXIL; verified {len(refusals)} refusals') + return 0 + + +def hardware(replay, sdk, work, root): + items = all_cases() + code = compute_program(items) + marker = request(work, root, code) + output = work / 'out.bin' + run = subprocess.run([replay, sdk, marker, work / 'cache', '0', output, '--direct']) + if run.returncode == 77: + return 77 + run.check_returncode() + words_out = list(struct.unpack(f'<{F.WORDS}I', output.read_bytes())) + expected = {} + for group in range(F.GROUPS): + for lane in range(32): + head = F.BASE + group * 1024 + lane * 32 + for idx, c in enumerate(items): + expected[head + idx] = c.expected(lane=lane) + bad = [] + for i, got in enumerate(words_out): + if i in expected: + if got != expected[i]: + bad.append((i, hex(got), hex(expected[i]))) + elif got != F.SENTINEL: + bad.append((i, hex(got), hex(F.SENTINEL))) + assert not bad, bad[:10] + print(f'native_packed_f16_clamp compute hardware: {len(items)} cases matched across {F.GROUPS}x32 lanes and guards') + return 0 + + +def pixel_program(pair): + code = [] + for idx, c in enumerate(pair): + code += emit_case(c) + lo_reg, hi_reg = 8 + 2 * idx, 9 + 2 * idx + code += [vop2(0x1B, lo_reg, 255, 4), 65535, vop2(0x16, hi_reg, 144, 4)] + # Each 16-bit half is exactly representable in binary32 as an integer in 0..65535. + code += [0x7E000C00 | reg << 17 | (256 + reg) for reg in (lo_reg, hi_reg)] + return patched_pixel(len(code), code, export=(0xF800180F, 0x0B0A0908)) + + +def pixel(cli, sdk, renderer, adapter, work): + items = [c for c in all_cases() if c.exec_mask == ALL_EXEC] + if len(items) % 2: + items.append(items[-1]) + vs = compile_hlsl(str(Path(sdk) / 'dxc.exe'), 'dxc', FULLSCREEN_VS, 'fullscreen', 'vs_6_0', work) + pairs = [items[i:i + 2] for i in range(0, len(items), 2)] + for idx, pair in enumerate(pairs): + shader = work / f'packed-f16-clamp-{idx}.ps' + shader.write_bytes(pixel_program(pair)) + cso = shader.with_suffix('.cso') + build = subprocess.run([cli, sdk, work / 'cache', 'gfx1013-container-ps', shader, cso], + capture_output=True, text=True, timeout=30) + assert build.returncode == 0, ([c.name for c in pair], build.stdout, build.stderr) + w0, w1 = pair[0].expected(), pair[1].expected() + ref = work / 'expected.bin' + ref.write_bytes(struct.pack('<4f', w0 & 0xFFFF, w0 >> 16, w1 & 0xFFFF, w1 >> 16)) + run = subprocess.run([renderer, adapter, '--startup-pixel-words', vs, cso, '1', '1', ref], + capture_output=True, text=True, timeout=30) + if run.returncode == 77: + return 77 + assert run.returncode == 0, (idx, [c.name for c in pair], run.stdout, run.stderr) + if 'debug_layer=enabled' in run.stdout: + assert 'debug_errors=0 debug_warnings=0' in run.stdout, run.stdout + print(f'native_packed_f16_clamp pixel ({adapter}): {len(pairs)} pixel draws ({len(items)} cases) matched') + return 0 + + +def main(mode, tool, sdk=None, *args): + if mode == 'ir': + return ir(tool) + with tempfile.TemporaryDirectory() as tmp: + work = Path(tmp) + if mode == 'pixel': + return pixel(tool, sdk, args[0], args[1], work) + shader = work / 'root.hlsl' + shader.write_text('#define SIG "DescriptorTable(UAV(u0,numDescriptors=8))"') + root = work / 'root.bin' + subprocess.run([Path(sdk) / 'dxc.exe', '-T', 'rootsig_1_1', '-E', 'SIG', '-Fo', root, shader], check=True) + return {'controls': controls, 'compute': hardware}[mode](tool, sdk, work, root.read_bytes()) + + +if __name__ == '__main__': + sys.exit(main(*sys.argv[1:])) diff --git a/tests/native_packed_f16_inline_check.py b/tests/native_packed_f16_inline_check.py new file mode 100644 index 0000000000..df66932ff7 --- /dev/null +++ b/tests/native_packed_f16_inline_check.py @@ -0,0 +1,328 @@ +"""Direct DXIL packed binary16 arithmetic and min/max with inline constant sources.""" +from dataclasses import dataclass +from fractions import Fraction +from pathlib import Path +import struct +import subprocess +import sys +import tempfile + +from f16_packed_model import half_op +from native_direct_container_check import patched_pixel +from native_dpp_mirror_check import vop2 +from native_dpp_quad_check import request +import native_f16_alu_check as F +from native_scalar_lds_check import sop1 +from startup_image_3d_check import FULLSCREEN_VS, compile_hlsl + + +OPS_3SRC = {'fma': 0x0e} +OPS_2SRC = {'add': 0x0f, 'mul': 0x10, 'min_f16': 0x11, 'max_f16': 0x12, 'min_u16': 0x0d, 'max_i16': 0x07} +OPS = {**OPS_3SRC, **OPS_2SRC} + +INLINE_F16_WORDS = { + 240: 0x3800, 241: 0xB800, 242: 0x3C00, 243: 0xBC00, + 244: 0x4000, 245: 0xC000, 246: 0x4400, 247: 0xC400, + 248: 0x3118, +} + +GUARD = 0x69696969 +PROLOGUE = [0xBE940304, 0xBE950380, 0xF408080A, 0xFA000020, 0x8F078C05, 0x34100087, 0x4A101007, 0xBF8CC07F] + + +def inline_word(enc): + if enc in INLINE_F16_WORDS: + return INLINE_F16_WORDS[enc] + if 128 <= enc <= 192: + return enc - 128 + if 193 <= enc <= 208: + return (192 - enc) & 0xFFFFFFFF + raise ValueError(enc) + + +def vop3p(op_name, dst, srcs, *, op_sel=0, op_sel_hi=7, neg_lo=0, neg_hi=0, clamp=0): + arity = 3 if op_name in OPS_3SRC else 2 + s0, s1 = srcs[0], srcs[1] + s2 = srcs[2] if arity == 3 else 0 + # Default op_sel_hi[2]=1 for 2-src instructions (LLVM MC convention). + hi2 = (op_sel_hi >> 2) & 1 if arity == 3 else 1 + w0 = (0xCC000000 | (OPS[op_name] << 16) | ((clamp & 1) << 15) | + (hi2 << 14) | ((op_sel & 7) << 11) | ((neg_hi & 7) << 8) | (dst & 0xFF)) + w1 = ((neg_lo & 7) << 29) | ((op_sel_hi & 3) << 27) | ((s2 & 0x1FF) << 18) | ((s1 & 0x1FF) << 9) | (s0 & 0x1FF) + return [w0, w1] + + +def f16_key(bits): + bits &= 0xFFFF + return (bits ^ 0xFFFF) if (bits & 0x8000) else (bits ^ 0x8000) + + +def f16_minmax(a, b, is_max): + a &= 0xFFFF + b &= 0xFFFF + a_nan = (a & 0x7FFF) > 0x7C00 + b_nan = (b & 0x7FFF) > 0x7C00 + if a_nan and b_nan: + return 0x7E00 + if a_nan: + return b + if b_nan: + return a + ka, kb = f16_key(a), f16_key(b) + return (a if ka > kb else b) if is_max else (a if ka < kb else b) + + +def int16_minmax(a, b, is_max, signed): + a &= 0xFFFF + b &= 0xFFFF + if signed: + sa = a - 0x10000 if (a & 0x8000) else a + sb = b - 0x10000 if (b & 0x8000) else b + return (a if sa > sb else b) if is_max else (a if sa < sb else b) + return (a if a > b else b) if is_max else (a if a < b else b) + + +def eval_case(op_name, raw_words, op_sel, op_sel_hi, neg_lo, neg_hi): + arity = 3 if op_name in OPS_3SRC else 2 + + def lane_eval(high): + sel = op_sel_hi if high else op_sel + neg = neg_hi if high else neg_lo + ops = [] + for j in range(arity): + half = (raw_words[j] >> (16 if ((sel >> j) & 1) else 0)) & 0xFFFF + if (neg >> j) & 1: + half ^= 0x8000 + ops.append(half) + if op_name in ('add', 'mul', 'fma'): + return half_op(op_name, *ops) + if op_name == 'min_f16': + return f16_minmax(ops[0], ops[1], False) + if op_name == 'max_f16': + return f16_minmax(ops[0], ops[1], True) + if op_name == 'min_u16': + return int16_minmax(ops[0], ops[1], False, False) + if op_name == 'max_i16': + return int16_minmax(ops[0], ops[1], True, True) + raise ValueError(op_name) + + return lane_eval(False) | (lane_eval(True) << 16) + + +@dataclass(frozen=True) +class Case: + name: str + op: str + srcs: tuple # encoding per operand (>=256 for VGPR v[idx-256], <=105 for SGPR, 128..208/240..248 inline, 255 literal) + vals: tuple # 32-bit raw value per operand (ignored for inline; used for VGPR/SGPR/literal) + op_sel: int = 0 + op_sel_hi: int = 7 + neg_lo: int = 0 + neg_hi: int = 0 + + def raw_words(self): + return tuple(inline_word(s) if 128 <= s < 255 else v for s, v in zip(self.srcs, self.vals)) + + def expected(self): + return eval_case(self.op, self.raw_words(), self.op_sel, self.op_sel_hi, self.neg_lo, self.neg_hi) + + +def all_cases(): + items = [] + # 1. All 9 inline binary16 float constants (240..248) broadcast to both lanes via op_sel=0, op_sel_hi=0. + base_vec = (0x4200 << 16) | 0x3E00 # hi=3.0, lo=1.5 + for enc in range(240, 249): + items.append(Case(f'mul_inline_{enc}_broadcast', 'mul', (257, enc), (base_vec, 0), op_sel=0, op_sel_hi=0b101)) + # 2. gfx1013 high-half zeroing on inline float constants (op_sel_hi selects bit 1 -> reads +0.0 = 0x0000). + items.append(Case('add_inline_242_hi_zero', 'add', (257, 242), ((0x4000 << 16) | 0x3C00, 0), op_sel=0, op_sel_hi=0b111)) + items.append(Case('mul_inline_244_lo_hi_zero', 'mul', (244, 257), (0, (0x4200 << 16) | 0x3C00), op_sel=0b001, op_sel_hi=0b111)) + # 3. neg_lo and neg_hi on inline float constants (including negating zeroed high half -> -0.0 = 0x8000). + items.append(Case('add_inline_242_neg_hi_zero', 'add', (257, 242), ((0x8000 << 16) | 0x3C00, 0), + op_sel=0, op_sel_hi=0b111, neg_lo=0b10, neg_hi=0b10)) + items.append(Case('mul_inline_240_neg_broadcast', 'mul', (257, 240), ((0x4400 << 16) | 0x4000, 0), + op_sel=0, op_sel_hi=0b101, neg_lo=0b10, neg_hi=0b10)) + # 4. Single-rounding FMA tie witness with inline float 240 (0.5) and inline int 129 (0x0001 = 2^-24). + # Low lane: (1 + 2^-10) * 0.5 + 2^-24 -> 0x3801 (double-rounded f32 product would give 0x3800). + # High lane: (1 + 3*2^-10) * 0.5 + 0 -> 0x3802. + items.append(Case('fma_inline_tie_pos', 'fma', (257, 240, 129), ((0x3C03 << 16) | 0x3C01, 0, 0), + op_sel=0, op_sel_hi=0b101)) + # Negative tie witness using neg_lo/neg_hi on inline 240 and inline 129 in src2 + SGPR src0. + items.append(Case('fma_inline_src0_242_src2_241', 'fma', (242, 257, 241), (0, (0x4000 << 16) | 0x3C00, 0), + op_sel=0, op_sel_hi=0b010)) + # 5. Inline integer constants: 128 (0), 129 (1=0x00000001), 192 (64=0x00000040), + # 193 (-1=0xffffffff -> NaN in both halves), 208 (-16=0xfffffff0 -> NaN hi, fff0=NaN lo). + items.append(Case('add_inline_int_192', 'add', (257, 192), ((0x4000 << 16) | 0x3C00, 0), op_sel=0, op_sel_hi=0b111)) + items.append(Case('fma_inline_int_193_nan', 'fma', (257, 242, 193), ((0x4000 << 16) | 0x3C00, 0, 0), + op_sel=0, op_sel_hi=0b101)) + items.append(Case('add_inline_int_208_nan', 'add', (257, 208), ((0x4000 << 16) | 0x3C00, 0), op_sel=0, op_sel_hi=0b111)) + # 6. Packed f16 min/max with inline float constants (242, 243, 244, high-half zeroing, and 193 NaN selecting numeric). + items.append(Case('min_f16_inline_242_broadcast', 'min_f16', (257, 242), ((0x4000 << 16) | 0x3800, 0), op_sel=0, op_sel_hi=0b101)) + items.append(Case('max_f16_inline_243_hi_zero', 'max_f16', (257, 243), ((0x8000 << 16) | 0xBC00, 0), op_sel=0, op_sel_hi=0b111)) + items.append(Case('min_f16_inline_193_nan', 'min_f16', (193, 257), (0, (0x4000 << 16) | 0x3C00), op_sel=0, op_sel_hi=0b111)) + items.append(Case('max_f16_inline_248_sgpr', 'max_f16', (10, 248), ((0x3400 << 16) | 0x3000, 0), op_sel=0, op_sel_hi=0b101)) + # 7. Packed integer min/max with inline integers (128, 129, 192, 193=-1, 208=-16). + items.append(Case('min_u16_inline_192', 'min_u16', (257, 192), ((0x0010 << 16) | 0x0050, 0), op_sel=0, op_sel_hi=0b111)) + items.append(Case('max_i16_inline_193_208', 'max_i16', (193, 208), (0, 0), op_sel=0, op_sel_hi=0b111)) + return items + + +def emit_case(c: Case): + code = [] + lit_tail = [] + for idx, (s, v) in enumerate(zip(c.srcs, c.vals)): + if s >= 256: + code += F.mov(s - 256, v) + elif s <= 105: + code += F.smov(s, v) + elif s == 255: + lit_tail = [v] + code += vop3p(c.op, 4, c.srcs, op_sel=c.op_sel, op_sel_hi=c.op_sel_hi, neg_lo=c.neg_lo, neg_hi=c.neg_hi) + code += lit_tail + return code + + +def compute_program(cases): + code = list(PROLOGUE) + want = [] + for slot, c in enumerate(cases): + code += emit_case(c) + F.store(slot * 4, 4) + want.append(c.expected()) + return code + [0xBF810000], want + + +def refusal_programs(): + return [ + # Special scalar sources refused in packed_f16_alu + (vop3p('add', 4, (257, 106)) + [0xBF810000], 'unsupported packed binary16 arithmetic source'), + (vop3p('mul', 4, (124, 257)) + [0xBF810000], 'unsupported packed binary16 arithmetic source'), + (vop3p('fma', 4, (257, 242, 126)) + [0xBF810000], 'unsupported packed binary16 arithmetic source'), + (vop3p('fma', 4, (257, 242, 253)) + [0xBF810000], 'unsupported packed binary16 arithmetic source'), + # Special scalar sources refused in packed_minmax + (vop3p('min_f16', 4, (257, 106)) + [0xBF810000], 'unsupported packed 16-bit min/max source'), + (vop3p('max_f16', 4, (124, 257)) + [0xBF810000], 'unsupported packed 16-bit min/max source'), + (vop3p('min_f16', 4, (257, 253)) + [0xBF810000], 'unsupported packed 16-bit min/max source'), + # Float inline constants refused on integer packed min/max + (vop3p('min_u16', 4, (257, 242)) + [0xBF810000], 'unsupported packed 16-bit min/max source'), + (vop3p('max_i16', 4, (240, 257)) + [0xBF810000], 'unsupported packed 16-bit min/max source'), + # Unused third-source modifier refused on 2-source VOP3P add + (vop3p('add', 4, (257, 242), neg_lo=4) + [0xBF810000], 'unsupported packed binary16 arithmetic encoding'), + ] + + +def ir(dumper): + items = all_cases() + code, want = compute_program(items) + refusals = refusal_programs() + with tempfile.TemporaryDirectory() as tmp: + work = Path(tmp) + run = F.dump(dumper, work, code, 'packed-f16-inline') + assert run.returncode == 0, run.stderr + stores = sorted(F.interpret(run.stdout)) + assert [addr for addr, _ in stores] == [4 * i for i in range(len(want))], stores[:4] + bad = [(i, items[i].name, hex(got), hex(exp)) + for i, ((_, got), exp) in enumerate(zip(stores, want)) if got != exp] + assert not bad, bad[:8] + for idx, (refused, why) in enumerate(refusals): + r = F.dump(dumper, work, refused, f'refused-{idx}') + assert r.returncode != 0 and why in r.stderr, (idx, why, r.returncode, r.stderr) + print(f'native_packed_f16_inline IR: {len(want)} cases matched exact model; {len(refusals)} refusals matched') + return 0 + + +def controls(cli, sdk, work, root): + items = all_cases() + code, want = compute_program(items) + marker = request(work, root, code) + output = marker.with_suffix('.cso') + result = subprocess.run([cli, sdk, work / 'cache', 'gfx1013-direct-cs@0', marker, output], + capture_output=True, text=True) + assert result.returncode == 0 and output.is_file(), (result.stdout, result.stderr) + dump = subprocess.run([Path(sdk) / 'dxc.exe', '-dumpbin', output], capture_output=True, text=True, check=True).stdout + assert 'fmul float' in dump and 'fadd float' in dump and '@dx.op.unaryBits.i32(i32 33,' in dump, dump + + refusals = refusal_programs() + for idx, (prog, why) in enumerate(refusals): + m = request(work, root, prog) + o = m.with_suffix(f'.refused{idx}.cso') + r = subprocess.run([cli, sdk, work / 'cache', 'gfx1013-direct-cs@0', m, o], capture_output=True, text=True) + assert r.returncode != 0 and why in r.stderr, (idx, why, r.stdout, r.stderr) + assert not o.exists(), o + + print(f'native_packed_f16_inline controls: compiled {len(want)} cases to DXIL; verified {len(refusals)} refusals') + return 0 + + +def hardware(replay, sdk, work, root): + items = all_cases() + code, want = compute_program(items) + marker = request(work, root, code) + output = work / 'out.bin' + run = subprocess.run([replay, sdk, marker, work / 'cache', '0', output, '--direct']) + if run.returncode == 77: + return 77 + run.check_returncode() + words_out = list(struct.unpack(f'<{F.WORDS}I', output.read_bytes())) + expected = [F.SENTINEL] * F.WORDS + for group in range(F.GROUPS): + for lane in range(32): + head = F.BASE + group * 1024 + lane * 32 + expected[head:head + len(want)] = want + mismatch = next((i for i, (a, b) in enumerate(zip(words_out, expected, strict=True)) if a != b), None) + assert mismatch is None, (mismatch, hex(words_out[mismatch]), hex(expected[mismatch])) + print(f'native_packed_f16_inline compute hardware: {len(want)} cases matched across {F.GROUPS}x32 lanes and guards') + return 0 + + +def pixel_program(case_a: Case, case_b: Case): + code = [] + for idx, c in enumerate((case_a, case_b)): + code += emit_case(c) + lo, hi = 8 + 2 * idx, 9 + 2 * idx + code += [vop2(0x1B, lo, 255, 4), 65535, vop2(0x16, hi, 144, 4)] + code += [0x7E000C00 | reg << 17 | (256 + reg) for reg in (lo, hi)] + return patched_pixel(len(code), code, export=(0xF800180F, 0x0B0A0908)) + + +def pixel(cli, sdk, renderer, adapter, work): + items = all_cases() + if len(items) % 2: + items.append(items[-1]) + vs = compile_hlsl(str(Path(sdk) / 'dxc.exe'), 'dxc', FULLSCREEN_VS, 'fullscreen', 'vs_6_0', work) + pairs = [(items[i], items[i + 1]) for i in range(0, len(items), 2)] + for idx, (ca, cb) in enumerate(pairs): + shader = work / f'inline-{idx}.ps' + shader.write_bytes(pixel_program(ca, cb)) + cso = shader.with_suffix('.cso') + build = subprocess.run([cli, sdk, work / 'cache', 'gfx1013-container-ps', shader, cso], + capture_output=True, text=True, timeout=30) + assert build.returncode == 0, (ca.name, cb.name, build.stdout, build.stderr) + ea, eb = ca.expected(), cb.expected() + ref = work / 'expected.bin' + ref.write_bytes(struct.pack('<4f', ea & 0xFFFF, ea >> 16, eb & 0xFFFF, eb >> 16)) + run = subprocess.run([renderer, adapter, '--startup-pixel-words', vs, cso, '1', '1', ref], + capture_output=True, text=True, timeout=30) + if run.returncode == 77: + return 77 + assert run.returncode == 0, (idx, ca.name, cb.name, run.stdout, run.stderr) + if 'debug_layer=enabled' in run.stdout: + assert 'debug_errors=0 debug_warnings=0' in run.stdout, run.stdout + print(f'native_packed_f16_inline pixel ({adapter}): {len(pairs)} paired draws ({len(all_cases())} cases) matched') + return 0 + + +def main(mode, tool, sdk=None, *args): + if mode == 'ir': + return ir(tool) + with tempfile.TemporaryDirectory() as tmp: + work = Path(tmp) + if mode == 'pixel': + return pixel(tool, sdk, args[0], args[1], work) + shader = work / 'root.hlsl' + shader.write_text('#define SIG "DescriptorTable(UAV(u0,numDescriptors=8))"') + root = work / 'root.bin' + subprocess.run([Path(sdk) / 'dxc.exe', '-T', 'rootsig_1_1', '-E', 'SIG', '-Fo', root, shader], check=True) + return {'controls': controls, 'compute': hardware}[mode](tool, sdk, work, root.read_bytes()) + + +if __name__ == '__main__': + sys.exit(main(*sys.argv[1:])) diff --git a/tests/native_packed_minmax_check.py b/tests/native_packed_minmax_check.py index f11f64507c..cc4607e44c 100644 --- a/tests/native_packed_minmax_check.py +++ b/tests/native_packed_minmax_check.py @@ -24,21 +24,41 @@ (0x4400C000, 0x3C003800, 1, 1), (0x00000000, 0x00018000, 3, 2), ) +MOD_CASES = ( + # a, b, op_sel, op_sel_hi, neg_lo, neg_hi, clamp + (0x38004000, 0x3C00BC00, 0, 3, 1, 2, 0), # neg_lo[0] vs neg_hi[1] asymmetric + (0xC0000001, 0x80003C00, 1, 2, 2, 1, 0), # neg_lo[1] vs neg_hi[0] cross-lane + (0x00008000, 0x80000000, 0, 3, 3, 0, 0), # neg_lo both (+/-0) without neg_hi + (0x7C007E01, 0xFC003800, 0, 3, 0, 3, 0), # neg_hi both (+/-Inf, NaN payload) + (0x8000C000, 0x3C000000, 0, 3, 0, 0, 1), # clamp -2.0 -> +0.0 and -0.0 -> +0.0 + (0x00013800, 0x3C000000, 0, 3, 0, 0, 1), # clamp preserves positive subnormal 0x0001 and 0.5..1.0 + (0x7C004000, 0xFC000000, 0, 3, 0, 0, 1), # clamp >1.0 / +Inf -> 1.0, -Inf -> +0.0 + (0x7E013800, 0x7E027BFF, 0, 3, 0, 0, 1), # clamp both-NaN -> +0.0, one-NaN picks numeric -> clamp + (0x3800B800, 0xC0004000, 0, 3, 3, 2, 1), # combined neg_lo + neg_hi + clamp +) SENTINEL = 0x69696969 INACTIVE = 0x13579bdf PROLOGUE = [0xBE940304, 0xBE950380, 0xF408080A, 0xFA000020, 0x8F078C05, 0x34100087, 0x4A101007, 0xBF8CC07F] -def packed(op, dst, lo, hi, *, first=257, second=258, bad=0): - return [0xCC004000 | op << 16 | lo << 11 | dst | bad, first | second << 9 | hi << 27] +def packed(op, dst, lo, hi, *, first=257, second=258, bad=0, neg_lo=0, neg_hi=0, clamp=0): + w0 = 0xCC004000 | (op << 16) | ((clamp & 1) << 15) | (lo << 11) | ((neg_hi & 7) << 8) | dst | bad + w1 = ((neg_lo & 7) << 29) | (hi << 27) | (second << 9) | first + return [w0, w1] -def compute_program(kind, *, bad=0, swap=False, flush=False, sparse=False): +def compute_program(kind, *, bad=0, swap=False, flush=False, sparse=False, neg_lo=0, neg_hi=0, clamp=0, mods=False): code = list(PROLOGUE) if flush: code.append(0xBFA50003) # s_denorm_mode: keep f32 denormals and flush f16 - for slot, (a, b, lo, hi) in enumerate(CASES): - source = {1: 23, 2: 255, 8: 128}.get(slot, 257) + rows = MOD_CASES if mods else CASES + for slot, row in enumerate(rows): + if mods: + a, b, lo, hi, m_lo, m_hi, m_clamp = row + else: + a, b, lo, hi = row + m_lo, m_hi, m_clamp = neg_lo, neg_hi, clamp + source = {1: 23, 2: 255, 8: 128}.get(slot, 257) if not mods else {2: 23, 4: 255}.get(slot, 257) if source == 23: code += [0xBE9703FF, a] # s_mov_b32 s23, literal elif source == 257: @@ -47,7 +67,8 @@ def compute_program(kind, *, bad=0, swap=False, flush=False, sparse=False): for j, op in enumerate(OPS[kind]): if sparse: code += [0x7E0802FF, INACTIVE, sop1(3, 126, 255), 0x55555555] - code += packed(op, 4, hi if swap else lo, lo if swap else hi, first=source, bad=bad) + code += packed(op, 4, hi if swap else lo, lo if swap else hi, first=source, bad=bad, + neg_lo=m_lo, neg_hi=m_hi, clamp=m_clamp) if source == 255: code.append(a) if sparse: @@ -80,24 +101,45 @@ def controls(cli, sdk, work, root, baseline=False): print(kind, run.stderr.strip()) continue assert run.returncode == 0, run.stdout + run.stderr - for bad in (1 << 15, 1 << 8, 1 << 13): - _, run = compile_compute(cli, sdk, work, root, kind, bad=bad) - assert run.returncode and 'packed 16-bit min/max encoding' in run.stderr, (kind, run.stderr) + if kind == 'f16': + _, run = compile_compute(cli, sdk, work, root, kind, mods=True) + assert run.returncode == 0, run.stdout + run.stderr + _, run = compile_compute(cli, sdk, work, root, kind, neg_lo=3, neg_hi=3, clamp=1) + assert run.returncode == 0, run.stdout + run.stderr + for bad_kwargs in ({'bad': 1 << 10}, {'bad': 1 << 13}, {'neg_lo': 4}): + _, run = compile_compute(cli, sdk, work, root, kind, **bad_kwargs) + assert run.returncode and 'packed 16-bit min/max encoding' in run.stderr, (kind, bad_kwargs, run.stderr) + else: + for bad in (1 << 15, 1 << 8, 1 << 13): + _, run = compile_compute(cli, sdk, work, root, kind, bad=bad) + assert run.returncode and 'packed 16-bit min/max encoding' in run.stderr, (kind, run.stderr) if not baseline: _, run = compile_compute(cli, sdk, work, root, 'f16', flush=True) assert run.returncode and 'denormal mode' in run.stderr, run.stderr - print('six opcodes compiled; clamp, negation, noncanonical third selector and f16 flush mode refused') + print('six opcodes compiled (f16 with neg_lo/neg_hi/clamp); reserved/integer mods and f16 flush mode refused') -def half_result(kind, maximum, a, b): +def half_result(kind, maximum, a, b, *, neg_a=False, neg_b=False, clamp=False): if kind == 'f16': + if neg_a: + a ^= 0x8000 + if neg_b: + b ^= 0x8000 x, y = (struct.unpack('<e', struct.pack('<H', v))[0] for v in (a, b)) if math.isnan(x): - return 0x7e00 if math.isnan(y) else b - if math.isnan(y): - return a - if x == y == 0: - return a & b if maximum else a | b + res = 0x7e00 if math.isnan(y) else b + elif math.isnan(y): + res = a + elif x == y == 0: + res = a & b if maximum else a | b + else: + res = a if (x > y if maximum else x < y) else b + if clamp: + if (res & 0x7fff) > 0x7c00 or (res & 0x8000): + return 0x0000 + if res > 0x3bff: + return 0x3c00 + return res elif kind == 'i16': x, y = (struct.unpack('<h', struct.pack('<H', v))[0] for v in (a, b)) else: @@ -106,11 +148,16 @@ def half_result(kind, maximum, a, b): def expected(kind, case, maximum, *, swap=False): - a, b, lo, hi = case + if len(case) == 7: + a, b, lo, hi, neg_lo, neg_hi, clamp = case + else: + a, b, lo, hi = case + neg_lo, neg_hi, clamp = 0, 0, 0 halves = [] - for select in (hi, lo) if swap else (lo, hi): + pairs = ((hi, neg_hi), (lo, neg_lo)) if swap else ((lo, neg_lo), (hi, neg_hi)) + for select, neg in pairs: x, y = (a >> (16 * (select & 1))) & 0xffff, (b >> (16 * (select >> 1))) & 0xffff - halves.append(half_result(kind, maximum, x, y)) + halves.append(half_result(kind, maximum, x, y, neg_a=bool(neg & 1), neg_b=bool(neg & 2), clamp=bool(clamp))) return halves[0] | halves[1] << 16 @@ -124,8 +171,9 @@ def compute_replay(replay, sdk, work, root, kind, **options): return struct.unpack('<2064I', output.read_bytes()) -def expected_buffer(kind, *, swap=False, sparse=False): - lane_words = [expected(kind, case, maximum, swap=swap) for case in CASES for maximum in (False, True)] +def expected_buffer(kind, *, swap=False, sparse=False, mods=False): + rows = MOD_CASES if mods else CASES + lane_words = [expected(kind, case, maximum, swap=swap) for case in rows for maximum in (False, True)] unused = [SENTINEL] * (32 - len(lane_words)) inactive = [INACTIVE] * len(lane_words) if sparse else lane_words pair = lane_words + unused + inactive + unused @@ -139,6 +187,11 @@ def draw_compute(replay, sdk, work, root): for index, (word, want) in enumerate(zip(actual, reference, strict=True)): assert word == want, (kind, index, hex(word), hex(want)) print(f'{kind}: 2064 Compute readback words matched') + actual = compute_replay(replay, sdk, work, root, 'f16', mods=True) + reference = expected_buffer('f16', mods=True) + for index, (word, want) in enumerate(zip(actual, reference, strict=True)): + assert word == want, ('f16_mods', index, hex(word), hex(want)) + print(f'f16 neg_lo/neg_hi/clamp: {len(MOD_CASES)}x2 Compute readback cases matched across 2064 words') actual = compute_replay(replay, sdk, work, root, 'f16', swap=True) assert actual == expected_buffer('f16', swap=True) count = sum(a != b for a, b in zip(actual, expected_buffer('f16'), strict=True)) @@ -150,11 +203,15 @@ def draw_compute(replay, sdk, work, root): def pixel_program(kind, case): - a, b, lo, hi = case + if len(case) == 7: + a, b, lo, hi, neg_lo, neg_hi, clamp = case + else: + a, b, lo, hi = case + neg_lo, neg_hi, clamp = 0, 0, 0 code = [0x7E0202FF, a, 0x7E0402FF, b] for j, op in enumerate(OPS[kind]): src, low, high = 4 + j, 8 + 2 * j, 9 + 2 * j - code += packed(op, src, lo, hi) + code += packed(op, src, lo, hi, neg_lo=neg_lo, neg_hi=neg_hi, clamp=clamp) code += [vop2(0x1b, low, 255, src), 65535, vop2(0x16, high, 144, src)] # Each unsigned halfword is exactly representable as binary32, even # if the packed result as a whole would encode a float NaN. @@ -165,14 +222,17 @@ def pixel_program(kind, case): def draw_pixel(cli, sdk, renderer, adapter, work): vs = compile_hlsl(str(Path(sdk) / 'dxc.exe'), 'dxc', FULLSCREEN_VS, 'fullscreen', 'vs_6_0', work) for kind in OPS: - for index in (0, 1, 3, 7): - case = CASES[index] - shader = work / f'{kind}-{index}.ps' + indices = (0, 1, 3, 7) + cases = [(f'{kind}-{index}', CASES[index]) for index in indices] + if kind == 'f16': + cases += [(f'f16-mod-{index}', case) for index, case in enumerate(MOD_CASES)] + for label, case in cases: + shader = work / f'{label}.ps' shader.write_bytes(pixel_program(kind, case)) cso = shader.with_suffix('.cso') build = subprocess.run([cli, sdk, work / 'cache', 'gfx1013-container-ps', shader, cso], capture_output=True, text=True, timeout=30) - assert build.returncode == 0, build.stdout + build.stderr + assert build.returncode == 0, (label, build.stdout + build.stderr) minimum, maximum = (expected(kind, case, flag) for flag in (False, True)) reference = work / 'expected.bin' reference.write_bytes(struct.pack('<4f', minimum & 0xffff, minimum >> 16, maximum & 0xffff, maximum >> 16)) @@ -180,10 +240,10 @@ def draw_pixel(cli, sdk, renderer, adapter, work): capture_output=True, text=True, timeout=30) if run.returncode == 77: raise SystemExit(77) - assert run.returncode == 0, (kind, index, run.stdout, run.stderr) + assert run.returncode == 0, (label, run.stdout, run.stderr) if 'debug_layer=enabled' in run.stdout: assert 'debug_errors=0 debug_warnings=0' in run.stdout, run.stdout - print(f'{kind}: four Pixel cases matched for both packed results') + print(f'{kind}: {len(cases)} Pixel cases matched for both packed results') if __name__ == '__main__': diff --git a/tests/native_pk_fmac_f16_check.py b/tests/native_pk_fmac_f16_check.py new file mode 100644 index 0000000000..a9301c94ad --- /dev/null +++ b/tests/native_pk_fmac_f16_check.py @@ -0,0 +1,275 @@ +"""Direct DXIL VOP2 v_pk_fmac_f16 lowering in Compute and Pixel shaders.""" +from dataclasses import dataclass +from pathlib import Path +import struct +import subprocess +import sys +import tempfile + +from f16_packed_model import half_op, same +from native_direct_container_check import patched_pixel +from native_dot2_f32_f16_check import p16 +from native_dpp_quad_check import request +import native_f16_alu_check as F +from native_packed_f16_inline_check import PROLOGUE, inline_word +from native_scalar_lds_check import sop1, vmove +from startup_image_3d_check import FULLSCREEN_VS, compile_hlsl + +OP_PK_FMAC_F16 = 0x3C +ALL_EXEC = 0xFFFFFFFF + + +def vop2_pk_fmac(dst, src0, vsrc1): + assert 256 <= vsrc1 < 512, vsrc1 + return ((OP_PK_FMAC_F16 << 25) | ((dst & 0xFF) << 17) | (((vsrc1 - 256) & 0xFF) << 9) | (src0 & 0x1FF)) + + +def vop3_pk_fmac_e64(dst, src0, vsrc1, *, clamp=0): + return [ + 0xD53C0000 | ((clamp & 1) << 15) | (dst & 0xFF), + ((vsrc1 & 0x1FF) << 9) | (src0 & 0x1FF), + ] + + +def eval_pk_fmac(s0_word, s1_word, acc_word): + lo = half_op('fma', s0_word & 0xFFFF, s1_word & 0xFFFF, acc_word & 0xFFFF) + hi = half_op('fma', (s0_word >> 16) & 0xFFFF, (s1_word >> 16) & 0xFFFF, (acc_word >> 16) & 0xFFFF) + return (hi << 16) | lo + + +@dataclass(frozen=True) +class Case: + name: str + steps: tuple + acc: int + exec_mask: int = ALL_EXEC + alias: str = 'none' + pixel_safe: bool = True + + def expected(self, lane=0): + if ((self.exec_mask >> lane) & 1) == 0: + return self.acc & 0xFFFFFFFF + cur = self.acc & 0xFFFFFFFF + for s0, v0, v1 in self.steps: + if self.alias == 'src0': + w0 = cur + elif s0 < 128 or s0 >= 255: + w0 = v0 & 0xFFFFFFFF + else: + w0 = inline_word(s0) + w1 = cur if self.alias == 'src1' else (v1 & 0xFFFFFFFF) + cur = eval_pk_fmac(w0, w1, cur) + return cur + + +def all_cases(): + return [ + # 1. Distinct low and high half FMA values. + Case('vgpr_basic', ((262, p16(0x3C00, 0x4000), p16(0x4200, 0x3800)),), p16(0x3800, 0xC000)), + # 2. Fused cancellation: (1 + 2^-6)^2 - 1 = 2^-5 + 2^-12 (0x2808), whereas unfused mul+add gives 2^-5 (0x2800). + Case('fused_cancellation', ((262, p16(0x3C10, 0xBC10), p16(0x3C10, 0x3C10)),), p16(0xBC00, 0xBC00)), + # 3. Back-to-back accumulation into vdst. + Case('multi_accumulate', + ((262, p16(0x3C00, 0x3800), p16(0x4000, 0x4000)), + (262, p16(0xBC00, 0x4000), p16(0x3C00, 0x4200))), + p16(0x3400, 0x3C00)), + # 4. Destination VGPR aliased with src0 or vsrc1. + Case('vgpr_dst_alias_src0', ((260, 0, p16(0x4000, 0x4200)),), p16(0x3C00, 0x3800), alias='src0'), + Case('vgpr_dst_alias_src1', ((262, p16(0x4200, 0x3C00), 0),), p16(0x3800, 0x4000), alias='src1'), + # 5. SGPR and 32-bit literal src0 encodings. + Case('sgpr_src0', ((10, p16(0x3C00, 0xC000), p16(0x4200, 0x3800)),), p16(0x3800, 0x4000)), + Case('literal_src0', ((255, p16(0x4000, 0x3C00), p16(0x3800, 0x4200)),), p16(0xBC00, 0x3400)), + # 6. Inline binary16 float constants (0.5, 1.0, -1.0) and inline integer 0 / subnormal 1. + Case('inline_f16_240', ((240, 0, p16(0x4000, 0x4400)),), p16(0x3C00, 0x3C00)), + Case('inline_f16_242', ((242, 0, p16(0x4000, 0x4400)),), p16(0x3800, 0x4000)), + Case('inline_f16_243', ((243, 0, p16(0x3C00, 0x4000)),), p16(0x4000, 0x4200)), + Case('inline_int_128', ((128, 0, p16(0x4000, 0x4400)),), p16(0xC200, 0x3C00)), + Case('inline_int_129', ((129, 0, p16(0x3C00, 0x3C00)),), p16(0x0002, 0x0001)), + # 7. Binary16 subnormal operands and subnormal outputs preserved cleanly. + Case('subnormal_io', ((262, p16(0x0001, 0x03FF), p16(0x3800, 0x3C00)),), p16(0x0001, 0x0001)), + # 8. Overflow from finite operands to +/-Inf. + Case('overflow_to_inf', ((262, p16(0x7BFF, 0xFBFF), p16(0x4000, 0x4000)),), + p16(0x3C00, 0xBC00), pixel_safe=False), + # 9. Partial EXEC mask: odd lanes update vdst, even lanes preserve pre-existing vdst. + Case('partial_exec_odd', ((262, p16(0x3C00, 0x4000), p16(0x4000, 0x4200)),), + p16(0x4500, 0xC100), exec_mask=0xAAAAAAAA, pixel_safe=False), + # 10. Signed zero, infinity, and NaN propagation. + Case('signed_zero_keep', ((262, p16(0x8000, 0x0000), p16(0x3C00, 0x8000)),), + p16(0x8000, 0x8000), pixel_safe=False), + Case('inf_and_nan', ((262, p16(0x7C00, 0x7E01), p16(0x3C00, 0x3C00)),), + p16(0xBC00, 0x3C00), pixel_safe=False), + ] + + +def emit_case(c: Case): + code = F.mov(4, c.acc) + if c.exec_mask != ALL_EXEC: + code += [sop1(3, 126, 255), c.exec_mask] + for s0, v0, v1 in c.steps: + lit_tail = [] + vsrc1 = 260 if c.alias == 'src1' else 261 + if c.alias != 'src1': + code += F.mov(vsrc1 - 256, v1) + src0 = 260 if c.alias == 'src0' else s0 + if c.alias != 'src0': + if src0 >= 256: + code += F.mov(src0 - 256, v0) + elif src0 <= 105: + code += F.smov(src0, v0) + elif src0 == 255: + lit_tail = [v0] + code.append(vop2_pk_fmac(4, src0, vsrc1)) + code += lit_tail + if c.exec_mask != ALL_EXEC: + code += [sop1(3, 126, 193)] + return code + + +def compute_program(cases): + code = list(PROLOGUE) + for slot, c in enumerate(cases): + code += emit_case(c) + F.store(slot * 4, 4) + return code + [0xBF810000] + + +def refusal_programs(): + cond_mode = [0xBF840001, 0xBFA5000F] # s_cbranch_scc0 +1; s_denorm_mode 15 + plain = [vop2_pk_fmac(4, 262, 261), 0xBF810000] + return [ + # VOP3 _e64 form of v_pk_fmac_f16. + (vop3_pk_fmac_e64(4, 262, 261) + [0xBF810000], 'unsupported packed binary16 arithmetic encoding'), + # DPP16, DPP8, and SDWA forms. + ([vop2_pk_fmac(4, 250, 261), 0xFF00E406, 0xBF810000], 'unsupported DPP arithmetic'), + ([vop2_pk_fmac(4, 233, 261), 0xC6886806, 0xBF810000], 'unsupported DPP arithmetic'), + ([vop2_pk_fmac(4, 249, 261), 0x06060606, 0xBF810000], 'unimplemented direct SDWA operand profile'), + # Special scalar source refused on src0 (vcc_lo). + ([vop2_pk_fmac(4, 106, 261), 0xBF810000], 'unsupported packed binary16 arithmetic source'), + # Unsupported binary16 rounding/denorm and conditional MODE write. + ([0xBFA40004] + plain, 'unsupported binary16 rounding or denormal mode'), + ([0xBFA50003] + plain, 'unsupported binary16 rounding or denormal mode'), + (cond_mode + plain, 'unsupported binary16 rounding or denormal mode'), + ] + + +def ir(dumper): + items = all_cases() + code = compute_program(items) + want = [c.expected(lane=0) for c in items] + refusals = refusal_programs() + with tempfile.TemporaryDirectory() as tmp: + work = Path(tmp) + run = F.dump(dumper, work, code, 'pk-fmac-f16') + assert run.returncode == 0, run.stderr + stores = sorted(F.interpret(run.stdout)) + assert [addr for addr, _ in stores] == [4 * i for i in range(len(want))], stores[:4] + bad = [(i, items[i].name, hex(got), hex(exp)) + for i, ((_, got), exp) in enumerate(zip(stores, want)) if not same(got, exp)] + assert not bad, bad[:8] + for idx, (refused, why) in enumerate(refusals): + r = F.dump(dumper, work, refused, f'refused-{idx}') + assert r.returncode != 0 and why in r.stderr, (idx, why, r.returncode, r.stderr) + print(f'native_pk_fmac_f16 IR: {len(want)} cases matched exact model; {len(refusals)} refusals matched') + return 0 + + +def controls(cli, sdk, work, root): + items = all_cases() + code = compute_program(items) + marker = request(work, root, code) + output = marker.with_suffix('.cso') + result = subprocess.run([cli, sdk, work / 'cache', 'gfx1013-direct-cs@0', marker, output], + capture_output=True, text=True) + assert result.returncode == 0 and output.is_file(), (result.stdout, result.stderr) + dump = subprocess.run([Path(sdk) / 'dxc.exe', '-dumpbin', output], capture_output=True, text=True, check=True).stdout + assert '@dx.op.unaryBits.i32(i32 33,' in dump and 'mul i32' in dump, dump + + refusals = refusal_programs() + for idx, (prog, why) in enumerate(refusals): + m = request(work, root, prog) + o = m.with_suffix(f'.refused{idx}.cso') + r = subprocess.run([cli, sdk, work / 'cache', 'gfx1013-direct-cs@0', m, o], capture_output=True, text=True) + assert r.returncode != 0 and why in r.stderr, (idx, why, r.stdout, r.stderr) + assert not o.exists(), o + + print(f'native_pk_fmac_f16 controls: compiled {len(items)} cases to DXIL; verified {len(refusals)} refusals') + return 0 + + +def hardware(replay, sdk, work, root): + items = all_cases() + code = compute_program(items) + marker = request(work, root, code) + output = work / 'out.bin' + run = subprocess.run([replay, sdk, marker, work / 'cache', '0', output, '--direct']) + if run.returncode == 77: + return 77 + run.check_returncode() + words_out = list(struct.unpack(f'<{F.WORDS}I', output.read_bytes())) + expected = {} + for group in range(F.GROUPS): + for lane in range(32): + head = F.BASE + group * 1024 + lane * 32 + for idx, c in enumerate(items): + expected[head + idx] = c.expected(lane=lane) + bad = [] + for i, got in enumerate(words_out): + if i in expected: + if not same(got, expected[i]): + bad.append((i, hex(got), hex(expected[i]))) + elif got != F.SENTINEL: + bad.append((i, hex(got), hex(F.SENTINEL))) + assert not bad, bad[:10] + print(f'native_pk_fmac_f16 compute hardware: {len(items)} cases matched across {F.GROUPS}x32 lanes and guards') + return 0 + + +def pixel_program(quad): + code = [] + for idx, c in enumerate(quad): + code += emit_case(c) + code.append(vmove(8 + idx, 256 + 4)) + return patched_pixel(len(code), code, export=(0xF800180F, 0x0B0A0908)) + + +def pixel(cli, sdk, renderer, adapter, work): + items = [c for c in all_cases() if c.pixel_safe] + while len(items) % 4: + items.append(items[-1]) + vs = compile_hlsl(str(Path(sdk) / 'dxc.exe'), 'dxc', FULLSCREEN_VS, 'fullscreen', 'vs_6_0', work) + quads = [items[i:i + 4] for i in range(0, len(items), 4)] + for idx, quad in enumerate(quads): + shader = work / f'pk-fmac-{idx}.ps' + shader.write_bytes(pixel_program(quad)) + cso = shader.with_suffix('.cso') + build = subprocess.run([cli, sdk, work / 'cache', 'gfx1013-container-ps', shader, cso], + capture_output=True, text=True, timeout=30) + assert build.returncode == 0, ([c.name for c in quad], build.stdout, build.stderr) + ref = work / 'expected.bin' + ref.write_bytes(struct.pack('<4I', *(c.expected(lane=0) for c in quad))) + run = subprocess.run([renderer, adapter, '--startup-pixel-words', vs, cso, '1', '1', ref], + capture_output=True, text=True, timeout=30) + if run.returncode == 77: + return 77 + assert run.returncode == 0, (idx, [c.name for c in quad], run.stdout, run.stderr) + if 'debug_layer=enabled' in run.stdout: + assert 'debug_errors=0 debug_warnings=0' in run.stdout, run.stdout + print(f'native_pk_fmac_f16 pixel ({adapter}): {len(quads)} quad draws matched') + return 0 + + +def main(mode, tool, sdk=None, *args): + if mode == 'ir': + return ir(tool) + with tempfile.TemporaryDirectory() as tmp: + work = Path(tmp) + if mode == 'pixel': + return pixel(tool, sdk, args[0], args[1], work) + shader = work / 'root.hlsl' + shader.write_text('#define SIG "DescriptorTable(UAV(u0,numDescriptors=8))"') + root = work / 'root.bin' + subprocess.run([Path(sdk) / 'dxc.exe', '-T', 'rootsig_1_1', '-E', 'SIG', '-Fo', root, shader], check=True) + return {'controls': controls, 'compute': hardware}[mode](tool, sdk, work, root.read_bytes()) + + +if __name__ == '__main__': + sys.exit(main(*sys.argv[1:])) diff --git a/tests/native_raw_load_cache_bits_check.py b/tests/native_raw_load_cache_bits_check.py new file mode 100644 index 0000000000..ac87d76d5d --- /dev/null +++ b/tests/native_raw_load_cache_bits_check.py @@ -0,0 +1,136 @@ +"""Compile raw MUBUF loads with cache hints and compare hardware UAV readback.""" +from pathlib import Path +import struct +import subprocess +import sys +import tempfile + +from native_direct_container_check import pack, words + + +GLC_DLC = (1 << 14) | (1 << 15) +SLC = 1 << 22 +REFUSAL = "raw buffer load needs a linear byte offset and no modifiers" +VIEWS = """x2w-global-srv-views 2 +select 0 +need raw_buffer +slot 0 raw_buffer 1 256 +slot 1 raw_buffer 1 256 +slot 2 texture 0 0 +slot 3 typed_buffer 4 256 +""" + + +def container(offen, cache_flags, extra_flags): + # Dispatch(1, 1, 1) runs group (0,0,0), with one wave32 and local IDs in v0. + # EXEC enables lanes 0..7. Each lane writes the first dword of a 16-byte u0 slot. + soffset = 128 if offen else 18 + code = words( + 0xbe810380, # s_mov_b32 s1, 0 + 0xbe830380, # s_mov_b32 s3, 0 + 0xf4080200, 0xfa000000, # s_load_dwordx4 s[8:11], s[0:1], 0 (selector t0) + 0xf4080300, 0xfa000020, # s_load_dwordx4 s[12:15], s[0:1], 32 (output u0) + 0xf4200404, 0xfa000000, # s_buffer_load_dword s16, s[8:11], 0 + 0xbf8cc07f, # s_waitcnt lgkmcnt(0) + 0x8f118510, # s_lshl_b32 s17, s16, 5 + 0xf4080501, 0x22000000, # s_load_dwordx4 s[20:23], s[2:3], s17 (selected heap SRV) + 0xbf8cc07f, # s_waitcnt lgkmcnt(0) + 0x34020084, # v_lshlrev_b32_e32 v1, 4, v0 + 0xbe92038c, # s_mov_b32 s18, 12 + 0xbefe03ff, 0x000000ff, # s_mov_b32 exec_lo, 0xff + 0xbeff0380, # s_mov_b32 exec_hi, 0 + 0xe0300000 | (int(offen) << 12) | cache_flags, + (soffset << 24) | 0x00050200 | int(offen) | extra_flags, # v2, v1/off, s[20:23] + 0xbf8c3f70, # s_waitcnt vmcnt(0) + 0xe0701000, 0x80030201, # buffer_store_dword v2, v1, s[12:15], 0 offen + 0xbf810000, # s_endpgm + ) + + # Same two root inputs as native_global_srv_heap_replay_check.py. + body = bytearray(256) + struct.pack_into("<Q", body, 0, 6) + for offset in (8, 16, 24, 32, 40, 48, 72): + struct.pack_into("<Q", body, offset, 0xDEADBEEFDEADBEEF) + record = 112 + struct.pack_into("<Q", body, 96, record) + struct.pack_into("<Q", body, record + 40, len(body)) + struct.pack_into("<I", body, record + 56, 2) + body.extend(struct.pack("<IIIIBBH", 3, 0, 1, 0, 0, 0, 0)) + body.extend(struct.pack("<IIIIBBH", 5, 0, 1, 0, 2, 0, 0)) + struct.pack_into("<QQII", body, record, len(body), len(code), 1 << 20, 32) + struct.pack_into("<II", body, record + 76, 512, 6) + struct.pack_into("<IIII", body, record + 120, 0x8400 | 0x1008, 32, 1, 1) + body.extend(code) + return pack(body) + + +def request_key(root, cdx): + key = 1469598103934665603 + for byte in b"native-container-1" + struct.pack("<Q", len(root)) + root + cdx: + key = ((key ^ byte) * 1099511628211) & 0xFFFFFFFFFFFFFFFF + return f"{key:016x}" + + +def run(*command): + return subprocess.run(command, capture_output=True, encoding="utf-8", errors="replace", timeout=100) + + +def main(fixture, compile_dxil, sdk): + with tempfile.TemporaryDirectory(prefix="x2w_raw_load_cache_") as scratch: + base = Path(scratch) + cache = base / "cache" + cache.mkdir() + root_path = base / "fixture.root" + result = run(fixture, "root", root_path) + if result.returncode != 0: + raise AssertionError((result.stdout, result.stderr)) + root = root_path.read_bytes() + + replays = [] + for name, offen, cache_flags, extra_flags, refused in ( + ("offen_glc_dlc", True, GLC_DLC, 0, False), + ("soffset_glc_dlc", False, GLC_DLC, 0, False), + ("offen_slc", True, 0, SLC, False), + ("offen_lds", True, GLC_DLC | (1 << 16), 0, True), + ("soffset_tfe", False, GLC_DLC, 1 << 23, True), + ): + directory = base / name + directory.mkdir() + cdx = container(offen, cache_flags, extra_flags) + key = request_key(root, cdx) + request = directory / f"req_{key}.cdx" + views = request.with_suffix(".views") + request.write_bytes(cdx) + request.with_suffix(".root").write_bytes(root) + views.write_text(VIEWS, encoding="ascii", newline="\n") + out_dir = base / f"{name}_out" + cso = out_dir / f"{key}.cs.cso" + result = run(compile_dxil, sdk, cache, "gfx1013-container-cs", "--requests", directory, out_dir) + if refused: + if result.returncode != 1 or REFUSAL not in result.stderr or cso.exists(): + raise AssertionError((name, result.stdout, result.stderr)) + continue + if result.returncode != 0 or "compiled=1 refused=0" not in result.stdout or not cso.exists(): + raise AssertionError((name, result.stdout, result.stderr)) + # Slot 0 starts at 0xA0000000 and increases by one per dword. + # OFFEN reads source word 4*lane. SOFFSET reads source word 3 in every lane. + expected = [0x69696969] * 72 + for lane in range(8): + expected[4 * lane] = 0xA0000000 + (4 * lane if offen else 3) + reference = directory / "expected.bin" + reference.write_bytes(words(*expected)) + replays.append((name, request, cso, views, reference)) + + for name, request, cso, views, reference in replays: + result = run(fixture, "replay", sdk, cache, request, cso, views, "hardware", "ok", "0", reference) + if result.returncode == 77: + print(result.stdout, result.stderr) + return 77 + if result.returncode != 0 or "output matches CPU reference (72 words)" not in result.stdout: + raise AssertionError((name, result.stdout, result.stderr)) + print(f"{name} matched the 72-word hardware readback") + return 0 + + +if __name__ == "__main__": + sys.exit(main(*sys.argv[1:])) diff --git a/tests/native_raw_store_cache_bits_check.py b/tests/native_raw_store_cache_bits_check.py new file mode 100644 index 0000000000..be08df7d50 --- /dev/null +++ b/tests/native_raw_store_cache_bits_check.py @@ -0,0 +1,68 @@ +"""Read back direct raw stores with cache hints and check modifier refusals.""" +import struct +import subprocess +import sys + +from native_bytewin_store_check import ( + GLC, GUARD_WORDS, IDXEN, LANE_BYTES, LANES, OUTPUT_WORDS, PLANE_BYTES, SENTINEL, + STORE_OPS, compute_program, main, request, sop1, +) + + +DLC = 1 << 15 +LDS = 1 << 16 +SLC = 1 << 22 +TFE = 1 << 23 +DWORD = STORE_OPS[0] +DWORDX4 = STORE_OPS[3] +REFUSAL = "raw store needs a linear byte offset" + + +def program(stores): + code = compute_program(ops=())[:-1] + # Groups (0,0,0) and (1,0,0) each run one wave32. + # Enable local lanes 0..7 in each group after initializing the data VGPRs. + code += [sop1(3, 126, 255), 0xff, sop1(3, 127, 128)] + for plane, (opcode, word1_flags) in enumerate(stores): + # One 1024-byte plane per store, 16 bytes per lane, including inactive lanes. + code += [opcode | plane * PLANE_BYTES, 0x80020208 | word1_flags] + return code + [0xBF810000] + + +def controls(cli, sdk, work, root): + for name, opcode, word1_flags in (("idxen", DWORD | GLC | IDXEN, 0), + ("lds", DWORD | GLC | LDS, 0), + ("tfe", DWORDX4 | GLC, TFE)): + marker = request(work, root, program(((opcode, word1_flags),))) + output = marker.with_suffix(".cso") + result = subprocess.run([cli, sdk, work / "cache", "gfx1013-direct-cs@0", marker, output], + capture_output=True, text=True) + assert result.returncode and REFUSAL in result.stderr and not output.exists(), (name, result.stderr) + print(f"{name}: refused") + return 0 + + +def hardware(replay, sdk, work, root): + stores = ((DWORD | GLC, 0), (DWORDX4 | GLC, 0), (DWORD | DLC, 0), (DWORDX4, SLC)) + marker = request(work, root, program(stores)) + output = work / "stores.bin" + result = subprocess.run([replay, sdk, marker, work / "cache", "0", output, "--direct"]) + if result.returncode == 77: + return 77 + result.check_returncode() + + expected = [SENTINEL] * OUTPUT_WORDS + for plane, width in enumerate((1, 4, 1, 4)): + for lane in range(LANES): + if lane % 32 < 8: + start = GUARD_WORDS + (plane * PLANE_BYTES + lane * LANE_BYTES) // 4 + expected[start:start + width] = [LANE_BYTES * lane + j + 1 for j in range(width)] + actual = struct.unpack(f"<{OUTPUT_WORDS}I", output.read_bytes()) + for word, (got, want) in enumerate(zip(actual, expected)): + assert got == want, (word, hex(got), hex(want)) + print("cache-hinted stores: updated words, untouched words and guards matched") + return 0 + + +if __name__ == "__main__": + sys.exit(main(*sys.argv[1:], checks={"controls": controls, "hardware": hardware})) diff --git a/tests/native_rcp_iflag_check.py b/tests/native_rcp_iflag_check.py new file mode 100644 index 0000000000..0f4faf7907 --- /dev/null +++ b/tests/native_rcp_iflag_check.py @@ -0,0 +1,265 @@ +"""v_rcp_iflag_f32 (VOP1, VOP3, SDWA, DPP16) in direct Compute and Pixel DXIL.""" +from dataclasses import dataclass +from pathlib import Path +import struct +import subprocess +import sys +import tempfile + +from native_direct_container_check import patched_pixel +from native_dpp_quad_check import request +import native_f16_alu_check as F +from native_packed_f16_inline_check import PROLOGUE +from native_scalar_lds_check import vmove +from startup_image_3d_check import FULLSCREEN_VS, compile_hlsl + + +def fbits(x): + return struct.unpack('<I', struct.pack('<f', x))[0] + + +def fval(b): + return struct.unpack('<f', struct.pack('<I', b & 0xFFFFFFFF))[0] + + +def vop1(op, dst, src0): + return [0x7E000000 | ((dst & 0xFF) << 17) | ((op & 0xFF) << 9) | (src0 & 0x1FF)] + + +def vop3(op, dst, src0, *, abs_bit=0, neg_bit=0, clamp=0, omod=0): + w0 = 0xD4000000 | ((op & 0x3FF) << 16) | ((clamp & 1) << 15) | ((abs_bit & 1) << 8) | (dst & 0xFF) + w1 = ((neg_bit & 1) << 29) | ((omod & 3) << 27) | (src0 & 0x1FF) + return [w0, w1] + + +def sdwa(op, dst, src_reg, *, src_scalar=0, abs_bit=0, neg_bit=0, clamp=0, omod=0, + src_sel=6, dst_sel=6, dst_unused=0): + w0 = 0x7E000000 | ((dst & 0xFF) << 17) | ((op & 0xFF) << 9) | 249 + ext = (((src_scalar & 1) << 23) | ((abs_bit & 1) << 21) | ((neg_bit & 1) << 20) | + ((src_sel & 7) << 16) | ((omod & 3) << 14) | ((clamp & 1) << 13) | + ((dst_unused & 3) << 11) | ((dst_sel & 7) << 8) | (src_reg & 0xFF)) + return [w0, ext] + + +def dpp(op, dst, src_vgpr, *, pattern=0xB1, row_mask=0xF, bank_mask=0xF): + w0 = 0x7E000000 | ((dst & 0xFF) << 17) | ((op & 0xFF) << 9) | 250 + ctrl = ((row_mask & 0xF) << 28) | ((bank_mask & 0xF) << 24) | ((pattern & 0x1FF) << 8) | (src_vgpr & 0xFF) + return [w0, ctrl] + + +def f32_inline(enc): + return {240: 0x3F000000, 241: 0xBF000000, 242: 0x3F800000, 243: 0xBF800000, + 244: 0x40000000, 245: 0xC0000000, 246: 0x40800000, 247: 0xC0800000}[enc] + + +@dataclass(frozen=True) +class Case: + name: str + form: str + src: int + val: int + abs_bit: int = 0 + neg_bit: int = 0 + clamp: int = 0 + omod: int = 0 + pixel_safe: bool = True + + def expected(self): + raw = f32_inline(self.src) if 240 <= self.src <= 248 else self.val + if self.abs_bit: + raw &= 0x7FFFFFFF + if self.neg_bit: + raw ^= 0x80000000 + r = 1.0 / fval(raw) + if self.omod == 1: + r *= 2.0 + elif self.omod == 2: + r *= 4.0 + elif self.omod == 3: + r *= 0.5 + if self.clamp: + r = 0.0 if r <= 0.0 else (1.0 if r >= 1.0 else r) + return fbits(r) + + +def all_cases(): + return [ + # VOP1: VGPR, SGPR, inline floats, literal. + Case('vop1_vgpr_two', 'vop1', 257, fbits(2.0)), + Case('vop1_vgpr_neg_four', 'vop1', 257, fbits(-4.0)), + Case('vop1_sgpr_eight', 'vop1', 10, fbits(8.0)), + Case('vop1_inline_240', 'vop1', 240, 0), + Case('vop1_inline_245', 'vop1', 245, 0), + Case('vop1_literal_eighth', 'vop1', 255, fbits(0.125)), + # VOP3: abs, neg, clamp, omod (*2, *4, *0.5). + Case('vop3_abs', 'vop3', 257, fbits(-2.0), abs_bit=1), + Case('vop3_neg', 'vop3', 257, fbits(4.0), neg_bit=1), + Case('vop3_clamp_hi', 'vop3', 257, fbits(0.25), clamp=1), + Case('vop3_clamp_lo', 'vop3', 257, fbits(-2.0), clamp=1), + Case('vop3_omod_2x', 'vop3', 257, fbits(4.0), omod=1), + Case('vop3_omod_4x', 'vop3', 257, fbits(8.0), omod=2), + Case('vop3_omod_half', 'vop3', 257, fbits(0.5), omod=3), + # SDWA: VGPR & SGPR DWORD with abs/neg/clamp. + Case('sdwa_vgpr_abs_neg', 'sdwa', 257, fbits(2.0), abs_bit=1, neg_bit=1), + Case('sdwa_sgpr_clamp', 'sdwa', 10, fbits(0.5), clamp=1), + # DPP16: quad_perm:[1,0,3,2] (lane 0 reads lane 1 = 0.25 -> 4.0) across compute lanes. + Case('dpp_quad_perm', 'dpp', 257, fbits(0.25), pixel_safe=False), + ] + + +def emit_case(c: Case, *, use_plain_rcp=False): + op_vop1 = 0x2A if use_plain_rcp else 0x2B + op_vop3 = 0x1AA if use_plain_rcp else 0x1AB + code = [] + if c.form == 'dpp': + code += F.mov(1, c.val) + code += dpp(op_vop1, 4, 1) + return code + if c.src >= 256: + code += F.mov(c.src - 256, c.val) + elif c.src <= 105: + code += F.smov(c.src, c.val) + if c.form == 'vop1': + code += vop1(op_vop1, 4, c.src) + if c.src == 255: + code.append(c.val) + elif c.form == 'vop3': + code += vop3(op_vop3, 4, c.src, abs_bit=c.abs_bit, neg_bit=c.neg_bit, clamp=c.clamp, omod=c.omod) + elif c.form == 'sdwa': + scalar = 1 if c.src <= 105 else 0 + reg = c.src if scalar else (c.src - 256) + code += sdwa(op_vop1, 4, reg, src_scalar=scalar, abs_bit=c.abs_bit, neg_bit=c.neg_bit, clamp=c.clamp) + else: + raise ValueError(c.form) + return code + + +def compute_program(cases, *, use_plain_rcp=False): + code = list(PROLOGUE) + want = [] + for slot, c in enumerate(cases): + code += emit_case(c, use_plain_rcp=use_plain_rcp) + F.store(slot * 4, 4) + want.append(c.expected()) + return code + [0xBF810000], want + + +def refusal_programs(): + return [ + # SDWA invalid dst_select=7 refused by SDWA profile validation. + (sdwa(0x2B, 4, 1, dst_sel=7) + [0xBF810000], 'unsupported SDWA destination modifier'), + # DPP16 partial row mask refused. + (dpp(0x2B, 4, 1, row_mask=0x5) + [0xBF810000], 'DPP requires a full-row, full-bank mask'), + ] + + +def controls(cli, sdk, work, root): + items = all_cases() + code, want = compute_program(items) + ctrl_code, _ = compute_program(items, use_plain_rcp=True) + m_iflag = request(work, root, code) + m_plain = request(work, root, ctrl_code) + o_iflag = work / 'iflag.cso' + o_plain = work / 'plain.cso' + for m, o in ((m_iflag, o_iflag), (m_plain, o_plain)): + r = subprocess.run([cli, sdk, work / 'cache', 'gfx1013-direct-cs@0', m, o], capture_output=True, text=True) + assert r.returncode == 0 and o.is_file(), (r.stdout, r.stderr) + d_iflag = subprocess.run([Path(sdk) / 'dxc.exe', '-dumpbin', o_iflag], capture_output=True, text=True, check=True).stdout + d_plain = subprocess.run([Path(sdk) / 'dxc.exe', '-dumpbin', o_plain], capture_output=True, text=True, check=True).stdout + assert 'fdiv float 1.000000e+00,' in d_iflag and d_iflag == d_plain, 'v_rcp_iflag_f32 DXIL mismatch vs v_rcp_f32' + + # Also verify Pixel stage compilation equivalence. + ps_items = [c for c in items if c.pixel_safe][:4] + ps_iflag = work / 'ps_iflag.ps' + ps_plain = work / 'ps_plain.ps' + ps_iflag.write_bytes(pixel_program(ps_items, use_plain_rcp=False)) + ps_plain.write_bytes(pixel_program(ps_items, use_plain_rcp=True)) + for src, cso in ((ps_iflag, ps_iflag.with_suffix('.cso')), (ps_plain, ps_plain.with_suffix('.cso'))): + r = subprocess.run([cli, sdk, work / 'cache', 'gfx1013-container-ps', src, cso], capture_output=True, text=True) + assert r.returncode == 0 and cso.is_file(), (r.stdout, r.stderr) + dp_iflag = subprocess.run([Path(sdk) / 'dxc.exe', '-dumpbin', ps_iflag.with_suffix('.cso')], + capture_output=True, text=True, check=True).stdout + dp_plain = subprocess.run([Path(sdk) / 'dxc.exe', '-dumpbin', ps_plain.with_suffix('.cso')], + capture_output=True, text=True, check=True).stdout + assert dp_iflag == dp_plain, 'Pixel DXIL mismatch vs v_rcp_f32' + + refusals = refusal_programs() + for idx, (prog, why) in enumerate(refusals): + m = request(work, root, prog) + o = work / f'refused-{idx}.cso' + r = subprocess.run([cli, sdk, work / 'cache', 'gfx1013-direct-cs@0', m, o], capture_output=True, text=True) + assert r.returncode != 0 and why in r.stderr, (idx, why, r.stdout, r.stderr) + assert not o.exists(), o + + print(f'native_rcp_iflag controls: {len(want)} Compute + {len(ps_items)} Pixel cases matched v_rcp_f32 DXIL; {len(refusals)} refusals matched') + return 0 + + +def hardware(replay, sdk, work, root): + items = all_cases() + code, want = compute_program(items) + marker = request(work, root, code) + output = work / 'out.bin' + run = subprocess.run([replay, sdk, marker, work / 'cache', '0', output, '--direct']) + if run.returncode == 77: + return 77 + run.check_returncode() + words_out = list(struct.unpack(f'<{F.WORDS}I', output.read_bytes())) + expected = [F.SENTINEL] * F.WORDS + for group in range(F.GROUPS): + for lane in range(32): + head = F.BASE + group * 1024 + lane * 32 + expected[head:head + len(want)] = want + mismatch = next((i for i, (a, b) in enumerate(zip(words_out, expected, strict=True)) if a != b), None) + assert mismatch is None, (mismatch, hex(words_out[mismatch]), hex(expected[mismatch])) + print(f'native_rcp_iflag compute hardware: {len(want)} cases matched across {F.GROUPS}x32 lanes and guards') + return 0 + + +def pixel_program(quad, *, use_plain_rcp=False): + code = [] + for idx, c in enumerate(quad): + code += emit_case(c, use_plain_rcp=use_plain_rcp) + code.append(vmove(8 + idx, 256 + 4)) + return patched_pixel(len(code), code, export=(0xF800180F, 0x0B0A0908)) + + +def pixel(cli, sdk, renderer, adapter, work): + items = [c for c in all_cases() if c.pixel_safe] + while len(items) % 4: + items.append(items[-1]) + vs = compile_hlsl(str(Path(sdk) / 'dxc.exe'), 'dxc', FULLSCREEN_VS, 'fullscreen', 'vs_6_0', work) + quads = [items[i:i + 4] for i in range(0, len(items), 4)] + for idx, quad in enumerate(quads): + shader = work / f'rcp-{idx}.ps' + shader.write_bytes(pixel_program(quad)) + cso = shader.with_suffix('.cso') + build = subprocess.run([cli, sdk, work / 'cache', 'gfx1013-container-ps', shader, cso], + capture_output=True, text=True, timeout=30) + assert build.returncode == 0, ([c.name for c in quad], build.stdout, build.stderr) + ref = work / 'expected.bin' + ref.write_bytes(struct.pack('<4I', *(c.expected() for c in quad))) + run = subprocess.run([renderer, adapter, '--startup-pixel-words', vs, cso, '1', '1', ref], + capture_output=True, text=True, timeout=30) + if run.returncode == 77: + return 77 + assert run.returncode == 0, (idx, [c.name for c in quad], run.stdout, run.stderr) + if 'debug_layer=enabled' in run.stdout: + assert 'debug_errors=0 debug_warnings=0' in run.stdout, run.stdout + print(f'native_rcp_iflag pixel ({adapter}): {len(quads)} quad draws matched') + return 0 + + +def main(mode, tool, sdk=None, *args): + with tempfile.TemporaryDirectory() as tmp: + work = Path(tmp) + if mode == 'pixel': + return pixel(tool, sdk, args[0], args[1], work) + shader = work / 'root.hlsl' + shader.write_text('#define SIG "DescriptorTable(UAV(u0,numDescriptors=8))"') + root = work / 'root.bin' + subprocess.run([Path(sdk) / 'dxc.exe', '-T', 'rootsig_1_1', '-E', 'SIG', '-Fo', root, shader], check=True) + return {'controls': controls, 'compute': hardware}[mode](tool, sdk, work, root.read_bytes()) + + +if __name__ == '__main__': + sys.exit(main(*sys.argv[1:])) diff --git a/tests/native_round_f16_check.py b/tests/native_round_f16_check.py new file mode 100644 index 0000000000..ccc211671b --- /dev/null +++ b/tests/native_round_f16_check.py @@ -0,0 +1,163 @@ +"""Direct compute v_floor_f16, v_ceil_f16, v_trunc_f16 and v_rndne_f16 (VOP1/VOP3A, high-half preserving).""" +from pathlib import Path +import struct +import subprocess +import sys +import tempfile + +from native_dpp_quad_check import request + +MASK = 0xFFFFFFFF +SENTINEL = 0x69696969 +HIGH_SEED = 0xBEEF0000 + +CASES = ( + 0xCAFE8000, # -0.0h (with high junk in src0) + 0x00000001, # +min_sub (2^-24) + 0x00008001, # -min_sub (-2^-24) + 0x00003800, # +0.5h (rndne ties to +0.0h) + 0x00003E00, # +1.5h (rndne ties to +2.0h) + 0x00004100, # +2.5h (rndne ties to +2.0h) + 0x0000BE00, # -1.5h (floor=-2, ceil=-1, trunc=-1, rndne=-2) + 0x000063FF, # +1023.5h (ceil/rndne carry into exponent -> 1024.0h = 0x6400) +) + + +def v_mov_lit(vdst, lit): + return [0x7E0002FF | ((vdst & 0xFF) << 17), lit & MASK] + + +def vop1(op, vdst, src0): + return 0x7E000000 | ((vdst & 0xFF) << 17) | ((op & 0xFF) << 9) | (src0 & 0x1FF) + + +def vop3_unary(op, vdst, src0, *, abs0=0, neg0=0, clamp=0, omod=0, op_sel=0): + w0 = (0xD4000000 | ((op & 0x3FF) << 16) | ((clamp & 1) << 15) | + ((op_sel & 0xF) << 11) | ((abs0 & 1) << 8) | (vdst & 0xFF)) + w1 = ((neg0 & 1) << 29) | ((omod & 3) << 27) | (src0 & 0x1FF) + return [w0, w1] + + +def program(): + code = [0xBE940304, 0xBE950380, 0xF408080A, 0xFA000020, + 0x8F078C05, 0x34100087, 0x4A101007, 0xBF8CC07F] + for ci, bits in enumerate(CASES): + code += v_mov_lit(2, bits) + # 0: VOP1 v_floor_f16 + code += v_mov_lit(4, HIGH_SEED | 0x1111) + [vop1(0x5B, 4, 258), 0xE0701000 | (4 * (ci * 4 + 0)), 0x80080408] + # 1: VOP1 v_ceil_f16 + code += v_mov_lit(4, HIGH_SEED | 0x2222) + [vop1(0x5C, 4, 258), 0xE0701000 | (4 * (ci * 4 + 1)), 0x80080408] + # 2: VOP3A v_trunc_f16 + code += v_mov_lit(4, HIGH_SEED | 0x3333) + vop3_unary(0x1DD, 4, 258) + [0xE0701000 | (4 * (ci * 4 + 2)), 0x80080408] + # 3: VOP3A v_rndne_f16 + code += v_mov_lit(4, HIGH_SEED | 0x4444) + vop3_unary(0x1DE, 4, 258) + [0xE0701000 | (4 * (ci * 4 + 3)), 0x80080408] + return code + [0xBF810000] + + +def round_f16(bits, mode, *, ties_away=False, lose_neg_zero=False): + bits &= 0xFFFF + sign = 0 if lose_neg_zero else (bits & 0x8000) + neg = (bits & 0x8000) != 0 + mag = bits & 0x7FFF + exp = (bits >> 10) & 0x1F + if exp >= 25: + return bits + if exp < 15: + if mode == 'trunc': + return sign + if mode == 'floor': + return 0xBC00 if (mag != 0 and neg) else sign + if mode == 'ceil': + return 0x3C00 if (mag != 0 and not neg) else sign + # rndne + if ties_away: + return (bits & 0x8000) | 0x3C00 if mag >= 0x3800 else sign + return (bits & 0x8000) | 0x3C00 if mag > 0x3800 else sign + frac_bits = 25 - exp + unit = 1 << frac_bits + mask = unit - 1 + half = unit >> 1 + frac = bits & mask + base = bits & (~mask & 0xFFFF) + if mode == 'trunc': + return base + if mode == 'floor': + return (base + unit) & 0xFFFF if (neg and frac != 0) else base + if mode == 'ceil': + return (base + unit) & 0xFFFF if ((not neg) and frac != 0) else base + # rndne + if ties_away: + inc = frac >= half + else: + inc = frac > half or (frac == half and (base & unit) != 0) + return (base + unit) & 0xFFFF if inc else base + + +def reference(*, ties_away=False, lose_neg_zero=False, zero_high=False): + hi = 0 if zero_high else HIGH_SEED + words = [SENTINEL] * 8 + for _lane in range(64): + for bits in CASES: + words.extend(( + hi | round_f16(bits, 'floor', ties_away=ties_away, lose_neg_zero=lose_neg_zero), + hi | round_f16(bits, 'ceil', ties_away=ties_away, lose_neg_zero=lose_neg_zero), + hi | round_f16(bits, 'trunc', ties_away=ties_away, lose_neg_zero=lose_neg_zero), + hi | round_f16(bits, 'rndne', ties_away=ties_away, lose_neg_zero=lose_neg_zero), + )) + return words + [SENTINEL] * 8 + + +def controls(cli, sdk, work, root): + marker = request(work, root, program()) + output = marker.with_suffix('.cso') + result = subprocess.run([cli, sdk, work / 'cache', 'gfx1013-direct-cs@0', marker, output], + capture_output=True, text=True) + assert result.returncode == 0 and output.is_file(), (result.stdout, result.stderr) + dump = subprocess.run([Path(sdk) / 'dxc.exe', '-dumpbin', output], capture_output=True, + text=True, check=True).stdout + assert 'shl i32 ' in dump and 'lshr i32 ' in dump, dump + for tag, bad, msg in ( + ('omod', vop3_unary(0x1DB, 4, 258, omod=1) + [0xBF810000], 'unsupported v_floor_f16 operand modifiers'), + ('op_sel', vop3_unary(0x1DE, 4, 258, op_sel=1) + [0xBF810000], 'unsupported v_rndne_f16 operand modifiers'), + ): + sub = work / tag + sub.mkdir(exist_ok=True) + bad_marker = request(sub, root, bad) + bad_res = subprocess.run([cli, sdk, work / 'cache', 'gfx1013-direct-cs@0', bad_marker, + bad_marker.with_suffix('.cso')], capture_output=True, text=True) + assert bad_res.returncode != 0 and msg in (bad_res.stdout + bad_res.stderr), (tag, bad_res.stdout, bad_res.stderr) + assert reference() != reference(ties_away=True) + assert reference() != reference(lose_neg_zero=True) + assert reference() != reference(zero_high=True) + print('v_floor/ceil/trunc/rndne_f16 DXIL verified; invalid modifiers refused; tie, -0 and high-half controls differ') + return 0 + + +def hardware(replay, sdk, work, root): + marker = request(work, root, program()) + output = work / 'out.bin' + result = subprocess.run([replay, sdk, marker, work / 'cache', '0', output, '--direct']) + if result.returncode == 77: + return 77 + result.check_returncode() + expected = reference() + actual = struct.unpack(f'<{len(expected)}I', output.read_bytes()) + mismatch = next((i for i, (a, e) in enumerate(zip(actual, expected)) if a != e), None) + if mismatch is not None: + raise AssertionError(f'word {mismatch}: got {actual[mismatch]:08x}, expected {expected[mismatch]:08x}') + print('v_floor/ceil/trunc/rndne_f16: 2048 result words (high halves kept) and 16 guards matched') + return 0 + + +def main(mode, executable, sdk): + with tempfile.TemporaryDirectory(prefix='x2w_native_round_f16_') as temp: + work = Path(temp) + shader = work / 'root.hlsl' + shader.write_text('#define SIG "DescriptorTable(UAV(u0,numDescriptors=8))"') + root = work / 'root.bin' + subprocess.run([Path(sdk) / 'dxc.exe', '-T', 'rootsig_1_1', '-E', 'SIG', '-Fo', root, shader], check=True) + return (controls if mode == 'controls' else hardware)(executable, sdk, work, root.read_bytes()) + + +if __name__ == '__main__': + raise SystemExit(main(sys.argv[1], sys.argv[2], sys.argv[3])) diff --git a/tests/native_rtv_variant_check.py b/tests/native_rtv_variant_check.py index f1e2c47de0..58980d090a 100644 --- a/tests/native_rtv_variant_check.py +++ b/tests/native_rtv_variant_check.py @@ -288,7 +288,8 @@ def draw(fmt=None): key = G.fnv(line.encode('ascii')) assert (cache / f'req_{key:016x}.rtv').read_bytes() == line.encode('ascii'), line variants.append((key, line, types, target)) - assert sorted(p.name for p in cache.iterdir()) == sorted( + # The first request also writes the stand-in's revision.txt; it is not a request. + assert sorted(p.name for p in cache.iterdir() if p.name != 'revision.txt') == sorted( [f'req_{base:016x}{e}' for e in ('.a', '.b', '.root')] + [f'req_{key:016x}.rtv' for key, *_ in variants]) check_published(cli, sdk, work / 'frontend', cache, base, variants) diff --git a/tests/native_s_not_b64_exec_check.py b/tests/native_s_not_b64_exec_check.py new file mode 100644 index 0000000000..e3763bec27 --- /dev/null +++ b/tests/native_s_not_b64_exec_check.py @@ -0,0 +1,143 @@ +"""Compile and replay 64-bit NOT and CSELECT with the compute mask registers.""" +from pathlib import Path +import struct +import subprocess +import sys +import tempfile + +from native_scalar_lds_check import scalar, sop1, vmove +from native_wave64_exec_salu_check import ( + END, EXEC, GROUP_STRIDE_WORDS, GUARD_WORDS, NEG_ONE, OUTPUT_WORDS, + SENTINEL, VCC, ZERO, compile_request, request, +) + + +NOT_B64, CSELECT_B64 = 0x08, 0x0B +MOV_B32, MOV_B64, LITERAL = 3, 4, 255 +M0, RESULT = 124, 24 +MASK32, MASK64 = (1 << 32) - 1, (1 << 64) - 1 +EXEC_MASK = 0xA5600FF00F0FF00F +VCC_MASK = 0x3150C4D2FFFFFFFF +PLANE_WORDS = 2 * GROUP_STRIDE_WORDS +CASES = ("not_exec", "not_vcc", "not_vcc_all_ones", "select_scc0", "select_scc1", "not_into_exec") + + +def move_pair(dst, bits): + return [sop1(MOV_B32, dst, LITERAL), bits & MASK32, + sop1(MOV_B32, dst + 1, LITERAL), bits >> 32] + + +def set_scc(value): + # s_cmp_eq_u32 0, 0 (SCC = 1) or s_cmp_eq_u32 0, 1 (SCC = 0). + return 0xBF060000 | (ZERO + (1 - value)) << 8 | ZERO + + +def store(vgpr, plane): + return [0xE0701000 | (4 * PLANE_WORDS * plane), 0x80080008 | vgpr << 8] + + +def program(case): + # Prepare every lane's address before narrowing EXEC. The shader uses + # the same two-group UAV layout as the wave64 EXEC SALU fixture. + words = [ + sop1(MOV_B64, EXEC, NEG_ONE), + sop1(MOV_B32, 20, 4), sop1(MOV_B32, 21, ZERO), + 0xF408080A, 0xFA000020, # s_load_dwordx4 s[32:35], s[20:21], 0x20 + scalar(0x1E, 7, 5, ZERO + 9), # s_lshl_b32 s7, s5, 9 + 0x34100082, # v_lshlrev_b32 v8, 2, v0 + 0x4A101007, # v_add_nc_u32 v8, s7, v8 + ] + words += move_pair(EXEC, EXEC_MASK) + words += move_pair(VCC, MASK64 if case == "not_vcc_all_ones" else VCC_MASK) + if case.startswith("select"): + words += [set_scc(int(case[-1])), scalar(CSELECT_B64, RESULT, EXEC, VCC)] + elif case == "not_into_exec": + words += [set_scc(0), sop1(NOT_B64, EXEC, EXEC), *store(0, 0)] + # Save both new EXEC words before restoring all lanes for readback. + words.append(sop1(MOV_B64, RESULT, EXEC)) + else: + source = EXEC if case == "not_exec" else VCC + words += [set_scc(int(case == "not_vcc_all_ones")), sop1(NOT_B64, RESULT, source)] + + words += [sop1(MOV_B64, EXEC, NEG_ONE), scalar(0x0A, RESULT + 2, ZERO + 1, ZERO)] + for plane, src in enumerate((RESULT, RESULT + 1, RESULT + 2), start=1): + words += [vmove(1, src), *store(1, plane)] + return words + [END] + + +def expected_words(wave_size, case): + if case.startswith("select"): + scc = int(case[-1]) + result = EXEC_MASK if scc else VCC_MASK + else: + source = {"not_exec": EXEC_MASK, "not_vcc": VCC_MASK, + "not_vcc_all_ones": MASK64, "not_into_exec": EXEC_MASK}[case] + result = source ^ MASK64 + scc = int(result != 0) + expected = [SENTINEL] * OUTPUT_WORDS + for group in range(2): + for lane in range(wave_size): + index = GUARD_WORDS + group * GROUP_STRIDE_WORDS + lane + if case == "not_into_exec" and result & (1 << lane): + expected[index] = lane + for plane, value in enumerate((result & MASK32, result >> 32, scc), start=1): + expected[index + plane * PLANE_WORDS] = value + return expected + + +def controls(cli, sdk, work, root): + cache = work / "cache" + failures = [] + for wave_size in (32, 64): + for case in CASES: + marker = request(work, root, wave_size, wave_size, program(case)) + output, result = compile_request(cli, sdk, cache, marker) + if result.returncode or not output.is_file(): + failures.append((wave_size, case, result.stdout, result.stderr)) + assert not failures, failures + + prefix = [sop1(MOV_B32, 23, ZERO), sop1(MOV_B32, M0, ZERO), set_scc(1)] + refusals = [ + (sop1(NOT_B64, RESULT, src), "invalid s_not_b64 source") + for src in (23, M0) + ] + [ + (scalar(CSELECT_B64, RESULT, a, b), "invalid s_cselect_b64 source") + for src in (23, M0) for a, b in ((src, ZERO), (ZERO, src)) + ] + [(scalar(CSELECT_B64, EXEC, ZERO, ZERO), "invalid s_cselect_b64 destination")] + for instruction, error in refusals: + marker = request(work, root, 64, 64, prefix + [instruction, END]) + output, result = compile_request(cli, sdk, cache, marker) + assert result.returncode and error in result.stderr, (error, result.stdout, result.stderr) + assert not output.exists(), output + print("Wave32 and wave64 compile controls and invalid operand refusals passed") + return 0 + + +def hardware(replay, sdk, work, root): + for wave_size in (32, 64): + for case in CASES: + marker = request(work, root, wave_size, wave_size, program(case)) + output = work / f"wave{wave_size}_{case}.bin" + result = subprocess.run([replay, sdk, marker, work / "cache", "0", output, "--direct"]) + if result.returncode == 77: + return 77 + result.check_returncode() + actual = struct.unpack(f"<{OUTPUT_WORDS}I", output.read_bytes()) + for index, (got, want) in enumerate(zip(actual, expected_words(wave_size, case))): + assert got == want, (wave_size, case, index, hex(got), hex(want)) + print(f"wave{wave_size} {case}: both groups and guards matched") + return 0 + + +def main(mode, tool, sdk): + with tempfile.TemporaryDirectory() as temp: + work = Path(temp) + shader, root_file = work / "root.hlsl", work / "root.bin" + shader.write_text('#define SIG "DescriptorTable(UAV(u0,numDescriptors=8))"') + subprocess.run([Path(sdk) / "dxc.exe", "-T", "rootsig_1_1", "-E", "SIG", + "-Fo", root_file, shader], check=True) + return {"controls": controls, "hardware": hardware}[mode](tool, sdk, work, root_file.read_bytes()) + + +if __name__ == "__main__": + sys.exit(main(*sys.argv[1:])) diff --git a/tests/native_salu64_check.py b/tests/native_salu64_check.py index 25c52f8381..41a94d07c4 100644 --- a/tests/native_salu64_check.py +++ b/tests/native_salu64_check.py @@ -47,7 +47,7 @@ def compute_program(instructions, dst): def controls(cli, sdk, work, root): for words, error in (([scalar(CSELECT, 126, NEG_ONE, ZERO), 0xBF810000], "invalid s_cselect_b64 destination"), - ([sop1(NOT, 24, 106), 0xBF810000], "invalid s_not_b64 source")): + ([sop1(NOT, 24, 127), 0xBF810000], "invalid s_not_b64 source")): marker = request(work, root, words) output = marker.with_suffix(".cso") result = subprocess.run([cli, sdk, work / "cache", "gfx1013-direct-cs@0", marker, output], diff --git a/tests/native_salu_bitscan64_check.py b/tests/native_salu_bitscan64_check.py index 859e60745a..a4cc011eea 100644 --- a/tests/native_salu_bitscan64_check.py +++ b/tests/native_salu_bitscan64_check.py @@ -182,7 +182,7 @@ def controls(cli, sdk, work, root): ([sop1(FF1_64, EXEC, 22), 0xBF810000], 'invalid s_ff1_i32_b64 destination'), ([sop1(FF0_64, 24, 23), 0xBF810000], 'invalid s_ff0_i32_b64 source'), ([sop1(FLBIT_B64, 24, VCC), 0xBF810000], 'invalid s_flbit_i32_b64 source'), - ([sop1(BCNT0_64, 24, EXEC), 0xBF810000], 'invalid s_bcnt0_i32_b64 source'), + ([sop1(BCNT0_64, 24, EXEC + 1), 0xBF810000], 'invalid s_bcnt0_i32_b64 source'), ([sop1(FLBIT_I64, 24, FLOAT_ONE), 0xBF810000], 'invalid s_flbit_i32_i64 source'), ) for n, (words, error) in enumerate(refused): diff --git a/tests/native_saveexec_wrexec_check.py b/tests/native_saveexec_wrexec_check.py new file mode 100644 index 0000000000..46708c6a31 --- /dev/null +++ b/tests/native_saveexec_wrexec_check.py @@ -0,0 +1,459 @@ +"""Direct Compute DXIL checks for all remaining SOP1 *_saveexec_* and *_wrexec_* ops (#3296, Refs #2935).""" +from pathlib import Path +import re +import struct +import subprocess +import sys +import tempfile + +from native_compute_clear_check import write_request +from native_dpp_mirror_check import vop2 +from native_f16_alu_check import _branch, _exec, _i32, pack, words as pack_words +from native_scalar_lds_check import scalar, sop1, vmove + + +MOV_B32, MOV_B64 = 3, 4 +ZERO, ONE, NEG_ONE, M0, LITERAL = 128, 129, 193, 124, 255 +VCC_LO, EXEC_LO, EXEC_HI = 106, 126, 127 +MASK32, MASK64 = 0xFFFFFFFF, (1 << 64) - 1 +GUARD_WORDS, OUTPUT_WORDS = 8, 2064 +GROUP_WORDS, PLANE_WORDS = 128, 256 +PLANE_BYTES = PLANE_WORDS * 4 +SENTINEL = 0x69696969 +END = 0xBF810000 +ACTIVE_SENTINEL = 0x11110000 + +# Remaining 9 wave32 SOP1 ops (0x3e..0x46) and 3 wave64 SOP1 ops (0x37..0x39). +WAVE32_OPS = ( + ("s_xor_saveexec_b32", 0x3E, True), + ("s_andn2_saveexec_b32", 0x3F, True), + ("s_orn2_saveexec_b32", 0x40, True), + ("s_nand_saveexec_b32", 0x41, True), + ("s_nor_saveexec_b32", 0x42, True), + ("s_xnor_saveexec_b32", 0x43, True), + ("s_andn1_saveexec_b32", 0x44, True), + ("s_orn1_saveexec_b32", 0x45, True), + ("s_andn1_wrexec_b32", 0x46, False), +) +WAVE64_OPS = ( + ("s_andn1_saveexec_b64", 0x37, True), + ("s_orn1_saveexec_b64", 0x38, True), + ("s_andn1_wrexec_b64", 0x39, False), +) + + +def op_kind(name): + return name.split("_")[1] + + +def combine_bits(op, a, b, width): + mask = (1 << width) - 1 + if op == "and": + return a & b + if op == "or": + return a | b + if op == "xor": + return a ^ b + if op == "andn2": + return a & (b ^ mask) + if op == "orn2": + return (a | (b ^ mask)) & mask + if op == "andn1": + return (a ^ mask) & b + if op == "orn1": + return ((a ^ mask) | b) & mask + if op == "nand": + return (a & b) ^ mask + if op == "nor": + return (a | b) ^ mask + if op == "xnor": + return (a ^ b) ^ mask + raise ValueError(op) + + +def set_scc(value): + # s_cmp_eq_u32 0, (0 for true, 1 for false) + return 0xBF060080 | ((ZERO if value else ONE) << 8) + + +def store(vgpr, plane): + return [0xE0701000 | (plane * PLANE_BYTES), 0x80080008 | (vgpr << 8)] + + +def compute_container(code_bytes, wave32=True, threads=None): + """Build a .cdx container compatible with native_compute_ir_dump (table=s4, group=s5).""" + if threads is None: + threads = 32 if wave32 else 64 + body = bytearray(256) + struct.pack_into("<Q", body, 0, 6) + for offset in (8, 16, 24, 32, 40, 48, 72): + struct.pack_into("<Q", body, offset, 0xDEADBEEFDEADBEEF) + record = 112 + struct.pack_into("<Q", body, 96, record) + struct.pack_into("<Q", body, record + 40, len(body)) + struct.pack_into("<I", body, record + 56, 1) + body.extend(pack_words(3, 0, 1, 0, 4)) + struct.pack_into("<QQ", body, record, len(body), len(code_bytes)) + struct.pack_into("<I", body, record + 20, 32 if wave32 else 0) + struct.pack_into("<II", body, record + 76, 512, 4) + struct.pack_into("<IIII", body, record + 120, 0x8A, threads, 1, 1) + body.extend(code_bytes) + return pack(body) + + +def request(work, root, wave_size, threads, prog_words): + z = 1 | (1 << 20 if wave_size == 32 else 0) + sa = struct.pack("<7I", 0, 0, 0, threads | (1 << 16), z, 0, 0x8A) + return write_request(work, prog_words, root, sa) + + +def wave32_cases(): + # (label, name, opcode, save, threads, old_exec, dst, src_reg, src_val, seed_reg) + return [ + # Non-zero cases (SCC=1, incoming SCC=0), asymmetric inputs to distinguish every op and operand order. + ("w32_xor_nz", "s_xor_saveexec_b32", 0x3E, True, 32, 0xA5A50003, 24, 22, 0x0F0F00F2, None), + ("w32_andn2_nz", "s_andn2_saveexec_b32", 0x3F, True, 32, 0x0F0F00F2, 24, 22, 0xA5A50003, None), + ("w32_orn2_nz", "s_orn2_saveexec_b32", 0x40, True, 32, 0xF0F0FF0C, 24, 22, 0x12340001, None), + ("w32_nand_nz", "s_nand_saveexec_b32", 0x41, True, 32, 0xA5A50003, 24, 22, 0xFFFF0002, None), + ("w32_nor_nz", "s_nor_saveexec_b32", 0x42, True, 32, 0x0F0F00F2, 24, 22, 0xF0F00004, None), + ("w32_xnor_nz", "s_xnor_saveexec_b32", 0x43, True, 32, 0xA5A50003, 24, 22, 0x5A5A00F2, None), + ("w32_andn1_nz", "s_andn1_saveexec_b32", 0x44, True, 32, 0xA5A50003, 24, 22, 0x0F0F0002, None), + ("w32_orn1_nz", "s_orn1_saveexec_b32", 0x45, True, 32, 0x00000011, 24, 22, 0xFFFF00FE, None), + ("w32_wr1_nz", "s_andn1_wrexec_b32", 0x46, False, 32, 0xA5A50003, 24, 22, 0x0F0F0002, None), + # Zero-result cases (SCC=0, incoming SCC=1), covering aliasing, inline, literal, VCC, EXEC_LO, partial wave. + ("w32_xor_z", "s_xor_saveexec_b32", 0x3E, True, 32, 0x12345678, 22, 22, 0x12345678, None), # dst == src + ("w32_andn2_z", "s_andn2_saveexec_b32", 0x3F, True, 32, 0xFFFFFFFF, 106, 22, 0x12345678, None), # dst=vcc_lo + ("w32_orn2_z", "s_orn2_saveexec_b32", 0x40, True, 32, 0xFFFFFFFF, 24, ZERO, 0, None), # inline 0 + ("w32_nand_z", "s_nand_saveexec_b32", 0x41, True, 32, 0xFFFFFFFF, 24, NEG_ONE, 0xFFFFFFFF, None), # inline -1 + ("w32_nor_z", "s_nor_saveexec_b32", 0x42, True, 32, 0xF0F0F0F0, 24, LITERAL, 0x0F0F0F0F, None), # literal + ("w32_xnor_z", "s_xnor_saveexec_b32", 0x43, True, 32, 0x55AA33CC, 24, 106, 0xAA55CC33, 106), # src=vcc_lo + ("w32_andn1_z", "s_andn1_saveexec_b32", 0x44, True, 8, 0x000000A5, 24, NEG_ONE, 0xFFFFFFFF, None), # partial + ("w32_orn1_z", "s_orn1_saveexec_b32", 0x45, True, 32, 0x00000000, 24, NEG_ONE, 0xFFFFFFFF, None), + ("w32_wr1_z", "s_andn1_wrexec_b32", 0x46, False, 32, 0x12345679, 22, 22, 0xFFFFFFFF, None), # dst == src + ("w32_xor_exec", "s_xor_saveexec_b32", 0x3E, True, 32, 0x000000FF, 24, EXEC_LO, 0x000000FF, None), # src=exec_lo + ] + + +def wave64_cases(): + # (label, name, opcode, save, threads, old_exec, dst, src_reg, src_val) + return [ + # Non-zero with bit 0 set (low & high both exercised). + ("w64_andn1_nz", "s_andn1_saveexec_b64", 0x37, True, 64, (0x80000013, 0x40000021), 24, 22, (0x00000012, 0x40000000)), + ("w64_orn1_nz", "s_orn1_saveexec_b64", 0x38, True, 64, (0x00000001, 0x40000000), 24, 22, (0xFFFFFF0E, 0xBFFFFF0F)), + ("w64_wr1_nz", "s_andn1_wrexec_b64", 0x39, False, 128, (0x80000013, 0x40000021), 22, 22, (0x00000012, 0x40000000)), # dst == src + # High-word-only non-zero (lo == 0, hi != 0 -> verifies SCC combines hi word, bit 0 == 0). + ("w64_andn1_hi", "s_andn1_saveexec_b64", 0x37, True, 64, (0x000000FF, 0x80000010), 24, 22, (0x000000FF, 0x0000000F)), + ("w64_orn1_hi", "s_orn1_saveexec_b64", 0x38, True, 64, (0x00000000, 0x00000001), 24, 22, (0xFFFFFFFF, 0xFFFFFFFE)), + ("w64_wr1_hi", "s_andn1_wrexec_b64", 0x39, False, 64, (0x000000FF, 0x80000010), 24, 22, (0x000000FF, 0x0000000F)), + # Zero-result cases (SCC=0, incoming SCC=1). + ("w64_andn1_z", "s_andn1_saveexec_b64", 0x37, True, 64, (0x80000012, 0x40000009), 24, NEG_ONE, (MASK32, MASK32)), + ("w64_orn1_z", "s_orn1_saveexec_b64", 0x38, True, 64, (0x00000000, 0x00000000), 24, NEG_ONE, (MASK32, MASK32)), + ("w64_wr1_z", "s_andn1_wrexec_b64", 0x39, False, 64, (0x80000012, 0x40000009), 24, 22, (MASK32, MASK32)), + ] + + +def build_wave32_program(case): + _, name, opcode, save, _, old_exec, dst, src_reg, src_val, seed_reg = case + new_exec = combine_bits(op_kind(name), src_val, old_exec, 32) + dst_val = old_exec if save else new_exec + scc = int(new_exec != 0) + # v8 = 512 * group.x + 4 * local.x; v1 = 0x11110000 + local.x + prog = [ + sop1(MOV_B32, 20, 4), sop1(MOV_B32, 21, ZERO), + 0xF408080A, 0xFA000020, # s_load_dwordx4 s[32:35], s[20:21], 0x20 + scalar(0x1E, 7, 5, ZERO + 9), # s_lshl_b32 s7, s5, 9 + vop2(0x1A, 8, ZERO + 2, 0), # v_lshlrev_b32 v8, 2, v0 + vop2(0x25, 8, 7, 8), # v_add_nc_u32 v8, s7, v8 + vop2(0x25, 1, LITERAL, 0), ACTIVE_SENTINEL, # v_add_nc_u32 v1, ACTIVE_SENTINEL, v0 + 0xBF8CC07F, # s_waitcnt lgkmcnt(0) + sop1(MOV_B32, EXEC_LO, LITERAL), old_exec, + ] + if seed_reg is not None: + prog += [sop1(MOV_B32, seed_reg, LITERAL), src_val] + elif src_reg < 106: + prog += [sop1(MOV_B32, src_reg, LITERAL), src_val] + prog.append(set_scc(1 - scc)) + prog.append(sop1(opcode, dst, src_reg)) + if src_reg == LITERAL: + prog.append(src_val) + prog += [ + *store(1, 0), # active-lane write under new EXEC + scalar(0x0A, 26, ONE, ZERO), # s_cselect_b32 s26, 1, 0 (captures SCC) + sop1(MOV_B32, 27, EXEC_LO), # capture new EXEC + sop1(MOV_B32, EXEC_LO, NEG_ONE), + ] + for plane, reg in ((1, dst), (2, 27), (3, 26)): + prog += [vmove(2, reg), *store(2, plane)] + prog.append(END) + return prog, new_exec, dst_val, scc + + +def build_wave64_program(case): + _, name, opcode, save, _, old_exec, dst, src_reg, src_val = case + old64 = old_exec[0] | (old_exec[1] << 32) + src64 = src_val[0] | (src_val[1] << 32) + new64 = combine_bits(op_kind(name), src64, old64, 64) + new_exec = (new64 & MASK32, new64 >> 32) + dst_val = old_exec if save else new_exec + scc = int(new64 != 0) + prog = [ + sop1(MOV_B64, 126, NEG_ONE), + sop1(MOV_B32, 20, 4), sop1(MOV_B32, 21, ZERO), + 0xF408080A, 0xFA000020, + scalar(0x1E, 7, 5, ZERO + 9), + vop2(0x1A, 8, ZERO + 2, 0), + vop2(0x25, 8, 7, 8), + vop2(0x25, 1, LITERAL, 0), ACTIVE_SENTINEL, + 0xBF8CC07F, + sop1(MOV_B32, EXEC_LO, LITERAL), old_exec[0], + sop1(MOV_B32, EXEC_HI, LITERAL), old_exec[1], + ] + if src_reg < 106: + prog += [ + sop1(MOV_B32, src_reg, LITERAL), src_val[0], + sop1(MOV_B32, src_reg + 1, LITERAL), src_val[1], + ] + prog += [ + set_scc(1 - scc), + sop1(opcode, dst, src_reg), + *store(1, 0), # plane 0: active lanes under new EXEC + scalar(0x0A, 26, ONE, ZERO), # s26 = SCC + sop1(MOV_B64, 28, EXEC_LO), # s[28:29] = new EXEC + sop1(MOV_B64, EXEC_LO, NEG_ONE), + ] + for plane, reg in ((1, dst), (2, dst + 1), (3, 26)): + prog += [vmove(2, reg), *store(2, plane)] + # Advance v8 by 4096 so planes 4 and 5 stay within the 12-bit MUBUF offset field. + prog += [0x4A1010FF, 0x1000] + for plane, reg in ((0, 28), (1, 29)): + prog += [vmove(2, reg), *store(2, plane)] + prog.append(END) + return prog, new_exec, dst_val, scc + + +def interpret(ir_text): + """Evaluate lane 0 of a straight-line DXIL compute module.""" + body = ir_text.split("define void @main()", 1)[1].split("\n}", 1)[0] + blocks, label, buf = {}, None, [] + for raw in body.splitlines(): + line = raw.strip() + if not line or line == "{": + continue + if line.endswith(":") and " " not in line: + if label is not None: + blocks[label] = buf + label, buf = line[:-1], [] + continue + buf.append(line) + if label is not None: + blocks[label] = buf + values, memory, shared_mem, stores = {}, {}, {}, [] + label, prev_label, steps = "entry", None, 0 + while steps < 200000: + steps += 1 + followed = False + for line in blocks[label]: + if line.startswith("br "): + prev_label, label = label, _branch(line, values) + followed = True + break + if line == "ret void": + return sorted(stores) + if (m := re.fullmatch(r"(%\w+) = call i32 @dx\.op\.waveActiveOp\.i32\(.+\)", line)): + values[m.group(1)] = ("i32", 0) + elif line.startswith("call void @dx.op.barrier("): + continue + elif (m := re.fullmatch(r"(%\w+) = getelementptr .+, i32 (\S+)$", line)): + values[m.group(1)] = ("sptr", _i32(m.group(2), values)) + elif (m := re.fullmatch(r"store i32 (\S+), i32 addrspace\(3\)\* (%\w+), align 4", line)): + shared_mem[values[m.group(2)][1]] = _i32(m.group(1), values) + elif (m := re.fullmatch(r"(%\w+) = load i32, i32 addrspace\(3\)\* (%\w+), align 4", line)): + values[m.group(1)] = ("i32", shared_mem.get(values[m.group(2)][1], 0)) + elif (m := re.fullmatch(r"(%\w+) = phi i32 (.+)", line)): + chosen = None + for val_tok, pred in re.findall(r"\[([^,\]]+), %([^\]]+)\]", m.group(2)): + if pred == prev_label: + chosen = _i32(val_tok.strip(), values) + break + assert chosen is not None, (line, prev_label) + values[m.group(1)] = ("i32", chosen) + else: + _exec(line, values, memory, stores) + if not followed: + raise AssertionError("block fell through: " + label) + raise AssertionError("step limit") + + +def refusal_programs(): + init64 = [sop1(MOV_B64, 22, NEG_ONE), sop1(MOV_B64, VCC_LO, NEG_ONE)] + return [ + (True, 32, [sop1(0x3E, EXEC_LO, NEG_ONE), END], "unsupported wave32 SAVEEXEC destination"), + (True, 32, [sop1(0x46, EXEC_LO, NEG_ONE), END], "unsupported wave32 SAVEEXEC destination"), + (True, 32, [sop1(0x44, M0, NEG_ONE), END], "unsupported wave32 SAVEEXEC destination"), + (False, 64, [sop1(0x3E, 24, NEG_ONE), END], "direct DXIL lowering for s_xor_saveexec_b32"), + (False, 64, [sop1(0x46, 24, NEG_ONE), END], "direct DXIL lowering for s_andn1_wrexec_b32"), + (False, 64, [*init64, sop1(0x39, 24, VCC_LO), END], "unsupported wave64 scalar operation"), + (False, 64, [*init64, sop1(0x39, 25, 22), END], "unsupported wave64 scalar operation"), + (False, 64, [*init64, sop1(0x37, 25, 22), END], "unsupported wave64 scalar operation"), + ] + + +def check_oracles(): + # Ensure mutant references (swapped n1/n2, dropped ~ on nand/nor/xnor, save-vs-wrexec swap) differ cleanly. + for op in ("andn1", "orn1"): + for a, b in ((0x0F0F0002, 0xA5A50003),): + assert combine_bits(op, a, b, 32) != combine_bits(op.replace("n1", "n2"), a, b, 32) + for op, alt in (("nand", "and"), ("nor", "or"), ("xnor", "xor")): + assert combine_bits(op, 0x0F0F00F2, 0xA5A50003, 32) != combine_bits(alt, 0x0F0F00F2, 0xA5A50003, 32) + + +def ir(dumper): + check_oracles() + with tempfile.TemporaryDirectory() as temp: + work = Path(temp) + for case in wave32_cases(): + label = case[0] + prog, new_exec, dst_val, scc = build_wave32_program(case) + path = work / f"{label}.cdx" + path.write_bytes(compute_container(pack_words(*prog), wave32=True, threads=case[4])) + run = subprocess.run([dumper, str(path)], capture_output=True, text=True) + assert run.returncode == 0, (label, run.stderr) + stores = dict(interpret(run.stdout)) + if new_exec & 1: + assert stores.get(0) == ACTIVE_SENTINEL, (label, stores) + else: + assert 0 not in stores, (label, stores) + assert stores.get(1 * PLANE_BYTES) == dst_val, (label, hex(stores.get(PLANE_BYTES, -1)), hex(dst_val)) + assert stores.get(2 * PLANE_BYTES) == new_exec, (label, hex(stores.get(2 * PLANE_BYTES, -1)), hex(new_exec)) + assert stores.get(3 * PLANE_BYTES) == scc, (label, stores.get(3 * PLANE_BYTES), scc) + + for case in wave64_cases(): + label = case[0] + prog, new_exec, dst_val, scc = build_wave64_program(case) + path = work / f"{label}.cdx" + path.write_bytes(compute_container(pack_words(*prog), wave32=False, threads=case[4])) + run = subprocess.run([dumper, str(path)], capture_output=True, text=True) + assert run.returncode == 0, (label, run.stderr) + stores = dict(interpret(run.stdout)) + if new_exec[0] & 1: + assert stores.get(0) == ACTIVE_SENTINEL, (label, stores) + else: + assert 0 not in stores, (label, stores) + assert stores.get(1 * PLANE_BYTES) == dst_val[0], (label, stores, dst_val) + assert stores.get(2 * PLANE_BYTES) == dst_val[1], (label, stores, dst_val) + assert stores.get(3 * PLANE_BYTES) == scc, (label, stores, scc) + assert stores.get(4 * PLANE_BYTES) == new_exec[0], (label, stores, new_exec) + assert stores.get(5 * PLANE_BYTES) == new_exec[1], (label, stores, new_exec) + + for idx, (wave32, threads, bad_prog, err) in enumerate(refusal_programs()): + path = work / f"refuse{idx}.cdx" + path.write_bytes(compute_container(pack_words(*bad_prog), wave32=wave32, threads=threads)) + run = subprocess.run([dumper, str(path)], capture_output=True, text=True) + assert run.returncode != 0 and err in run.stderr, (idx, err, run.returncode, run.stderr) + + print(f"evaluated IR for {len(wave32_cases())} wave32 and {len(wave64_cases())} wave64 cases, " + f"plus {len(refusal_programs())} refusals") + return 0 + + +def controls(cli, sdk, work, root): + check_oracles() + cache = work / "cache" + compiled = 0 + for wave_size, builder, items in ((32, build_wave32_program, wave32_cases()), + (64, build_wave64_program, wave64_cases())): + for case in items: + label = case[0] + prog, _, _, _ = builder(case) + marker = request(work, root, wave_size, case[4], prog) + cso = marker.with_suffix(".cso") + cso.unlink(missing_ok=True) + res = subprocess.run([cli, sdk, cache, "gfx1013-direct-cs@0", marker, cso], + capture_output=True, text=True) + assert res.returncode == 0 and cso.is_file(), (label, res.stdout, res.stderr) + compiled += 1 + + refusals = refusal_programs() + for idx, (wave32, threads, bad_prog, err) in enumerate(refusals): + marker = request(work, root, 32 if wave32 else 64, threads, bad_prog) + cso = marker.with_suffix(".cso") + cso.unlink(missing_ok=True) + res = subprocess.run([cli, sdk, cache, "gfx1013-direct-cs@0", marker, cso], + capture_output=True, text=True) + assert res.returncode != 0 and err in res.stderr, (idx, err, res.stdout, res.stderr) + assert not cso.exists(), cso + + print(f"compiled {compiled} wave32/wave64 cases cleanly and verified {len(refusals)} refusals") + return 0 + + +def hardware(replay, sdk, work, root): + cache = work / "cache" + for case in wave32_cases(): + label, _, _, _, threads, _, _, _, _, _ = case + prog, new_exec, dst_val, scc = build_wave32_program(case) + marker = request(work, root, 32, threads, prog) + out = work / f"{label}.bin" + run = subprocess.run([replay, sdk, marker, cache, "0", out, "--direct"]) + if run.returncode == 77: + return 77 + run.check_returncode() + actual = list(struct.unpack(f"<{OUTPUT_WORDS}I", out.read_bytes())) + expected = [SENTINEL] * OUTPUT_WORDS + for group in range(2): + for lane in range(threads): + pos = GUARD_WORDS + group * GROUP_WORDS + lane + if new_exec & (1 << lane): + expected[pos] = ACTIVE_SENTINEL | lane + expected[pos + 1 * PLANE_WORDS] = dst_val + expected[pos + 2 * PLANE_WORDS] = new_exec + expected[pos + 3 * PLANE_WORDS] = scc + assert actual == expected, (label, [ + (i, hex(a), hex(b)) for i, (a, b) in enumerate(zip(actual, expected)) if a != b + ][:10]) + + for case in wave64_cases(): + label, _, _, _, threads, _, _, _, _ = case + prog, new_exec, dst_val, scc = build_wave64_program(case) + marker = request(work, root, 64, threads, prog) + out = work / f"{label}.bin" + run = subprocess.run([replay, sdk, marker, cache, "0", out, "--direct"]) + if run.returncode == 77: + return 77 + run.check_returncode() + actual = list(struct.unpack(f"<{OUTPUT_WORDS}I", out.read_bytes())) + expected = [SENTINEL] * OUTPUT_WORDS + for group in range(2): + for local in range(threads): + lane = local % 64 + pos = GUARD_WORDS + group * GROUP_WORDS + local + if new_exec[lane // 32] & (1 << (lane % 32)): + expected[pos] = ACTIVE_SENTINEL | local + expected[pos + 1 * PLANE_WORDS] = dst_val[0] + expected[pos + 2 * PLANE_WORDS] = dst_val[1] + expected[pos + 3 * PLANE_WORDS] = scc + expected[pos + 4 * PLANE_WORDS] = new_exec[0] + expected[pos + 5 * PLANE_WORDS] = new_exec[1] + assert actual == expected, (label, [ + (i, hex(a), hex(b)) for i, (a, b) in enumerate(zip(actual, expected)) if a != b + ][:10]) + + print(f"replayed {len(wave32_cases())} wave32 and {len(wave64_cases())} wave64 cases on GPU with guards") + return 0 + + +def main(mode, tool, sdk=None): + if mode == "ir": + return ir(tool) + with tempfile.TemporaryDirectory() as temp: + work = Path(temp) + shader = work / "root.hlsl" + shader.write_text('#define SIG "DescriptorTable(UAV(u0,numDescriptors=8))"') + root = work / "root.bin" + subprocess.run([Path(sdk) / "dxc.exe", "-T", "rootsig_1_1", "-E", "SIG", + "-Fo", root, shader], check=True) + return {"controls": controls, "hardware": hardware}[mode](tool, sdk, work, root.read_bytes()) + + +if __name__ == "__main__": + sys.exit(main(*sys.argv[1:])) diff --git a/tests/native_scalar_lds_check.py b/tests/native_scalar_lds_check.py index 1ff289498c..4f4a9280c5 100644 --- a/tests/native_scalar_lds_check.py +++ b/tests/native_scalar_lds_check.py @@ -64,7 +64,7 @@ def built_root_readback(work, gpu, sdk): source, root = work / "built.hlsl", work / "built.root" source.write_text('#define SIG "SRV(t0),DescriptorTable(UAV(u0,numDescriptors=8))"') subprocess.run([Path(sdk) / "dxc.exe", "-T", "rootsig_1_1", "-E", "SIG", "-Fo", root, source], check=True) - sa = struct.pack("<7I", 0, 0, 0, 32 | 1 << 16, 1, 0, 0x80 | 7 << 1) + sa = struct.pack("<7I", 0, 0, 0, 32 | 1 << 16, 1 | (1 << 20), 0, 0x80 | 7 << 1) for offset in (96, 92): # Build the byte-address V# in s16:19 from root SRV s4:5. Each # group selects an aligned index. Group 1 ends at the view limit. @@ -150,7 +150,7 @@ def vop2(op, dst, a, b): expected[pos] = exact & full if enabled else a for lane in range(64): expected[8 + 32 * lane + 2 * idx + 1] = ballot - sa = struct.pack("<7I", 0, 0, 0, 32 | 1 << 16, 1, 0, 0x80 | 5 << 1) + sa = struct.pack("<7I", 0, 0, 0, 32 | 1 << 16, 1 | (1 << 20), 0, 0x80 | 5 << 1) marker = write_request(work, words + [0xbf810000], (work / "root.bin").read_bytes(), sa) dest = work / "carry-readback.bin" subprocess.run([gpu, sdk, marker, work / "cache", "0", dest, "--direct"], check=True) @@ -186,7 +186,7 @@ def half_mad_readback(work, gpu, sdk): low, high = (-2**31, 2**31-1) if signed else (0, 2**32-1) exact = min(high, max(low, exact)) values.append(exact & 0xffffffff) - sa = struct.pack("<7I", 0, 0, 0, 32 | 1 << 16, 1, 0, 0x80 | 5 << 1) + sa = struct.pack("<7I", 0, 0, 0, 32 | 1 << 16, 1 | (1 << 20), 0, 0x80 | 5 << 1) marker = write_request(work, words + [0xbf810000], (work / "root.bin").read_bytes(), sa) dest = work / "half-mad-readback.bin" subprocess.run([gpu, sdk, marker, work / "cache", "0", dest, "--direct"], check=True) @@ -218,7 +218,7 @@ def descriptor_scc_readback(work, gpu, sdk): 0x7d100af9, 0x00968e80, vmove(9, 14), 0xe070100c, 0x80080908, 0xbf810000] marker = write_request(work, words, (work / "root.bin").read_bytes(), - struct.pack("<7I", 0, 0, 0, 32 | 1 << 16, 1, 0, 0x80 | 5 << 1)) + struct.pack("<7I", 0, 0, 0, 32 | 1 << 16, 1 | (1 << 20), 0, 0x80 | 5 << 1)) dest = work / "descriptor-scc.bin" subprocess.run([gpu, sdk, marker, work / "cache", "0", dest, "--direct"], check=True) expected = [0x69696969] * 2064 @@ -235,7 +235,7 @@ def main(gpu, sdk): src, root = work / "root.hlsl", work / "root.bin" src.write_text('#define SIG "DescriptorTable(UAV(u0,numDescriptors=8))"') subprocess.run([Path(sdk) / "dxc.exe", "-T", "rootsig_1_1", "-E", "SIG", "-Fo", root, src], check=True) - sa = struct.pack("<7I", 0, 0, 0, 32 | 1 << 16, 1, 0, 0x808a) + sa = struct.pack("<7I", 0, 0, 0, 32 | 1 << 16, 1 | (1 << 20), 0, 0x808a) expected = [0x69696969] * 2064 for group in range(2): start = 8 + 16 * group diff --git a/tests/native_sdwa_f16_check.py b/tests/native_sdwa_f16_check.py index efa78ab37e..a992c50621 100644 --- a/tests/native_sdwa_f16_check.py +++ b/tests/native_sdwa_f16_check.py @@ -12,6 +12,7 @@ BYTE_1, WORD_0, WORD_1, DWORD = 1, 4, 5, 6 PAD, SEXT, PRESERVE = 0, 1, 2 NEG, ABS, SCALAR = 0x10, 0x20, 0x80 +CLAMP = 1 << 13 OLD = 0xa55a1357 GUARD = 0x69696969 ADD_CO_CI, PKRTZ = 0x28, 0x2f @@ -19,10 +20,38 @@ LANE_BYTE_SHIFT = fixture.SHIFT - 1 -def sdwa(opcode, dst, unused, src0, src1, reg0=1, reg1=2, dst_mod=0): +def sdwa(opcode, dst, unused, src0, src1=0, reg0=1, reg1=2, dst_mod=0, unary=False): ext = (reg0 | (dst << 8) | (unused << 11) | dst_mod | (src0 << 16) | (src1 << 24)) - return fixture.vop2(opcode, 3, 249, reg1) + [ext] + instruction = fixture.vop1(opcode, 3, 249) if unary else fixture.vop2(opcode, 3, 249, reg1) + return instruction + [ext] + + +def cvt_sdwa(src0, dst_mod=CLAMP): + # VOP1 opcode 0x0b, v3 destination, SDWA escape, then v1 with DWORD/PAD. + return [0x7e000000 | (3 << 17) | (0x0b << 9) | 249, + 1 | (DWORD << 8) | dst_mod | (src0 << 16)] + + +class ClampCase: + op = 'v_cvt_f32_f16 clamp' + dest = 3 + + def __init__(self, half, selector): + self.selector = selector + # Put a distinct in-range value in the other half to expose a wrong selector. + other = 0x3400 + self.word = (half << 16) | other if selector == WORD_1 else (other << 16) | half + value = struct.unpack('<e', struct.pack('<H', half))[0] + # An ordered > comparison maps NaN, negative values and -0.0 to +0.0. + result = min(value, 1.0) if value > 0.0 else 0.0 + self.want = struct.unpack('<I', struct.pack('<f', result))[0] + + def emit(self): + return fixture.mov(1, self.word) + fixture.mov(self.dest, OLD) + cvt_sdwa(self.selector) + + def matches(self, got): + return got == self.want class Case: @@ -34,24 +63,30 @@ def __init__(self, op, a, b, dst, unused, src0, src1): self.src0, self.src1 = src0, src1 self.shift = 16 if dst == WORD_1 else 0 self.mask = 0xffff << self.shift + self.alternate = model.rsq_rounding(self.read(a, src0))[1] if op == 'rsq' else None self.want = self.expected(src0, src1, unused) - def expected(self, src0, src1, unused): - def read(value, control): - picked = model.pick(value, (control & 7) == WORD_1) - return fixture.modified(picked, bool(control & ABS), bool(control & NEG), 0) + @staticmethod + def read(value, control): + picked = model.pick(value, (control & 7) == WORD_1) + return fixture.modified(picked, bool(control & ABS), bool(control & NEG), 0) - result = fixture.binary16(self.op, read(self.a, src0), read(self.b, src1)) + def expected(self, src0, src1, unused): + result = fixture.binary16(self.op, self.read(self.a, src0), self.read(self.b, src1)) other = OLD & ~self.mask if unused == PRESERVE else 0 return (result << self.shift) | other def emit(self): + if self.op in fixture.UNARY_CODE: + return (fixture.mov(1, self.a) + fixture.mov(self.dest, OLD) + + sdwa(fixture.UNARY_CODE[self.op], self.dst, self.unused, self.src0, unary=True)) return (fixture.mov(1, self.a) + fixture.mov(2, self.b) + fixture.mov(self.dest, OLD) + sdwa(fixture.OP_CODE[self.op], self.dst, self.unused, self.src0, self.src1)) def matches(self, got): return (got & ~self.mask == self.want & ~self.mask and - fixture.same_binary16((got & self.mask) >> self.shift, (self.want & self.mask) >> self.shift)) + fixture.same_alu_result((got & self.mask) >> self.shift, + (self.want & self.mask) >> self.shift, self.op, self.alternate)) def cases(): @@ -69,10 +104,24 @@ def cases(): # neg on one source and abs on the other: -(1.0) + |-2.0| = 1.0; dropping either modifier changes the sum. Case('add', 0x44003c00, 0xc0004500, WORD_1, PAD, WORD_0 | NEG, WORD_1 | ABS), ] + for op in fixture.UNARY_CODE: + items.append(Case(op, 0xc4003800, 0, WORD_1, PRESERVE, WORD_1 | ABS, 0)) + items.append(Case(op, 0x44004000, 0, WORD_0, PAD, DWORD | NEG, 0)) + items += [ + Case('rsq', 0x44000000, 0, WORD_1, PAD, WORD_0 | NEG, 0), + Case('rsq', 0x3bfe4400, 0, WORD_1, PRESERVE, WORD_1, 0), + Case('exp', 0x91c54400, 0, WORD_1, PRESERVE, WORD_1 | ABS, 0), + ] assert len(items) < fixture.STRIDE return items +def clamp_cases(): + # -1, 2, quiet NaN, -0, smallest positive subnormal, 0.5, and 1. + halves = (0xbc00, 0x4000, 0x7e01, 0x8000, 0x0001, 0x3800, 0x3c00) + return [ClampCase(half, selector) for selector in (WORD_0, WORD_1) for half in halves] + + def check_mutants(items): # Manual lowering mutants that must fail: swap WORD_0/WORD_1 on either # source, or ignore UNUSED_PRESERVE by zeroing the other destination half. @@ -90,18 +139,19 @@ def refusals(): add = fixture.OP_CODE['add'] dest_error = 'unsupported SDWA destination modifier' src_error = 'invalid SDWA source modifier' - vgpr_error = 'SDWA binary16 source must be a VGPR' return [ (sdwa(add, DWORD, PAD, WORD_0, WORD_0), dest_error), (sdwa(add, WORD_0, PAD, BYTE_1, WORD_0), src_error), - (sdwa(add, WORD_0, PAD, WORD_0 | SCALAR, WORD_0), vgpr_error), - (sdwa(add, WORD_0, PAD, WORD_0, WORD_0 | SCALAR, reg1=242), vgpr_error), (sdwa(add, WORD_0, PAD, WORD_0, WORD_0 | 8), src_error), (sdwa(add, WORD_0, SEXT, WORD_0, WORD_0), dest_error), (sdwa(add, WORD_0, PAD, WORD_0, WORD_0, dst_mod=1 << 13), dest_error), (sdwa(add, WORD_0, PAD, WORD_0, WORD_0, dst_mod=1 << 14), dest_error), + (cvt_sdwa(WORD_0, 1 << 14), dest_error), + (cvt_sdwa(WORD_1, CLAMP | (1 << 14)), dest_error), (sdwa(0x39, WORD_0, PAD, WORD_0, WORD_0), 'unimplemented direct SDWA operand profile'), # max (sdwa(0x3a, WORD_0, PAD, WORD_0, WORD_0), 'unimplemented direct SDWA operand profile'), # min + (sdwa(0x55, WORD_0, PAD, DWORD, dst_mod=1 << 13, unary=True), dest_error), + (sdwa(0x57, WORD_0, PAD, WORD_0, unary=True), 'unimplemented direct SDWA operand profile'), ] + [ (sdwa(op, WORD_0, PAD, DWORD, DWORD, dst_mod=1 << modifier), dest_error) for op in (PKRTZ, ADD_CO_CI) for modifier in (13, 14) @@ -205,6 +255,8 @@ def run_gpu(gpu, sdk, items, code): if __name__ == '__main__': items = cases() check_mutants(items) + items += clamp_cases() + assert len(items) < fixture.STRIDE code, _ = fixture.program(items) if len(sys.argv) == 3 and sys.argv[1] == 'ir': run_ir(sys.argv[2], items, code) diff --git a/tests/native_sdwa_f16_scalar_check.py b/tests/native_sdwa_f16_scalar_check.py new file mode 100644 index 0000000000..b2af56513a --- /dev/null +++ b/tests/native_sdwa_f16_scalar_check.py @@ -0,0 +1,113 @@ +"""Direct compute binary16 SDWA scalar sources. Use ir DUMPER or gpu STORE_REPLAY SDK.""" +import struct +import subprocess +import sys +import tempfile +from pathlib import Path + +import f16_packed_model as model +import native_f16_alu_check as fixture +from native_compute_clear_check import write_request +from native_sdwa_f16_check import DWORD, OLD, PAD, PRESERVE, SCALAR, WORD_0, WORD_1, sdwa + +SGPR = 9 +WORDS = {SGPR: 0x44004000, 256 + 1: 0x48003c00, 256 + 2: 0x45004200} +SOURCE_WORDS = {**WORDS, **fixture.INLINE_F16, 128: 0} + + +def instruction(op, unused, left, left_sel, right, right_sel): + def control(source, selector): + return selector | (SCALAR if source < 256 else 0) + + return sdwa(op, WORD_0, unused, control(left, left_sel), control(right, right_sel), + reg0=left & 255, reg1=right & 255) + + +class Case: + dest = 3 + + def __init__(self, op, unused, left, left_sel, right, right_sel): + self.instruction = instruction(fixture.OP_CODE[op], unused, left, left_sel, right, right_sel) + + def half(source, selector): + return model.pick(SOURCE_WORDS[source], selector == WORD_1) + + result = fixture.binary16(op, half(left, left_sel), half(right, right_sel)) + self.want = (OLD & 0xffff0000 if unused == PRESERVE else 0) | result + + def emit(self): + return (fixture.smov(SGPR, WORDS[SGPR]) + + fixture.mov(1, WORDS[257]) + fixture.mov(2, WORDS[258]) + + fixture.mov(self.dest, OLD) + self.instruction) + + +def cases(): + return [ + Case('add', PAD, SGPR, DWORD, 258, WORD_0), + Case('add', PRESERVE, 242, WORD_0, 128, DWORD), + Case('mul', PRESERVE, 257, WORD_0, SGPR, WORD_1), + Case('sub', PAD, 257, WORD_1, SGPR, DWORD), + Case('subrev', PAD, 257, WORD_1, SGPR, WORD_0), + ] + + +def refusals(): + add = fixture.OP_CODE['add'] + return [ + (instruction(add, PAD, 255, WORD_0, 258, WORD_0), 'literal is unavailable in SDWA'), + (instruction(add, PAD, 257, WORD_0, SGPR, WORD_1 | 8), 'invalid SDWA source modifier'), + (instruction(add, PAD, 258, WORD_0, 242, WORD_1), 'unsupported SDWA binary16 inline constant selection'), + # These captured min/max forms also need an arithmetic lowering. + (instruction(0x39, PRESERVE, SGPR, DWORD, 258, WORD_1), 'unimplemented direct SDWA operand profile'), + (instruction(0x3a, PAD, 257, WORD_0, 258, WORD_0), 'unimplemented direct SDWA operand profile'), + ] + + +def run_ir(dumper, items): + with tempfile.TemporaryDirectory() as tmp: + work = Path(tmp) + # Isolate each shape so one decode refusal cannot hide another. + for index, case in enumerate(items): + code, _ = fixture.program([case]) + run = fixture.dump(dumper, work, code, f'case-{index}') + assert run.returncode == 0, (index, run.stderr) + stores = fixture.interpret(run.stdout) + assert stores == [(0, case.want)], (index, stores, hex(case.want)) + for index, (words, why) in enumerate(refusals()): + run = fixture.dump(dumper, work, words + [0xbf810000], f'refused-{index}') + assert run.returncode != 0 and why in run.stderr, (why, run.returncode, run.stderr) + print(f'native_sdwa_f16_scalar IR: {len(items)} results and {len(refusals())} refusals') + + +def run_gpu(gpu, sdk, items): + code, expected = fixture.program(items) + with tempfile.TemporaryDirectory() as tmp: + work = Path(tmp) + src, root = work / 'root.hlsl', work / 'root.bin' + src.write_text('#define SIG "DescriptorTable(UAV(u0,numDescriptors=8))"') + subprocess.run([str(Path(sdk) / 'dxc.exe'), '-T', 'rootsig_1_1', '-E', 'SIG', '-Fo', root, src], check=True) + sa = struct.pack('<7I', 0, 0, 0, 32 | (1 << 16), 1 | (1 << 20), 0, 0x80 | (5 << 1)) + marker = write_request(work, code, root.read_bytes(), sa) + dest = work / 'sdwa-f16-scalar-readback.bin' + run = subprocess.run([gpu, sdk, str(marker), str(work / 'cache'), '0', str(dest), '--direct']) + if run.returncode == 77: + sys.exit(77) + run.check_returncode() + # The preamble sets EXEC_LO=1. Group IDs 0 and 1 in s5 select + # wave32 records at DWORDs 8 and 136, with contiguous lane-0 results. + stores = {slot: want for offsets in fixture.group_offsets(len(items)) + for slot, want in zip(offsets, expected)} + actual = struct.unpack(f'<{fixture.WORDS}I', dest.read_bytes()) + for index, got in enumerate(actual): + want = stores.get(index, fixture.SENTINEL) + assert got == want, (index, hex(got), hex(want)) + print(f'native_sdwa_f16_scalar GPU: {len(stores)} results and {fixture.WORDS - len(stores)} guards') + + +if __name__ == '__main__': + if len(sys.argv) == 3 and sys.argv[1] == 'ir': + run_ir(sys.argv[2], cases()) + elif len(sys.argv) == 4 and sys.argv[1] == 'gpu': + run_gpu(sys.argv[2], sys.argv[3], cases()) + else: + sys.exit(__doc__) diff --git a/tests/native_slot67_wave_size_check.py b/tests/native_slot67_wave_size_check.py new file mode 100644 index 0000000000..d6e3ce1a96 --- /dev/null +++ b/tests/native_slot67_wave_size_check.py @@ -0,0 +1,69 @@ +"""Compare slot 67 wave64 and wave32 lane counts for the same source-built program.""" +from pathlib import Path +import struct +import subprocess +import sys +import tempfile + +from native_compute_clear_check import write_request + + +PROGRAM = ( + 0xBE940304, 0xBE950380, # s[20:21] = UAV table address from s4 + 0xF408080A, 0xFA000020, # s_load_dwordx4 s[32:35], s[20:21], 0x20 + 0x8F078805, # s_lshl_b32 s7, s5, 8 (group byte offset) + 0x34100082, # v_lshlrev_b32 v8, 2, v0 (local byte offset) + 0x4A101007, # v_add_nc_u32 v8, s7, v8 + 0xD7650001, 0x000100C1, # v_mbcnt_lo_u32_b32 v1, -1, 0 + 0xD7660001, 0x000202C1, # v_mbcnt_hi_u32_b32 v1, -1, v1 + 0xE0701000, 0x80080108, # buffer_store_dword v1, v8, s[32:35], 0 offen + 0xBF810000, # s_endpgm +) +THREADS = 64 +DISPATCH_THREADS = 2 * THREADS # native_store_replay dispatches two groups +GUARD = 8 +OUTPUT_WORDS = 2064 +SENTINEL = 0x69696969 + + +def main(cli, replay, sdk): + with tempfile.TemporaryDirectory() as temp: + work = Path(temp) + shader, root = work / "root.hlsl", work / "root.bin" + shader.write_text('#define SIG "DescriptorTable(UAV(u0,numDescriptors=8))"') + subprocess.run([Path(sdk) / "dxc.exe", "-T", "rootsig_1_1", "-E", "SIG", + "-Fo", root, shader], check=True) + # (wave size, threads per group): a wave64 request with a 32-thread group has one guest wave of lanes 0..31. + cases = ((64, 64), (32, 64), (64, 32)) + markers = {} + for wave_size, threads in cases: + z = 1 | (1 << 20 if wave_size == 32 else 0) + sa = struct.pack("<7I", 0, 0, 0, threads | (1 << 16), z, 0, 0x8A) + markers[wave_size, threads] = write_request(work, PROGRAM, root.read_bytes(), sa) + + cache, batch = work / "cache", work / "batch" + subprocess.run([cli, sdk, cache, "gfx1013-direct-cs@0", "--requests", work, batch], + check=True) + for marker in markers.values(): + assert (batch / f"{marker.stem[4:]}.cs.cso").is_file(), marker + + for (wave_size, threads), marker in markers.items(): + output = work / f"wave{wave_size}_{threads}.bin" + result = subprocess.run([replay, sdk, marker, cache, "0", output, "--direct"]) + if result.returncode == 77: + return 77 + result.check_returncode() + actual = struct.unpack(f"<{OUTPUT_WORDS}I", output.read_bytes()) + expected = [SENTINEL] * OUTPUT_WORDS + # Each group stores its lane indices at a 256-byte group offset (s_lshl_b32 s7, s5, 8). + for group in range(2): + for tid in range(threads): + expected[GUARD + group * THREADS + tid] = tid % min(wave_size, threads) + for index, (got, want) in enumerate(zip(actual, expected)): + assert got == want, (wave_size, index, got, want) + print(f"wave{wave_size}, {threads}-thread groups: {2 * threads} lane indices and buffer guards matched") + return 0 + + +if __name__ == "__main__": + sys.exit(main(*sys.argv[1:])) diff --git a/tests/native_smem_vcc_wave64_check.py b/tests/native_smem_vcc_wave64_check.py new file mode 100644 index 0000000000..061db04b09 --- /dev/null +++ b/tests/native_smem_vcc_wave64_check.py @@ -0,0 +1,121 @@ +"""Compile and replay direct wave64 scalar loads that use VCC as scalar data.""" +from pathlib import Path +import struct +import subprocess +import sys +import tempfile + +from native_compute_clear_check import write_request +from native_dpp_mirror_check import vop2 +from native_scalar_lds_check import scalar, sop1, vmove + + +THREADS = 64 +LANE_WORDS = 16 +GUARD_WORDS = 8 +OUTPUT_WORDS = 2064 +SENTINEL = 0x69696969 +INPUT_BASE = 0x51AA0000 +EXEC_LO, EXEC_HI = 0x5A5AA5A5, 0xA5A55A5A + + +def program(first_dst=104): + # Use the same root SRV, synthesized byte descriptor and UAV slot as the wave32 fixture. + words = [ + sop1(4, 126, 193), # s_mov_b64 exec, -1 + sop1(4, 16, 4), sop1(3, 18, 255), 132, sop1(3, 19, 255), 0x31016FAC, + sop1(3, 20, 6), sop1(3, 21, 128), 0xF4080000 | 40 << 6 | 10, 0xFA000020, + 0xF4280008 | first_dst << 6, 0xFA000000, # s_buffer_load_dwordx4 s[104:107], s[16:19], 0 + 0xBF8CC07F, + scalar(0x1E, 12, 7, 140), # group.x * 4096 bytes + vop2(0x1A, 8, 134, 0), vop2(0x25, 8, 12, 8), # group byte base + local.x * 64 + sop1(3, 30, 106), # s_mov_b32 s30, vcc_lo + ] + + def store(reg, slot): + return [vmove(9, reg), 0xE0701000 | slot * 4, 0x800A0908] + + for slot, reg in enumerate((104, 105, 30, 107)): + words += store(reg, slot) + words += [ + 0xF40C0002 | 100 << 6, 0xFA000050, # s_load_dwordx8 s[100:107], s[4:5], 80 + 0xBF8CC07F, sop1(3, 30, 107), # s_mov_b32 s30, vcc_hi + ] + for slot, reg in enumerate((*range(100, 107), 30), start=4): + words += store(reg, slot) + words += [ + sop1(3, 106, 132), sop1(3, 107, 136), # scalar byte offsets 4 and 8 + 0xF4200008 | 30 << 6, 106 << 25 | 24, # s_buffer_load_dword s30, s[16:19], vcc_lo + 24 + 0xF4000002 | 31 << 6, 107 << 25 | 32, # s_load_dword s31, s[4:5], vcc_hi + 32 + 0xBF8CC07F, + *store(30, 12), *store(31, 13), + sop1(3, 126, 255), EXEC_LO, sop1(3, 127, 255), EXEC_HI, + 0xF4040002 | 106 << 6, 0xFA000014, # s_load_dwordx2 vcc, s[4:5], 20 + 0xBF8CC07F, + vmove(1, 129), vop2(1, 9, 128, 1), # v_cndmask_b32 v9, 0, v1, vcc + 0xE0701000 | 14 * 4, 0x800A0908, # EXEC-inactive lanes retain the sentinel + 0xBF810000, + ] + return words + + +def request(work, root, first_dst): + # .sa dword 4 bit 20 is clear, so each 64-thread group is one guest wave64. + sa = struct.pack("<7I", 0, 0, 0, THREADS | 1 << 16, 1, 0, 0x80 | 7 << 1) + return write_request(work, program(first_dst), root, sa) + + +def reference(): + expected = [SENTINEL] * OUTPUT_WORDS + vcc = (INPUT_BASE + 5) | ((INPUT_BASE + 6) << 32) + exec_mask = EXEC_LO | (EXEC_HI << 32) + loaded = [INPUT_BASE + index for index in (*range(4), *range(20, 28), 7, 10)] + for group in range(2): + for lane in range(THREADS): + pos = GUARD_WORDS + (group * THREADS + lane) * LANE_WORDS + expected[pos:pos + len(loaded)] = loaded + if exec_mask & (1 << lane): + expected[pos + 14] = (vcc >> lane) & 1 + return expected + + +def controls(tool, sdk, work, root): + for dst, error in ((104, ""), (105, "unsupported scalar memory destination range")): + marker = request(work, root, dst) + output = marker.with_suffix(".cso") + result = subprocess.run([tool, sdk, work / "cache", "gfx1013-direct-cs@0", marker, output], + capture_output=True, text=True) + if error: + assert result.returncode != 0 and error in result.stderr, (result.stdout, result.stderr) + assert not output.exists(), output + else: + assert result.returncode == 0 and output.exists(), (result.stdout, result.stderr) + return 0 + + +def hardware(tool, sdk, work, root): + marker = request(work, root, 104) + output = work / "out.bin" + result = subprocess.run([tool, sdk, marker, work / "cache", "0", output, "--direct"]) + if result.returncode == 77: + return 77 + result.check_returncode() + actual = struct.unpack(f"<{OUTPUT_WORDS}I", output.read_bytes()) + for word, (got, want) in enumerate(zip(actual, reference())): + assert got == want, f"word {word}: got {got:#010x}, expected {want:#010x}" + print("Wave64 SMEM scalar data, both VCC mask halves, and all guards matched.") + return 0 + + +def main(mode, tool, sdk): + with tempfile.TemporaryDirectory() as temp: + work = Path(temp) + source, root = work / "built.hlsl", work / "built.root" + source.write_text('#define SIG "SRV(t0),DescriptorTable(UAV(u0,numDescriptors=8))"') + subprocess.run([Path(sdk) / "dxc.exe", "-T", "rootsig_1_1", "-E", "SIG", + "-Fo", root, source], check=True) + return {"controls": controls, "hardware": hardware}[mode](tool, sdk, work, root.read_bytes()) + + +if __name__ == "__main__": + sys.exit(main(*sys.argv[1:])) diff --git a/tests/native_startup_request_cache_check.py b/tests/native_startup_request_cache_check.py index f6154395bb..2fc995ec6d 100644 --- a/tests/native_startup_request_cache_check.py +++ b/tests/native_startup_request_cache_check.py @@ -179,6 +179,7 @@ def check_controls(cli: Path, sdk: Path) -> int: cs_manifest = cache / f"{cs_key:016x}.txt" assert cs_cso.read_bytes().startswith(b"DXBC") assert cs_manifest.stat().st_mtime_ns >= cs_cso.stat().st_mtime_ns + assert not (cache / f"{cs_key:016x}.cs.hlsl").exists() assert not (cache / f"req_{cs_key:016x}.cso").exists() assert cs_manifest.read_text(encoding="ascii") == ( "x2w-manifest 2\n" @@ -189,6 +190,7 @@ def check_controls(cli: Path, sdk: Path) -> int: "udsrc 1 rootconst 0 1\n" "srv 0 buf table 1 64\n" "uav 0 table 1 32\n" + "native 1\n" ) assert G.pending_keys(str(cache), skip_failed=False) == [], "published entries not recognised as complete" diff --git a/tests/native_store_replay.cpp b/tests/native_store_replay.cpp index dd76c8bfcf..e6eb4f1846 100644 --- a/tests/native_store_replay.cpp +++ b/tests/native_store_replay.cpp @@ -62,9 +62,9 @@ void report_adapter(ID3D12Device* device) { // A reference directory supplies independently compiled DXIL and its user-data layout. // --direct exercises the same direct DXIL frontend used by the runtime. int wmain(int argc, wchar_t **argv) { - if (argc != 6 && argc != 7) return 2; + if (argc < 6 || argc > 8) return 2; try { - const auto mode = argc == 7 ? std::wstring_view(argv[6]) : std::wstring_view{}; + const auto mode = argc >= 7 ? std::wstring_view(argv[6]) : std::wstring_view{}; const bool warp = mode == L"--direct-warp"; ComPtr<IDXGIAdapter> adapter; if (warp) { @@ -102,6 +102,7 @@ int wmain(int argc, wchar_t **argv) { fs::path marker=argv[2], dest=argv[5]; const bool null_array = mode == L"--direct-null-srv"; const bool direct = null_array || warp || mode == L"--direct"; + if (argc == 8 && !direct) return 2; if (direct) { D3D12_FEATURE_DATA_SHADER_MODEL model{D3D_SHADER_MODEL_6_6}; D3D12_FEATURE_DATA_D3D12_OPTIONS1 waves{}; @@ -119,6 +120,13 @@ int wmain(int argc, wchar_t **argv) { UINT index=0; for (auto &block:p.constants) for (unsigned j=0;j<block.count;++j) args[index++]=constant(j); + std::vector<unsigned> strides; + if (argc == 8) { + std::ifstream input{fs::path(argv[7])}; + unsigned stride; + while (input >> stride) strides.push_back(stride); + if (!input.eof()) throw std::runtime_error("invalid descriptor stride metadata"); + } UINT roots[64]{}; if (reference) { fs::path base=fs::path(argv[6])/marker.stem().wstring().substr(4); @@ -233,7 +241,8 @@ int wmain(int argc, wchar_t **argv) { if(reference){ ID3D12DescriptorHeap* h=heap.Get();cmd.list->SetDescriptorHeaps(1,&h);cmd.list->SetComputeRootSignature(p.root.Get()); cmd.list->SetComputeRoot32BitConstants(0,64,roots,0); - } else p.bind(cmd.list.Get(),heap.Get(),heap->GetGPUDescriptorHandleForHeapStart(),step,args.data(),atomic); + } else p.bind(cmd.list.Get(),heap.Get(),heap->GetGPUDescriptorHandleForHeapStart(),step,args.data(),atomic, + nullptr,strides); cmd.list->Dispatch(2,1,1); for(auto &w:windows) if(w.write) { transition(cmd.list.Get(),w.resource.Get(),D3D12_RESOURCE_STATE_UNORDERED_ACCESS,D3D12_RESOURCE_STATE_COPY_SOURCE); diff --git a/tests/native_uav_slots_check.py b/tests/native_uav_slots_check.py new file mode 100644 index 0000000000..f4598c602c --- /dev/null +++ b/tests/native_uav_slots_check.py @@ -0,0 +1,51 @@ +"""Check the DXIL shader flag for more than 8 UAV slots in direct compute. + +DXC sets flag 0x8000 when a module declares more than 8 UAV slots, and the validator +refuses a module whose declared flags differ ("Flags must match usage"). Each program +stores to N buffer descriptors read from one table, so the module declares N UAVs. +8 UAVs must compile without the flag (the negative control); 9 must compile with it. +""" +from pathlib import Path +import re +import subprocess +import sys +import tempfile + +from native_direct_container_check import compute, words + + +def program(uavs): + code = [0xBEFE03C1, 0xBE810380] # s_mov_b32 exec_lo, -1; s_mov_b32 s1, 0 + for k in range(uavs): + # s_load_dwordx4 s[4+4k:7+4k], s[0:1], 32*k (table entries are 32-byte aligned) + code += [0xF4080000 | (4 + 4 * k) << 6, 0xFA000000 | 32 * k] + code += [ + 0xBF8CC07F, # s_waitcnt lgkmcnt(0) + (26 << 25) | (5 << 17) | 130, # v_lshlrev_b32 v5, 2, v0 + ] + for k in range(uavs): + # buffer_store_dword v0, v5, s[4+4k:7+4k], 0 offen + code += [0xE0701000, 0x80000005 | (1 + k) << 16] + code.append(0xBF810000) # s_endpgm + return compute(words(*code), table=True) + + +def main(cli, sdk): + with tempfile.TemporaryDirectory() as temp: + work = Path(temp) + for uavs in (8, 9): + source = work / f'uav{uavs}.c67' + source.write_bytes(program(uavs)) + shader = source.with_suffix('.cso') + run = subprocess.run([cli, sdk, work / 'cache', 'gfx1013-container-cs', source, shader], + capture_output=True, text=True, timeout=60) + declared = len(re.findall(r'^u\d+ ', run.stdout, re.M)) + assert run.returncode == 0 and shader.is_file(), (uavs, run.stdout, run.stderr) + assert declared == uavs, (uavs, declared, run.stdout) + print(f'{uavs} UAVs: compiled and validated') + + +if __name__ == '__main__': + if len(sys.argv) != 3: + sys.exit('usage: native_uav_slots_check.py COMPILE_DXIL DXC_BIN_DIR') + main(*sys.argv[1:]) diff --git a/tests/native_wave64_exec_salu_check.py b/tests/native_wave64_exec_salu_check.py new file mode 100644 index 0000000000..854e520b09 --- /dev/null +++ b/tests/native_wave64_exec_salu_check.py @@ -0,0 +1,127 @@ +"""Compile and replay slot 67 scalar EXEC operands in both wave models.""" +from pathlib import Path +import struct +import subprocess +import sys +import tempfile + +from native_compute_clear_check import write_request +from native_scalar_lds_check import scalar, sop1, vmove + + +BCNT1_B64, BFM_B64 = 0x10, 0x25 +VCC, EXEC, ZERO, NEG_ONE = 106, 126, 128, 193 +COUNT_ERROR = "invalid s_bcnt1_i32_b64 source" +BFM_ERROR = "invalid s_bfm_b64 destination" +GROUP_STRIDE_WORDS = 128 +GUARD_WORDS, OUTPUT_WORDS = 8, 2064 +SENTINEL = 0x69696969 +END = 0xBF810000 + + +def request(work, root, wave_size, threads, words): + z = 1 | (1 << 20 if wave_size == 32 else 0) + sa = struct.pack("<7I", 0, 0, 0, threads | (1 << 16), z, 0, 0x8A) + return write_request(work, words, root, sa) + + +def program(wave_size, operation): + # s4 is the UAV table and s5 is group.x. v0 is local.x. + # Replay dispatches groups 0 and 1. The byte address is 512 * group.x + 4 * local.x. + if wave_size == 64: + words = [sop1(4, EXEC, NEG_ONE)] + else: + # Explicitly enable all 32 lanes and seed the tracked upper word. + words = [sop1(3, EXEC, NEG_ONE), sop1(3, EXEC + 1, ZERO + 1)] + words += [ + sop1(3, 20, 4), sop1(3, 21, ZERO), + 0xF408080A, 0xFA000020, # s_load_dwordx4 s[32:35], s[20:21], 0x20 + scalar(0x1E, 7, 5, ZERO + 9), # s_lshl_b32 s7, s5, 9 + 0x34100082, # v_lshlrev_b32 v8, 2, v0 + 0x4A101007, # v_add_nc_u32 v8, s7, v8 + ] + if operation == "count": + words += [ + 0x36040083, # v_and_b32 v2, 3, v0 + 0x7DA40480, # v_cmpx_eq_u32 0, v2 + 0x7DAA00A0, # v_cmpx_ne_u32 32, v0 + sop1(BCNT1_B64, 24, EXEC), + vmove(1, 24), + ] + data = 1 + else: + width, offset = (16, 0) if operation == "lower" else (32, 32) + words.append(scalar(BFM_B64, EXEC, ZERO + width, ZERO + offset)) + data = 0 + return words + [0xE0701000, 0x80080008 | data << 8, END] + + +def expected_words(wave_size, threads, operation): + expected = [SENTINEL] * OUTPUT_WORDS + for group in range(2): + for local in range(threads): + lane = local % wave_size + word = GUARD_WORDS + group * GROUP_STRIDE_WORDS + local + if operation == "count" and local % 4 == 0 and local != 32: + # Wave64 loses lane 32 in the first guest wave only. Wave32 + # counts eight lower bits and the explicitly set EXEC_HI bit. + expected[word] = 9 if wave_size == 32 else 15 if local < 64 else 16 + elif operation == "lower" and lane < 16: + expected[word] = local + elif operation == "upper" and lane >= 32: + expected[word] = local + return expected + + +def compile_request(cli, sdk, cache, marker): + output = marker.with_suffix(".cs.cso") + result = subprocess.run([cli, sdk, cache, "gfx1013-direct-cs@0", marker, output], + capture_output=True, text=True) + return output, result + + +def main(cli, replay, sdk): + with tempfile.TemporaryDirectory() as temp: + work = Path(temp) + shader, root_file = work / "root.hlsl", work / "root.bin" + shader.write_text('#define SIG "DescriptorTable(UAV(u0,numDescriptors=8))"') + subprocess.run([Path(sdk) / "dxc.exe", "-T", "rootsig_1_1", "-E", "SIG", + "-Fo", root_file, shader], check=True) + root = root_file.read_bytes() + cache = work / "cache" + cases = [(64, threads, op) for threads in (64, 128) for op in ("count", "lower", "upper")] + cases.append((32, 32, "count")) + positives = [] + for wave_size, threads, op in cases: + marker = request(work, root, wave_size, threads, program(wave_size, op)) + output, result = compile_request(cli, sdk, cache, marker) + assert result.returncode == 0 and output.is_file(), ( + wave_size, threads, op, result.stdout, result.stderr) + positives.append((wave_size, threads, op, marker)) + + for instruction, error in ( + (sop1(BCNT1_B64, 24, VCC), COUNT_ERROR), + (scalar(BFM_B64, VCC, ZERO + 16, ZERO), BFM_ERROR), + (sop1(BCNT1_B64, 24, 23), COUNT_ERROR), + ): + marker = request(work, root, 64, 64, [instruction, END]) + output, result = compile_request(cli, sdk, cache, marker) + assert result.returncode and error in result.stderr, (error, result.stdout, result.stderr) + assert not output.exists(), output + + for wave_size, threads, op, marker in positives: + output = work / f"wave{wave_size}_{threads}_{op}.bin" + result = subprocess.run([replay, sdk, marker, cache, "0", output, "--direct"]) + if result.returncode == 77: + return 77 + result.check_returncode() + actual = struct.unpack(f"<{OUTPUT_WORDS}I", output.read_bytes()) + expected = expected_words(wave_size, threads, op) + for index, (got, want) in enumerate(zip(actual, expected)): + assert got == want, (wave_size, threads, op, index, hex(got), hex(want)) + print(f"wave{wave_size}, {threads} threads, {op}: both groups and guards matched") + return 0 + + +if __name__ == "__main__": + sys.exit(main(*sys.argv[1:])) diff --git a/tests/native_wave_request_check.py b/tests/native_wave_request_check.py index 0965e3e047..cdab046316 100644 --- a/tests/native_wave_request_check.py +++ b/tests/native_wave_request_check.py @@ -165,7 +165,7 @@ def main(cli, gpu, sdk): source.write_text('#define SIG "DescriptorTable(SRV(t0,numDescriptors=16)),DescriptorTable(UAV(u0,numDescriptors=16))"') root = work / "root.bin" subprocess.run([Path(sdk) / "dxc.exe", "-T", "rootsig_1_1", "-E", "SIG", "-Fo", root, source], check=True) - sa = struct.pack("<7I", 0, 0, 0, 8 | (8 << 16), 1, 0, 0x8d8c) + sa = struct.pack("<7I", 0, 0, 0, 8 | (8 << 16), 1 | (1 << 20), 0, 0x8d8c) # s4 and s5 are the two guest tables. The byte offsets deliberately differ # from the desktop registers that the translator assigns to them. words = [ @@ -206,7 +206,7 @@ def main(cli, gpu, sdk): source.write_text('#define SIG "DescriptorTable(SRV(t0,numDescriptors=16)),' 'DescriptorTable(UAV(u0,numDescriptors=16)),RootConstants(num32BitConstants=4,b0)"') subprocess.run([Path(sdk) / "dxc.exe", "-T", "rootsig_1_1", "-E", "SIG", "-Fo", root, source], check=True) - sa = struct.pack("<7I", 0, 0, 0, 32 | (1 << 16), 1, 0, 0x198) + sa = struct.pack("<7I", 0, 0, 0, 32 | (1 << 16), 1 | (1 << 20), 0, 0x198) # One 32-lane group per tile. s6/s7 are root constants and s12/s13 are the group IDs. code = [ 0xbe940304, 0xbe950380, 0xbe960305, 0xbe970380, diff --git a/tests/native_wave_virtual_derivative_check.py b/tests/native_wave_virtual_derivative_check.py new file mode 100644 index 0000000000..17dfacfa3c --- /dev/null +++ b/tests/native_wave_virtual_derivative_check.py @@ -0,0 +1,93 @@ +"""Packed slot-67 control for implicit derivatives in a virtual wave64 group. + +The virtual-wave scheduler needs the packed state, more than one guest wave64, +and a conditional branch plus a synchronizing instruction. The container +fixture does not enter that path. This source-built request keeps the explicit +LOD and ordinary implicit cases compiling, and requires the combination to be +refused at the image opcode instead of producing a shader with no scheduler +readback. +""" +import struct +import subprocess +import sys +import tempfile +from pathlib import Path + +from native_compute_clear_check import write_request + + +WIDTH = 8 +SAMPLER = (0x12, 0xFFF000, 0x04500000, 0) + + +def bits(value): + return struct.unpack("<I", struct.pack("<f", value))[0] + + +def vop2(op, dst, src0, src1): + return (op << 25) | (dst << 17) | (src1 << 9) | src0 + + +def setup(): + # One guest table at s4: the texture descriptor is loaded from it before + # s4:7 is reused for the sampler constants the image op consumes. + code = [ + 0xBEFE04C1, # s_mov_b64 exec, -1 (wave64) + 0xBE850380, # s5 = 0, the high half of the table address + 0xF40C0202, 0xFA000000, # s_load_dwordx8 s[8:15], s[4:5], 0 + ] + for reg, value in enumerate(SAMPLER, start=4): + code += [0xBE8003FF | (reg << 16), value] + return code + + +def program(implicit, control): + code = setup() + code += [ + vop2(22, 3, 130, 0), vop2(27, 3, 131, 3), vop2(19, 3, 130, 3), + vop2(26, 4, 151, 3), vop2(37, 4, 255, 4), bits(1 / WIDTH), + vop2(27, 1, 129, 0), 0x7E020D01, vop2(8, 1, 260, 1), + vop2(27, 4, 136, 0), 0x7E080D04, vop2(8, 4, 255, 4), bits(0.0625), + vop2(3, 1, 260, 1), 0x7E0402F0, 0x7E060D03, + ] + if control: + code += [0xBF880004, 0xBF8A0000] # s_cbranch_execz +4; s_barrier + code += [0xBF8CC07F, 0xF0000108 | ((32 if implicit else 36) << 18), 0x00220401] + code.append(0xBF810000) + return code + + +def main(cli, sdk): + with tempfile.TemporaryDirectory() as temporary: + work = Path(temporary) + source, root = work / "root.hlsl", work / "root.bin" + source.write_text('#define SIG "DescriptorTable(SRV(t0,numDescriptors=8)),' + 'DescriptorTable(UAV(u0,numDescriptors=8))"', encoding="ascii") + subprocess.run([Path(sdk) / "dxc.exe", "-T", "rootsig_1_1", "-E", "SIG", + "-Fo", root, source], check=True) + # Tagged slot-67 state: dword 0 and dword 1 select the packed ABI, dword 3 + # is X|Y<<16, dword 4 holds Z and the wave size, and dword 6 is RSRC2. + sa = struct.pack("<7I", 0x4005cf00, 0x6c090102, 0, 128 | (1 << 16), 1, 0, 0x8d8c) + cases = ( + ("implicit", True, False, 0, None), + ("explicit", False, True, 0, None), + ("implicit-virtual", True, True, 1, "implicit derivatives with virtual wave64 groups"), + ) + for name, implicit, control, expected, diagnostic in cases: + marker = write_request(work, program(implicit, control), root.read_bytes(), sa) + output = work / f"{name}.cso" + run = subprocess.run([cli, sdk, work / "cache", "gfx1013-direct-cs@0", marker, output], + capture_output=True, text=True, timeout=60) + assert run.returncode == expected, (name, run.stdout, run.stderr) + if diagnostic: + assert diagnostic in run.stderr and not output.exists(), (name, run.stderr) + print(f"{name}: refused at the image opcode: {diagnostic}") + else: + assert output.is_file(), (name, run.stdout, run.stderr) + print(f"{name}: packed slot-67 request compiled") + print("virtual-wave derivative control passed") + return 0 + + +if __name__ == "__main__": + sys.exit(main(*sys.argv[1:])) diff --git a/tests/native_wrexec64_check.py b/tests/native_wrexec64_check.py new file mode 100644 index 0000000000..c88b11456f --- /dev/null +++ b/tests/native_wrexec64_check.py @@ -0,0 +1,112 @@ +"""Check slot 67 wave64 WREXEC lane stores, destination words and SCC.""" +from pathlib import Path +import struct +import subprocess +import sys +import tempfile + +from native_compute_clear_check import write_request +from native_dpp_mirror_check import vop2 +from native_scalar_lds_check import scalar, sop1, vmove + + +MOV_B32, ANDN2_WREXEC_B64 = 3, 0x3A +ZERO, ONE, NEG_ONE, LITERAL = 128, 129, 193, 255 +EXEC_LO, EXEC_HI = 126, 127 +OLD_EXEC = (0x80000012, 0x40000009) +GUARD_WORDS, OUTPUT_WORDS = 8, 2064 +GROUP_WORDS, PLANE_WORDS = 128, 256 +SENTINEL = 0x69696969 +CASES = ( + # X, source words, destination, incoming SCC, expected result, expected SCC + (64, (0x80000084, 0xC0000021), 24, 0, (0x84, 0x80000020), 1), + (128, (0x80000084, 0xC0000021), 24, 0, (0x84, 0x80000020), 1), + (128, (0x80000002, 0xC0000021), 22, 0, (0, 0x80000020), 1), + (64, OLD_EXEC, 24, 1, (0, 0), 0), +) + + +def program(source, dst, incoming_scc, src=22): + # s4 holds the table, s5 holds group.x and v0 holds local.x. + # v8 = 512 * group.x + 4 * local.x, calculated before narrowing EXEC. + words = [ + sop1(MOV_B32, 20, 4), sop1(MOV_B32, 21, ZERO), + 0xF408080A, 0xFA000020, + scalar(0x1E, 7, 5, ZERO + 9), + vop2(0x1A, 8, ZERO + 2, 0), vop2(0x25, 8, 7, 8), + 0xBF8CC07F, + sop1(MOV_B32, EXEC_LO, LITERAL), OLD_EXEC[0], + sop1(MOV_B32, EXEC_HI, LITERAL), OLD_EXEC[1], + sop1(MOV_B32, 22, LITERAL), source[0], + sop1(MOV_B32, 23, LITERAL), source[1], + 0xBF060080 | (ZERO if incoming_scc else ONE) << 8, # s_cmp_eq_u32 + sop1(ANDN2_WREXEC_B64, dst, src), + 0xE0701000, 0x80080008, # store v0 under the new EXEC + scalar(0x0A, 26, ONE, ZERO), # s_cselect_b32 captures SCC + sop1(MOV_B32, EXEC_LO, NEG_ONE), sop1(MOV_B32, EXEC_HI, NEG_ONE), + ] + for plane, reg in enumerate((dst, dst + 1, 26), start=1): + words += [vmove(4, reg), 0xE0701000 | (plane * PLANE_WORDS * 4), 0x80080408] + return words + [0xBF810000] + + +def request(work, root, threads, words): + # .sa dword 4 bit 20 is clear, selecting the wave64 model. + sa = struct.pack("<7I", 0, 0, 0, threads | (1 << 16), 1, 0, 0x8A) + return write_request(work, words, root, sa) + + +def expected_output(threads, result, scc): + expected = [SENTINEL] * OUTPUT_WORDS + for group in range(2): + for local in range(threads): + index = GUARD_WORDS + group * GROUP_WORDS + local + lane = local % 64 + if result[lane // 32] & (1 << (lane % 32)): + expected[index] = local + for plane, value in enumerate((*result, scc), start=1): + expected[index + plane * PLANE_WORDS] = value + return expected + + +def main(cli, replay, sdk): + with tempfile.TemporaryDirectory() as temp: + work = Path(temp) + shader, root_file = work / "root.hlsl", work / "root.bin" + shader.write_text('#define SIG "DescriptorTable(UAV(u0,numDescriptors=8))"') + subprocess.run([Path(sdk) / "dxc.exe", "-T", "rootsig_1_1", "-E", "SIG", + "-Fo", root_file, shader], check=True) + root = root_file.read_bytes() + cache = work / "cache" + compile_cmd = [cli, sdk, cache, "gfx1013-direct-cs@0"] + replay_cases = [] + for threads, source, dst, incoming_scc, result, scc in CASES: + marker = request(work, root, threads, program(source, dst, incoming_scc)) + output = marker.with_suffix(".cso") + compiled = subprocess.run([*compile_cmd, marker, output], capture_output=True, text=True) + assert compiled.returncode == 0 and output.is_file(), (compiled.stdout, compiled.stderr) + replay_cases.append((threads, result, scc, marker)) + + for src, dst in ((106, 24), (23, 24), (22, 25)): + marker = request(work, root, 64, program(CASES[0][1], dst, 0, src)) + output = marker.with_suffix(".cso") + compiled = subprocess.run([*compile_cmd, marker, output], capture_output=True, text=True) + assert compiled.returncode != 0 and "unsupported wave64 scalar operation" in compiled.stderr, ( + src, dst, compiled.stdout, compiled.stderr) + assert not output.exists(), output + + for threads, result, scc, marker in replay_cases: + output = marker.with_suffix(".bin") + replayed = subprocess.run([replay, sdk, marker, cache, "0", output, "--direct"]) + if replayed.returncode == 77: + return 77 + replayed.check_returncode() + actual = struct.unpack(f"<{OUTPUT_WORDS}I", output.read_bytes()) + for index, (got, want) in enumerate(zip(actual, expected_output(threads, result, scc))): + assert got == want, (threads, result, index, hex(got), hex(want)) + print(f"wave64 X={threads}, EXEC={result[1]:08x}:{result[0]:08x}, SCC={scc} matched") + return 0 + + +if __name__ == "__main__": + sys.exit(main(*sys.argv[1:])) diff --git a/tests/offscreen_check.cpp b/tests/offscreen_check.cpp index cd778d429e..3d53da367c 100644 --- a/tests/offscreen_check.cpp +++ b/tests/offscreen_check.cpp @@ -1041,6 +1041,12 @@ OperationResult run_bvh_root_roundtrip(const OperationContext& ctx) return {OutcomeKind::pass, nullptr}; } +OperationResult run_compute_waterfall_oracle(const OperationContext& ctx) +{ + check_compute_waterfall_oracle(ctx.device, ctx.argv[3]); + return {OutcomeKind::pass, nullptr}; +} + OperationResult run_bvh_differential(const OperationContext& ctx) { return skip_if_false(check_bvh_differential(ctx.device, false)); @@ -1329,7 +1335,8 @@ OperationResult run_startup_sampler_heap(const OperationContext& ctx) // The expected value is four comma-separated hex words. Omit the sampler line for point wrap. // --startup-image-2d-array takes the same arguments: the texels are two slices of a 2D array and the // third coordinate is the slice. --startup-image-2d-array-mips uses a 4x4 array of two slices with three -// mip levels whose cells all differ (tests/startup_image_3d.cpp). +// mip levels whose cells all differ (tests/startup_image_3d.cpp). --startup-image-cube binds six 4x4 faces as a +// TextureCube whose 96 texels all differ (#2943); z is passed through as for the other modes. OperationResult run_startup_image_3d(const OperationContext& ctx) { const bool array_mips = std::strcmp(ctx.argv[2], "--startup-image-2d-array-mips") == 0; @@ -1337,6 +1344,7 @@ OperationResult run_startup_image_3d(const OperationContext& ctx) const bool array = array_mips || std::strcmp(ctx.argv[2], "--startup-image-2d-array") == 0; const bool one_dimensional = one_dimensional_mips || std::strcmp(ctx.argv[2], "--startup-image-1d") == 0; const bool two_dimensional = std::strcmp(ctx.argv[2], "--startup-image-2d") == 0; + const bool cube = std::strcmp(ctx.argv[2], "--startup-image-cube") == 0; float z = 0.0f; if (two_dimensional && ctx.argv[5][0] == '0' && (ctx.argv[5][1] == 'x' || ctx.argv[5][1] == 'X')) { char* end = nullptr; @@ -1353,7 +1361,7 @@ OperationResult run_startup_image_3d(const OperationContext& ctx) float color[4]{}; const char* sampler = ctx.argc == 8 ? ctx.argv[7] : "smp 0 0x0 0x0 0x0 0x0"; check_startup_image_3d(ctx.device, ctx.argv[3], ctx.argv[4], z, color, sampler, array, - array_mips || one_dimensional_mips ? 3 : 1, one_dimensional, two_dimensional); + array_mips || one_dimensional_mips ? 3 : 1, one_dimensional, two_dimensional, 0, 0, 4, cube); std::uint32_t bits[4]; std::memcpy(bits, color, sizeof(bits)); if (std::memcmp(bits, expected, sizeof(bits)) != 0) { @@ -1754,6 +1762,7 @@ const OperationSpec kOperations[] = { {"--startup-image-store-reject-load", 3, 3, nullptr, kNoGate, run_startup_image_store_reject_load}, {"--startup-image-2d-array", 7, 8, nullptr, kNoGate, run_startup_image_3d}, {"--startup-image-2d-array-mips", 7, 8, nullptr, kNoGate, run_startup_image_3d}, + {"--startup-image-cube", 7, 8, nullptr, kNoGate, run_startup_image_3d}, {"--startup-image-load-d16", 7, 7, nullptr, kNoGate, run_startup_image_load_d16}, {"--startup-packed-position", 5, 5, nullptr, kNoGate, run_startup_packed_position}, {"--startup-sharedexp-target", 3, 3, nullptr, kNoGate, run_startup_sharedexp_target}, @@ -1833,6 +1842,7 @@ const OperationSpec kOperations[] = { {"--mesh-depth-pair-fallback", 7, 7, nullptr, kGateSm60MeshFallback, run_mesh_depth_pair_fallback}, {"--mesh-shadow", 7, 8, validate_mesh_shadow_args, kNoGate, run_mesh_shadow}, {"--bvh-root-roundtrip", 3, 3, nullptr, kNoGate, run_bvh_root_roundtrip}, + {"--compute-waterfall-oracle", 4, 4, nullptr, kNoGate, run_compute_waterfall_oracle}, {"--bvh-differential", 3, 3, nullptr, kNoGate, run_bvh_differential}, {"--bvh-differential-pipeline", 3, 3, nullptr, kNoGate, run_bvh_differential_pipeline}, {"--bvh-hits", 3, 3, nullptr, kGateSm65, run_bvh_hits}, diff --git a/tests/patch_manifest_check.py b/tests/patch_manifest_check.py index 8f2f7477ad..8c353bc7d3 100644 --- a/tests/patch_manifest_check.py +++ b/tests/patch_manifest_check.py @@ -1,7 +1,9 @@ """Schema, loader and hash-gate controls for tools/patch_manifest.py on a synthetic PE32+.""" import hashlib +import json from pathlib import Path +import re import subprocess import sys import tempfile @@ -18,6 +20,9 @@ from call_evidence_check import SECTION_RVA, build_pe32_plus # noqa: E402 REPLACEMENT = "90c3" +# Revisions of each pipeline's form, not the runtime's current ones: the loader checks the form only. +REVISION = {"graphics": "x2w-startup-shader-12", "compute": "x2w-startup-shader-12cs", + "mesh86": "x2w-startup-mesh-86-4"} def manifest_text(input_sha256, original, patches=None): @@ -35,6 +40,39 @@ def manifest_text(input_sha256, original, patches=None): return f'[target]\ninput_sha256 = "{input_sha256}"\n{patches}' +def memory_patch(pid, rva, replacement=REPLACEMENT): + """One [[patch]] of kind memory; parse checks the shape of expect_sha256, not the bytes it hashes.""" + return f""" +[[patch]] +id = "{pid}" +kind = "memory" +why = "synthetic fixture" +remove_when = "never; this is a test" +rva = {rva:#x} +expect_sha256 = "{hashlib.sha256(pid.encode()).hexdigest()}" +bytes = "{replacement}" +""" + + +def shader_patch(pid="s001", key="00c0ffee0badf00d", pipeline="compute", revision=None, exts=None): + """One [[patch]] of kind shader; its files are named after the patch and hashed from their names.""" + revision = revision or REVISION[pipeline] + exts = patch_manifest.PIPELINES[pipeline][2] if exts is None else exts + files = ", ".join(f'{{ ext = "{ext}", file = "{pid}{ext}", ' + f'sha256 = "{hashlib.sha256((pid + ext).encode()).hexdigest()}" }}' for ext in exts) + return f""" +[[patch]] +id = "{pid}" +kind = "shader" +why = "synthetic fixture" +remove_when = "never; this is a test" +key = "{key}" +pipeline = "{pipeline}" +revision = "{revision}" +files = [{files}] +""" + + class PatchManifest(unittest.TestCase): def setUp(self): self.tmp = tempfile.TemporaryDirectory() @@ -59,7 +97,10 @@ def test_bound_input_loads(self): self.assertEqual(plan["manifest_sha256"], hashlib.sha256(self.manifest.read_bytes()).hexdigest()) self.assertEqual(plan["input_sha256"], self.digest) [patch] = plan["patches"] - self.assertEqual((patch["id"], patch["rva"], patch["bytes"]), ("p001", SECTION_RVA, bytes.fromhex(REPLACEMENT))) + self.assertEqual(patch, {"id": "p001", "kind": "memory", "why": "synthetic fixture", + "remove_when": "never; this is a test", "rva": SECTION_RVA, + "expect_sha256": hashlib.sha256(self.original).hexdigest(), + "bytes": bytes.fromhex(REPLACEMENT)}) result = self.cli(self.input) self.assertEqual(result.returncode, 0, result.stderr) self.assertIn('"p001"', result.stdout) @@ -69,6 +110,30 @@ def test_wrong_input_is_refused(self): self.assertEqual(result.returncode, 1, result.stdout) self.assertIn("manifest is for another input", result.stderr) self.assertEqual(result.stdout, "") + # An input that cannot be opened is a diagnostic too, not a traceback. + result = self.cli(self.input.with_name("absent.bin")) + self.assertEqual(result.returncode, 1, result.stdout) + self.assertIn("patch manifest: [Errno", result.stderr) + self.assertNotIn("Traceback", result.stderr) + self.assertEqual(result.stdout, "") + + def test_memory_patches_side_by_side(self): + # Adjacent spans do not overlap, the order of the [[patch]] tables does not matter, and RVA 0 is in range. + # The ids follow neither the addresses nor their reverse, so spans sorted by id either way refuse this case. + text = manifest_text(self.digest, self.original, patches="".join( + memory_patch(pid, rva) for pid, rva in (("p001", SECTION_RVA + 4), ("p003", SECTION_RVA + 2), + ("p000", SECTION_RVA), ("p002", 0)))) + _, patches = patch_manifest.parse(text) + self.assertEqual([(p["id"], p["rva"]) for p in patches], + [("p001", SECTION_RVA + 4), ("p003", SECTION_RVA + 2), ("p000", SECTION_RVA), ("p002", 0)]) + # One shared byte is an overlap, in either order. + for first, second in ((SECTION_RVA, SECTION_RVA + 1), (SECTION_RVA + 1, SECTION_RVA)): + with self.subTest(first=first, second=second): + text = manifest_text(self.digest, self.original, + patches=memory_patch("p001", first) + memory_patch("p002", second)) + with self.assertRaises(ValueError) as caught: + patch_manifest.parse(text) + self.assertRegex(str(caught.exception), r"patches p00[12] and p00[12] overlap") def test_malformed_manifests_are_refused(self): sha = self.digest @@ -85,8 +150,13 @@ def test_malformed_manifests_are_refused(self): "duplicate patch id: p001": ok + ok.split("[target]", 1)[1].split("\n", 2)[2], "patches p001 and p002 overlap": ok + second, "bytes must be": ok.replace(REPLACEMENT, "90c"), + "p001 bytes must be a non-empty": ok.replace(f'bytes = "{REPLACEMENT}"', 'bytes = ""'), "rva must be": ok.replace(f"rva = {SECTION_RVA:#x}", "rva = true"), "input_sha256 must be": ok.replace(sha, sha.upper()), + # A hash or key with trailing text is malformed, not a hash of another input. + "input_sha256 must be 64 lowercase hex digits": ok.replace(sha, sha + "0"), + "p001 expect_sha256 must be 64": ok.replace(hashlib.sha256(self.original).hexdigest(), + hashlib.sha256(self.original).hexdigest() + "x"), "at least one [[patch]]": "patch = []\n" + manifest_text(sha, self.original, patches=""), } for message, text in cases.items(): @@ -107,6 +177,161 @@ def test_malformed_manifests_are_refused(self): self.assertIn("patch manifest: [[patch]] 0: kind ['memory'] is not supported", result.stderr) self.assertNotIn("Traceback", result.stderr) + def test_load_data_gates_the_bytes_given(self): + image, other = self.input.read_bytes(), self.other.read_bytes() + self.assertEqual(patch_manifest.load_data(self.manifest, image), patch_manifest.load(self.manifest, self.input)) + with self.assertRaises(ValueError) as caught: + patch_manifest.load_data(self.manifest, other) + self.assertIn("manifest is for another input", str(caught.exception)) + # The bytes in hand decide, not the file they came from: the input file now holds the other image. + self.input.write_bytes(other) + self.assertEqual(patch_manifest.load_data(self.manifest, bytearray(image))["input_sha256"], self.digest) + with self.assertRaises(ValueError): + patch_manifest.load(self.manifest, self.input) + + def test_shader_patches(self): + sha = self.digest + ok = manifest_text(sha, self.original) + # Accepted beside a memory patch: each pipeline with its required files, mesh86 also with its pixel shader + # and compute also with its Python translator's HLSL. + text = (ok + shader_patch("s001") + shader_patch("s002", "0123456789abcdef", "graphics") + + shader_patch("s003", "fedcba9876543210", "mesh86") + + shader_patch("s004", "0000000000000001", "mesh86", exts=(".mesh86.txt", ".ms.cso", ".ps.cso")) + + shader_patch("s005", "0000000000000002", "compute", exts=(".txt", ".cs.cso", ".cs.hlsl"))) + target, patches = patch_manifest.parse(text) + self.assertEqual([(p["id"], p["kind"]) for p in patches], [("p001", "memory")] + [ + (pid, "shader") for pid in ("s001", "s002", "s003", "s004", "s005")]) + s001 = patches[1] + self.assertEqual((s001["key"], s001["pipeline"], s001["revision"]), + ("00c0ffee0badf00d", "compute", "x2w-startup-shader-12cs")) + self.assertEqual(s001["files"], [ + {"ext": ".txt", "file": "s001.txt", "sha256": hashlib.sha256(b"s001.txt").hexdigest()}, + {"ext": ".cs.cso", "file": "s001.cs.cso", "sha256": hashlib.sha256(b"s001.cs.cso").hexdigest()}]) + self.assertEqual([f["ext"] for f in patches[4]["files"]], [".mesh86.txt", ".ms.cso", ".ps.cso"]) + self.assertEqual([f["ext"] for f in patches[5]["files"]], [".txt", ".cs.cso", ".cs.hlsl"]) + # The CLI lists shader ids with the memory ones. + self.manifest.write_text(text, encoding="utf-8", newline="\n") + result = self.cli(self.input) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual(json.loads(result.stdout)["patch_ids"], ["p001", "s001", "s002", "s003", "s004", "s005"]) + good = shader_patch() + cases = { + "key must be 16 lowercase hex digits": ok + shader_patch(key="00c0ffee0badf00"), + "s001 key must be 16 lowercase hex": ok + shader_patch(key="00C0FFEE0BADF00D"), + "patch s001 key must be 16 lowercase hex digits": ok + shader_patch(key="00c0ffee0badf00d0"), + "pipeline must be one of: graphics, compute, mesh86": ok + shader_patch().replace('"compute"', '"vertex"'), + "revision 'x2w-startup-shader-12' is not a compute key revision (x2w-startup-shader-<n>cs)": + ok + shader_patch(revision="x2w-startup-shader-12"), + "s002 revision 'x2w-startup-shader-12cs' is not a graphics key revision (x2w-startup-shader-<n>)": + ok + shader_patch("s002", pipeline="graphics", revision="x2w-startup-shader-12cs"), + "revision 'x2w-startup-mesh-57-3' is not a mesh86 key revision (x2w-startup-mesh-86-<n>)": + ok + shader_patch(pipeline="mesh86", revision="x2w-startup-mesh-57-3"), + "revision 'x2w-startup-shader-cs' is not a compute": ok + shader_patch(revision="x2w-startup-shader-cs"), + "revision 'x2w-startup-shader-012cs' is not a compute": + ok + shader_patch(revision="x2w-startup-shader-012cs"), + "revision 29 is not a compute": ok + shader_patch().replace('"x2w-startup-shader-12cs"', "29"), + "files must be a non-empty array": ok + good.replace(good[good.index("files = "):], "files = []\n"), + "files[0] has unknown keys: size": ok + good.replace('{ ext = ".txt",', '{ size = 1, ext = ".txt",'), + "files[1] is missing: sha256": ok + good.replace( + f', sha256 = "{hashlib.sha256(b"s001.cs.cso").hexdigest()}"', ""), + "files[1] ext '.vs.cso' is not a compute translation file (.txt, .cs.cso, .cs.hlsl)": + ok + shader_patch(exts=(".txt", ".vs.cso")), + "s001 lists .txt twice": ok + shader_patch(exts=(".txt", ".cs.cso", ".txt")), + "s001 compute override is missing: .cs.cso": ok + shader_patch(exts=(".txt",)), + "s002 graphics override is missing: .vs.cso, .ps.cso": + ok + shader_patch("s002", pipeline="graphics", exts=(".txt",)), + "files[0] file must be a non-empty string": ok + good.replace('file = "s001.txt"', 'file = ""'), + **{f"files[0] file {name!r} must be a bare file name": + ok + good.replace('file = "s001.txt"', f"file = '{name}'") + for name in ("sub/s001.txt", "sub\\s001.txt", "/s001.txt", "C:s001.txt", "..", ".")}, + # The runtime that reads these files runs on Windows: names it can't hold, shortens or opens as a device. + **{f"files[0] file {name!r} has a character a Windows file name cannot hold": + ok + good.replace('file = "s001.txt"', f"file = '{name}'") + for name in ("a*b", "a?b", "a<b", "a>b", "a|b", 'a"b', "a\tb")}, + "files[0] file 'a\\x01b' has a character": ok + good.replace('file = "s001.txt"', 'file = "a\\u0001b"'), + **{f"files[0] file {name!r} ends in a dot or a space, which Windows drops": + ok + good.replace('file = "s001.txt"', f"file = '{name}'") for name in ("s001.txt.", "s001.txt ")}, + **{f"files[0] file {name!r} is a Windows device name": + ok + good.replace('file = "s001.txt"', f"file = '{name}'") + for name in ("NUL", "CON.txt", "Com1", "nul .txt", "CONIN$", "conout$.txt", + "COM\u00b9", "lpt\u00b3.cso")}, + "files[0] sha256 must be 64 lowercase hex digits": ok + good.replace( + hashlib.sha256(b"s001.txt").hexdigest(), hashlib.sha256(b"s001.txt").hexdigest().upper()), + "patches s001 and s002 override the same key 00c0ffee0badf00d": ok + good + shader_patch("s002"), + "has unknown keys: rva": ok + good.replace('key = "', 'rva = 0x1000\nkey = "'), + "[[patch]] 1 is missing: files": ok + good[:good.index("files = ")], + "kind 'shaders' is not supported": ok + good.replace('"shader"', '"shaders"'), + } + for message, case in cases.items(): + with self.subTest(message): + with self.assertRaises(ValueError) as caught: + patch_manifest.parse(case) + self.assertIn(message, str(caught.exception)) + # A device name only as a prefix, a space inside a name and a leading dot are still file names. + for name in ("console.txt", "nulls.cso", "a b.txt", "com10.txt", "conin.txt", ".s001.txt"): + with self.subTest(name): + _, patches = patch_manifest.parse(ok + good.replace('file = "s001.txt"', f"file = '{name}'")) + self.assertEqual(patches[-1]["files"][0]["file"], name) + + def test_shader_revision_forms_match_the_runtime(self): + # The runtime's current revision of each pipeline has the loader's form, so a bump (a new <n>) still loads. + # Whether a manifest names the current revision is for a later consumer to check against the runtime. + draw = (ROOT / "src/startup_stubs/d3d12_draw.inl").read_text(encoding="utf-8") + mesh86 = (ROOT / "src/startup_stubs/mesh86_cache.inl").read_text(encoding="utf-8") + found = { + "graphics": re.findall(r'constexpr char revision\[\] = "(x2w-startup-shader-[^"]*)";', draw), + "compute": re.findall(r'constexpr char compute_revision\[\] = "([^"]*)";', draw), + "mesh86": re.findall(r'constexpr char revision\[\] = "([^"]*)";', mesh86), + } + self.assertEqual(set(found), set(patch_manifest.PIPELINES)) + for pipeline, revisions in found.items(): + with self.subTest(pipeline): + self.assertEqual(len(revisions), 1, revisions) + self.assertTrue(patch_manifest.REVISIONS[pipeline].fullmatch(revisions[0]), revisions[0]) + + def test_shader_files_match_the_runtime(self): + # The translation files each pipeline's loader in the runtime reads for one key: cache_path(..., L"", key, ext) + # and mesh86's load_stage(ext, ...). mesh86 reads its .ps.cso only for a request with a pixel shader, and + # compute looks for its .cs.hlsl only when the .txt has no native line: neither is required. + reads = re.compile(r'(?:cache_path\(\w+, L"", [\w.]+, |load_stage\()L"(\.[a-z0-9.]+)"') + sources = {"graphics": "d3d12_draw.inl", "compute": "d3d12_compute_dispatch.inl", "mesh86": "mesh86_cache.inl"} + self.assertEqual(set(sources), set(patch_manifest.PIPELINES)) + for pipeline, name in sources.items(): + text = (ROOT / "src/startup_stubs" / name).read_text(encoding="utf-8") + with self.subTest(pipeline): + self.assertEqual(set(reads.findall(text)), set(patch_manifest.PIPELINES[pipeline][1])) + mesh86 = (ROOT / "src/startup_stubs/mesh86_cache.inl").read_text(encoding="utf-8") + self.assertIn('(!request.ps.empty() && !load_stage(L".ps.cso", ps))', mesh86) + self.assertEqual(set(patch_manifest.PIPELINES["mesh86"][1]) - set(patch_manifest.PIPELINES["mesh86"][2]), + {".ps.cso"}) + compute = (ROOT / "src/startup_stubs/d3d12_compute_dispatch.inl").read_text(encoding="utf-8") + self.assertIn("if (output == x2w::NativeComputeOutput::unmarked) {", compute) + self.assertEqual(set(patch_manifest.PIPELINES["compute"][1]) - set(patch_manifest.PIPELINES["compute"][2]), + {".cs.hlsl"}) + + def test_deep_nesting_is_refused(self): + def nested(depth): + return "x = " + "[" * depth + "]" * depth + "\n" + manifest_text(self.digest, self.original) + + # Shape control: a shallow array gets past tomllib and is refused only for its unknown key. + with self.assertRaises(ValueError) as caught: + patch_manifest.parse(nested(50)) + self.assertIn("manifest has unknown keys: x", str(caught.exception)) + # Twice the recursion limit, set here so a runner that raised it cannot parse the array: refused, not a + # RecursionError. The CLI runs in a new interpreter, whose limit is the default 1000. + limit = sys.getrecursionlimit() + self.addCleanup(sys.setrecursionlimit, limit) + sys.setrecursionlimit(1000) + with self.assertRaises(ValueError) as caught: + patch_manifest.parse(nested(2000)) + self.assertIn("manifest is nested too deeply to parse", str(caught.exception)) + self.manifest.write_text(nested(2000), encoding="utf-8", newline="\n") + result = self.cli(self.input) + self.assertEqual(result.returncode, 1, result.stdout) + self.assertEqual(result.stdout, "") + self.assertIn("patch manifest: manifest is nested too deeply to parse", result.stderr) + self.assertNotIn("Traceback", result.stderr) + if __name__ == "__main__": unittest.main() diff --git a/tests/probe_root_devices_cli_check.py b/tests/probe_root_devices_cli_check.py new file mode 100644 index 0000000000..bc80aa06cf --- /dev/null +++ b/tests/probe_root_devices_cli_check.py @@ -0,0 +1,575 @@ +"""CLI, path-guard, symlink, atomic-replace, and temp-copy mutation suite for tools/probe_root_devices.py.""" + +from contextlib import redirect_stderr, redirect_stdout +import hashlib +import importlib.util +import io +import json +import os +from pathlib import Path +import struct +import subprocess +import sys +from tempfile import TemporaryDirectory +import unittest +from unittest import mock + +ROOT = Path(__file__).resolve().parents[1] +TOOL = ROOT / "tools" / "probe_root_devices.py" +sys.path.insert(0, str(ROOT / "tools")) + +import probe_root_devices # noqa: E402 + + +IMAGE_BASE = 0x180000000 +SECTION_RVA = 0x1000 +RAW_OFFSET = 0x200 +RAW_SIZE = 0x1000 + +MUTATIONS = ( + ( + "drop_bin_is_dir_guard", + " if not args.bin.is_dir():\n" + ' raise NotADirectoryError(f"--bin path is not a directory: {args.bin}")\n', + " if False:\n" + ' raise NotADirectoryError(f"--bin path is not a directory: {args.bin}")\n', + ), + ( + "drop_control_cso_is_file_guard", + " if not control_path.is_file():\n" + ' raise FileNotFoundError(f"Control shader is missing or not a file: {control_path}")\n', + " if False:\n" + ' raise FileNotFoundError(f"Control shader is missing or not a file: {control_path}")\n', + ), + ( + "drop_dest_is_dir_guard", + " if dest.is_dir():\n" + ' raise IsADirectoryError(f"Output path is a directory: {dest}")\n', + " if False:\n" + ' raise IsADirectoryError(f"Output path is a directory: {dest}")\n', + ), + ( + "drop_dest_inside_build_guard", + " if dest.resolve().is_relative_to(args.build.resolve()):\n" + ' parser.error("Choose an input directory separate from the report directory")\n', + " if False:\n" + ' parser.error("Choose an input directory separate from the report directory")\n', + ), + ( + "drop_tmp_unlink_cleanup", + " if temporary is not None:\n" + " temporary.unlink(missing_ok=True)\n", + " if False:\n" + " temporary.unlink(missing_ok=True)\n", + ), +) + + +def _make_dxbc_rts0(rts0: bytes) -> bytes: + program = struct.pack("<II4sIII", 0, 8, b"DXIL", 0, 16, 4) + b"BC\xc0\xde\x00\x00\x00\x00" + parts = [ + b"DXIL" + struct.pack("<I", len(program)) + program, + b"RTS0" + struct.pack("<I", len(rts0)) + rts0, + ] + table_end = 32 + 4 * len(parts) + offsets = [] + cursor = table_end + for part in parts: + offsets.append(cursor) + cursor += len(part) + body = b"".join(parts) + return ( + b"DXBC" + + bytes(16) + + struct.pack("<III", 1, table_end + len(body), len(parts)) + + struct.pack(f"<{len(parts)}I", *offsets) + + body + ) + + +def _build_pe32_plus(containers: list[bytes]) -> tuple[bytes, list[tuple[int, int]]]: + payload = bytearray(RAW_SIZE) + cursor = 0 + layout = [] + for blob in containers: + cursor = (cursor + 15) & ~15 + rva = SECTION_RVA + cursor + payload[cursor:cursor + len(blob)] = blob + cursor += len(blob) + layout.append((rva, len(blob))) + vsize = max(1, cursor) + size_of_image = SECTION_RVA + ((vsize + 0xFFF) // 0x1000) * 0x1000 + pe_offset = 0x80 + buf = bytearray(RAW_OFFSET + RAW_SIZE) + buf[0:2] = b"MZ" + struct.pack_into("<I", buf, 60, pe_offset) + buf[pe_offset:pe_offset + 4] = b"PE\0\0" + struct.pack_into("<HHIIIHH", buf, pe_offset + 4, 0x8664, 1, 0, 0, 0, 240, 0x2022) + opt = pe_offset + 24 + struct.pack_into( + "<HBBIIIIIQIIHHHHHHIIIIHHQQQQII", + buf, + opt, + 0x20B, 0, 0, 0, RAW_SIZE, 0, 0, SECTION_RVA, IMAGE_BASE, + 0x1000, 0x200, 6, 0, 0, 0, 6, 0, 0, size_of_image, RAW_OFFSET, + 0, 3, 0, 0, 0, 0, 0, 0, 16, + ) + sec = opt + 240 + struct.pack_into( + "<8sIIIIIIHHI", + buf, + sec, + b".rdata\0\0", vsize, SECTION_RVA, RAW_SIZE, RAW_OFFSET, + 0, 0, 0, 0, 0x40000040, + ) + buf[RAW_OFFSET:RAW_OFFSET + RAW_SIZE] = payload + return bytes(buf), layout + + +def _setup_bin(bin_dir: Path) -> None: + bin_dir.mkdir(parents=True, exist_ok=True) + (bin_dir / "compute_root.cso").write_bytes(b"CTRL_ROOT") + (bin_dir / "compute_tables.cso").write_bytes(b"CTRL_TABLES") + + +def _fake_probe_ok(cmd, *, input, stdout, check, timeout): + warp_only = "--warp-only" in cmd + row = {"cleared": 0, "remaining_flags": 0, "serialize": "0x00000000", "warp": "0x00000000"} + if not warp_only: + row["hardware"] = "0x00000000" + return subprocess.CompletedProcess(cmd, 0, (json.dumps(row) + "\n").encode("utf-8")) + + +def _run_main(mod, argv: list[str], repo: Path, fake_run=_fake_probe_ok) -> tuple[int, str, str]: + out = io.StringIO() + err = io.StringIO() + with ( + mock.patch.object(mod, "PROJECT", repo), + mock.patch.object(mod.subprocess, "run", side_effect=fake_run), + redirect_stdout(out), + redirect_stderr(err), + ): + try: + code = mod.main(argv) + except SystemExit as exc: + code = exc.code if isinstance(exc.code, int) else 2 + return code, out.getvalue(), err.getvalue() + + +def _load_temp_module(path: Path, name: str): + spec = importlib.util.spec_from_file_location(name, path) + if spec is None or spec.loader is None: + raise AssertionError(f"could not create module spec for {path}") + mod = importlib.util.module_from_spec(spec) + sys.modules[name] = mod + try: + spec.loader.exec_module(mod) + except Exception: + sys.modules.pop(name, None) + raise + return mod + + +class ProbeRootDevicesCliTests(unittest.TestCase): + def _create_fixture(self, base: Path) -> tuple[Path, Path, Path, Path]: + repo = base / "repo" + calls = repo / "out" / "calls" + calls.mkdir(parents=True) + build_dir = base / "build" + build_dir.mkdir() + bin_dir = base / "bin" + _setup_bin(bin_dir) + + rts0 = struct.pack("<6I", 2, 1, 24, 0, 0, 0) + pe_bytes, layout = _build_pe32_plus([_make_dxbc_rts0(rts0)]) + names = probe_root_devices.NAMES + (build_dir / names[0]).write_bytes(pe_bytes) + inventory = { + names[0]: { + "sha256": hashlib.sha256(pe_bytes).hexdigest(), + "containers": [{"rva": hex(layout[0][0]), "bytes": layout[0][1]}], + }, + names[1]: {"sha256": "0" * 64, "containers": []}, + names[2]: {"sha256": "0" * 64, "containers": []}, + } + (calls / "six-apis.json").write_text(json.dumps(inventory), encoding="utf-8") + return repo, calls, build_dir, bin_dir + + def test_atomic_json_write_and_zero_leftover_temps(self) -> None: + for warp_only in (True, False): + with self.subTest(warp_only=warp_only), TemporaryDirectory() as tmp: + repo, calls, build_dir, bin_dir = self._create_fixture(Path(tmp)) + argv = [str(build_dir), "--bin", str(bin_dir)] + if warp_only: + argv.append("--warp-only") + code, out, err = _run_main(probe_root_devices, argv, repo) + self.assertEqual(code, 0, err) + self.assertEqual(err, "") + dest_name = "root-devices-warp.json" if warp_only else "root-devices.json" + dest = calls / dest_name + self.assertTrue(dest.is_file()) + self.assertIn(str(dest), out) + self.assertEqual(sorted(p.name for p in calls.iterdir()), sorted([dest_name, "six-apis.json"])) + report = json.loads(dest.read_text(encoding="utf-8")) + self.assertIn(probe_root_devices.NAMES[0], report["images"]) + + def test_upfront_bin_control_build_inventory_and_image_guards(self) -> None: + with TemporaryDirectory() as tmp: + base = Path(tmp) + repo, calls, build_dir, bin_dir = self._create_fixture(base) + file_bin = base / "bin_as_file" + file_bin.write_text("not a dir", encoding="ascii") + file_build = base / "build_as_file" + file_build.write_text("not a dir", encoding="ascii") + + # Non-dir --bin (missing or file) exits 1 before invoking subprocess.run. + for bad_bin in (base / "missing_bin", file_bin): + code, _, err = _run_main( + probe_root_devices, + ["--warp-only", "--bin", str(bad_bin)], + repo, + fake_run=mock.Mock(side_effect=AssertionError("subprocess called for bad --bin")), + ) + self.assertEqual(code, 1) + self.assertNotIn("Traceback", err) + self.assertIn("--bin path is not a directory", err) + + # Missing or directory control .cso exits 1 before invoking subprocess.run. + bad_cso_bin = base / "bad_cso_bin" + bad_cso_bin.mkdir() + (bad_cso_bin / "compute_root.cso").mkdir() + (bad_cso_bin / "compute_tables.cso").write_bytes(b"ok") + code, _, err = _run_main( + probe_root_devices, + ["--warp-only", "--bin", str(bad_cso_bin)], + repo, + fake_run=mock.Mock(side_effect=AssertionError("subprocess called for dir .cso")), + ) + self.assertEqual(code, 1) + self.assertNotIn("Traceback", err) + self.assertIn("Control shader is missing or not a file", err) + + # Non-dir --build exits 1 cleanly. + for bad_build in (base / "missing_build", file_build): + code, _, err = _run_main( + probe_root_devices, + [str(bad_build), "--warp-only", "--bin", str(bin_dir)], + repo, + ) + self.assertEqual(code, 1) + self.assertNotIn("Traceback", err) + self.assertIn("Build directory is not a directory", err) + + # Missing or directory six-apis.json exits 1 cleanly. + inv = calls / "six-apis.json" + saved_inv = inv.read_text(encoding="utf-8") + inv.unlink() + code, _, err = _run_main( + probe_root_devices, [str(build_dir), "--warp-only", "--bin", str(bin_dir)], repo + ) + self.assertEqual(code, 1) + self.assertNotIn("Traceback", err) + self.assertIn("Inventory file is missing or not a file", err) + + inv.mkdir() + code, _, err = _run_main( + probe_root_devices, [str(build_dir), "--warp-only", "--bin", str(bin_dir)], repo + ) + self.assertEqual(code, 1) + self.assertNotIn("Traceback", err) + self.assertIn("Inventory file is missing or not a file", err) + inv.rmdir() + inv.write_text(saved_inv, encoding="utf-8") + + # Directory where PE image is expected exits 1 cleanly. + img = build_dir / probe_root_devices.NAMES[0] + saved_img = img.read_bytes() + img.unlink() + img.mkdir() + code, _, err = _run_main( + probe_root_devices, [str(build_dir), "--warp-only", "--bin", str(bin_dir)], repo + ) + self.assertEqual(code, 1) + self.assertNotIn("Traceback", err) + self.assertIn("Build image is missing or not a file", err) + img.rmdir() + img.write_bytes(saved_img) + + # Real missing root_device_probe.exe (unmocked subprocess.run) exits 1 cleanly. + proc = subprocess.run( + [sys.executable, "-B", str(TOOL), "--warp-only", "--bin", str(bin_dir)], + capture_output=True, + text=True, + timeout=30, + ) + self.assertEqual(proc.returncode, 1) + self.assertNotIn("Traceback", proc.stderr) + self.assertIn("probe_root_devices:", proc.stderr) + + def test_dest_dir_file_parent_and_inside_build_guards(self) -> None: + with TemporaryDirectory() as tmp: + base = Path(tmp) + repo, calls, build_dir, bin_dir = self._create_fixture(base) + dest = calls / "root-devices-warp.json" + + # dest is a directory + dest.mkdir() + code, _, err = _run_main( + probe_root_devices, [str(build_dir), "--warp-only", "--bin", str(bin_dir)], repo + ) + self.assertEqual(code, 1) + self.assertNotIn("Traceback", err) + self.assertIn("Output path is a directory", err) + dest.rmdir() + + # dest inside args.build exits 2 + code, _, err = _run_main( + probe_root_devices, [str(repo), "--warp-only", "--bin", str(bin_dir)], repo + ) + self.assertEqual(code, 2) + self.assertNotIn("Traceback", err) + self.assertIn("separate from the report directory", err) + + # dest.parent is a regular file + repo2 = base / "repo_file_parent" + (repo2 / "out").mkdir(parents=True) + (repo2 / "out" / "calls").write_text("keep-parent-file", encoding="ascii") + code, _, err = _run_main( + probe_root_devices, [str(build_dir), "--warp-only", "--bin", str(bin_dir)], repo2 + ) + self.assertEqual(code, 1) + self.assertNotIn("Traceback", err) + self.assertIn("Output parent is not a directory", err) + self.assertEqual((repo2 / "out" / "calls").read_text(encoding="ascii"), "keep-parent-file") + + def test_atomic_replace_allows_symlink_and_hardlink_dest(self) -> None: + # Restored main behaviour: temporary.replace(dest) renames over the + # directory entry, so it never writes through a symlink or hardlink. + with TemporaryDirectory() as tmp: + base = Path(tmp) + repo, calls, build_dir, bin_dir = self._create_fixture(base) + dest = calls / "root-devices-warp.json" + inv = calls / "six-apis.json" + inv_text = inv.read_text(encoding="utf-8") + + # dest hardlinked to six-apis.json: report written, inventory unchanged. + dest.hardlink_to(inv) + code, _, err = _run_main( + probe_root_devices, [str(build_dir), "--warp-only", "--bin", str(bin_dir)], repo + ) + self.assertEqual(code, 0, err) + self.assertTrue(dest.is_file()) + self.assertFalse(dest.is_symlink()) + self.assertEqual(inv.read_text(encoding="utf-8"), inv_text) + self.assertIn(probe_root_devices.NAMES[0], json.loads(dest.read_text(encoding="utf-8"))["images"]) + + # dest a symlink to six-apis.json: the link is replaced by the report. + dest.unlink() + dest.symlink_to(inv) + code, _, err = _run_main( + probe_root_devices, [str(build_dir), "--warp-only", "--bin", str(bin_dir)], repo + ) + self.assertEqual(code, 0, err) + self.assertTrue(dest.is_file()) + self.assertFalse(dest.is_symlink()) + self.assertEqual(inv.read_text(encoding="utf-8"), inv_text) + + # dest.parent a directory symlink to another folder: report lands there. + target = base / "target_calls" + target.mkdir() + (target / "six-apis.json").write_text(inv_text, encoding="utf-8") + repo2 = base / "repo_parent_link" + (repo2 / "out").mkdir(parents=True) + (repo2 / "out" / "calls").symlink_to(target, target_is_directory=True) + code, _, err = _run_main( + probe_root_devices, [str(build_dir), "--warp-only", "--bin", str(bin_dir)], repo2 + ) + self.assertEqual(code, 0, err) + self.assertTrue((target / "root-devices-warp.json").is_file()) + self.assertEqual((target / "six-apis.json").read_text(encoding="utf-8"), inv_text) + + def test_guards_fail_before_reading_or_measuring(self) -> None: + # Behavioural pins for the remaining guards (M1-M4): each guard must + # fail before the guarded read/measure is attempted, not merely with a + # different message. A deleted guard lets the guarded operation run, + # which the mocks below turn into a test error. + with TemporaryDirectory() as tmp: + base = Path(tmp) + repo, calls, build_dir, bin_dir = self._create_fixture(base) + real_read_bytes = Path.read_bytes + + def _no_read(name): + def _guarded(path_self, *args, **kwargs): + if path_self.name == name: + raise AssertionError(f"read attempted for {name} despite guard") + return real_read_bytes(path_self, *args, **kwargs) + + return _guarded + + def _no_image_measure(cmd, *, input, stdout, check, timeout): + if input not in (b"CTRL_ROOT", b"CTRL_TABLES"): + raise AssertionError("image probe called despite guard") + return _fake_probe_ok(cmd, input=input, stdout=stdout, check=check, timeout=timeout) + + # M1: missing build fails before the inventory is read, and wins + # over a missing inventory (guard ordering, not just wording). + (calls / "six-apis.json").unlink() + with mock.patch.object(Path, "read_bytes", _no_read("six-apis.json")): + code, _, err = _run_main( + probe_root_devices, + [str(base / "missing_build"), "--warp-only", "--bin", str(bin_dir)], + repo, + ) + self.assertEqual(code, 1) + self.assertIn("Build directory is not a directory", err) + (calls / "six-apis.json").write_text( + json.dumps( + { + probe_root_devices.NAMES[0]: { + "sha256": "0" * 64, + "containers": [], + }, + probe_root_devices.NAMES[1]: {"sha256": "0" * 64, "containers": []}, + probe_root_devices.NAMES[2]: {"sha256": "0" * 64, "containers": []}, + } + ), + encoding="utf-8", + ) + + # M2: dest.parent is a file fails before any image probe runs. + repo2 = base / "repo_file_parent" + (repo2 / "out").mkdir(parents=True) + (repo2 / "out" / "calls").write_text("keep-parent-file", encoding="ascii") + code, _, err = _run_main( + probe_root_devices, + [str(build_dir), "--warp-only", "--bin", str(bin_dir)], + repo2, + fake_run=_no_image_measure, + ) + self.assertEqual(code, 1) + self.assertIn("Output parent is not a directory", err) + + # M3: missing inventory fails before the inventory is read. + (calls / "six-apis.json").unlink() + with mock.patch.object(Path, "read_bytes", _no_read("six-apis.json")): + code, _, err = _run_main( + probe_root_devices, [str(build_dir), "--warp-only", "--bin", str(bin_dir)], repo + ) + self.assertEqual(code, 1) + self.assertIn("Inventory file is missing or not a file", err) + # Restore the fixture inventory for the M4 case below. + repo3, calls3, build_dir3, bin_dir3 = self._create_fixture(base / "fixture2") + repo, calls, build_dir, bin_dir = repo3, calls3, build_dir3, bin_dir3 + + # M4: missing build image fails before the image is read. + img = build_dir / probe_root_devices.NAMES[0] + img.unlink() + with mock.patch.object(Path, "read_bytes", _no_read(probe_root_devices.NAMES[0])): + code, _, err = _run_main( + probe_root_devices, [str(build_dir), "--warp-only", "--bin", str(bin_dir)], repo + ) + self.assertEqual(code, 1) + self.assertIn("Build image is missing or not a file", err) + + def test_os_replace_failure_preserves_bytes_and_zero_temps(self) -> None: + with TemporaryDirectory() as tmp: + repo, calls, build_dir, bin_dir = self._create_fixture(Path(tmp)) + dest = calls / "root-devices-warp.json" + dest.write_text("existing-report\n", encoding="utf-8") + with mock.patch.object(os, "replace", side_effect=OSError("simulated replace failure")): + code, _, err = _run_main( + probe_root_devices, [str(build_dir), "--warp-only", "--bin", str(bin_dir)], repo + ) + self.assertEqual(code, 1) + self.assertNotIn("Traceback", err) + self.assertIn("simulated replace failure", err) + self.assertEqual(dest.read_text(encoding="utf-8"), "existing-report\n") + self.assertEqual(sorted(p.name for p in calls.iterdir()), ["root-devices-warp.json", "six-apis.json"]) + + def test_argparse_py314_safe(self) -> None: + with TemporaryDirectory() as tmp: + repo = Path(tmp) / "repo" + code_help, out_help, err_help = _run_main(probe_root_devices, ["--help"], repo) + self.assertEqual(code_help, 0) + self.assertEqual(err_help, "") + self.assertIn("usage:", out_help.lower()) + + for bad_argv in (["--bogus-flag"], ["build_one", "extra_arg"]): + with self.subTest(argv=bad_argv): + code, _, err = _run_main(probe_root_devices, bad_argv, repo) + self.assertNotEqual(code, 0) + self.assertNotIn("Traceback", err) + self.assertIn("unrecognized", err.lower()) + + def test_fast_temp_copy_mutations(self) -> None: + source = TOOL.read_text(encoding="utf-8") + for label, target, replacement in MUTATIONS: + with self.subTest(mutation=label), TemporaryDirectory() as tmp: + base = Path(tmp) + repo, calls, build_dir, bin_dir = self._create_fixture(base) + file_bin = base / "file_bin" + file_bin.write_text("not dir", encoding="ascii") + bad_cso_bin = base / "bad_cso_bin" + bad_cso_bin.mkdir() + (bad_cso_bin / "compute_root.cso").mkdir() + (bad_cso_bin / "compute_tables.cso").write_bytes(b"ok") + dest = calls / "root-devices-warp.json" + + checks = { + "drop_bin_is_dir_guard": lambda mod: self.assertIn( + "--bin path is not a directory", + _run_main(mod, ["--warp-only", "--bin", str(file_bin)], repo)[2], + ), + "drop_control_cso_is_file_guard": lambda mod: self.assertIn( + "Control shader is missing or not a file", + _run_main(mod, ["--warp-only", "--bin", str(bad_cso_bin)], repo)[2], + ), + "drop_dest_is_dir_guard": lambda mod: self._assert_dir_guard_fires( + mod, build_dir, bin_dir, repo, dest + ), + "drop_dest_inside_build_guard": lambda mod: self.assertEqual( + _run_main(mod, [str(repo), "--warp-only", "--bin", str(bin_dir)], repo)[0], + 2, + ), + "drop_tmp_unlink_cleanup": lambda mod: self._assert_replace_leaves_zero_temps( + mod, build_dir, bin_dir, repo, calls, dest + ), + } + + self.assertEqual(source.count(target), 1, target) + mut_path = base / f"probe_root_devices_{label}.py" + mut_path.write_text(source.replace(target, replacement, 1), encoding="utf-8") + mod_name = f"probe_root_devices_mut_{label}" + mod = _load_temp_module(mut_path, mod_name) + try: + with self.assertRaises(AssertionError, msg=f"mutation {label} escaped detection"): + checks[label](mod) + finally: + sys.modules.pop(mod_name, None) + + def _assert_dir_guard_fires(self, mod, build_dir: Path, bin_dir: Path, repo: Path, dest: Path) -> None: + dest.mkdir() + try: + _, _, err = _run_main(mod, [str(build_dir), "--warp-only", "--bin", str(bin_dir)], repo) + finally: + if dest.is_dir(): + dest.rmdir() + self.assertIn("Output path is a directory", err) + + def _assert_replace_leaves_zero_temps( + self, mod, build_dir: Path, bin_dir: Path, repo: Path, calls: Path, dest: Path + ) -> None: + dest.write_text("keep", encoding="utf-8") + try: + with mock.patch.object(os, "replace", side_effect=OSError("boom")): + _run_main(mod, [str(build_dir), "--warp-only", "--bin", str(bin_dir)], repo) + self.assertEqual(sorted(p.name for p in calls.iterdir()), ["root-devices-warp.json", "six-apis.json"]) + finally: + for extra in list(calls.iterdir()): + if extra.name not in ("six-apis.json", "root-devices-warp.json"): + extra.unlink(missing_ok=True) + dest.unlink(missing_ok=True) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/rectlist_draw_check.cpp b/tests/rectlist_draw_check.cpp index 75fd169f90..9466765257 100644 --- a/tests/rectlist_draw_check.cpp +++ b/tests/rectlist_draw_check.cpp @@ -121,7 +121,7 @@ void execute_draw( const D3D12_VERTEX_BUFFER_VIEW vbv{ upload_vb->GetGPUVirtualAddress(), - sizeof(Vertex) * vertex_count, + static_cast<UINT>(sizeof(Vertex) * vertex_count), sizeof(Vertex) }; list->IASetVertexBuffers(0, 1, &vbv); diff --git a/tests/startup_acphal_xma_activity.cpp b/tests/startup_acphal_xma_activity.cpp new file mode 100644 index 0000000000..08c9ae7c72 --- /dev/null +++ b/tests/startup_acphal_xma_activity.cpp @@ -0,0 +1,548 @@ +// Source-built check of the activity counter in the AcpHal and XApu stand-ins (src/startup_stubs/acphal.cpp and +// xapu.cpp, X2W_AUDIO_ACTIVITY=1, docs/startup-runtime.md). One caller script fills, changes and clears XMA contexts, +// submits HAL commands and enqueues XApu commands. Each case runs in a child process of its own: +// on counter on: the exports and the logged lines report exactly what the script did, and a freed and +// reused context array is no longer counted +// none counter on, but the caller writes only next to the contexts and sends nothing: every count is 0 and no +// activity line is logged +// off counter unset, same script as on: the exports report nothing and no line is logged +// unload counter on: AcpHalAllocateShapeContexts runs again without an ApuFree (the old array's last changes count, +// later ones do not, the new array is counted), then the caller unloads both DLLs and stays alive for 1.5 s; +// it must exit 0, so nothing of either DLL may run after FreeLibrary +// The stand-ins log a due activity line only inside a call into them, so the cases call the exports before they read +// the log. +// Every call's result, output and last error, and the final context bytes, must be the same with the counter on and +// off. The 64-byte context stride and the command class (first UINT32) are stand-in conventions, not a console layout. +// Usage: startup_acphal_xma_activity <AcpHal.dll> <xapu.dll> +#ifndef WIN32_LEAN_AND_MEAN +#define WIN32_LEAN_AND_MEAN +#endif +#ifndef NOMINMAX +#define NOMINMAX +#endif +#include <windows.h> + +#include <cstdint> +#include <cstdio> +#include <cstring> +#include <initializer_list> +#include <iterator> +#include <map> +#include <string> +#include <utility> +#include <vector> + +namespace { +using u64 = std::uint64_t; +using CreateHeapFn = long(__cdecl*)(u64, u64); +using AllocFn = long(__cdecl*)(void**, std::uint32_t*, u64, u64, u64); +using FreeFn = long(__cdecl*)(void*); +using HalCreateFn = long(__cdecl*)(void**); +using ShapeAllocFn = long(__cdecl*)(void*); +using HalConnectFn = long(__stdcall*)(void*, unsigned, unsigned); +using HalSubmitFn = long(__stdcall*)(void*, unsigned, u64, unsigned, const unsigned*, u64); +using ConnectFn = long(__cdecl*)(const void*, void*, u64*); +using EnqueueFn = long(__cdecl*)(u64, const void*, u64, u64); +using CountFn = std::uint32_t(__cdecl*)(u64, u64); +using DequeueFn = long(__cdecl*)(u64, void*); +using DisconnectFn = long(__cdecl*)(u64); +using ActivityFn = BOOL(WINAPI*)(ULONGLONG*); + +constexpr std::uint32_t contexts = 350; +constexpr int acphal_fields = 15, xapu_fields = 19; +// x2w_acphal_xma_activity: watched, live, filled, changed, cleared, HAL submits, submits of type 0..7, other types. +enum { watched = 0, live = 1, filled = 2, changed = 3, cleared = 4, submits = 5, submit_type0 = 6, submit_other = 14 }; +// x2w_xapu_command_counts: classes 0..15, larger classes, unreadable commands, unknown handles. +enum { class_other = 16, unreadable = 17, rejected = 18 }; + +struct ShapeContexts { + std::uint32_t counts[6]{}; + unsigned char* arrays[6]{}; + std::uint32_t apu[6]{}; +}; +static_assert(sizeof(ShapeContexts) == 0x60, "ShapeContexts layout"); + +struct Api { + CreateHeapFn create_heap; + AllocFn alloc; + FreeFn free; + HalCreateFn hal_create; + ShapeAllocFn shape_alloc; + ConnectFn connect; + EnqueueFn enqueue; + CountFn result_count; + DequeueFn dequeue; + DisconnectFn disconnect; + ActivityFn acphal_activity; + ActivityFn xapu_counts; +}; + +int failures; +std::string transcript; // every result, output and last error, compared between the on and off runs + +void check(bool condition, const char* what) +{ + if (condition) return; + std::printf("FAIL: %s\n", what); + ++failures; +} + +// Calls are made with a sentinel last error, so a stand-in that changes the caller's last error shows up. +void note(const char* what, long hr, unsigned long long value = 0) +{ + char line[160]; + std::snprintf(line, sizeof(line), "%s hr=0x%08lx value=0x%llx last_error=%lu\n", what, static_cast<unsigned long>(hr), value, + GetLastError()); + transcript += line; +} +void sentinel() { SetLastError(0x5A5A); } + +// XApuConnect refuses a shared buffer size of 0 (the u32 at input +0x0C) with E_INVALIDARG; 4 KiB is enough here. +void set_buffer_size(unsigned char* connect_input) +{ + const std::uint32_t bytes = 0x1000; + std::memcpy(connect_input + 0x0C, &bytes, sizeof(bytes)); +} + +// One aligned 8-byte store, so the sampler sees the context before or after it, never half written. +void store(unsigned char* base, std::uint32_t context, unsigned word, u64 value) +{ + InterlockedExchange64(reinterpret_cast<volatile LONG64*>(base + context * 64u + word * 8u), static_cast<LONG64>(value)); +} + +struct Snapshot { + BOOL on = FALSE; + ULONGLONG v[xapu_fields > acphal_fields ? xapu_fields : acphal_fields]; +}; + +Snapshot take(ActivityFn fn) +{ + Snapshot s; + for (auto& x : s.v) x = 0xA5A5A5A5A5A5A5A5ull; // the export must overwrite every field, on or off + s.on = fn(s.v); + return s; +} + +using Fields = std::initializer_list<std::pair<int, u64>>; // (field, value) pairs + +// Every field is zero except the listed ones. +void expect(const char* label, const Snapshot& s, BOOL on, int fields, Fields nonzero) +{ + bool good = s.on == on; + for (int i = 0; i < fields; ++i) { + u64 want = 0; + for (const auto& f : nonzero) + if (f.first == i) want = f.second; + good = good && s.v[i] == want; + } + if (good) return; + std::printf("FAIL: %s: returned %d, fields", label, s.on); + for (int i = 0; i < fields; ++i) std::printf(" %llu", s.v[i]); + std::printf("\n"); + ++failures; +} + +// The fields expected with the counter on; with it off the export returns FALSE and every field must be zero. +void expect_on(const char* label, const Snapshot& s, bool on, int fields, Fields when_on) +{ + expect(label, s, on, fields, on ? when_on : Fields{}); +} + +std::string read_file(const char* path) +{ + std::string text; + HANDLE file = CreateFileA(path, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr, OPEN_EXISTING, 0, nullptr); + if (file == INVALID_HANDLE_VALUE) return text; + char buffer[4096]; + DWORD got = 0; + while (ReadFile(file, buffer, sizeof(buffer), &got, nullptr) && got) text.append(buffer, got); + CloseHandle(file); + return text; +} + +// Sums the name=value tokens of the activity lines in the log, keyed "xma.<name>" or "xapu.<name>"; zero sums are +// dropped. A bare number names a submit type (xma) or a command class (xapu). The live=n/m token is not a count. +std::map<std::string, u64> activity_sums(const std::string& log, int* lines) +{ + std::map<std::string, u64> sums; + *lines = 0; + std::size_t at = 0; + while (at < log.size()) { + std::size_t end = log.find('\n', at); + if (end == std::string::npos) end = log.size(); + const std::string line = log.substr(at, end - at); + at = end + 1; + const char* kind = line.find("x2w-audio xma-activity t=") != std::string::npos ? "xma." + : line.find("x2w-audio xapu-activity t=") != std::string::npos ? "xapu." + : nullptr; + if (!kind) continue; + ++*lines; + std::size_t pos = line.find(" s: "); + while (pos != std::string::npos && pos < line.size()) { + const std::size_t start = pos + 1; + pos = line.find(' ', start); + std::string token = line.substr(start, pos == std::string::npos ? std::string::npos : pos - start); + while (!token.empty() && (token.back() == ';' || token.back() == '\r')) token.pop_back(); + const std::size_t eq = token.find('='); + if (eq == std::string::npos || token.find('/') != std::string::npos) continue; + sums[kind + token.substr(0, eq)] += std::strtoull(token.c_str() + eq + 1, nullptr, 10); + } + } + for (auto it = sums.begin(); it != sums.end();) it = it->second ? std::next(it) : sums.erase(it); + return sums; +} + +std::string describe(const std::map<std::string, u64>& sums) +{ + std::string text; + for (const auto& s : sums) text += " " + s.first + "=" + std::to_string(s.second); + return text; +} + +int activity_lines(const char* log_path) +{ + int lines = 0; + activity_sums(read_file(log_path), &lines); + return lines; +} + +// The caller script of the on and off cases. Snapshots are taken between phases and no other counted call runs while +// the contexts are written, so each context moves once between two samples. +void script(const Api& api, bool on) +{ + sentinel(); + note("ApuCreateHeap", api.create_heap(0x200000, 0)); + void* hal = nullptr; + sentinel(); + note("AcpHalCreate", api.hal_create(&hal), hal != nullptr); + if (!hal) return check(false, "AcpHalCreate returns an object"); + auto* const* table = *reinterpret_cast<void* const* const*>(hal); + auto hal_connect = reinterpret_cast<HalConnectFn>(table[0]); + auto hal_submit = reinterpret_cast<HalSubmitFn>(table[2]); + sentinel(); + note("AcpHal connect", hal_connect(hal, 0x1000, 0x1000)); + ShapeContexts ctx{}; + ctx.counts[4] = contexts; + sentinel(); + note("AcpHalAllocateShapeContexts", api.shape_alloc(&ctx), ctx.apu[4]); + unsigned char* const base = ctx.arrays[4]; + if (!base) return check(false, "XMA contexts allocated"); + expect_on("before any write", take(api.acphal_activity), on, acphal_fields, {{watched, contexts}}); + + // Fill 5 contexts, one word each; context 349 uses its last word. + store(base, 0, 0, 0x1111); + store(base, 1, 3, 0x2222); + store(base, 2, 0, 0x3333); + store(base, 100, 5, 0x4444); + store(base, 349, 7, 0x5555); + expect_on("after 5 fills", take(api.acphal_activity), on, acphal_fields, + {{watched, contexts}, {live, 5}, {filled, 5}}); + // Change 3 live contexts: the same word, the last word, another word. + store(base, 0, 0, 0x1112); + store(base, 1, 7, 0x2223); + store(base, 100, 2, 0x4445); + expect_on("after 3 changes", take(api.acphal_activity), on, acphal_fields, + {{watched, contexts}, {live, 5}, {filled, 5}, {changed, 3}}); + // Clear 2 contexts. + store(base, 2, 0, 0); + store(base, 349, 7, 0); + expect_on("after 2 clears", take(api.acphal_activity), on, acphal_fields, + {{watched, contexts}, {live, 3}, {filled, 5}, {changed, 3}, {cleared, 2}}); + + const unsigned input = 0x12345678u; + for (unsigned type : {1u, 1u, 3u, 12u}) { + sentinel(); + note("AcpHal submit", hal_submit(hal, type, 0x1234, 2, &input, 0), type); + } + const auto after_submits = take(api.acphal_activity); + expect_on("after 4 HAL submits", after_submits, on, acphal_fields, + {{watched, contexts}, {live, 3}, {filled, 5}, {changed, 3}, {cleared, 2}, {submits, 4}, {submit_type0 + 1, 2}, + {submit_type0 + 3, 1}, {submit_other, 1}}); + + unsigned char connect_input[0x18]{}, connect_output[0x10]{}; + set_buffer_size(connect_input); + u64 handle = 0; + sentinel(); + note("XApuConnect", api.connect(connect_input, connect_output, &handle), handle); + unsigned char command[0x60]{}; + for (std::uint32_t command_class : {1u, 1u, 2u, 1u, 2u, 0x20u}) { + std::memcpy(command, &command_class, sizeof(command_class)); + sentinel(); + note("XApuEnqueueCommand", api.enqueue(handle, command, 0, 0), command_class); + } + sentinel(); + note("XApuEnqueueCommand null command", api.enqueue(handle, nullptr, 0, 0)); + std::uint32_t one = 1; + std::memcpy(command, &one, sizeof(one)); + sentinel(); + note("XApuEnqueueCommand unknown handle", api.enqueue(handle + 0x100, command, 0, 0)); + // A type 3 command whose 8-byte header ends where free address space begins (the rest of the page's allocation + // granule), sent with typed completions on. An X2W_WITH_OPUS build refuses it with E_POINTER before the queue, as + // too short to decode, and must still count it as class 3; without Opus it is queued like any other command. + // X2W_PROBE_PRECHECK=1 (every case) refuses the free tail without touching it, so no fault is taken. Typed + // completions are set for this call only. + SYSTEM_INFO system{}; + GetSystemInfo(&system); + auto* page = static_cast<unsigned char*>( + VirtualAlloc(nullptr, system.dwPageSize, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)); + MEMORY_BASIC_INFORMATION after{}; + const bool free_after = + page && VirtualQuery(page + system.dwPageSize, &after, sizeof(after)) && after.State == MEM_FREE; + check(free_after, "free address space after the short command"); + if (free_after) { + unsigned char* short_command = page + system.dwPageSize - 8; + const std::uint32_t three = 3; + std::memcpy(short_command, &three, sizeof(three)); + SetEnvironmentVariableA("X2W_XAPU_TYPED_COMPLETIONS", "1"); + sentinel(); + note("XApuEnqueueCommand short type 3 command", api.enqueue(handle, short_command, 0, 0)); + SetEnvironmentVariableA("X2W_XAPU_TYPED_COMPLETIONS", nullptr); + } + if (page) VirtualFree(page, 0, MEM_RELEASE); + sentinel(); + const std::uint32_t pending = api.result_count(handle, 0); + note("XApuGetResultCount", 0, pending); + for (int i = 0; i < 8; ++i) { + unsigned char result[0x58]; + std::memset(result, 0xCC, sizeof(result)); + sentinel(); + const long hr = api.dequeue(handle, result); + unsigned sum = 0; + for (unsigned char b : result) sum += b; + note("XApuDequeueResult", hr, sum); + } + sentinel(); + note("XApuDisconnect", api.disconnect(handle)); + expect_on("XApu commands", take(api.xapu_counts), on, xapu_fields, + {{1, 3}, {2, 2}, {3, 1}, {class_other, 1}, {unreadable, 1}, {rejected, 1}}); + + unsigned hash = 2166136261u; // FNV-1a of the context bytes: the counter never writes caller memory + for (std::uint32_t i = 0; i < contexts * 64; ++i) hash = (hash ^ base[i]) * 16777619u; + sentinel(); + note("context bytes", 0, hash); + + // Freed contexts stop being watched; the block that comes back is not counted. + sentinel(); + note("ApuFree contexts", api.free(base)); + void* again = nullptr; + std::uint32_t again_apu = 0; + sentinel(); + note("ApuAlloc same size", api.alloc(&again, &again_apu, contexts * 64, 64, 0), again_apu); + sentinel(); + note("same block", 0, again == base); + check(again == base, "ApuAlloc of the same size returns the freed context block"); + if (again) { + auto* p = static_cast<unsigned char*>(again); + store(p, 0, 0, 0x6666); + store(p, 5, 1, 0x7777); + store(p, 300, 7, 0x8888); + Sleep(50); // several 10 ms sample periods + } + expect_on("after free and reuse", take(api.acphal_activity), on, acphal_fields, + {{filled, 5}, {changed, 3}, {cleared, 2}, {submits, 4}, {submit_type0 + 1, 2}, {submit_type0 + 3, 1}, + {submit_other, 1}}); +} + +// Zero-write control: the counter is on, the caller writes only to the block after the contexts and sends nothing. +void script_none(const Api& api) +{ + api.create_heap(0x200000, 0); + void* hal = nullptr; + check(api.hal_create(&hal) == 0 && hal, "AcpHalCreate"); + ShapeContexts ctx{}; + ctx.counts[4] = contexts; + check(api.shape_alloc(&ctx) == 0 && ctx.arrays[4], "AcpHalAllocateShapeContexts"); + void* next = nullptr; + std::uint32_t next_apu = 0; + check(api.alloc(&next, &next_apu, 0x1000, 64, 0) == 0 && next, "ApuAlloc after the contexts"); + // The control writes the 64 bytes right after the last context, so it is only meaningful if they are adjacent. + check(next_apu == ctx.apu[4] + contexts * 64, "the next block starts right after the last context"); + if (next) { + store(static_cast<unsigned char*>(next), 0, 0, 0x9999); + store(static_cast<unsigned char*>(next), 0, 7, 0x9999); + } + unsigned char connect_input[0x18]{}, connect_output[0x10]{}; + set_buffer_size(connect_input); + u64 handle = 0; + check(api.connect(connect_input, connect_output, &handle) == 0, "XApuConnect"); + check(api.disconnect(handle) == 0, "XApuDisconnect"); + Sleep(50); + expect("zero-write control", take(api.acphal_activity), TRUE, acphal_fields, {{watched, contexts}}); + expect("zero-write control XApu", take(api.xapu_counts), TRUE, xapu_fields, {}); +} + +// The unload case. Nothing in it is compared with another run. +void script_unload(const Api& api, HMODULE acphal, HMODULE xapu) +{ + check(api.create_heap(0x200000, 0) == 0, "ApuCreateHeap"); + void* hal = nullptr; + check(api.hal_create(&hal) == 0 && hal, "AcpHalCreate"); + if (!hal) return; + auto hal_submit = reinterpret_cast<HalSubmitFn>((*reinterpret_cast<void* const* const*>(hal))[2]); + const unsigned input = 0; + check(hal_submit(hal, 1, 0x1234, 2, &input, 0) == 0, "AcpHal submit"); + ShapeContexts first{}, second{}; + first.counts[4] = contexts; + second.counts[4] = 4; + check(api.shape_alloc(&first) == 0 && first.arrays[4], "first AcpHalAllocateShapeContexts"); + if (!first.arrays[4]) return; + store(first.arrays[4], 0, 0, 0x1111); // not sampled yet: the re-run's last sample of this array counts it + check(api.shape_alloc(&second) == 0 && second.arrays[4] && second.arrays[4] != first.arrays[4], + "AcpHalAllocateShapeContexts again, without ApuFree, gives another array"); + if (!second.arrays[4]) return; + store(first.arrays[4], 1, 0, 0x2222); // the old array is no longer watched + store(second.arrays[4], 3, 7, 0x3333); // the new one is, up to its last word + expect("re-run without ApuFree", take(api.acphal_activity), TRUE, acphal_fields, + {{watched, 4}, {live, 1}, {filled, 2}, {submits, 1}, {submit_type0 + 1, 1}}); + unsigned char connect_input[0x18]{}, connect_output[0x10]{}, command[0x60]{}; + set_buffer_size(connect_input); + u64 handle = 0; + command[0] = 1; + check(api.connect(connect_input, connect_output, &handle) == 0, "XApuConnect"); + api.enqueue(handle, command, 0, 0); + expect("XApu command before unload", take(api.xapu_counts), TRUE, xapu_fields, {{1, 1}}); + // Unloading must really unmap both images, else the wait below proves nothing. + const void* const code[] = {reinterpret_cast<const void*>(api.create_heap), reinterpret_cast<const void*>(api.enqueue)}; + check(FreeLibrary(acphal) && FreeLibrary(xapu), "FreeLibrary of both stand-ins"); + for (const void* address : code) { + HMODULE still = nullptr; + check(!GetModuleHandleExA(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, + static_cast<const char*>(address), &still), + "the stand-in is unloaded after FreeLibrary"); + } + Sleep(1500); // past a 10 ms sample period and a 1 s line interval: a leftover thread of either DLL would run now +} + +int run_case(const char* name, const char* acphal_path, const char* xapu_path, const char* transcript_path) +{ + HMODULE acphal = LoadLibraryA(acphal_path), xapu = LoadLibraryA(xapu_path); + if (!acphal || !xapu) return std::printf("FAIL: cannot load the stand-ins\n"), 2; + Api api{}; + api.create_heap = reinterpret_cast<CreateHeapFn>(GetProcAddress(acphal, "ApuCreateHeap")); + api.alloc = reinterpret_cast<AllocFn>(GetProcAddress(acphal, "ApuAlloc")); + api.free = reinterpret_cast<FreeFn>(GetProcAddress(acphal, "ApuFree")); + api.hal_create = reinterpret_cast<HalCreateFn>(GetProcAddress(acphal, "AcpHalCreate")); + api.shape_alloc = reinterpret_cast<ShapeAllocFn>(GetProcAddress(acphal, "AcpHalAllocateShapeContexts")); + api.acphal_activity = reinterpret_cast<ActivityFn>(GetProcAddress(acphal, "x2w_acphal_xma_activity")); + api.connect = reinterpret_cast<ConnectFn>(GetProcAddress(xapu, "XApuConnect")); + api.enqueue = reinterpret_cast<EnqueueFn>(GetProcAddress(xapu, "XApuEnqueueCommand")); + api.result_count = reinterpret_cast<CountFn>(GetProcAddress(xapu, "XApuGetResultCount")); + api.dequeue = reinterpret_cast<DequeueFn>(GetProcAddress(xapu, "XApuDequeueResult")); + api.disconnect = reinterpret_cast<DisconnectFn>(GetProcAddress(xapu, "XApuDisconnect")); + api.xapu_counts = reinterpret_cast<ActivityFn>(GetProcAddress(xapu, "x2w_xapu_command_counts")); + if (!api.create_heap || !api.alloc || !api.free || !api.hal_create || !api.shape_alloc || !api.acphal_activity || !api.connect || + !api.enqueue || !api.result_count || !api.dequeue || !api.disconnect || !api.xapu_counts) + return std::printf("FAIL: missing export\n"), 2; + char log_path[MAX_PATH] = ""; + GetEnvironmentVariableA("X2W_TRAP_LOG", log_path, MAX_PATH); + check(api.acphal_activity(nullptr) == FALSE && api.xapu_counts(nullptr) == FALSE, "the exports refuse a null output"); + + if (!std::strcmp(name, "unload")) { + script_unload(api, acphal, xapu); + } else if (!std::strcmp(name, "none")) { + script_none(api); + Sleep(1500); // longer than the line interval: an unchanged count writes no line + take(api.acphal_activity); + take(api.xapu_counts); + check(activity_lines(log_path) == 0, "zero-write control logs no activity line"); + } else { + const bool on = !std::strcmp(name, "on"); + script(api, on); + if (on) { + const std::map<std::string, u64> want = { + {"xma.filled", 5}, {"xma.changed", 3}, {"xma.cleared", 2}, {"xma.submits", 4}, {"xma.1", 2}, + {"xma.3", 1}, {"xma.other", 1}, {"xapu.commands", 8}, {"xapu.1", 3}, {"xapu.2", 2}, + {"xapu.3", 1}, {"xapu.other", 1}, {"xapu.unreadable", 1}, {"xapu.rejected", 1}}; + std::map<std::string, u64> got; + int lines = 0; + for (int waited = 0; waited <= 5000; waited += 100) { // a call a second after the start writes the line + take(api.acphal_activity); + take(api.xapu_counts); + got = activity_sums(read_file(log_path), &lines); + if (got == want) break; + Sleep(100); + } + if (got != want) { + std::printf("FAIL: logged activity lines (%d) sum to%s\n expected%s\n", lines, describe(got).c_str(), + describe(want).c_str()); + ++failures; + } + } else { + Sleep(1500); + take(api.acphal_activity); + take(api.xapu_counts); + check(activity_lines(log_path) == 0, "counter off logs no activity line"); + check(read_file(log_path).find("-activity") == std::string::npos, "counter off logs nothing about activity"); + } + HANDLE out = CreateFileA(transcript_path, GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, 0, nullptr); + DWORD wrote = 0; + check(out != INVALID_HANDLE_VALUE && WriteFile(out, transcript.data(), static_cast<DWORD>(transcript.size()), &wrote, nullptr) && + wrote == transcript.size(), + "transcript written"); + if (out != INVALID_HANDLE_VALUE) CloseHandle(out); + } + std::printf(failures ? "case %s: %d failure(s)\n" : "case %s: ok\n", name, failures); + return failures ? 1 : 0; +} + +DWORD spawn(const char* self, const char* name, const char* acphal, const char* xapu, const std::string& dir) +{ + const std::string log = dir + "\\" + name + ".log", out = dir + "\\" + name + ".txt"; + SetEnvironmentVariableA("X2W_AUDIO_PERMISSIVE", "1"); + SetEnvironmentVariableA("X2W_AUDIO_ACTIVITY", std::strcmp(name, "off") ? "1" : nullptr); + SetEnvironmentVariableA("X2W_PROBE_PRECHECK", "1"); // the short command's free tail is refused, not touched + SetEnvironmentVariableA("X2W_TRAP_LOG", log.c_str()); + std::string cmd = std::string("\"") + self + "\" --case " + name + " \"" + acphal + "\" \"" + xapu + "\" \"" + out + "\""; + // The child writes to this process's stdout and stderr, so its lines reach the CTest log. + STARTUPINFOA si{}; + si.cb = sizeof(si); + si.dwFlags = STARTF_USESTDHANDLES; + si.hStdInput = GetStdHandle(STD_INPUT_HANDLE); + si.hStdOutput = GetStdHandle(STD_OUTPUT_HANDLE); + si.hStdError = GetStdHandle(STD_ERROR_HANDLE); + for (HANDLE h : {si.hStdOutput, si.hStdError}) SetHandleInformation(h, HANDLE_FLAG_INHERIT, HANDLE_FLAG_INHERIT); + std::fflush(stdout); + PROCESS_INFORMATION pi{}; + if (!CreateProcessA(nullptr, cmd.data(), nullptr, nullptr, TRUE, 0, nullptr, nullptr, &si, &pi)) return 0xFFFFFFFFu; + DWORD code = 0xFFFFFFFEu; + // 12 s per case keeps all four inside the CTest TIMEOUT of 60 s, so a hung case is named, not killed with the parent. + if (WaitForSingleObject(pi.hProcess, 12000) == WAIT_OBJECT_0) GetExitCodeProcess(pi.hProcess, &code); + else TerminateProcess(pi.hProcess, 0xFFFFFFFDu); // our own child, by handle + CloseHandle(pi.hThread); + CloseHandle(pi.hProcess); + return code; +} +} // namespace + +int main(int argc, char** argv) +{ + if (argc == 6 && !std::strcmp(argv[1], "--case")) return run_case(argv[2], argv[3], argv[4], argv[5]); + if (argc != 3) return std::printf("usage: startup_acphal_xma_activity <AcpHal.dll> <xapu.dll>\n"), 2; + char temp[MAX_PATH]; + if (!GetTempPathA(MAX_PATH, temp)) return std::printf("FAIL: no temp folder\n"), 2; + const std::string dir = std::string(temp) + "x2w_xma_activity_" + std::to_string(GetCurrentProcessId()); + if (!CreateDirectoryA(dir.c_str(), nullptr)) return std::printf("FAIL: cannot create %s\n", dir.c_str()), 2; + char self[MAX_PATH]; + GetModuleFileNameA(nullptr, self, MAX_PATH); + for (const char* name : {"on", "none", "off", "unload"}) { + const DWORD code = spawn(self, name, argv[1], argv[2], dir); + if (code) { + std::printf("FAIL: case %s exited 0x%08lx\n", name, static_cast<unsigned long>(code)); + ++failures; + } + } + const std::string on = read_file((dir + "\\on.txt").c_str()), off = read_file((dir + "\\off.txt").c_str()); + check(!on.empty(), "the on case wrote a transcript"); + if (on != off) { + std::size_t at = 0; + while (at < on.size() && at < off.size() && on[at] == off[at]) ++at; + const std::size_t line = on.rfind('\n', at) == std::string::npos ? 0 : on.rfind('\n', at) + 1; + std::printf("FAIL: results differ with the counter on and off, first at: on '%s' off '%s'\n", + on.substr(line, on.find('\n', line) - line).c_str(), off.substr(line, off.find('\n', line) - line).c_str()); + ++failures; + } + for (const char* file : {"on.log", "none.log", "off.log", "unload.log", "on.txt", "off.txt"}) DeleteFileA((dir + "\\" + file).c_str()); + RemoveDirectoryA(dir.c_str()); + std::printf(failures ? "startup_acphal_xma_activity: %d failure(s)\n" : "startup_acphal_xma_activity: ok\n", failures); + return failures ? 1 : 0; +} diff --git a/tests/startup_address_console_check.py b/tests/startup_address_console_check.py index 10e07f388d..53bde47822 100644 --- a/tests/startup_address_console_check.py +++ b/tests/startup_address_console_check.py @@ -1,6 +1,6 @@ """Draw textures published by address (device slot 70) whose texels are in a console layout. - <consumer> <backend> fourteen textures, three cubes and six volume mips, each drawn once; every + <consumer> <backend> fourteen textures, three cubes and nine volume mips, each drawn once; every pixel of the 512x128 target is compared with the texel the view names; then three held descriptions and one texture whose address is announced as XG rows after it was published @@ -121,21 +121,27 @@ def address(self, mip, x, y): # A volume in the 4 KiB standard mode (0x105): addrlib lays a 3D resource in a standard mode out in thick -# blocks (Gfx10Lib::HwlIsThick). The 12 address bits of a 4-byte element follow the one-pipe row of -# GFX10_SW_4K_S3_PATINFO; the block is 8x16x8 elements. The volume is stored a layer of blocks (8 deep) at -# a time, and each layer holds that layer of every mip: the shared tail block first when the chain has -# one, then the mips from the smallest to the largest, blocks in x, then y. Mip sizes round up. A mip is in -# the tail when it is at most 8 wide and 8 high and at most five mips remain; tail mip k from the end sits -# at byte (k << 8) of the tail block, which, read as 4x4x4 micro blocks, is its origin in x and y. -THICK_4K_S3 = {4: "0 0 X0 Y0 Z0 Y1 X1 Z1 Y2 X2 Z2 Y3"} +# blocks (Gfx10Lib::HwlIsThick). The 12 address bits of an element follow the one-pipe row of +# GFX10_SW_4K_S3_PATINFO for its size; the block is 8x16x8 elements of 4 bytes, or 8x8x8 of 8. The volume is +# stored a layer of blocks (8 deep) at a time, and each layer holds that layer of every mip: the shared tail +# block first when the chain has one, then the mips from the smallest to the largest, blocks in x, then y. +# Mip sizes round up. A mip is in the tail when it is at most a block wide and half a block high and at most +# five mips remain; tail mip k from the end sits at byte (k << 8) of the tail block, which, read as 256-byte +# micro blocks (4x4x4 elements of 4 bytes, 4x2x4 of 8), is its origin in x and y. A BC1 volume is the volume +# of its 4x4 blocks, 8-byte elements one depth layer each: the sides are first rounded up to whole blocks, +# and every mip size after that is in blocks. +THICK_4K_S3 = {4: "0 0 X0 Y0 Z0 Y1 X1 Z1 Y2 X2 Z2 Y3", 8: "0 0 0 X0 Z0 Y0 X1 Z1 Y1 X2 Z2 Y2"} +MICRO_3D = {4: (4, 4), 8: (4, 2)} class ConsoleVolume: - def __init__(self, width, height, depth, element, mips=1): + def __init__(self, width, height, depth, element, mips=1, texels=1): + width, height = -(-width // texels), -(-height // texels) self.width, self.height, self.depth = width, height, depth self.bits = THICK_4K_S3[element].split() self.block = [1 << sum(b[0] == axis for b in self.bits) for axis in "XYZ"] bw, bh, bd = self.block + mw, mh = MICRO_3D[element] size = [(max(1, -(-width // (1 << m))), max(1, -(-height // (1 << m)))) for m in range(mips)] tail = next((m for m, (w, h) in enumerate(size) if mips > 1 and w <= bw and h <= bh // 2 and mips - m <= 5), mips) @@ -148,7 +154,7 @@ def __init__(self, width, height, depth, element, mips=1): for m in range(tail, mips): at = (4 - (m - tail)) << 8 self.start[m] = 0 - self.origin[m] = (4 * ((at >> 9 & 1) | (at >> 10 & 2)), 4 * ((at >> 8 & 1) | (at >> 9 & 2))) + self.origin[m] = (mw * ((at >> 9 & 1) | (at >> 10 & 2)), mh * ((at >> 8 & 1) | (at >> 9 & 2))) self.layer = offset self.bytes = self.layer * -(-depth // bd) @@ -205,8 +211,13 @@ def volume_texel(x, y, z, mip=0): return bytes(((7 * x + 1) & 255, (5 * y + 3) & 255, (29 * z + 11) & 255, 255 - 16 * mip)) -# name, width, height, depth, format, layout, mips, viewed mip: RGBA8 in the 4 KiB standard mode, one mip -# viewed as a Texture3D. Each target tile of the viewed mip's width and height draws one depth layer. The +def volume_bc1_block(x, y, z, mip=0): + """The block of BC1 volume block (x, y) of layer z: one colour, which differs between neighbours.""" + return bc1_block(mip, x, y + 3 * z) + + +# name, width, height, depth, format, layout, mips, viewed mip: RGBA8 or BC1 in the 4 KiB standard mode, one +# mip viewed as a Texture3D. Each target tile of the viewed mip's width and height draws one depth layer. The # chains view a mip outside the tail and one inside it. VOLUMES = [ ("RGBA8 volume 17x17x17 4 KiB standard", 17, 17, 17, RGBA8, 0x105, 1, 0), @@ -215,6 +226,9 @@ def volume_texel(x, y, z, mip=0): ("RGBA8 volume 32x32x32 6 mips, mip 3 in the tail", 32, 32, 32, RGBA8, 0x105, 6, 3), ("RGBA8 volume 20x24x16 5 mips, mip 1", 20, 24, 16, RGBA8, 0x105, 5, 1), ("RGBA8 volume 20x24x16 5 mips, mip 3 in the tail", 20, 24, 16, RGBA8, 0x105, 5, 3), + ("BC1 volume 48x40x12 4 KiB standard", 48, 40, 12, BC1, 0x105, 1, 0), + ("BC1 volume 64x64x8 5 mips, mip 1", 64, 64, 8, BC1, 0x105, 5, 1), + ("BC1 volume 64x64x8 5 mips, mip 3 in the tail", 64, 64, 8, BC1, 0x105, 5, 3), ] @@ -222,29 +236,38 @@ def mip_sides(width, height, depth, mip): return max(1, width >> mip), max(1, height >> mip), max(1, depth >> mip) -def build_volume(width, height, depth, mips=1): - """Backing bytes of a volume and its mips, built from the S3 row above.""" - console = ConsoleVolume(width, height, depth, 4, mips) +def volume_colour(fmt, x, y, z, mip): + """The RGBA8 colour a correct detile shows at texel (x, y, z) of a mip.""" + return volume_bc1_block(x // 4, y // 4, z, mip)[1] if fmt == BC1 else volume_texel(x, y, z, mip) + + +def build_volume(width, height, depth, mips=1, fmt=RGBA8): + """Backing bytes of a volume and its mips, built from the S3 rows above.""" + texels, element = (4, 8) if fmt == BC1 else (1, 4) + console = ConsoleVolume(width, height, depth, element, mips, texels) backing = bytearray(console.bytes) seen = set() for mip in range(mips): w, h, d = mip_sides(width, height, depth, mip) for z in range(d): - for y in range(h): - for x in range(w): + for y in range(-(-h // texels)): + for x in range(-(-w // texels)): at = console.address(x, y, z, mip) - if at in seen or at + 4 > len(backing): + if at in seen or at + element > len(backing): raise AssertionError(f"oracle address {at:#x} of mip {mip} ({x},{y},{z}) is shared or outside " "the volume") seen.add(at) - backing[at:at + 4] = volume_texel(x, y, z, mip) + if fmt == BC1: + backing[at:at + 8] = volume_bc1_block(x, y, z, mip)[0] + else: + backing[at:at + 4] = volume_texel(x, y, z, mip) return backing def check_volume(directory, consumer, backend, case, held=None): name, width, height, depth, fmt, layout, mips, viewed = case source = directory / "texels.bin" - source.write_bytes(build_volume(width, height, depth, mips)) + source.write_bytes(build_volume(width, height, depth, mips, fmt)) width, height, depth = mip_sides(width, height, depth, viewed) across = -(-TARGET_W // width) hlsl = ("Texture3D<float4> t : register(t0);\n" @@ -274,7 +297,7 @@ def check_volume(directory, consumer, backend, case, held=None): z = (x // width + (y // height) * across) % depth layers.add(z) pixel = actual[4 * (y * TARGET_W + x):4 * (y * TARGET_W + x) + 4] - expect = volume_texel(x % width, y % height, z, viewed) + expect = volume_colour(fmt, x % width, y % height, z, viewed) if pixel != expect: raise AssertionError(f"{name}: pixel ({x},{y}) layer {z} actual {pixel.hex()} expected {expect.hex()}") if len(layers) != depth: diff --git a/tests/startup_audio_timeline_cli_check.py b/tests/startup_audio_timeline_cli_check.py index 18fe157a00..f6bba434db 100644 --- a/tests/startup_audio_timeline_cli_check.py +++ b/tests/startup_audio_timeline_cli_check.py @@ -239,9 +239,9 @@ def test_csv_error_and_non_utf8_inputs_exit_2_without_traceback(self) -> None: valid_jsonl.write_bytes(_jsonl_bytes([{"action": "a", "qpc": 100.0}])) flags = ["--process-origin-qpc", "100", "--action", "a"] - nul_csv = root / "nul.csv" + nul_csv = root / "nul_byte.csv" nul_csv.write_bytes(b"process_s,frames,rms,peak,flags\n0.0,4800,\x000.1,0.2,0\n") - self._assert_exit_2([str(nul_csv), str(valid_jsonl), *flags], expected_fragment="nul.csv:2:") + self._assert_exit_2([str(nul_csv), str(valid_jsonl), *flags], expected_fragment="nul_byte.csv:2:") # Field larger than csv.field_size_limit() triggers real csv.Error in both in-process & subprocess. oversized_csv = root / "oversized.csv" diff --git a/tests/startup_command_list_slot_names.cpp b/tests/startup_command_list_slot_names.cpp index a7e0602440..20d2e586cb 100644 --- a/tests/startup_command_list_slot_names.cpp +++ b/tests/startup_command_list_slot_names.cpp @@ -53,7 +53,7 @@ int main() {50, "OMSetRenderTargets"}, {52, "ClearRenderTargetView"}, {61, "ExecuteIndirect"}, - {139, "Reset"}, + {139, "Reset (console)"}, }; for (const auto& entry : handled) expect(is(entry.first, entry.second), "slot " + std::to_string(entry.first) + " is " + entry.second); @@ -61,12 +61,16 @@ int main() const std::vector<std::pair<int, const char*>> between = { {0, "QueryInterface"}, {1, "AddRef"}, {2, "Release"}, {3, "GetPrivateData"}, {4, "SetPrivateData"}, {5, "SetPrivateDataInterface"}, {6, "SetName"}, {8, "GetType"}, + {10, "Reset"}, {11, "ClearState"}, {14, "Dispatch"}, {15, "CopyBufferRegion"}, {16, "CopyTextureRegion"}, {17, "CopyResource"}, {18, "CopyTiles"}, {19, "ResolveSubresource"}, {24, "OMSetStencilRef"}, + {27, "ExecuteBundle"}, + {28, "BeginQuery"}, {29, "EndQuery"}, {30, "ResolveQueryData"}, {31, "SetPredication"}, + {56, "SetMarker"}, {57, "BeginEvent"}, {58, "EndEvent"}, }; for (const auto& entry : between) expect(is(entry.first, entry.second), "slot " + std::to_string(entry.first) + " is " + entry.second); - // From SetDescriptorHeaps on the console slot is the desktop slot plus four: 28 desktop methods in a row. + // From SetDescriptorHeaps through DiscardResource the console slot is the desktop slot plus four. const std::vector<const char*> shifted = { "SetDescriptorHeaps", "SetComputeRootSignature", "SetGraphicsRootSignature", "SetComputeRootDescriptorTable", "SetGraphicsRootDescriptorTable", "SetComputeRoot32BitConstant", "SetGraphicsRoot32BitConstant", @@ -74,19 +78,21 @@ int main() "SetGraphicsRootConstantBufferView", "SetComputeRootShaderResourceView", "SetGraphicsRootShaderResourceView", "SetComputeRootUnorderedAccessView", "SetGraphicsRootUnorderedAccessView", "IASetIndexBuffer", "IASetVertexBuffers", "SOSetTargets", "OMSetRenderTargets", "ClearDepthStencilView", "ClearRenderTargetView", - "ClearUnorderedAccessViewUint", "ClearUnorderedAccessViewFloat", "DiscardResource", "BeginQuery", "EndQuery", - "ResolveQueryData", "SetPredication"}; - expect(shifted.size() == 28, "the shifted run has 28 methods"); + "ClearUnorderedAccessViewUint", "ClearUnorderedAccessViewFloat", "DiscardResource"}; + expect(shifted.size() == 24, "the shifted run has 24 methods"); for (std::size_t i = 0; i < shifted.size(); ++i) expect(is(32 + static_cast<int>(i), shifted[i]), "slot " + std::to_string(32 + i) + " is " + shifted[i]); - // The run ends at 59 with the desktop slot 55; the desktop methods after it (56 to 59, plus four) are not named. - expect(is(59, "SetPredication"), "slot 59 is the desktop slot 55 plus four"); + // The run ends at 55 with DiscardResource; 56 to 58 keep the desktop marker names. + expect(is(55, "DiscardResource"), "slot 55 is the desktop slot 51 plus four"); + expect(is(56, "SetMarker"), "slot 56 is SetMarker"); + expect(is(57, "BeginEvent"), "slot 57 is BeginEvent"); + expect(is(58, "EndEvent"), "slot 58 is EndEvent"); // Slots that are not known stay unnamed: a name there would be a guess. - // 10 and 11: this console list resets through 139. 27 to 31: the remaining unconfirmed methods before the shift. - // Other slots from 60 up have unconfirmed meanings. -1 and 4096: outside the table. - std::vector<int> unknown = {10, 11, 27, 28, 29, 30, 31, 60, 62, 63, 64, 66, 68, 70, 71, 72, 74, 75, 100, 126, - 131, 132, 138, 140, 142, 146, 255, 256, 999, 4096, -1, -100}; + // 59 and 60 are console-only markers; 62 and up are console-only methods not named in this table. + // 148 is the console allocation method and stays unnamed. -1 and 4096: outside the table. + std::vector<int> unknown = {59, 60, 62, 63, 64, 66, 68, 70, 71, 72, 74, 75, 100, 126, + 131, 132, 138, 140, 142, 146, 147, 148, 149, 255, 256, 999, 4096, -1, -100}; for (const int slot : unknown) expect(x2w_list_slots::name(slot) == nullptr, "slot " + std::to_string(slot) + " has no name"); // Names are unique within the table and never empty, so a log line says which method it was. @@ -98,7 +104,7 @@ int main() for (const std::string& earlier : seen) expect(earlier != got, std::string("the name ") + got + " is used once"); seen.push_back(got); } - expect(seen.size() == 10 + 15 + 28 + 2, "the named slots are 0 to 9, 12 to 26, 32 to 59, 61 and 139"); + expect(seen.size() == 61, "the named slots are 0 to 58, 61 and 139"); if (failures) { std::fprintf(stderr, "%d check(s) failed\n", failures); diff --git a/tests/startup_compile_lds_request_cli_check.py b/tests/startup_compile_lds_request_cli_check.py new file mode 100644 index 0000000000..903874b91e --- /dev/null +++ b/tests/startup_compile_lds_request_cli_check.py @@ -0,0 +1,709 @@ +#!/usr/bin/env python3 +"""Offline unit, CLI, warm-reuse, path-guard, and mutation suite for tools/startup/compile_lds_request.py.""" + +from __future__ import annotations + +from contextlib import redirect_stderr, redirect_stdout +import hashlib +import io +import json +import os +from pathlib import Path +import re +import runpy +import struct +import subprocess +import sys +import tempfile +import types +import unittest +from unittest import mock +import warnings + +ROOT = Path(__file__).resolve().parents[1] +TOOLS_STARTUP = ROOT / "tools" / "startup" +TESTS_DIR = ROOT / "tests" +TOOL = TOOLS_STARTUP / "compile_lds_request.py" +sys.path.insert(0, str(TOOLS_STARTUP)) +sys.path.insert(0, str(TESTS_DIR)) +import compile_lds_request # noqa: E402 +from startup_compute_translate_check import state_a, write_request # noqa: E402 +from startup_gfx2hlsl_compute_check import CASES, USER7, TGID_X # noqa: E402 + +COMPANION_EXTS = (".root", ".data", ".desc", ".sa", ".sb") +_REAL_SUBPROCESS_RUN = subprocess.run + + +def _run_main(module, argv: list[str] | None) -> tuple[int, str, str]: + stdout = io.StringIO() + stderr = io.StringIO() + with warnings.catch_warnings(), redirect_stdout(stdout), redirect_stderr(stderr): + warnings.simplefilter("ignore", ResourceWarning) + try: + code = module.main(argv) + except SystemExit as exc: + code = exc.code + if not isinstance(code, int): + if code is not None: + stderr.write(f"{code}\n") + code = 0 if code is None else 1 + return code, stdout.getvalue(), stderr.getvalue() + + +def _run_subprocess(*args: str) -> subprocess.CompletedProcess[str]: + return _REAL_SUBPROCESS_RUN( + [sys.executable, "-B", str(TOOL), *args], + capture_output=True, + text=True, + timeout=30, + ) + + +def _setup_env(base: Path) -> tuple[Path, Path, Path, Path]: + compiler = base / "fake_compile_dxil.exe" + compiler.write_bytes(b"FAKE_DXIL_COMPILER") + sdk = base / "sdk" + sdk.mkdir() + output = base / "output" + cache = base / "cache" + return compiler, sdk, output, cache + + +def _write_case_f(work: Path) -> tuple[int, Path]: + _, code, rsrc2, group, _ = CASES["F"] + key = write_request(work, code, state_a(group, rsrc2)) + return key, work / f"req_{key:016x}.c67" + + +def _fake_compile_dxil(calls: list[list[object]] | None = None, *, validate_paths: bool = True): + def _runner(cmd, check=False, **_kwargs): + assert check is True + if calls is not None: + calls.append(list(cmd)) + compiler, sdk, cache, profile, stage, bytecode = cmd + if validate_paths: + assert Path(compiler).is_file() + assert Path(sdk).is_dir() + assert profile == "cs_6_6" + assert Path(stage).is_file() + assert Path(cache).parent.exists() or not Path(cache).exists() + Path(bytecode).write_bytes(b"DXBC_SYNTHETIC_CSO") + return subprocess.CompletedProcess(cmd, 0) + + return _runner + + +class CompileLdsRequestPositiveTests(unittest.TestCase): + def test_synthetic_c67_compile_warm_reuse_and_damaged_bundle_detection(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + req_dir = base / "req" + req_dir.mkdir() + compiler, sdk, output, cache = _setup_env(base) + key, marker = _write_case_f(req_dir) + calls: list[list[object]] = [] + + argv = [ + str(marker), + str(output), + "--compiler", + str(compiler), + "--sdk", + str(sdk), + "--cache", + str(cache), + "--rw-image", + "0", + "0", + "--wave-size", + "32", + ] + with mock.patch.object(compile_lds_request.subprocess, "run", side_effect=_fake_compile_dxil(calls)): + code, out, err = _run_main(compile_lds_request, argv) + + self.assertIs(type(code), int) + self.assertEqual(code, 0, err) + self.assertEqual(err, "") + self.assertEqual(len(calls), 1) + dest = Path(out.strip()) + self.assertTrue(dest.is_dir()) + self.assertEqual(list(output.iterdir()), [dest]) + + hlsl = (dest / f"{key:016x}.cs.hlsl").read_text(encoding="utf-8") + self.assertIn("[WaveSize(32)]\n[numthreads(", hlsl) + self.assertIn("#pragma x2w_lds ", hlsl) + self.assertIn("#pragma x2w_vop2 ", hlsl) + self.assertIn("GroupMemoryBarrierWithGroupSync();", hlsl) + self.assertEqual((dest / f"{key:016x}.cs.cso").read_bytes(), b"DXBC_SYNTHETIC_CSO") + self.assertIn("group 64 1 1", (dest / f"{key:016x}.txt").read_text(encoding="utf-8").splitlines()) + + replay_raw = (dest / "replay.json").read_bytes() + replay = json.loads(replay_raw.decode("utf-8")) + self.assertEqual(replay["schema"], 1) + self.assertEqual(replay["profile"], "cs_6_6") + self.assertEqual(replay["rw_image"], [0, 0]) + self.assertEqual(replay["wave_size"], 32) + for rel, expected_sha in replay["sha256"].items(): + self.assertEqual(hashlib.sha256((dest / rel).read_bytes()).hexdigest(), expected_sha) + + # Warm reuse: identical inputs collide on dest, verify all sha256 entries, and succeed idempotently. + with mock.patch.object(compile_lds_request.subprocess, "run", side_effect=_fake_compile_dxil(calls)): + code_warm, out_warm, err_warm = _run_main(compile_lds_request, argv) + self.assertEqual(code_warm, 0, err_warm) + self.assertEqual(err_warm, "") + self.assertEqual(Path(out_warm.strip()), dest) + self.assertEqual(list(output.iterdir()), [dest]) + + # Damaged artifact sha256 detection: corrupting .cs.cso fails cleanly with no temp leftovers. + cso_path = dest / f"{key:016x}.cs.cso" + saved_cso = cso_path.read_bytes() + cso_path.write_bytes(b"CORRUPT_CSO") + with mock.patch.object(compile_lds_request.subprocess, "run", side_effect=_fake_compile_dxil()): + code_dmg, out_dmg, err_dmg = _run_main(compile_lds_request, argv) + self.assertEqual(code_dmg, 1) + self.assertEqual(out_dmg, "") + self.assertNotIn("Traceback", err_dmg) + self.assertIn("damaged replay artifact", err_dmg) + self.assertEqual(list(output.iterdir()), [dest]) + cso_path.write_bytes(saved_cso) + + # Corrupting replay.json on disk also triggers refusal cleanly. + (dest / "replay.json").write_text("{corrupt}\n", encoding="utf-8") + with mock.patch.object(compile_lds_request.subprocess, "run", side_effect=_fake_compile_dxil()): + code_rep, out_rep, err_rep = _run_main(compile_lds_request, argv) + self.assertEqual(code_rep, 1) + self.assertEqual(out_rep, "") + self.assertNotIn("Traceback", err_rep) + self.assertIn("damaged replay artifact replay.json", err_rep) + self.assertEqual(list(output.iterdir()), [dest]) + (dest / "replay.json").write_bytes(replay_raw) + + # Wave size 64 and argv=None sys.argv forwarding. + argv64 = argv[:-1] + ["64"] + with ( + mock.patch.object(sys, "argv", [str(TOOL), *argv64]), + mock.patch.object(compile_lds_request.subprocess, "run", side_effect=_fake_compile_dxil()), + ): + code64, out64, err64 = _run_main(compile_lds_request, None) + self.assertEqual(code64, 0, err64) + self.assertEqual(err64, "") + dest64 = Path(out64.strip()) + self.assertNotEqual(dest64, dest) + self.assertIn("[WaveSize(64)]", (dest64 / f"{key:016x}.cs.hlsl").read_text(encoding="utf-8")) + self.assertEqual(sorted(output.iterdir()), sorted([dest, dest64])) + + +class CompileLdsRequestNegativeAndMutationTests(unittest.TestCase): + def _assert_clean_failure( + self, + argv: list[str], + *, + expected_code: int | None = 1, + fragments: tuple[str, ...] = (), + check_subprocess: bool = True, + ) -> str: + code, out, err = _run_main(compile_lds_request, argv) + if expected_code is None: + self.assertNotEqual(code, 0) + else: + self.assertEqual(code, expected_code, err) + self.assertEqual(out, "") + self.assertNotIn("Traceback", err) + self.assertTrue(err.strip()) + for fragment in fragments: + self.assertIn(fragment.lower(), err.lower()) + + if check_subprocess: + proc = _run_subprocess(*argv) + if expected_code is None: + self.assertNotEqual(proc.returncode, 0) + else: + self.assertEqual(proc.returncode, expected_code, proc.stderr) + self.assertEqual(proc.stdout, "") + self.assertNotIn("Traceback", proc.stderr) + for fragment in fragments: + self.assertIn(fragment.lower(), proc.stderr.lower()) + return err + + def test_missing_companion_and_hostile_path_refusals(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + req_dir = base / "req" + req_dir.mkdir() + compiler, sdk, _, cache = _setup_env(base) + key, marker = _write_case_f(req_dir) + absent_out = base / "absent_parent" / "output" + file_target = base / "regular_file" + file_target.write_text("KEEP", encoding="utf-8") + dir_path = base / "some_dir" + dir_path.mkdir() + + def make_argv( + *, + m: Path = marker, + o: Path = absent_out, + comp: Path = compiler, + s: Path = sdk, + ca: Path = cache, + ) -> list[str]: + return [ + str(m), + str(o), + "--compiler", + str(comp), + "--sdk", + str(s), + "--cache", + str(ca), + "--rw-image", + "0", + "0", + "--wave-size", + "32", + ] + + with ( + mock.patch.object( + compile_lds_request.gfx, + "load_compute_request", + side_effect=AssertionError("load_compute_request called on invalid path"), + ), + mock.patch.object( + compile_lds_request.subprocess, + "run", + side_effect=AssertionError("subprocess.run called on invalid path"), + ), + ): + # Marker missing / dir / non-regular. + self._assert_clean_failure( + make_argv(m=req_dir / "req_0123456789abcdef.c67"), + fragments=("request marker", "not found"), + ) + self._assert_clean_failure( + make_argv(m=dir_path / "req_0123456789abcdef.c67"), + fragments=("request marker", "not found"), + ) + dir_marker = base / "req_0123456789abcdef.c67" + dir_marker.mkdir() + self._assert_clean_failure(make_argv(m=dir_marker), fragments=("request marker", "directory")) + + # Missing or directory companion files. + for ext in COMPANION_EXTS: + comp_file = marker.with_suffix(ext) + saved = comp_file.read_bytes() + comp_file.unlink() + self._assert_clean_failure(make_argv(), fragments=(f"companion {ext}", "not found")) + comp_file.mkdir() + self._assert_clean_failure(make_argv(), fragments=(f"companion {ext}", "directory")) + comp_file.rmdir() + comp_file.write_bytes(saved) + + # Compiler missing / dir / non-regular. + self._assert_clean_failure(make_argv(comp=base / "missing.exe"), fragments=("compiler", "not found")) + self._assert_clean_failure(make_argv(comp=dir_path), fragments=("compiler", "directory")) + + # SDK missing / file. + self._assert_clean_failure(make_argv(s=base / "missing_sdk"), fragments=("sdk", "not found")) + self._assert_clean_failure(make_argv(s=file_target), fragments=("sdk", "not a directory")) + + # Output / cache existing regular file or file-backed parent. + self._assert_clean_failure(make_argv(o=file_target), fragments=("output", "not a directory")) + self._assert_clean_failure( + make_argv(o=file_target / "sub"), + fragments=("output parent", "not a directory"), + ) + self._assert_clean_failure(make_argv(ca=file_target), fragments=("cache", "not a directory")) + self._assert_clean_failure( + make_argv(ca=file_target / "sub"), + fragments=("cache parent", "not a directory"), + ) + + # Non-regular file input (mocked unconditionally). + with mock.patch.object(Path, "is_file", return_value=False): + self._assert_clean_failure( + make_argv(), + fragments=("not a regular file",), + check_subprocess=False, + ) + + self.assertFalse(absent_out.parent.exists()) + self.assertEqual(file_target.read_text(encoding="utf-8"), "KEEP") + + # Symlinked output/cache are the caller's chosen location and now + # succeed: the bundle is written through the link into its target. + link_out = base / "link_out" + try: + link_out.symlink_to(dir_path) + except OSError as exc: + if getattr(exc, "winerror", None) != 1314: + raise + else: + with mock.patch.object(compile_lds_request.subprocess, "run", side_effect=_fake_compile_dxil()): + code_link, out_link, err_link = _run_main(compile_lds_request, make_argv(o=link_out)) + self.assertEqual(code_link, 0, err_link) + self.assertEqual(err_link, "") + dest_link = Path(out_link.strip()) + self.assertEqual(dest_link.resolve().parent, dir_path) + self.assertTrue((dest_link / f"{key:016x}.cs.hlsl").is_file()) + self.assertEqual(list(link_out.iterdir()), [dest_link]) + # The same bundle through a symlinked cache warm-reuses the + # bundle written above instead of refusing the link. + with mock.patch.object(compile_lds_request.subprocess, "run", side_effect=_fake_compile_dxil()): + code_ca, out_ca, err_ca = _run_main(compile_lds_request, make_argv(o=dir_path, ca=link_out)) + self.assertEqual(code_ca, 0, err_ca) + self.assertEqual(err_ca, "") + self.assertEqual(Path(out_ca.strip()), dest_link.resolve()) + + def test_fifo_output_and_dangling_symlink_parent_refusals(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + req_dir = base / "req" + req_dir.mkdir() + compiler, sdk, output, cache = _setup_env(base) + _, marker = _write_case_f(req_dir) + + def make_argv(*, o: Path = output, ca: Path = cache) -> list[str]: + return [ + str(marker), + str(o), + "--compiler", + str(compiler), + "--sdk", + str(sdk), + "--cache", + str(ca), + "--rw-image", + "0", + "0", + "--wave-size", + "32", + ] + + ran = False + # A FIFO is neither a file nor a directory: refused, not written through. + if hasattr(os, "mkfifo"): + fifo_out = base / "fifo_out" + os.mkfifo(fifo_out) + self._assert_clean_failure(make_argv(o=fifo_out), fragments=("output", "not a directory")) + ran = True + + # A dangling symlink as a parent is not a directory: refused, not followed. + dangling = base / "dangling" + try: + dangling.symlink_to(base / "no_such_target") + except OSError as exc: + if getattr(exc, "winerror", None) != 1314: + raise + else: + self._assert_clean_failure( + make_argv(o=dangling / "output"), + fragments=("output parent", "not a directory"), + ) + self._assert_clean_failure( + make_argv(ca=dangling / "cache"), + fragments=("cache parent", "not a directory"), + ) + ran = True + + if not ran: + self.skipTest("neither FIFOs nor symlinks are available on this platform") + + def test_translator_bug_keeps_traceback_and_out_of_range_branch_is_clean(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + req_dir = base / "req" + req_dir.mkdir() + compiler, sdk, output, cache = _setup_env(base) + + def make_argv(m: Path) -> list[str]: + return [ + str(m), + str(output), + "--compiler", + str(compiler), + "--sdk", + str(sdk), + "--cache", + str(cache), + "--rw-image", + "0", + "0", + "--wave-size", + "32", + ] + + def write_modified_case(name: str, dword_index: int, value: int) -> Path: + _, code, rsrc2, group, _ = CASES[name] + words = list(struct.unpack(f"<{len(code) // 4}I", code)) + words[dword_index] = value + key = write_request(req_dir, struct.pack(f"<{len(words)}I", *words), state_a(group, rsrc2)) + return req_dir / f"req_{key:016x}.c67" + + # A translator bug (bad literal) must keep its traceback instead of + # being swallowed into a clean "error:" line. + bad_marker = write_modified_case("F", 4, 0xbf84C07F) + with self.assertRaises(ValueError) as raised: + _run_main(compile_lds_request, make_argv(bad_marker)) + self.assertIn("invalid literal for int()", str(raised.exception)) + proc = _run_subprocess(*make_argv(bad_marker)) + self.assertNotEqual(proc.returncode, 0) + self.assertEqual(proc.stdout, "") + self.assertIn("Traceback", proc.stderr) + self.assertIn("invalid literal for int()", proc.stderr) + + # An out-of-range branch target is refused cleanly as unsupported. + branch_marker = write_modified_case("extracted-tid", 9, 0xbf852005) + self._assert_clean_failure( + make_argv(branch_marker), + fragments=("branch target", "outside the compute stage"), + ) + + def test_cli_arg_errors_key_mismatch_conditional_barrier_and_compiler_failure(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + req_dir = base / "req" + req_dir.mkdir() + compiler, sdk, output, cache = _setup_env(base) + _, marker = _write_case_f(req_dir) + + def make_argv(m: Path = marker, rw: tuple[str, str] = ("0", "0"), wave: str = "32") -> list[str]: + return [ + str(m), + str(output), + "--compiler", + str(compiler), + "--sdk", + str(sdk), + "--cache", + str(cache), + "--rw-image", + rw[0], + rw[1], + "--wave-size", + wave, + ] + + # Argparse / --rw-image / marker name errors exit 2 cleanly without tracebacks. + for argv, frags in ( + (make_argv(m=req_dir / "bad_marker.c67"), ("req_<16 hex digits>.c67",)), + (make_argv(rw=("-1", "0")), ("nonnegative",)), + (make_argv(rw=("0", "-32")), ("nonnegative",)), + (make_argv(rw=("0", "16")), ("32-byte-aligned",)), + (make_argv(wave="16"), ("invalid choice",)), + ): + with self.subTest(argv=argv): + self._assert_clean_failure(argv, expected_code=2, fragments=frags) + + # Compiler nonzero exit (subprocess.CalledProcessError) cleans temp dir and exits 1. + def failing_run(cmd, check=False, **_kwargs): + raise subprocess.CalledProcessError(2, cmd) + + with mock.patch.object(compile_lds_request.subprocess, "run", side_effect=failing_run): + self._assert_clean_failure(make_argv(), expected_code=1, fragments=("returned non-zero exit status",), check_subprocess=False) + self.assertEqual(list(output.iterdir()), []) + + # Conditional s_barrier in synthetic .c67 request is rejected cleanly. + cond_dir = base / "cond" + cond_dir.mkdir() + # s_cbranch_scc0 1 (+4 bytes over s_barrier) ; s_barrier ; s_endpgm + cond_code = bytes.fromhex("010084bf" "00008abf" "000081bf") + cond_key = write_request(cond_dir, cond_code, state_a((64, 1, 1), USER7 | TGID_X | (1 << 15))) + cond_marker = cond_dir / f"req_{cond_key:016x}.c67" + with mock.patch.object( + compile_lds_request.subprocess, + "run", + side_effect=AssertionError("subprocess.run called for conditional barrier"), + ): + self._assert_clean_failure( + make_argv(m=cond_marker), + expected_code=1, + fragments=("workgroup barrier is conditional",), + ) + self.assertEqual(list(output.iterdir()), []) + + # Damaged .data bytes fail key verification with expected message and __main__ propagates SystemExit(1). + data_path = marker.with_suffix(".data") + data_path.write_bytes(bytes(b ^ 1 for b in data_path.read_bytes())) + self._assert_clean_failure(make_argv(), expected_code=1, fragments=("do not match the key",)) + self.assertEqual(list(output.iterdir()), []) + + stdout_m, stderr_m = io.StringIO(), io.StringIO() + with ( + mock.patch.object(sys, "argv", [str(TOOL), *make_argv()]), + redirect_stdout(stdout_m), + redirect_stderr(stderr_m), + self.assertRaises(SystemExit) as exited, + ): + runpy.run_path(str(TOOL), run_name="__main__") + self.assertEqual(exited.exception.code, 1) + self.assertEqual(stdout_m.getvalue(), "") + self.assertNotIn("Traceback", stderr_m.getvalue()) + self.assertIn("do not match the key", stderr_m.getvalue()) + + def test_fast_self_mutation_controls(self) -> None: + source = TOOL.read_text(encoding="utf-8") + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + req_dir = base / "req" + req_dir.mkdir() + compiler, sdk, output, cache = _setup_env(base) + key, marker = _write_case_f(req_dir) + file_target = base / "regular_file" + file_target.write_text("KEEP", encoding="utf-8") + + cond_dir = base / "cond" + cond_dir.mkdir() + cond_code = bytes.fromhex("010084bf" "00008abf" "000081bf") + cond_key = write_request(cond_dir, cond_code, state_a((64, 1, 1), USER7 | TGID_X | (1 << 15))) + cond_marker = cond_dir / f"req_{cond_key:016x}.c67" + + def argv_for(m=marker, o=output, comp=compiler, s=sdk, ca=cache, rw=("0", "0")): + return [ + str(m), str(o), + "--compiler", str(comp), + "--sdk", str(s), + "--cache", str(ca), + "--rw-image", rw[0], rw[1], + "--wave-size", "32", + ] + + # Build one valid bundle so drop_bundle_sha256_check can probe damaged artifact detection. + with mock.patch.object(compile_lds_request.subprocess, "run", side_effect=_fake_compile_dxil()): + code_init, out_init, err_init = _run_main(compile_lds_request, argv_for()) + self.assertEqual(code_init, 0, err_init) + dest = Path(out_init.strip()) + cso_path = dest / f"{key:016x}.cs.cso" + saved_cso = cso_path.read_bytes() + + def check_drop_marker_guard(mod): + # Dropping the guard no longer refuses the missing marker + # cleanly: the tool either reaches the copy and crashes on the + # missing file, or reports a different error. Either way the + # guard's refusal is gone, which is what this control detects. + try: + with mock.patch.object(mod.subprocess, "run", side_effect=_fake_compile_dxil()): + _, _, err = _run_main(mod, argv_for(m=req_dir / "req_0123456789abcdef.c67")) + except Exception: + return + self.assertNotIn("request marker file not found", err.lower()) + + def check_drop_companion_guard(mod): + root_file = marker.with_suffix(".root") + saved = root_file.read_bytes() + root_file.unlink() + try: + try: + with mock.patch.object(mod.subprocess, "run", side_effect=_fake_compile_dxil()): + _, _, err = _run_main(mod, argv_for()) + except Exception: + return + self.assertNotIn("companion .root file not found", err.lower()) + finally: + root_file.write_bytes(saved) + + def check_drop_compiler_guard(mod): + with mock.patch.object(mod.subprocess, "run", side_effect=_fake_compile_dxil(validate_paths=False)): + _, _, err = _run_main(mod, argv_for(comp=base / "missing.exe")) + self.assertNotIn("compiler file not found", err.lower()) + + def check_drop_sdk_guard(mod): + with mock.patch.object(mod.subprocess, "run", side_effect=_fake_compile_dxil(validate_paths=False)): + _, _, err = _run_main(mod, argv_for(s=base / "missing_sdk")) + self.assertNotIn("sdk directory not found", err.lower()) + + def check_drop_rw_image_guard(mod): + with mock.patch.object(mod.subprocess, "run", side_effect=_fake_compile_dxil()): + code, _, err = _run_main(mod, argv_for(rw=("-1", "0"))) + self.assertEqual(code, 0, err) + self.assertNotIn("nonnegative", err.lower()) + + def check_drop_bundle_sha256(mod): + cso_path.write_bytes(b"DAMAGED") + try: + with mock.patch.object(mod.subprocess, "run", side_effect=_fake_compile_dxil()): + code, _, err = _run_main(mod, argv_for()) + self.assertEqual(code, 0, err) + finally: + cso_path.write_bytes(saved_cso) + + def check_drop_conditional_barrier(mod): + with mock.patch.object(mod.subprocess, "run", side_effect=_fake_compile_dxil()): + code, _, err = _run_main(mod, argv_for(m=cond_marker)) + self.assertNotIn("workgroup barrier is conditional", err.lower()) + self.assertEqual(code, 0, err) + + # Mutation targets are regular expressions, not exact source lines: + # they pin the distinctive structure (call, guard, loop) without + # depending on quote style, exception type or message wording, so + # a reword or requote of a guard does not silently unpin the control. + mutations = ( + ( + "drop_marker_guard", + r" _validate_regular_file\(args\.marker, [^\n]*\)\n", + " pass\n", + check_drop_marker_guard, + ), + ( + "drop_companion_guard", + r" for ext in \([^\n]*\):\n" + r" _validate_regular_file\(args\.marker\.with_suffix\(ext\), [^\n]*\)\n", + " pass\n", + check_drop_companion_guard, + ), + ( + "drop_compiler_guard", + r" _validate_regular_file\(args\.compiler, [^\n]*\)\n", + " pass\n", + check_drop_compiler_guard, + ), + ( + "drop_sdk_guard", + r" if not args\.sdk\.exists\(\):\n" + r" raise [^\n]*\n" + r" if not args\.sdk\.is_dir\(\):\n" + r" raise [^\n]*\n", + " pass\n", + check_drop_sdk_guard, + ), + ( + "drop_rw_image_guard", + r" if param < 0 or off < 0 or off ?% ?32:\n" + r" parser\.error\([^\n]*\)\n", + " pass\n", + check_drop_rw_image_guard, + ), + ( + "drop_bundle_sha256", + r" for relative, digest in metadata\[['\"]sha256['\"]\]\.items\(\):\n" + r" try:\n" + r" data = \(dest / relative\)\.read_bytes\(\)\n" + r" except OSError:\n" + r" raise [^\n]*\n" + r" if hashlib\.sha256\(data\)\.hexdigest\(\) != digest:\n" + r" raise [^\n]*\n", + " pass\n", + check_drop_bundle_sha256, + ), + ( + "drop_conditional_barrier", + r" if i not in post\[0\]:\n" + r" raise [^\n]*\n", + " pass\n", + check_drop_conditional_barrier, + ), + ) + for label, pattern, replacement, check_fn in mutations: + with self.subTest(mutation=label): + self.assertEqual(len(re.findall(pattern, source)), 1, f"target not unique for {label}") + mod = types.ModuleType(f"compile_lds_request_mut_{label}") + mod.__file__ = str(TOOL) + sys.modules[mod.__name__] = mod + try: + exec(compile(re.sub(pattern, replacement, source, count=1), str(TOOL), "exec"), mod.__dict__) + check_fn(mod) + finally: + sys.modules.pop(mod.__name__, None) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/startup_compute_dispatch_check.py b/tests/startup_compute_dispatch_check.py index 33ca1733c4..5d81322f4d 100644 --- a/tests/startup_compute_dispatch_check.py +++ b/tests/startup_compute_dispatch_check.py @@ -13,7 +13,8 @@ 2. after gfx2hlsl.py --pending with DXC: all 320 words equal the case's expectation; 3. dispatch-none (no Dispatch recorded): every word keeps the sentinel; 4. dispatch-swapped (the two descriptors exchanged, so the output names the buffer without unordered access): - refused with one logged reason, every word keeps the sentinel and the input is unchanged; + refused with "an output buffer has no unordered access", every word keeps the sentinel and the input is + unchanged; 5. dispatch-same-root (the same compute root set again after the constants): all 320 words still match; 6. five more refusals, each with its one logged reason and an untouched output: dispatch-missing-word (no slot 37 call), dispatch-root-changed (another compute root and back after the constants), dispatch-reset (list closed @@ -22,6 +23,8 @@ 7. slot 35 selects the correct table at descriptor index 2 instead of the swapped pair at the heap start; setting the same heap again preserves the table, but changing the compute root or view heap after binding must refuse at the table lookup, not an earlier check. +8. published output compatibility: the same bytecode is refused with either stale native manifest + and runs with the current native marker or with the Python sidecar. Exit 77 only if the initial probe cannot use the adapter or required heaps. """ import os @@ -78,6 +81,7 @@ def main(consumer, dxc, adapter): with tempfile.TemporaryDirectory() as temporary: directory = Path(temporary) cache, env = prepare_case(directory, adapter) + env.pop('X2W_NATIVE_SHADERS', None) # Exercise published translations. untouched, expected = [C.SENTINEL] * C.WORDS, C.expected('A') assert expected != untouched @@ -98,6 +102,28 @@ def main(consumer, dxc, adapter): text=True, env=dict(os.environ, X2W_DXC=dxc)).stdout assert f'{key:016x}: ok' in out, out + manifest = cache / f'{key:016x}.txt' + hlsl = cache / f'{key:016x}.cs.hlsl' + python_manifest = manifest.read_bytes() + python_hlsl = hlsl.read_bytes() + assert not any(line.startswith(b'native ') for line in python_manifest.splitlines()) + hlsl.unlink() + for marker, reason in ( + (b'', 'native translation without a revision; rebuild it'), + (b'native 0\n', 'native translation from another compiler revision; rebuild it'), + ): + manifest.write_bytes(python_manifest + marker) + got, result = dispatch(directory, consumer, env, 'dispatch') + assert got == untouched, 'a stale native output wrote the output buffer' + assert len(lines(result, 'Dispatch(3, 2, 2) refused: ' + reason)) == 1, result.stderr[-3000:] + + # Reuse working bytecode to isolate the manifest gate from native adapter requirements. + manifest.write_bytes(python_manifest + b'native 1\n') + got, result = dispatch(directory, consumer, env, 'dispatch') + assert got == expected and not lines(result, 'refused:'), result.stderr[-3000:] + hlsl.write_bytes(python_hlsl) + manifest.write_bytes(python_manifest) + got, result = dispatch(directory, consumer, env, 'dispatch') wrong = [i for i in range(C.WORDS) if got[i] != expected[i]] assert not wrong, 'word=%d got=%08x expected=%08x (%d words differ)\n%s' % ( @@ -120,9 +146,9 @@ def main(consumer, dxc, adapter): refused = lines(result, 'refused: ') census = lines(result, 'x2w-render compute census') assert len(census) == 3 and census[1].endswith( - 'reason "an output is not an aliased placed buffer range with unordered access": 1 keys, 1 dispatches') \ + 'reason "an output buffer has no unordered access": 1 keys, 1 dispatches') \ and '[00000000 00000000 ' not in census[2], census - assert len(refused) == 1 and 'an output is not an aliased placed buffer range with unordered access' in refused[0], \ + assert len(refused) == 1 and 'an output buffer has no unordered access' in refused[0], \ result.stderr[-3000:] got, result = dispatch(directory, consumer, env, 'dispatch-same-root') assert got == expected and not lines(result, 'refused'), 'setting the same compute root again lost the constants' diff --git a/tests/startup_compute_dispatch_input_check.py b/tests/startup_compute_dispatch_input_check.py index 57b9e88392..66acb20d30 100644 --- a/tests/startup_compute_dispatch_input_check.py +++ b/tests/startup_compute_dispatch_input_check.py @@ -43,6 +43,8 @@ def main(consumer, dxc, adapter): with tempfile.TemporaryDirectory() as temporary: directory = Path(temporary) cache, env = prepare(directory) + env.pop('X2W_TRANSLATED_TITLE_INPUT_SNAPSHOT', None) # prepare() copies os.environ: every baseline run starts with the flag off + env.pop("X2W_D3D12_RING_RELEASE_AT_SUBMIT", None) env.update(X2W_D3D12_LIST_NOOP='1', X2W_D3D12_DEBUG='1') # guest lists; debug-layer messages go to the log if adapter == 'hardware': env['X2W_TEST_DISPATCH_HARDWARE'] = '1' @@ -85,6 +87,45 @@ def main(consumer, dxc, adapter): assert got == expected and len(lines(result, 'Dispatch(3, 2, 2) translated')) == 1 and not lines(result, 'refused: '), result.stderr[-3000:] errors = [line for line in lines(result, 'x2w-d3d12-debug ') if ' sev=0 ' in line or ' sev=1 ' in line] assert not errors, errors[0] + # Opt-in X2W_TRANSLATED_TITLE_INPUT_SNAPSHOT: an input in a placed buffer that does not alias title memory holds + # its bytes only in title memory (the desktop copy is zeros). Off, it is refused; on, the bytes are snapshotted + # into the snapshot pool and all 320 words match; with title memory zero (dispatch-input-copied) the dispatch runs + # on zeros: not refused, not the expected words, not untouched. + snapshot_env = dict(env, X2W_TRANSLATED_TITLE_INPUT_SNAPSHOT='1') + got, result = dispatch(directory, consumer, env, 'dispatch-input-snapshot') + assert got == untouched and lines(result, 'refused: ')[0].endswith(CONTROLS[3][1]), result.stderr[-3000:] + got, result = dispatch(directory, consumer, snapshot_env, 'dispatch-input-snapshot') + assert got == expected and len(lines(result, 'Dispatch(3, 2, 2) translated')) == 1 and not lines(result, 'refused: '), result.stderr[-3000:] + assert len(lines(result, 'comes from a snapshot of title memory (1280 bytes)')) == 1, result.stderr[-3000:] + errors = [line for line in lines(result, 'x2w-d3d12-debug ') if ' sev=0 ' in line or ' sev=1 ' in line] + assert not errors, errors[0] + got, result = dispatch(directory, consumer, snapshot_env, 'dispatch-input-copied') + assert len(lines(result, 'Dispatch(3, 2, 2) translated')) == 1 and not lines(result, 'refused: '), result.stderr[-3000:] + assert got != expected and got != untouched, 'a snapshot of zero title memory must not give the expected words' + # Long run: 48 frames of dispatches whose 8 MiB title-memory input is snapshotted each frame, the queue completed between + # frames: 384 MiB in all, three times the snapshot pool (128 MiB). The pool must be recycled: every frame translates, + # gives the first frame's words (the consumer exits 85 if one does not), the last frame matches the CPU reference + # and no reservation is refused. + # With release enabled, keep the submitted lists closed to exercise release without Reset. + for release, mode in ((False, 'dispatch-input-snapshot-long'), (True, 'dispatch-input-snapshot-long-keep')): + long_env = dict(snapshot_env) + if release: + long_env["X2W_D3D12_RING_RELEASE_AT_SUBMIT"] = "1" + got, result = dispatch(directory, consumer, long_env, mode) + assert got == expected and not lines(result, 'refused: '), result.stderr[-3000:] + assert not lines(result, 'reservation refused'), lines(result, 'reservation refused') + assert len(lines(result, 'Dispatch(3, 2, 2) translated')) >= 1, result.stderr[-3000:] + # The input must really come from a snapshot (8 MiB), not be read in place: an empty long case would pass everything above. + assert len(lines(result, 'comes from a snapshot of title memory (8388608 bytes)')) == 1, result.stderr[-3000:] + errors = [line for line in lines(result, 'x2w-d3d12-debug ') if ' sev=0 ' in line or ' sev=1 ' in line] + assert not errors, errors[0] + # An all-zero descriptor is an unbound buffer: the dispatch runs on zeros instead of being refused (the empty + # control above has a nonzero base and stays refused). + got, result = dispatch(directory, consumer, env, 'dispatch-input-null') + assert len(lines(result, 'Dispatch(3, 2, 2) translated')) == 1 and not lines(result, 'refused: '), result.stderr[-3000:] + assert len(lines(result, 'comes from zeros for a null descriptor (16 bytes)')) == 1, result.stderr[-3000:] + assert got != expected and got != untouched, 'a null input must read zeros, not the expected words' + print(f'{adapter}: title-input snapshot: off refused, on all {C.WORDS} words match, zero title memory runs on zeros') print(f'startup_compute_dispatch_input: PASS on {adapter} (all {C.WORDS} words match, also with the input behind ' f'a memory view token; {len(CONTROLS)} inputs refused, each with its own reason and an untouched output)') diff --git a/tests/startup_compute_dispatch_native_check.py b/tests/startup_compute_dispatch_native_check.py index d622bc9858..027565cc40 100644 --- a/tests/startup_compute_dispatch_native_check.py +++ b/tests/startup_compute_dispatch_native_check.py @@ -76,7 +76,9 @@ def main(consumer, dxc_dir, adapter): refused = lines(result, 'refused: ') assert got == untouched, 'a Dispatch with no descriptor at table byte 32 wrote the output' assert len(refused) == 1 and 'no translation' not in refused[0], result.stderr[-3000:] - published = sorted(p.name for p in cache.iterdir() if not p.name.startswith('req_') and p.name != 'native') + # The first request writes revision.txt; it is cache metadata, not a publication. + published = sorted(p.name for p in cache.iterdir() + if not p.name.startswith('req_') and p.name not in ('native', 'revision.txt')) assert not published, f'the native route left {published} in the cache' (directory / 'program').write_bytes(case_a) diff --git a/tests/startup_compute_dispatch_output_check.py b/tests/startup_compute_dispatch_output_check.py new file mode 100644 index 0000000000..45729991e1 --- /dev/null +++ b/tests/startup_compute_dispatch_output_check.py @@ -0,0 +1,92 @@ +"""Named reasons for a translated compute output that is not an aliased placed buffer range (list slot 14). + +usage: startup_compute_dispatch_output_check.py <startup_stream_consumer> <dxc> <warp|hardware> + +The consumer records case A of startup_gfx2hlsl_compute_check.py as startup_compute_dispatch_check.py does. After +gfx2hlsl.py --pending with DXC, the unchanged recording still matches all 320 words. Then the output descriptor or +its buffer is changed one condition at a time, and each dispatch is refused with its own reason in the log and the +census and writes no output word: + +- dispatch-output-texture-token: the token of a texture view where the output descriptor was; +- zero records, a range over 16 MiB (stride 4, 4 Mi + 1 records) and a range 16 bytes past the placed output + buffer, through X2W_TEST_DISPATCH_FIELDS (synthetic values); +- dispatch-output-unplaced: memory between the two placed buffers; +- dispatch-output-copied: a buffer placed there at an offset the desktop cannot alias, so it is a separate copy; +- dispatch-output-state: the output buffer placed (and aliased) in the unordered access state; +- dispatch-output-unaligned: the output starts 8 bytes into its buffer; +- dispatch-swapped: the output names the input buffer, which has no unordered access. + +A resource with an aliased placement and no recorded information also reports the common state reason; no +fixture reaches it. Exit 77 when the adapter is not available. +""" +from pathlib import Path +import os +import struct +import subprocess +import sys +import tempfile + +import startup_gfx2hlsl_compute_check as C +from startup_compute_dispatch_check import dispatch, lines, prepare_case +from startup_stream_check import gfx2hlsl as G + + +def fields(records, stride=4): + return struct.pack('<6I', 4, C.WORDS, 0, stride, records, 0) + + +CONTROLS = ( + ('dispatch-output-texture-token', None, 'an output buffer descriptor is a view token'), + ('dispatch', fields(0), 'an output buffer descriptor has zero records'), + ('dispatch', fields((16 << 20) // 4 + 1), 'an output buffer range is over 16 MiB or not whole dwords'), + ('dispatch', fields(C.WORDS + 4), 'an output range crosses the end of a placed buffer'), + ('dispatch-output-unplaced', None, 'an output is in title memory outside any placed buffer'), + ('dispatch-output-copied', None, 'an output is in a placed buffer that does not alias title memory'), + ('dispatch-output-state', None, "an output buffer's resource was not created in the common state"), + ('dispatch-output-unaligned', None, 'an output buffer range is not 16-byte aligned in its resource'), + ('dispatch-swapped', None, 'an output buffer has no unordered access'), +) + + +def main(consumer, dxc, adapter): + with tempfile.TemporaryDirectory() as temporary: + directory = Path(temporary) + cache, env = prepare_case(directory, adapter) + untouched, expected = [C.SENTINEL] * C.WORDS, C.expected('A') + + got, result = dispatch(directory, consumer, env, 'dispatch', probe=True) + print(result.stdout, end='') + assert got == untouched and len(lines(result, 'refused: no translation')) == 1, result.stderr[-3000:] + published = lines(result, 'x2w-draw compute request') + assert published and ' published ' in published[0], result.stderr[-3000:] + key = int(published[0].split()[3], 16) + out = subprocess.run([sys.executable, '-B', G.__file__, '--pending', cache], check=True, capture_output=True, + text=True, env=dict(os.environ, X2W_DXC=dxc)).stdout + assert f'{key:016x}: ok' in out, out + + got, result = dispatch(directory, consumer, env, 'dispatch') + assert got == expected and not lines(result, 'refused'), result.stderr[-3000:] + + for mode, words, reason in CONTROLS: + case_env = dict(env) + if words: + (directory / 'fields').write_bytes(words) + case_env['X2W_TEST_DISPATCH_FIELDS'] = str(directory / 'fields') + got, result = dispatch(directory, consumer, case_env, mode) + name = mode if not words else f'{mode} fields {struct.unpack("<6I", words)[3:5]}' + assert got == untouched, f'{name}: a refused Dispatch wrote the output' + refused = lines(result, 'refused: ') + census = lines(result, 'x2w-render compute census') + assert len(refused) == 1 and refused[0].endswith('refused: ' + reason), f'{name}:\n{result.stderr[-3000:]}' + assert len(census) == 3 and census[1].endswith(f'reason "{reason}": 1 keys, 1 dispatches'), (name, census) + if mode == 'dispatch-output-state': # the buffer is aliased, so only its state is refused + placed = [line for line in lines(result, 'Device::slot133') if ' state=0x8 ' in line] + assert len(placed) == 1 and '-> 0x00000000 aliased ' in placed[0], (name, placed) + print(f'startup_compute_dispatch_output: PASS on {adapter} (all {C.WORDS} words match; {len(CONTROLS)} outputs ' + 'refused, each with its own reason and an untouched output)') + + +if __name__ == '__main__': + if len(sys.argv) != 4 or sys.argv[3] not in ('warp', 'hardware'): + sys.exit(__doc__) + main(*sys.argv[1:]) diff --git a/tests/startup_compute_dispatch_texture_dims_check.py b/tests/startup_compute_dispatch_texture_dims_check.py new file mode 100644 index 0000000000..2081ea54f2 --- /dev/null +++ b/tests/startup_compute_dispatch_texture_dims_check.py @@ -0,0 +1,167 @@ +"""Translated compute programs reading 1D, 2D-array and 3D texture views through the stand-in's Dispatch (slot 14). + +usage: startup_compute_dispatch_texture_dims_check.py <startup_stream_consumer> <dxc> <warp|hardware> + +Case A of startup_gfx2hlsl_compute_check.py with one image_load (for 1D an image_sample_lz at the texel's +center, because gfx2hlsl lowers no 1D image_load) spliced before its store: the texel read is XORed into every +stored word. The program's manifest names the dimension of its texture input (`srv 1 tex1d`, +`tex2da` or `tex3d`, table byte 64). The consumer (dispatch-texdim-<1d|2da|3d>) uploads a described R32_FLOAT +texture, texel (x + 4 y + 16 slice) = 0.25 * (index + 1), subresource by subresource, and creates its view at table byte 64 +(device slot 18): + +- 1d: eight texels, the program reads x = 5 (1.5); +- 2da: 4x4 with six slices, the view starts at slice 1, the program reads x = 1, y = 2, relative slice 2, which + is slice 3 of the texture (14.5); +- 3d: 4x4x4, the program reads x = 3, y = 1, z = 2 (10.0). + +Per dimension: before translation the dispatch is refused with "no translation" and writes nothing; after +gfx2hlsl.py --pending with DXC all 320 words equal case A's words XORed with the texel's bits on the 288 written +words (the rest keep the sentinel). Controls, each refused with one logged reason and an untouched output: +the title's view is a 2D view of a 2D texture (-mismatch), the view has no description (-undescribed), the view +has a ResourceMinLODClamp of 1.0, which does not fit as address_view_fits reads views (-clamped; a view outside the +texture would remove the device when the title creates it), and the published manifest line rewritten to tex2d (and, for +a second mutant, to another non-2D dimension): the runtime must read the manifest's dimension, not the title's. +Exit 77 when the adapter is not available. +""" +from pathlib import Path +import struct +import sys +import tempfile + +import startup_compute_dispatch_texture_check as T +import startup_gfx2hlsl_compute_check as C +from startup_compute_dispatch_check import lines +from startup_compute_request_check import DATA, prepare +from startup_compute_translate_check import state_a +from startup_stream_check import gfx2hlsl as G + +LOAD = 'image_load v12, %s, s[24:31] dmask:0x1 dim:SQ_RSRC_IMG_%s' +# MIMG: dword 0 is 0xf0000000 | dmask << 8 | dim << 3 (1D 0, 3D 2, 2D array 5); dword 1 holds vaddr 8, vdata 12 and +# srsrc 24 / 4 in its three low bytes. The decoder below must read each word back as the text of its dictionary key. +DIM_FIELD = {'1D': 0, '3D': 2, '2D_ARRAY': 5} + +# name: (manifest word, image dim, texel coordinates, expected texel value, refusal word for the view, manifest line) +KINDS = { + '1d': ('tex1d', '1D', (5,), 1.5, '1D', 'srv 1 tex1d table 1 64'), + '2da': ('tex2da', '2D_ARRAY', (1, 2, 2), 14.5, '2D array', 'srv 1 tex2da table 1 64'), + '3d': ('tex3d', '3D', (3, 1, 2), 10.0, '3D', 'srv 1 tex3d table 1 64'), +} +# What the consumer holds: texel (x, y, slice) is 0.25 * (x + 4 y + 16 slice + 1); the 2D-array view starts at slice 1. +FIRST_SLICE = {'1d': 0, '2da': 1, '3d': 0} + + +def texel(kind, coordinates): + x, y, z = (*coordinates, 0, 0)[:3] + return 0.25 * (x + 4 * y + 16 * (z + FIRST_SLICE[kind]) + 1) + + +def vmov(register, value): + return bytes([0x80 + value, 0x02, register * 2, 0x7e]).hex() # v_mov_b32_e32 v<register>, <inline constant> + + +def program(kind): + _, dim, coordinates, _, _, _ = KINDS[kind] + C.SPLICE.update({T.XOR: '05190a3a', 's_waitcnt vmcnt(0)': '703f8cbf'}) + if dim == '1D': + # gfx2hlsl lowers a 1D image only as image_sample, _lz or _l (no image_load), so the texel is read by a + # level-zero sample at its center under the all-zero (wrap, point) sampler of the sample test. + center = struct.unpack('<I', struct.pack('<f', (coordinates[0] + 0.5) / 8))[0] + move = 'v_mov_b32 v8, 0x%08x' % center + load = 'image_sample_lz v12, v8, s[24:31], s[20:23] dmask:0x1 dim:SQ_RSRC_IMG_1D' + C.SPLICE[move] = 'ff02107e' + struct.pack('<I', center).hex() + C.SPLICE[load] = '00019cf0' '080ca600' # image_sample_lz: dword 0 as the 2D word of the sample test, dim 0 + steps = ['s_mov_b64 s[20:21], 0', 's_mov_b64 s[22:23], 0', 's_load_dwordx8 s[24:31], s[10:11], 0x40', move, + 's_waitcnt lgkmcnt(0)', load, 's_waitcnt vmcnt(0)', T.XOR] + else: + registers = 'v[8:%d]' % (7 + len(coordinates)) + load = LOAD % (registers, dim) + movs = ['v_mov_b32 v%d, %d' % (8 + i, value) for i, value in enumerate(coordinates)] + C.SPLICE.update({'v_mov_b32 v%d, %d' % (8 + i, value): vmov(8 + i, value) for i, value in enumerate(coordinates)}) + C.SPLICE[load] = bytes([DIM_FIELD[dim] << 3, 1, 0, 0xf0]).hex() + '080c0600' + steps = ['s_load_dwordx8 s[24:31], s[10:11], 0x40', *movs, 's_waitcnt lgkmcnt(0)', load, 's_waitcnt vmcnt(0)', + T.XOR] + code = C.splice(*steps) + decoded = [i[3].replace('_e32', '') for i in G.decode(code) if i[0] >= C.STORE_A][:len(steps)] + assert decoded == [step.replace('_e32', '') for step in steps], decoded + return code + + +def check(directory, consumer, dxc, kind, adapter): + name, dim, coordinates, value, refusal, line = KINDS[kind] + assert texel(kind, coordinates) == value, (kind, texel(kind, coordinates)) + cache, base = prepare(directory) + env = dict(base, X2W_D3D12_LIST_NOOP='1', X2W_D3D12_DEBUG='1') + if adapter == 'hardware': + env['X2W_TEST_DISPATCH_HARDWARE'] = '1' + (directory / 'compute_root').write_bytes(C.root_blob(table_range=True)) + env['X2W_TEST_COMPUTE_ROOT'] = str(directory / 'compute_root') + _, _, rsrc2, group, groups = C.CASES['A'] + assert groups == (3, 2, 2) and (C.KEY, C.STRIDE) == (0x01234567, 0x9e3779b9), 'the consumer hard-codes case A' + code = program(kind) + (directory / 'program').write_bytes(code) + (directory / 'data').write_bytes(DATA) + (directory / 'state').write_bytes(state_a(group, rsrc2)) + bits = struct.unpack('<I', struct.pack('<f', value))[0] + written = 24 * 3 * 2 * 2 # threads per group times groups; the words past them keep the sentinel + untouched, plain = [C.SENTINEL] * C.WORDS, C.expected('A') + assert plain[written:] == untouched[written:] + expected = [word ^ bits for word in plain[:written]] + plain[written:] + layout = '<%dI' % C.WORDS + mode = 'dispatch-texdim-' + kind + + got, result = T.run(directory, consumer, env, mode, layout) + assert got == untouched, 'a Dispatch without a translation wrote the output' + assert len(lines(result, 'Dispatch(3, 2, 2) refused: no translation')) == 1, result.stderr[-3000:] + key = int(lines(result, 'x2w-draw compute request')[0].split()[3], 16) + T.translate(cache, dxc, key) + manifest = cache / f'{key:016x}.txt' + original = manifest.read_text() + assert line in original.splitlines() and 'srv 0 buf table 1 0' in original.splitlines(), original + + got, result = T.run(directory, consumer, env, mode, layout) + wrong = [i for i in range(C.WORDS) if got[i] != expected[i]] + assert not wrong, '%s: word=%d got=%08x expected=%08x (%d words differ)\n%s' % ( + kind, wrong[0], got[wrong[0]], expected[wrong[0]], len(wrong), result.stderr[-3000:]) + assert len(lines(result, 'Dispatch(3, 2, 2) translated')) == 1, result.stderr[-3000:] + layer = T.clean(result) + assert sum(a != b for a, b in zip(got, plain)) == written, 'the texel must change every written word' + + def refused(label, control_mode, reason): + got, result = T.run(directory, consumer, env, control_mode, layout) + logged = lines(result, 'refused: ') + assert got == untouched and len(logged) == 1 and logged[0].endswith('refused: ' + reason), ( + label, logged, result.stderr[-3000:]) + assert not lines(result, 'Dispatch(3, 2, 2) translated'), label + errors = [l for l in lines(result, 'x2w-d3d12-debug ') if ' sev=0 ' in l or ' sev=1 ' in l] + assert not errors, (label, errors[0]) + + refused('view dimension', mode + '-mismatch', f'an input texture view is not {refusal}') + refused('no description', mode + '-undescribed', f'an input {refusal} texture has no recorded view description') + refused('view does not fit', mode + '-clamped', 'an input texture view does not fit its texture') + + # Mutants: the dimension is the manifest's. The title's view is of this kind, so another name must be refused. + for other in ('tex2d', 'tex1d' if kind != '1d' else 'tex3d'): + reason = {'tex1d': 'an input texture view is not 1D', 'tex2d': 'an input texture view is not 2D', + 'tex3d': 'an input texture view is not 3D'}[other] + assert original.count(line) == 1 + manifest.write_bytes(original.replace(line, line.replace(name, other)).encode()) + refused('manifest ' + other, mode, reason) + manifest.write_bytes(original.encode()) + got, result = T.run(directory, consumer, env, mode, layout) + assert got == expected and len(lines(result, 'Dispatch(3, 2, 2) translated')) == 1, result.stderr[-3000:] + print(f'{adapter}: {kind}: {C.WORDS} words match the texel {value} ({written} written words changed); ' + f'view of another dimension, no description, a view that does not fit and a manifest line rewritten to tex2d or ' + f'another dimension are each refused with the output untouched; debug layer: {layer}', flush=True) + + +def main(consumer, dxc, adapter): + with tempfile.TemporaryDirectory() as temporary: + for kind in KINDS: + check(Path(temporary) / kind, consumer, dxc, kind, adapter) + print(f'startup_compute_dispatch_texture_dims: PASS on {adapter}') + + +if __name__ == '__main__': + if len(sys.argv) != 4 or sys.argv[3] not in ('warp', 'hardware'): + sys.exit(__doc__) + main(*sys.argv[1:]) diff --git a/tests/startup_compute_half_buffer_uav_check.py b/tests/startup_compute_half_buffer_uav_check.py new file mode 100644 index 0000000000..e941d3aeb1 --- /dev/null +++ b/tests/startup_compute_half_buffer_uav_check.py @@ -0,0 +1,135 @@ +"""Publish a synthetic D16 slot 67 program and check its typed buffer output.""" + +from pathlib import Path +import struct +import subprocess +import sys +from tempfile import TemporaryDirectory + +from native_dpp_mirror_check import vop2 +from native_gather_lod_check import render +from native_scalar_lds_check import scalar, sop1 +from startup_compute_dispatch_check import dispatch, lines, prepare_case +from startup_compute_translate_check import state_a, write_request +from startup_gfx2hlsl_compute_check import SENTINEL, TGID_X, TGID_Y, TGID_Z, USER7, WORDS, root_blob + + +FORMAT_WIDTHS = ((1, 13), (2, 29), (4, 71)) +OFFSET = 8 +RECORDS = 13 +MODE = 'dispatch-records32-output-offset' +STATE = state_a((32, 1, 1), USER7 | TGID_X | TGID_Y | TGID_Z) + + +def program(channels): + opcode = 0x84 + channels - 1 + words = [ + sop1(3, 20, 6), sop1(3, 21, 128), + 0xf408080a, 0xfa000020, # output descriptor s[32:35], table byte 32 + 0xbf8cc07f, + scalar(0x26, 8, 8, 131), # 3 * group.y + scalar(0x26, 9, 9, 134), # 6 * group.z + scalar(0, 11, 7, 8), scalar(0, 11, 11, 9), + scalar(0x1e, 11, 11, 133), # 32 * flat group index + vop2(0x25, 8, 11, 0), # v8 = element index within the view + vop2(0x1d, 1, 255, 0), 0xc0003c00, # v1 = packed [-2, 1 + lane/1024] + 0x7e0402ff, 0xbc003800, # v2 = packed [-1, 0.5] + 0xe0002000 | (opcode << 18), 0x80080108, + 0xbf810000, + ] + return struct.pack('<%dI' % len(words), *words) + + +def expected(channels): + data = bytearray(struct.pack('<%dI' % WORDS, *([SENTINEL] * WORDS))) + for lane in range(RECORDS): + halves = (0x3c00 + lane, 0xc000, 0x3800, 0xbc00) + struct.pack_into('<%dH' % channels, data, OFFSET + lane * channels * 2, *halves[:channels]) + return list(struct.unpack('<%dI' % WORDS, data)) + + +def check_words(got, want, label): + first = next(((i, a, b) for i, (a, b) in enumerate(zip(got, want)) if a != b), None) + if first is not None: + word, actual, expected_word = first + raise AssertionError(f'{label}: word {word} expected {expected_word:08x}, read {actual:08x}') + + +def publish(compile_dxil, sdk, cache, key, stride): + result = subprocess.run([compile_dxil, sdk, cache.parent / 'native', 'gfx1013-direct-cs@0', + '--requests', cache, cache], capture_output=True, text=True, timeout=30) + manifest = cache / f'{key}.txt' + assert result.returncode == 0 and manifest.is_file(), (result.stdout, result.stderr) + text = manifest.read_text() + assert f'uav 0 bufhalf table 1 32 bytes {stride}' in text.splitlines(), text + assert not (cache / f'{key}.cs.hlsl').exists(), 'expected native publication' + + +def check_compiler(compile_dxil, sdk): + with TemporaryDirectory() as directory: + for channels, _ in FORMAT_WIDTHS: + cache = Path(directory) / str(channels) + cache.mkdir() + key = write_request(cache, program(channels), STATE, root=root_blob(table_range=True)) + publish(compile_dxil, sdk, cache, f'{key:016x}', channels * 2) + + +def check(compile_dxil, consumer, sdk, work, adapter, channels, format_code): + cache, env = prepare_case(work, adapter) + env.pop('X2W_NATIVE_SHADERS', None) + env.pop('X2W_NATIVE_SHADERS_ONLY', None) + (work / 'program').write_bytes(program(channels)) + (work / 'state').write_bytes(STATE) + fields = work / 'fields.bin' + env['X2W_TEST_DISPATCH_FIELDS'] = str(fields) + stride = channels * 2 + word3 = 0x01000fac | (format_code << 12) + untouched = [SENTINEL] * WORDS + + def run(view_stride=stride, records=RECORDS, descriptor_word=word3, *, probe=False): + fields.write_bytes(struct.pack('<6I', 4, WORDS, 0, view_stride, records, descriptor_word)) + return dispatch(work, consumer, env, MODE, probe=probe) + + got, result = run(probe=True) + check_words(got, untouched, 'before translation') + assert lines(result, 'Dispatch(3, 2, 2) refused: no translation'), result.stderr[-3000:] + [request] = cache.glob('req_*.c67') + key = request.stem.removeprefix('req_') + publish(compile_dxil, sdk, cache, key, stride) + got, result = run() + check_words(got, expected(channels), f'{channels} channels') + assert len(lines(result, 'Dispatch(3, 2, 2) translated')) == 1 and not lines(result, 'refused:'), result.stderr[-3000:] + assert not [line for line in lines(result, 'x2w-d3d12-debug ') if ' sev=0 ' in line or ' sev=1 ' in line] + layers = lines(result, 'x2w-d3d12 debug layer: ') + layer = 'enabled' if layers and '0x00000000' in layers[0] else 'unavailable' + print(f'{channels} channels: {RECORDS} typed records at byte {OFFSET} and all guards match on {adapter} ' + f'(debug layer {layer})') + + wrong_shape = 'a half buffer store requires matching format, stride and structured bounds' + for options, reason in ( + ({'view_stride': stride + 2}, wrong_shape), + ({'view_stride': stride | 0x8000}, wrong_shape), + ({'descriptor_word': 0x01016fac}, wrong_shape), + ({'descriptor_word': word3 ^ 1}, wrong_shape), + ({'descriptor_word': word3 | 1 << 28}, wrong_shape), + ({'records': WORDS * 4 // stride}, 'an output range crosses the end of a placed buffer'), + ): + got, result = run(**options) + check_words(got, untouched, options) + assert len(lines(result, 'Dispatch(3, 2, 2) refused: ' + reason)) == 1, (options, result.stderr[-3000:]) + print(f'{channels} channels: invalid views refused and output remained untouched') + + +def main(compile_dxil, consumer, renderer, sdk, adapter): + wave = render(renderer, adapter, '--shader-wave32') + assert wave.returncode == 0, wave.stdout + wave.stderr + with TemporaryDirectory() as directory: + for channels, format_code in FORMAT_WIDTHS: + check(compile_dxil, consumer, sdk, Path(directory) / str(channels), adapter, channels, format_code) + + +if __name__ == '__main__': + if sys.argv[1] == 'compile': + check_compiler(*sys.argv[2:]) + else: + main(*sys.argv[1:]) diff --git a/tests/startup_compute_root_srv_dispatch_check.py b/tests/startup_compute_root_srv_dispatch_check.py index 177462f9c6..4411d2f20a 100644 --- a/tests/startup_compute_root_srv_dispatch_check.py +++ b/tests/startup_compute_root_srv_dispatch_check.py @@ -172,11 +172,11 @@ def check_single_root_srv(base, consumer, dxc, adapter): # Manifest parser refusal controls on bad `srv ... buf root ...` lines and descriptor-word udsrc on a root SRV. for bad_manifest, expected_reason in ( (manifest.replace("srv 0 buf root 2", "srv 0 buf root -1"), - "a resource that is not a raw table buffer or a 2D texture"), + "a resource that is not a raw table buffer or a 1D/2D/2D-array/3D texture"), (manifest.replace("srv 0 buf root 2", "srv 0 buf root 2 trailing"), - "a resource that is not a raw table buffer or a 2D texture"), + "a resource that is not a raw table buffer or a 1D/2D/2D-array/3D texture"), (manifest.replace("srv 0 buf root 2", "srv 1 buf root 2"), - "a resource that is not a raw table buffer or a 2D texture"), + "a resource that is not a raw table buffer or a 1D/2D/2D-array/3D texture"), (manifest.replace("ud 3\nudsrc 0 rootconst 0 0\nudsrc 1 rootconst 0 1\nudsrc 2 rootconst 0 2", "ud 4\nudsrc 0 rootconst 0 0\nudsrc 1 rootconst 0 1\nudsrc 2 rootconst 0 2\nudsrc 3 stride 0"), "an entry value names a descriptor that is not a buffer input or output"), @@ -185,6 +185,8 @@ def check_single_root_srv(base, consumer, dxc, adapter): sub_cache, sub_env = setup_case(sub, two_srvs=False, adapter=adapter) (sub_cache / f"{key:016x}.txt").write_text(bad_manifest, encoding="utf-8") (sub_cache / f"{key:016x}.cs.cso").write_bytes(cso_path.read_bytes()) + # The Python translator's sidecar marks these unmarked manifests as Python output, not stale native output. + (sub_cache / f"{key:016x}.cs.hlsl").write_bytes(hlsl_path.read_bytes()) got, result = run(sub, consumer, sub_env, "dispatch-root-srv") assert got == [SENTINEL] * WORDS assert lines(result, f"compute pipeline {key:016x} not translated: {expected_reason}"), result.stderr[-3000:] diff --git a/tests/startup_compute_translate_check.py b/tests/startup_compute_translate_check.py index dbf5d63248..069b6b2a9d 100644 --- a/tests/startup_compute_translate_check.py +++ b/tests/startup_compute_translate_check.py @@ -29,8 +29,8 @@ def state_a(group, rsrc2): - # The observed offsets: dword 3 = X | Y << 16, dword 4 = Z, dword 6 = COMPUTE_PGM_RSRC2. - return struct.pack('<7I', 0, 0, 0, group[0] | group[1] << 16, group[2], 0, rsrc2) + # Dword 3 holds X and Y, dword 4 holds Z and the wave32 bit, and dword 6 holds COMPUTE_PGM_RSRC2. + return struct.pack('<7I', 0, 0, 0, group[0] | group[1] << 16, group[2] | (1 << 20), 0, rsrc2) def write_request(cache, code, state, data=DATA, root=None, desc_sizes=None): diff --git a/tests/startup_compute_waterfall_heap_check.py b/tests/startup_compute_waterfall_heap_check.py new file mode 100644 index 0000000000..3229de8bd5 --- /dev/null +++ b/tests/startup_compute_waterfall_heap_check.py @@ -0,0 +1,488 @@ +"""Per-lane resource-heap record index inside a compute v_readfirstlane_b32 waterfall loop (#2644 T3). + +usage: + startup_compute_waterfall_heap_check.py [--llvm-mc <llvm-mc>] + startup_compute_waterfall_heap_check.py --dxil <dxc> + startup_compute_waterfall_heap_check.py --oracle <dxc> <offscreen_check> <warp|hardware> + startup_compute_waterfall_heap_check.py --dispatch <startup_stream_consumer> <dxc> <warp|hardware> + +Covers: +1. gfx2hlsl translation and manifest generation for bounded per-lane resource-heap indices in compute + waterfall loops, including both direct heap offsets (s_lshl_b32 + s_load_dwordx4 s[...], s[8:9], sI) + and the adjacent 64-bit pointer-add carry form (s_add_u32 + s_add_u32 0, src_scc / s_addc_u32, with + either in-body s_lshl_b32 or pre-loop v_lshlrev_b32 ..., 5), plus v_min_u32 and v_bfe_u32 bounds. +2. Soundness negative controls: unbounded keys, oversized masks, one-arm diamond bounds, bounded writes under + narrowed EXEC, missing/wrong shift, missing resheap root flag, non-zero high word, broken carry, descriptor + mutation, exit-live scalars, and forbidden store/formatted/idxen uses. +3. Independent DXIL handle metadata assertions via DXC cs_6_0: confirms the resource handle selects SRV space 2 + [0..3] with nonUniformIndex=true, and that stripping NonUniformResourceIndex changes it to false. +4. Four-record GPU oracle (--oracle): reference, static switch, no-marker, and first-active (asserting the + exact 12/25 first-active mismatches that distinguish lane-local selection from a wave-uniform shortcut). +5. End-to-end stand-in Dispatch fixture (--dispatch): translates both the direct-offset and 64-bit carry + waterfall programs via gfx2hlsl.py --pending, dispatches all five oracle key patterns plus active-lane + subsets through d3d12_xs.dll with the debug layer enabled, and verifies a short-range view heap that omits + the highest record (3) refuses cleanly before Dispatch. +""" +import argparse +import os +from pathlib import Path +import re +import struct +import subprocess +import sys +import tempfile + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE)) + +import array_atomics_dxil_check as dxil # noqa: E402 +from startup_compute_dispatch_check import dispatch, lines # noqa: E402 +from startup_compute_request_check import DATA, prepare # noqa: E402 +from startup_compute_translate_check import state_a # noqa: E402 +import startup_gfx2hlsl_compute_check as C # noqa: E402 +import startup_gfx2hlsl_heap_record_check as H # noqa: E402 +from startup_gfx2hlsl_compute_check import G, assemble, refused # noqa: E402 + +GROUP = (4, 1, 1) +NO_DATA = bytes(C.WORDS * 4) + +# Bounded four-record waterfall program matching the reference fixture (`bounded-waterfall.s`). +BOUNDED_PREFIX = ( + ('s_mov_b32 s12, s7', '07038cbe'), + ('s_mov_b32 s13, 0', '80038dbe'), + ('s_load_dwordx8 s[40:47], s[12:13], 0x0', '060a0cf4000000fa'), + ('s_waitcnt lgkmcnt(0)', '7fc08cbf'), + ('s_mov_b32 s9, 0', '800389be'), + ('v_lshlrev_b32_e32 v4, 2, v0', '82000834'), + ('buffer_load_dword v5, v4, s[40:43], 0 offen', '001030e004050a80'), + ('s_waitcnt vmcnt(0)', '703f8cbf'), +) +MASK_AND3 = ('v_and_b32_e32 v5, 3, v5', '830a0a36') +INIT_AND_GUARD = ( + ('v_mov_b32_e32 v7, 13', '8d020e7e'), + ('s_mov_b32 s26, exec_lo', '7e039abe'), + ('v_cmpx_gt_u32_e32 s4, v0', '0400a87d'), + ('s_mov_b32 s21, exec_lo', '7e0395be'), +) +HEAD = ('v_readfirstlane_b32 s22, v5', '05052c7e') +COMPARE = ('v_cmpx_eq_i32_e32 s22, v5', '160a247d') +SHIFT5 = ('s_lshl_b32 s23, s22, 5', '1685178f') +HEAP_LOAD = ('s_load_dwordx4 s[28:31], s[8:9], s23', '040708f40000002e') +CARRY_ADD_S23 = ( + ('s_add_u32 s24, s8, s23', '08171880'), + ('s_add_u32 s25, 0, src_scc', '80fd1980'), + ('s_load_dwordx4 s[28:31], s[24:25], 0x0', '0c0708f4000000fa'), +) +CARRY_ADD_S22 = ( + ('s_add_u32 s24, s8, s22', '08161880'), + ('s_add_u32 s25, 0, src_scc', '80fd1980'), + ('s_load_dwordx4 s[28:31], s[24:25], 0x0', '0c0708f4000000fa'), +) +WAIT_LGKM = ('s_waitcnt lgkmcnt(0)', '7fc08cbf') +BODY_LOAD = ('buffer_load_dword v7, v4, s[28:31], 0 offen', '001030e004070780') +WAIT_VM = ('s_waitcnt vmcnt(0)', '703f8cbf') +CLOSE = ('s_andn2_wrexec_b32 s21, s21', '154795be') +RESTORE = ('s_mov_b32 exec_lo, s26', '1a03febe') +FINAL_STORE = ('buffer_store_dword v7, v4, s[44:47], 0 offen', '001070e004070b80') +END = ('s_endpgm', '000081bf') + +ENCODINGS = { + 'v_min_u32_e32 v5, 3, v5': '830a0a26', + 'v_bfe_u32 v5, v5, 0, 2': '050048d505010a02', + 'v_lshlrev_b32_e32 v5, 5, v5': '850a0a34', + 'v_lshlrev_b32_e32 v5, 4, v5': '840a0a34', + 'v_and_b32_e32 v5, 0x7ff, v5': 'ff0a0a36ff070000', + 's_lshl_b32 s22, s22, 5': '1685168f', + 's_lshl_b32 s23, s22, 4': '1684178f', + 's_mov_b32 s24, s23': '170398be', + 's_mov_b32 s24, s22': '160398be', + 's_load_dwordx4 s[28:31], s[8:9], s24': '040708f400000030', + 's_load_dwordx4 s[28:31], s[8:9], s22': '040708f40000002c', + 's_load_dwordx4 s[28:31], s[22:23], 0x0': '0b0708f4000000fa', + 's_addc_u32 s25, s9, 0': '09801982', + 's_mov_b32 s9, 1': '810389be', + 's_cmp_eq_u32 s4, 0': '048006bf', + 's_cbranch_scc0 1': '010084bf', + 's_cbranch_scc0 2': '020084bf', + 's_branch 1': '010082bf', + 's_nop 0': '000080bf', + 's_or_b32 s31, s31, 0': '1f801f88', + 's_mov_b32 s22, 0': '800396be', + 'v_mov_b32_e32 v7, s22': '16020e7e', + 'v_mov_b32_e32 v7, s28': '1c020e7e', + 'buffer_load_dword v7, v4, s[28:31], 0 idxen': '002030e004070780', + 'buffer_load_format_x v7, v4, s[28:31], 0 offen': '001000e004070780', + 'buffer_store_dword v7, v4, s[28:31], 0 offen': '001070e004070780', +} + +BOUNDED_ORACLE_HLSL = """\ +ByteAddressBuffer keys : register(t0); +#if defined(STATIC_SWITCH) +ByteAddressBuffer r0 : register(t1), r1 : register(t2), r2 : register(t3), r3 : register(t4); +#else +ByteAddressBuffer records[4] : register(t1); +#endif +RWByteAddressBuffer result : register(u0); +cbuffer config : register(b0) { uint active; }; + +[RootSignature("SRV(t0), DescriptorTable(SRV(t1, numDescriptors=4)), UAV(u0), RootConstants(num32BitConstants=1,b0)")] +[numthreads(4, 1, 1)] +void main(uint3 tid : SV_GroupThreadID) +{ + uint lane = tid.x; + uint value = 13; + if (lane < active) { +#if defined(FIRST_ACTIVE) + uint index = keys.Load(0) & 3; +#else + uint index = keys.Load(4 * lane) & 3; +#endif +#if defined(STATIC_SWITCH) + switch (index) { + case 0: value = r0.Load(4 * lane); break; + case 1: value = r1.Load(4 * lane); break; + case 2: value = r2.Load(4 * lane); break; + default: value = r3.Load(4 * lane); break; + } +#elif defined(NO_MARKER) + value = records[index].Load(4 * lane); +#else + value = records[NonUniformResourceIndex(index)].Load(4 * lane); +#endif + } + result.Store(4 * lane, value); +} +""" + +ORACLE_ROWS = ((0, 1, 2, 3), (3, 2, 1, 0), (2, 1, 2, 3), (4, 9, 14, 19), (7, 7, 7, 7)) + + +def row_pair(asm): + return (asm, ENCODINGS[asm]) + + +def build_program(*, bound=(MASK_AND3,), init=INIT_AND_GUARD, body=(SHIFT5, HEAP_LOAD, WAIT_LGKM, BODY_LOAD, WAIT_VM), + after_restore=()): + loop = (HEAD, COMPARE, *body, CLOSE) + offset = -(sum(len(bytes.fromhex(code)) for _, code in loop) // 4 + 1) + branch = ('s_cbranch_scc1 %d' % offset, struct.pack('<I', 0xbf850000 | (offset & 0xffff)).hex()) + return (*BOUNDED_PREFIX, *bound, *init, *loop, branch, RESTORE, *after_restore, FINAL_STORE, END) + + +def assemble_rows(rows): + return b''.join(bytes.fromhex(code) for _, code in rows) + + +def translate(rows, *, root=None): + pipe = G.ComputePipeline(assemble_rows(rows), root or H.root_blob(), H.RSRC2, GROUP) + return pipe.hlsl_cs(), pipe.manifest() + + +def trace_srv_handle(ir_text, *, expected_binding): + """Follow buffer RawBufferLoad handle back to createHandle / createHandleFromBinding in DXIL IR.""" + definitions, metadata, named = dxil.parse_module(ir_text) + roots = named.get('!dx.resources', []) + assert len(roots) == 1, 'module missing !dx.resources' + srvs = metadata[roots[0]][0] + srv_table = {} + for entry in ([] if srvs == 'null' else metadata[srvs]): + fields = metadata[entry] + rid = dxil.integers(fields[0])[0] + srv_table[rid] = {'space': dxil.integers(fields[3])[0], 'lower': dxil.integers(fields[4])[0], + 'size': dxil.integers(fields[5])[0]} + + loads = [ops for op, ops in definitions.values() if op in ('rawBufferLoad', 'bufferLoad')] + found = [] + for ops in loads: + handle = dxil.last_value(ops[1]) + while definitions.get(handle, (None,))[0] == 'annotateHandle': + handle = dxil.last_value(definitions[handle][1][1]) + op, operands = definitions.get(handle, (None, None)) + if op == 'createHandle': + rclass = dxil.integers(operands[1])[0] + binding = srv_table.get(dxil.integers(operands[2])[0]) if rclass == 0 else None + idx, flag = operands[3], operands[4] + elif op == 'createHandleFromBinding': + lower, upper, space, rclass = dxil.integers(operands[1]) + binding = {'space': space, 'lower': lower, 'size': upper - lower + 1} if rclass == 0 else None + idx, flag = operands[2], operands[3] + else: + continue + if binding == expected_binding: + found.append({ + 'creation': op, + 'binding': binding, + 'index_var': dxil.last_value(idx), + 'non_uniform': dxil.last_value(flag) == 'true', + 'raw': idx, + }) + assert len(found) == 1, f'expected one load on {expected_binding}, found {found}\n{ir_text}' + return found[0] + + +def verify_dxil(dxc, hlsl_source, *, expected_binding, check_stripped=True): + with tempfile.TemporaryDirectory() as tmp: + src = Path(tmp) / 'shader.hlsl' + cso = Path(tmp) / 'shader.cso' + src.write_text(hlsl_source, encoding='ascii') + subprocess.run([dxc, '-Gis', '-T', 'cs_6_0', '-E', 'main', '-Fo', cso, src], check=True) + ir = subprocess.run([dxc, '-dumpbin', cso], check=True, capture_output=True, text=True).stdout + traced = trace_srv_handle(ir, expected_binding=expected_binding) + assert traced['non_uniform'], f'DXIL lost nonUniformIndex on {expected_binding}: {traced}' + if check_stripped: + assert 'NonUniformResourceIndex(' in hlsl_source + stripped = Path(tmp) / 'stripped.hlsl' + cso_no = Path(tmp) / 'stripped.cso' + stripped.write_text(hlsl_source.replace('NonUniformResourceIndex(', '('), encoding='ascii') + subprocess.run([dxc, '-Gis', '-T', 'cs_6_0', '-E', 'main', '-Fo', cso_no, stripped], check=True) + ir_no = subprocess.run([dxc, '-dumpbin', cso_no], check=True, capture_output=True, text=True).stdout + traced_no = trace_srv_handle(ir_no, expected_binding=expected_binding) + assert not traced_no['non_uniform'], f'failed to detect omitted NonUniformResourceIndex: {traced_no}' + + +def check_translator(llvm_mc=None): + # Positive forms. + hlsl_a, man_a = translate(build_program()) + assert 'ByteAddressBuffer rh[4] : register(t0, space2);' in hlsl_a + assert 'rh[NonUniformResourceIndex(h0)].Load(a + 0)' in hlsl_a + assert man_a.endswith('uav 0 table 1 16\nresheap 4 2\n'), man_a + + # 64-bit pointer add + src_scc carry form (post-loop shift and pre-loop v_lshlrev_b32). + hlsl_b, man_b = translate(build_program(body=(SHIFT5, *CARRY_ADD_S23, WAIT_LGKM, BODY_LOAD, WAIT_VM))) + assert 'rh[NonUniformResourceIndex(h0)].Load(a + 0)' in hlsl_b and 'resheap 4 2\n' in man_b + hlsl_pre, man_pre = translate(build_program(bound=(MASK_AND3, row_pair('v_lshlrev_b32_e32 v5, 5, v5')), + body=(*CARRY_ADD_S22, WAIT_LGKM, BODY_LOAD, WAIT_VM))) + assert 'h0 = (s22 >> 5);' in hlsl_pre and 'rh[NonUniformResourceIndex(h0)].Load(a + 0)' in hlsl_pre + assert 'resheap 4 2\n' in man_pre + + # s_addc_u32 high-word carry, v_min_u32, v_bfe_u32, in-place s_lshl_b32, and clobber of s22 after load. + translate(build_program(body=(SHIFT5, ('s_add_u32 s24, s8, s23', '08171880'), row_pair('s_addc_u32 s25, s9, 0'), + ('s_load_dwordx4 s[28:31], s[24:25], 0x0', '0c0708f4000000fa'), + WAIT_LGKM, BODY_LOAD, WAIT_VM))) + translate(build_program(bound=(row_pair('v_min_u32_e32 v5, 3, v5'),))) + hlsl_bfe, man_bfe = translate(build_program(bound=(row_pair('v_bfe_u32 v5, v5, 0, 2'),))) + assert 'resheap 4 2\n' in man_bfe and 'rh[NonUniformResourceIndex(h0)].Load' in hlsl_bfe + hlsl_inp, _ = translate(build_program(body=(row_pair('s_lshl_b32 s22, s22, 5'), + row_pair('s_load_dwordx4 s[28:31], s[8:9], s22'), + WAIT_LGKM, BODY_LOAD, WAIT_VM))) + assert 'h0 = (s22 >> 5);' in hlsl_inp + hlsl_reused, _ = translate(build_program(body=(SHIFT5, HEAP_LOAD, WAIT_LGKM, row_pair('s_mov_b32 s22, 0'), + BODY_LOAD, WAIT_VM))) + assert 'h0 = s22;' in hlsl_reused and 'rh[NonUniformResourceIndex(h0)].Load' in hlsl_reused + hlsl_ocpy, _ = translate(build_program(body=(SHIFT5, row_pair('s_mov_b32 s24, s23'), + row_pair('s_load_dwordx4 s[28:31], s[8:9], s24'), + WAIT_LGKM, BODY_LOAD, WAIT_VM))) + assert 'h0 = s22;' in hlsl_ocpy + + # Negative controls: every missing proof or forbidden extension stays refused. + controls = ( + ('unbounded key', build_program(bound=()), 'per-lane descriptor selection requires a proven bound heap range'), + ('oversized mask', build_program(bound=(row_pair('v_and_b32_e32 v5, 0x7ff, v5'),)), + 'per-lane descriptor selection requires a proven bound heap range'), + ('only one diamond arm bounds key', + build_program(bound=(row_pair('s_cmp_eq_u32 s4, 0'), row_pair('s_cbranch_scc0 2'), MASK_AND3, + row_pair('s_branch 1'), row_pair('s_nop 0'))), + 'per-lane descriptor selection requires a proven bound heap range'), + ('bounded after EXEC narrowed without prior bound', + build_program(bound=(), init=(('v_mov_b32_e32 v7, 13', '8d020e7e'), ('s_mov_b32 s26, exec_lo', '7e039abe'), + ('v_cmpx_gt_u32_e32 s4, v0', '0400a87d'), MASK_AND3, + ('s_mov_b32 s21, exec_lo', '7e0395be'))), + 'per-lane descriptor selection requires a proven bound heap range'), + ('missing shift', build_program(body=(row_pair('s_load_dwordx4 s[28:31], s[8:9], s22'), + WAIT_LGKM, BODY_LOAD, WAIT_VM)), + 'per-lane descriptor selection requires a proven bound heap range'), + ('wrong shift', build_program(body=(row_pair('s_lshl_b32 s23, s22, 4'), HEAP_LOAD, + WAIT_LGKM, BODY_LOAD, WAIT_VM)), + 'per-lane descriptor selection requires a proven bound heap range'), + ('wrong pre-loop shift', + build_program(bound=(MASK_AND3, row_pair('v_lshlrev_b32_e32 v5, 4, v5')), + body=(*CARRY_ADD_S22, WAIT_LGKM, BODY_LOAD, WAIT_VM)), + 'per-lane descriptor selection requires a proven bound heap range'), + ('non-resheap base', build_program(body=(row_pair('s_load_dwordx4 s[28:31], s[22:23], 0x0'), + WAIT_LGKM, BODY_LOAD, WAIT_VM)), + 'per-lane descriptor selection requires a proven bound heap range'), + ('modified descriptor word', build_program(body=(SHIFT5, HEAP_LOAD, WAIT_LGKM, + row_pair('s_or_b32 s31, s31, 0'), BODY_LOAD, WAIT_VM)), + 'per-lane descriptor selection requires a proven bound heap range'), + ('non-zero resheap high word', + build_program(bound=(row_pair('s_mov_b32 s9, 1'), MASK_AND3)), + 'whose high word is not a constant zero'), + ('missing carry on s_add_u32 pointer add', + build_program(body=(SHIFT5, ('s_add_u32 s24, s8, s23', '08171880'), + ('s_load_dwordx4 s[28:31], s[24:25], 0x0', '0c0708f4000000fa'), + WAIT_LGKM, BODY_LOAD, WAIT_VM)), + 'per-lane descriptor selection requires a proven bound heap range'), + ('live key at loop exit', + build_program(after_restore=(row_pair('v_mov_b32_e32 v7, s22'),)), 'body scalar is live at the loop exit'), + ('live descriptor word at loop exit', + build_program(after_restore=(row_pair('v_mov_b32_e32 v7, s28'),)), 'body scalar is live at the loop exit'), + ('idxen load through per-lane descriptor', + build_program(body=(SHIFT5, HEAP_LOAD, WAIT_LGKM, + row_pair('buffer_load_dword v7, v4, s[28:31], 0 idxen'), WAIT_VM)), + 'has unproved modifiers'), + ('formatted load through per-lane descriptor', + build_program(body=(SHIFT5, HEAP_LOAD, WAIT_LGKM, + row_pair('buffer_load_format_x v7, v4, s[28:31], 0 offen'), WAIT_VM)), + 'is not proven lane-local'), + ('store through per-lane descriptor', + build_program(body=(SHIFT5, HEAP_LOAD, WAIT_LGKM, + row_pair('buffer_store_dword v7, v4, s[28:31], 0 offen'), WAIT_VM)), + 'is not proven lane-local'), + ) + for label, rows, expected in controls: + try: + refused(expected, lambda: translate(rows)) + except AssertionError as err: + raise AssertionError(f'{label}: {err}') from None + refused('per-lane descriptor selection requires a proven bound heap range', + lambda: translate(build_program(), root=H.root_blob(flags=0))) + + # Check binary reassembly against llvm-mc if provided. + checked_asm = 0 + if llvm_mc: + seen = set() + for asm, hexcode in (*BOUNDED_PREFIX, MASK_AND3, *INIT_AND_GUARD, HEAD, COMPARE, SHIFT5, HEAP_LOAD, + *CARRY_ADD_S23, *CARRY_ADD_S22, WAIT_LGKM, BODY_LOAD, WAIT_VM, CLOSE, RESTORE, + FINAL_STORE, END, *ENCODINGS.items()): + if asm not in seen and 's_cbranch' not in asm and 's_branch' not in asm: + seen.add(asm) + got = assemble(llvm_mc, asm + '\n') + assert got == bytes.fromhex(hexcode), f'{asm}: {got.hex()} != {hexcode}' + checked_asm += 1 + print(f'startup_compute_waterfall_heap: PASS (translator + {len(controls) + 1} refused controls' + + (f' + {checked_asm} llvm-mc encodings' if checked_asm else '') + ')') + + +def check_oracle(dxc, offscreen_check, adapter): + expected_binding = {'space': 0, 'lower': 1, 'size': 4} + with tempfile.TemporaryDirectory() as tmp: + d = Path(tmp) + hlsl = d / 'bounded.hlsl' + hlsl.write_text(BOUNDED_ORACLE_HLSL, encoding='ascii') + results = {} + variants = ( + ('reference', [], True, ((25, 0),)), + ('static-switch', ['-D', 'STATIC_SWITCH'], None, ((25, 0),)), + ('first-active', ['-D', 'FIRST_ACTIVE'], None, ((13, 12),)), + # On WARP, dropping NonUniformResourceIndex still matches 25/25; on GPUs that scalarize dynamic + # descriptor loads (such as RX 7900 XTX), it reads lane 0 and mismatches 12/25, like first-active. + ('no-marker', ['-D', 'NO_MARKER'], False, ((25, 0), (13, 12))), + ) + for name, defs, want_nu, valid_counts in variants: + cso = d / f'{name}.cso' + subprocess.run([dxc, '-T', 'cs_6_0', '-E', 'main', *defs, '-Fo', cso, hlsl], check=True) + if want_nu is not None: + ir = subprocess.run([dxc, '-dumpbin', cso], check=True, capture_output=True, text=True).stdout + traced = trace_srv_handle(ir, expected_binding=expected_binding) + assert traced['non_uniform'] is want_nu, (name, traced) + res = subprocess.run([offscreen_check, adapter, '--compute-waterfall-oracle', cso], + capture_output=True, text=True) + if res.returncode == 77: + print(res.stdout + res.stderr) + return 77 + assert res.returncode == 0, f'{name} failed:\n{res.stdout}{res.stderr}' + m = re.search(r'dispatches=25 matches=(\d+) mismatches=(\d+)', res.stdout) + assert m, res.stdout + res.stderr + got_m, got_mis = int(m[1]), int(m[2]) + assert (got_m, got_mis) in valid_counts, f'{name}: got {(got_m, got_mis)}' + results[name] = (got_m, got_mis) + print(f"startup_compute_waterfall_heap_oracle ({adapter}): PASS {results}") + return 0 + + +def check_dispatch(consumer, dxc, adapter): + shapes = ( + ('direct', assemble_rows(build_program())), + ('carry64', assemble_rows(build_program(body=(SHIFT5, *CARRY_ADD_S23, WAIT_LGKM, BODY_LOAD, WAIT_VM)))), + ) + for label, program_bytes in shapes: + with tempfile.TemporaryDirectory() as temporary: + directory = Path(temporary) + cache, env = prepare(directory) + env.update(X2W_D3D12_LIST_NOOP='1', X2W_D3D12_DEBUG='1') + if adapter == 'hardware': + env['X2W_TEST_DISPATCH_HARDWARE'] = '1' + (directory / 'compute_root').write_bytes(H.root_blob(table_range=True)) + env['X2W_TEST_COMPUTE_ROOT'] = str(directory / 'compute_root') + (directory / 'program').write_bytes(program_bytes) + (directory / 'data').write_bytes(NO_DATA) + (directory / 'state').write_bytes(state_a(GROUP, H.RSRC2)) + untouched = [C.SENTINEL] * C.WORDS + + # 1. Before translation: refused with "no translation", output untouched. + got, result = dispatch(directory, consumer, env, 'dispatch-heap-waterfall') + if result.returncode == 77: + print(result.stdout + result.stderr) + return 77 + assert got == untouched, f'{label}: untranslated dispatch wrote output' + assert len(lines(result, 'Dispatch(1, 1, 1) refused: no translation')) == 1, result.stderr[-3000:] + published = lines(result, 'x2w-draw compute request') + assert published and ' published ' in published[0], result.stderr[-3000:] + key = int(published[0].split()[3], 16) + + # 2. Offline translate and validate DXIL nonUniformIndex metadata. + out = subprocess.run([sys.executable, '-B', G.__file__, '--pending', cache], check=True, + capture_output=True, text=True, env=dict(os.environ, X2W_DXC=dxc)).stdout + assert f'{key:016x}: ok' in out, out + assert 'resheap 4 2\n' in (cache / f'{key:016x}.txt').read_text(encoding='ascii') + verify_dxil(dxc, (cache / f'{key:016x}.cs.hlsl').read_text(encoding='ascii'), + expected_binding={'space': 2, 'lower': 0, 'size': 4}) + + # 3. Positive readback across the oracle key sets and active lane counts (0, 2, 4). + cases = [(keys, 4) for keys in ORACLE_ROWS] + [((0, 1, 2, 3), 2), ((0, 1, 2, 3), 0)] + for idx, (keys, active) in enumerate(cases): + in_path = directory / f'in-{idx}.bin' + in_words = list(keys) + [0] * (C.WORDS - 4) + in_path.write_bytes(struct.pack(f'<{C.WORDS}I', *in_words)) + case_env = dict(env, X2W_TEST_DISPATCH_IN=str(in_path), X2W_TEST_DISPATCH_ACTIVE=str(active)) + got, result = dispatch(directory, consumer, case_env, 'dispatch-heap-waterfall') + assert len(lines(result, 'Dispatch(1, 1, 1) translated')) == 1 and not lines(result, 'refused'), \ + result.stderr[-3000:] + errors = [ln for ln in lines(result, 'x2w-d3d12-debug ') if ' sev=0 ' in ln or ' sev=1 ' in ln] + assert not errors, errors[0] + expected = [1000 * ((keys[lane] & 3) + 1) + 17 * lane if lane < active else 13 for lane in range(4)] + untouched[4:] + wrong = [i for i in range(C.WORDS) if got[i] != expected[i]] + assert not wrong, f'{label} case {idx} keys={keys} active={active} word={wrong[0]} got={got[wrong[0]]:08x} expected={expected[wrong[0]]:08x}' + + # 4. Short-range negative control: 3-descriptor heap omits record 3 and must refuse before Dispatch. + in_path = directory / 'in-short.bin' + in_path.write_bytes(struct.pack(f'<{C.WORDS}I', 0, 1, 2, 3, *([0] * (C.WORDS - 4)))) + short_env = dict(env, X2W_TEST_DISPATCH_IN=str(in_path), X2W_TEST_DISPATCH_ACTIVE='4') + got, result = dispatch(directory, consumer, short_env, 'dispatch-heap-waterfall-short') + assert got == untouched, f'{label}: short-range control modified output' + ref = lines(result, 'refused: ') + census = lines(result, 'x2w-render compute census') + want_reason = "a heap record is outside the list's view heap" + assert len(ref) == 1 and want_reason in ref[0], result.stderr[-3000:] + assert len(census) == 3 and census[1].endswith(f'reason "{want_reason}": 1 keys, 1 dispatches'), census + errors = [ln for ln in lines(result, 'x2w-d3d12-debug ') if ' sev=0 ' in ln or ' sev=1 ' in ln] + assert not errors, errors[0] + print(f'startup_compute_waterfall_heap_dispatch ({adapter}): PASS (direct + carry64 translated, ' + f'DXIL nonUniformIndex verified, all {len(cases)} key/active readbacks matched, short-range control refused)') + return 0 + + +def main(): + parser = argparse.ArgumentParser(add_help=False) + parser.add_argument('--llvm-mc') + parser.add_argument('--dxil') + parser.add_argument('--oracle', nargs=3) + parser.add_argument('--dispatch', nargs=3) + args, unknown = parser.parse_known_args() + if unknown: + sys.exit(__doc__) + if args.dxil: + hlsl, _ = translate(build_program()) + verify_dxil(args.dxil, hlsl, expected_binding={'space': 2, 'lower': 0, 'size': 4}) + print('startup_compute_waterfall_heap_dxil: PASS (nonUniformIndex true with intrinsic, false without)') + return 0 + if args.oracle: + return check_oracle(*args.oracle) + if args.dispatch: + return check_dispatch(*args.dispatch) + check_translator(args.llvm_mc) + return 0 + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/tests/startup_debug_check.py b/tests/startup_debug_check.py index b0900a5922..299e407ff8 100644 --- a/tests/startup_debug_check.py +++ b/tests/startup_debug_check.py @@ -7,6 +7,10 @@ ends the run as the timeout does; one left from an earlier run is removed at start. The launcher keeps the debug heap off unless the caller sets _NO_DEBUG_HEAP=0. X2W_NOP_SOFT_ASSERTS=1 replaces a main-image INT3 with a NOP after the first continue, and the probe repeats one site when STARTUP_DEBUG_PROBE_ASSERTS is set. +--assert-sites N steps over every hit at up to N distinct main-image sites, however often each +repeats, and stops at the first hit of one more site. +With both budgets, each counts only the hits it covers (hits A, B, A with --assert-sites 1 +--continue-asserts 2 all continue). tests/startup_debug_probe.cpp is the main input: it hits two breakpoints, optionally repeats a third, reserves 256 MiB, prints its debug-heap flags, waits 3 s and exits 0. @@ -212,6 +216,40 @@ def stack_read(address, size): assert "process exited with 0x00000000" in out, out assert breakpoint_sites(logdir, image).count(repeated[0]) == repeats, text(logdir / "events.txt") + # --assert-sites 3: every hit at the three sites is stepped over, however often the third + # repeats, with no hit budget at all. + many = 20 + out, logdir = run(probe, work, "assert-sites", {"STARTUP_DEBUG_PROBE_ASSERTS": str(many)}, + options=("--assert-sites", "3")) + assert "process exited with 0x00000000" in out, out + assert f"debug-probe repeated {many}\n" in text(logdir / "stdout.txt"), text(logdir / "stdout.txt") + assert breakpoint_sites(logdir, image).count(repeated[0]) == many, text(logdir / "events.txt") + # Control: a hit budget of three runs out at the repeated site's second hit. + out, _ = run(probe, work, "assert-sites-control", {"STARTUP_DEBUG_PROBE_ASSERTS": str(many)}, + options=("--continue-asserts", "3")) + assert f"stopped at breakpoint (0x80000003) at {image}+{repeated[0]:#x}" in out, out + # Two sites: the first hit at the third site stops the run. + out, logdir = run(probe, work, "assert-sites-two", {"STARTUP_DEBUG_PROBE_ASSERTS": str(many)}, + options=("--assert-sites", "2")) + assert f"stopped at breakpoint (0x80000003) at {image}+{repeated[0]:#x}" in out, out + assert breakpoint_sites(logdir, image).count(repeated[0]) == 1, text(logdir / "events.txt") + # X2W_STOP_AT still stops at a site the site budget covers. + out, _ = run(probe, work, "assert-sites-stop", {"X2W_STOP_AT": f"{sites[1]:x}"}, + options=("--assert-sites", "3")) + assert f"stopped at breakpoint (0x80000003) at {image}+{sites[1]:#x}" in out, out + # Both budgets: the hits A, B, A with --assert-sites 1 --continue-asserts 2. The site budget + # covers A, the hit budget B, and A's second hit is still A, so the probe runs to its end. + out, logdir = run(probe, work, "assert-sites-combined", {"STARTUP_DEBUG_PROBE_REVISIT": "1"}, + options=("--assert-sites", "1", "--continue-asserts", "2")) + assert "process exited with 0x00000000" in out, out + assert breakpoint_sites(logdir, image) == [sites[0], sites[1], sites[0]], text(logdir / "events.txt") + # Control: the hit budget alone runs out at A's second hit, so the site budget is what continues it. + out, _ = run(probe, work, "assert-sites-combined-control", {"STARTUP_DEBUG_PROBE_REVISIT": "1"}, + options=("--continue-asserts", "2")) + assert f"stopped at breakpoint (0x80000003) at {image}+{sites[0]:#x}" in out, out + out, _ = run(probe, work, "assert-sites-negative", {}, options=("--assert-sites", "-1")) + assert "expected an --assert-sites value of 0 or greater" in out, out + # X2W_DUMP_AT: a dump one second in, while the probe is still alive. out, logdir = run(probe, work, "dump", {"X2W_DUMP_AT": "1"}) assert "process exited with 0x00000000" in out, out diff --git a/tests/startup_debug_probe.cpp b/tests/startup_debug_probe.cpp index 4c1db8e51c..e4f2e4fcf1 100644 --- a/tests/startup_debug_probe.cpp +++ b/tests/startup_debug_probe.cpp @@ -1,6 +1,7 @@ // Input for the startup debugger's diagnostics check (tests/startup_debug_check.py). It reaches two // breakpoints in its own image, the way a retail image keeps soft asserts, and with -// STARTUP_DEBUG_PROBE_ASSERTS=<n> n more at a third site (the repeated-assert case). It also +// STARTUP_DEBUG_PROBE_ASSERTS=<n> n more at a third site (the repeated-assert case). With +// STARTUP_DEBUG_PROBE_REVISIT=1 it reaches the first breakpoint once more after the second. It also // reserves one large range, reports whether the loader gave it the debug heap, stays alive for a // moment and exits 0. // With STARTUP_DEBUG_PROBE_DLL=<file> and STARTUP_DEBUG_PROBE_EXPORT=<name> it also loads that DLL @@ -145,6 +146,9 @@ int main() { first_assert(); second_assert(); + if (const char* const revisit = std::getenv("STARTUP_DEBUG_PROBE_REVISIT"); revisit && *revisit == '1') { + first_assert(); + } const char* const repeated = std::getenv("STARTUP_DEBUG_PROBE_ASSERTS"); const int repeated_count = repeated ? std::atoi(repeated) : 0; repeated_assert(repeated_count); diff --git a/tests/startup_gameinput_contracts_check.cpp b/tests/startup_gameinput_contracts_check.cpp index ef56832b4f..780843e1d0 100644 --- a/tests/startup_gameinput_contracts_check.cpp +++ b/tests/startup_gameinput_contracts_check.cpp @@ -37,7 +37,7 @@ struct GamepadState { static_assert(sizeof(GamepadState) == 28, "GamepadState layout"); struct IGameInputDevice { - const void* const* vtbl; + void* const* vtbl; HRESULT QueryInterface(const GUID* iid, void** out) { @@ -72,7 +72,7 @@ struct IGameInputDevice { }; struct IGameInputReading { - const void* const* vtbl; + void* const* vtbl; HRESULT QueryInterface(const GUID* iid, void** out) { @@ -131,7 +131,7 @@ using DeviceCallback = void(__stdcall*)(std::uint64_t token, void* context, IGam std::uint32_t previousStatus); struct IGameInput { - const void* const* vtbl; + void* const* vtbl; HRESULT QueryInterface(const GUID* iid, void** out) { diff --git a/tests/startup_gameinput_history.cpp b/tests/startup_gameinput_history.cpp index 8afd0caa16..bf311a7a33 100644 --- a/tests/startup_gameinput_history.cpp +++ b/tests/startup_gameinput_history.cpp @@ -32,11 +32,11 @@ struct PadShared { }; struct IGameInputDevice { - const void* const* vtbl; + void* const* vtbl; }; struct IGameInputReading { - const void* const* vtbl; + void* const* vtbl; std::uint32_t Release() { @@ -61,7 +61,7 @@ struct IGameInputReading { }; struct IGameInput { - const void* const* vtbl; + void* const* vtbl; std::uint32_t Release() { diff --git a/tests/startup_gameinput_keys.cpp b/tests/startup_gameinput_keys.cpp index b25ea7acff..610f9c739b 100644 --- a/tests/startup_gameinput_keys.cpp +++ b/tests/startup_gameinput_keys.cpp @@ -40,11 +40,11 @@ static_assert(sizeof(GamepadState) == 28, "GamepadState layout"); // Minimal vtable-matching C++ views of GameInput v0 COM interfaces. struct IGameInputDeviceVtbl; struct IGameInputDevice { - const void* const* vtbl; + void* const* vtbl; }; struct IGameInputReading { - const void* const* vtbl; + void* const* vtbl; std::uint32_t AddRef() { @@ -93,7 +93,7 @@ using DeviceCallback = void(__stdcall*)(std::uint64_t token, void* context, IGam std::uint32_t previousStatus); struct IGameInput { - const void* const* vtbl; + void* const* vtbl; std::uint32_t Release() { diff --git a/tests/startup_gameinput_script.cpp b/tests/startup_gameinput_script.cpp index b7b861256f..fc861e3fd2 100644 --- a/tests/startup_gameinput_script.cpp +++ b/tests/startup_gameinput_script.cpp @@ -27,7 +27,7 @@ static_assert(sizeof(GamepadState) == 28, "GamepadState layout"); struct IGameInputDevice; struct IGameInputReading { - const void* const* vtbl; + void* const* vtbl; std::uint32_t Release() { @@ -42,7 +42,7 @@ struct IGameInputReading { }; struct IGameInput { - const void* const* vtbl; + void* const* vtbl; std::uint32_t Release() { diff --git a/tests/startup_gameinput_script_syntax.cpp b/tests/startup_gameinput_script_syntax.cpp index 226cfe9cb2..5edf5eede2 100644 --- a/tests/startup_gameinput_script_syntax.cpp +++ b/tests/startup_gameinput_script_syntax.cpp @@ -43,7 +43,7 @@ struct PadShared { }; struct IGameInputReading { - const void* const* vtbl; + void* const* vtbl; std::uint32_t Release() { using Fn = std::uint64_t(__stdcall*)(IGameInputReading*); @@ -56,7 +56,7 @@ struct IGameInputReading { } }; struct IGameInput { - const void* const* vtbl; + void* const* vtbl; HRESULT GetCurrentReading(std::uint32_t kind, void* device, IGameInputReading** reading) { using Fn = HRESULT(__stdcall*)(IGameInput*, std::uint32_t, void*, IGameInputReading**); diff --git a/tests/startup_gfx10_layout_check.cpp b/tests/startup_gfx10_layout_check.cpp index f0d54e13c1..4ea0f8d657 100644 --- a/tests/startup_gfx10_layout_check.cpp +++ b/tests/startup_gfx10_layout_check.cpp @@ -227,7 +227,8 @@ void check_refusals() refused("linear volume", d); d = good; d.Layout = static_cast<D3D12_TEXTURE_LAYOUT>(0x115); refused("XOR mode", d); d = good; d.Layout = static_cast<D3D12_TEXTURE_LAYOUT>(0x209); refused("layout outside 0x1xx", d); - d = good; d.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE3D; refused("volume", d); + d = good; d.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE3D; + d.Layout = static_cast<D3D12_TEXTURE_LAYOUT>(0x109); refused("volume outside 0x105", d); d = good; d.SampleDesc.Count = 4; refused("multisampled", d); d = good; d.Format = DXGI_FORMAT_R32G32B32_FLOAT; refused("12-byte texels", d); d = good; d.MipLevels = 16; refused("16 mips", d); @@ -285,9 +286,9 @@ void check_address_textures() d = texture(256, 256, 1, 1, DXGI_FORMAT_BC7_UNORM, 0x105); d.SampleDesc.Count = 2; expect("multisampled", d, false); - d = texture(256, 256, 1, 1, DXGI_FORMAT_BC7_UNORM, 0x105); + d = texture(256, 256, 1, 1, DXGI_FORMAT_BC7_UNORM, 0x109); d.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE3D; - expect("volume", d, false); + expect("volume outside 0x105", d, false); expect("BC1 width not whole blocks", texture(126, 128, 1, 1, DXGI_FORMAT_BC1_UNORM, 0x105), false); expect("BC1 height not whole blocks", texture(128, 126, 1, 1, DXGI_FORMAT_BC1_UNORM, 0x10a), false); expect("RGBA8 odd sides", texture(257, 129, 1, 1, DXGI_FORMAT_R8G8B8A8_UNORM, 0x106), true); diff --git a/tests/startup_gfx10_volume_check.cpp b/tests/startup_gfx10_volume_check.cpp index a7f617195c..17c9ba4156 100644 --- a/tests/startup_gfx10_volume_check.cpp +++ b/tests/startup_gfx10_volume_check.cpp @@ -6,14 +6,16 @@ // the texture padded to whole blocks; // - a mip chain: each layer of blocks holds the tail block, then the mips from the smallest to the largest, // and the tail mips sit at their origins inside the tail block; +// - a block-compressed volume: laid out as the uncompressed volume of its 4x4 blocks, one depth layer each; // - that every element of a volume gets its own bytes inside the texture, and that a tile followed by a // detile (with padded row and layer pitches) returns the texels it started from, for every mip; // - the descriptions it takes and refuses, and the slot-70 views it allows on them. // `--addrlib` compares the size and every element address of a set of volumes with // Addr2ComputeSurfaceInfo and Addr2ComputeSurfaceAddrFromCoord (ADDR_RSRC_TEX_3D, ADDR_SW_4KB_S) and // skips (77) when the build has no addrlib. `--mutate thin` lays each volume out as a thin 2D array of -// its depth layers, and `--mutate tail` puts every mip of the tail at the start of the tail block; both -// are negative controls and must fail. +// its depth layers, `--mutate tail` puts every mip of the tail at the start of the tail block, and +// `--mutate bc` sizes a block-compressed volume's blocks and mips by its texel sides instead of its 4x4 +// blocks; all three are negative controls and must fail. // // Reference: AMD addrlib as Mesa carries it under src/amd/addrlib, at the revision tools/fetch_addrlib.py // pins (Mesa 25.1.0, commit 5c142e46f3f6e752ed745fd48912ebb8fad67145): src/gfx10/gfx10SwizzlePattern.h, @@ -35,6 +37,7 @@ using x2w_startup::gfx10::Layout; int failures = 0; bool thin = false; // --mutate thin bool flat_tail = false; // --mutate tail +bool bc_texels = false; // --mutate bc void fail(const std::string& what) { @@ -60,6 +63,15 @@ D3D12_RESOURCE_DESC volume(UINT width, UINT height, UINT depth, DXGI_FORMAT form Layout layout_of(D3D12_RESOURCE_DESC d) { if (thin) d.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; + const x2w_startup::gfx10::Element element = x2w_startup::gfx10::element_of(d.Format); + if (bc_texels && element.texels > 1) { + // The same volume with an uncompressed element of the block's size: blocks and mips are sized + // by the texel sides, while the elements visited stay the 4x4 blocks. + d.Format = element.bytes == 8 ? DXGI_FORMAT_R16G16B16A16_UNORM : DXGI_FORMAT_R32G32B32A32_UINT; + Layout l(d); + l.texels = element.texels; + return l; + } Layout l(d); for (UINT mip = l.first_tail; flat_tail && mip < l.mips; ++mip) l.origin_x[mip] = l.origin_y[mip] = 0; return l; @@ -143,6 +155,34 @@ void check_mip_chain() expect("mip 2 next layer of blocks", at(l, 0, 0, 8, 2), 11 * 4096 + 0x800); } +// A block-compressed volume is the volume of its 4x4 blocks: BC1 64x64x16 with five mips takes the +// addresses of an 8-byte 16x16x16 volume with five mips, and BC7 48x20x9 with three mips those of a +// 16-byte 12x5x9 volume with three mips, element for element. +void check_block_compressed() +{ + struct Pair { + D3D12_RESOURCE_DESC bc, blocks; + }; + const Pair pairs[] = { + {volume(64, 64, 16, DXGI_FORMAT_BC1_UNORM, 0x105, 5), volume(16, 16, 16, DXGI_FORMAT_R16G16B16A16_UNORM, 0x105, 5)}, + {volume(48, 20, 9, DXGI_FORMAT_BC7_UNORM, 0x105, 3), volume(12, 5, 9, DXGI_FORMAT_R32G32B32A32_UINT, 0x105, 3)}, + }; + for (const Pair& pair : pairs) { + const Layout bc = layout_of(pair.bc), blocks = layout_of(pair.blocks); + const std::string name = "block-compressed " + std::to_string(pair.bc.Width) + "x" + std::to_string(pair.bc.Height); + if (bc.bytes() != blocks.bytes()) fail(name + ": size " + std::to_string(bc.bytes())); + bool same = true; + for (UINT mip = 0; mip < bc.mips; ++mip) { + if (bc.columns(mip) < blocks.columns(mip) || bc.rows(mip) < blocks.rows(mip) || bc.layers(mip) != blocks.layers(mip)) + same = false; + for (UINT z = 0; z < blocks.layers(mip); ++z) + for (UINT y = 0; y < blocks.rows(mip); ++y) + for (UINT x = 0; x < blocks.columns(mip); ++x) same = same && at(bc, x, y, z, mip) == at(blocks, x, y, z, mip); + } + if (!same) fail(name + ": an element differs from the uncompressed volume of its blocks"); + } +} + struct Shape { UINT width, height, depth; DXGI_FORMAT format; @@ -159,6 +199,12 @@ const Shape shapes[] = { {16, 16, 16, DXGI_FORMAT_R32G32B32A32_FLOAT, 5}, {8, 4, 8, DXGI_FORMAT_R8G8B8A8_UNORM, 4}, {64, 64, 64, DXGI_FORMAT_R16_FLOAT, 2}, {33, 17, 9, DXGI_FORMAT_R16G16B16A16_FLOAT, 6}, {4, 4, 64, DXGI_FORMAT_R8_UNORM, 7}, {256, 32, 8, DXGI_FORMAT_R16_FLOAT, 9}, + // Block-compressed volumes: 8- and 16-byte blocks, with and without a chain, sides that are not + // powers of two, and mips smaller than a block. + {64, 64, 16, DXGI_FORMAT_BC1_UNORM, 5}, {32, 32, 32, DXGI_FORMAT_BC7_UNORM, 6}, + {12, 20, 9, DXGI_FORMAT_BC5_UNORM, 5}, {256, 256, 8, DXGI_FORMAT_BC3_UNORM, 9}, + {4, 4, 4, DXGI_FORMAT_BC4_UNORM, 3}, {128, 128, 128, DXGI_FORMAT_BC5_SNORM, 8}, + {40, 8, 3, DXGI_FORMAT_BC6H_UF16, 1}, }; void check_distinct_and_round_trip() @@ -225,8 +271,8 @@ void check_descriptions() supported("more mips than a layout holds", d, false); d.MipLevels = 0; supported("no mips", d, false); - supported("BC1", volume(32, 32, 32, DXGI_FORMAT_BC1_UNORM), false); - supported("BC7", volume(32, 32, 32, DXGI_FORMAT_BC7_UNORM), false); + supported("BC1", volume(32, 32, 32, DXGI_FORMAT_BC1_UNORM), true); + supported("BC7 with a mip chain", volume(32, 32, 32, DXGI_FORMAT_BC7_UNORM, 0x105, 6), true); supported("4 KiB display", volume(32, 32, 32, DXGI_FORMAT_R8G8B8A8_UNORM, 0x106), false); supported("256 B standard", volume(32, 32, 32, DXGI_FORMAT_R8G8B8A8_UNORM, 0x101), false); supported("64 KiB standard", volume(32, 32, 32, DXGI_FORMAT_R8G8B8A8_UNORM, 0x109), false); @@ -250,7 +296,9 @@ void check_descriptions() d = good; d.Flags = D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; address("unordered access", d, false); - address("BC7", volume(32, 32, 32, DXGI_FORMAT_BC7_UNORM), false); + address("BC7", volume(32, 32, 32, DXGI_FORMAT_BC7_UNORM), true); + address("BC1 not whole blocks wide", volume(30, 32, 32, DXGI_FORMAT_BC1_UNORM), false); + address("BC1 any depth", volume(32, 32, 3, DXGI_FORMAT_BC1_UNORM), true); d = good; d.MipLevels = 6; address("mip chain", d, true); @@ -329,6 +377,19 @@ int addrlib_check() create.regValue.gbAddrConfig = 0x40 | 4u | (4u << 8); if (AddrCreate(&create, &created) != ADDR_OK) return 1; const AddrFormat addr_formats[5] = {ADDR_FMT_8, ADDR_FMT_16, ADDR_FMT_8_8_8_8, ADDR_FMT_16_16_16_16, ADDR_FMT_32_32_32_32}; + // A block-compressed format is passed as itself, so that addrlib turns its texel sides into blocks. + const auto addr_format = [&](DXGI_FORMAT f, UINT size) { + switch (f) { + case DXGI_FORMAT_BC1_UNORM: return ADDR_FMT_BC1; + case DXGI_FORMAT_BC2_UNORM: return ADDR_FMT_BC2; + case DXGI_FORMAT_BC3_UNORM: return ADDR_FMT_BC3; + case DXGI_FORMAT_BC4_UNORM: return ADDR_FMT_BC4; + case DXGI_FORMAT_BC5_UNORM: case DXGI_FORMAT_BC5_SNORM: return ADDR_FMT_BC5; + case DXGI_FORMAT_BC6H_UF16: return ADDR_FMT_BC6; + case DXGI_FORMAT_BC7_UNORM: return ADDR_FMT_BC7; + default: return addr_formats[size]; + } + }; std::vector<D3D12_RESOURCE_DESC> cases; for (const Shape& s : shapes) cases.push_back(volume(s.width, s.height, s.depth, s.format, 0x105, s.mips)); for (UINT size = 0; size < 5; ++size) @@ -342,6 +403,14 @@ int addrlib_check() for (const auto& side : chains) for (UINT mips = 2; ((std::max)({side[0], side[1], side[2]}) >> (mips - 1)) != 0; ++mips) cases.push_back(volume(side[0], side[1], side[2], by_size[size], 0x105, mips)); + // Every mip count of a set of block-compressed chains, for each BC format. + constexpr DXGI_FORMAT bc[] = {DXGI_FORMAT_BC1_UNORM, DXGI_FORMAT_BC2_UNORM, DXGI_FORMAT_BC3_UNORM, DXGI_FORMAT_BC4_UNORM, + DXGI_FORMAT_BC5_UNORM, DXGI_FORMAT_BC6H_UF16, DXGI_FORMAT_BC7_UNORM}; + constexpr UINT bc_chains[4][3] = {{64, 64, 16}, {12, 20, 9}, {4, 4, 32}, {256, 8, 8}}; + for (DXGI_FORMAT f : bc) + for (const auto& side : bc_chains) + for (UINT mips = 1; ((std::max)({side[0], side[1], side[2]}) >> (mips - 1)) != 0; ++mips) + cases.push_back(volume(side[0], side[1], side[2], f, 0x105, mips)); unsigned compared = 0, elements = 0, mismatches = 0; for (const D3D12_RESOURCE_DESC& d : cases) { const Layout l(d); @@ -354,7 +423,7 @@ int addrlib_check() in.flags.texture = 1; in.swizzleMode = ADDR_SW_4KB_S; in.resourceType = ADDR_RSRC_TEX_3D; - in.format = addr_formats[size]; + in.format = addr_format(d.Format, size); in.bpp = l.bytes_per_element * 8; in.width = l.width; in.height = l.height; @@ -387,8 +456,8 @@ int addrlib_check() ain.flags.texture = 1; ain.resourceType = ADDR_RSRC_TEX_3D; ain.bpp = in.bpp; - ain.unalignedWidth = l.width; - ain.unalignedHeight = l.height; + ain.unalignedWidth = l.columns(0); // in elements: 4x4 blocks for BC + ain.unalignedHeight = (l.height + l.texels - 1) / l.texels; ain.numSlices = l.depth; ain.numMipLevels = l.mips; ain.numSamples = 1; @@ -416,13 +485,15 @@ int main(int argc, char** argv) const bool mutate = argc == 3 && std::strcmp(argv[1], "--mutate") == 0; thin = mutate && std::strcmp(argv[2], "thin") == 0; flat_tail = mutate && std::strcmp(argv[2], "tail") == 0; - if (argc != 1 && !thin && !flat_tail) { - std::printf("usage: startup_gfx10_volume_check [--addrlib | --mutate thin | --mutate tail]\n"); + bc_texels = mutate && std::strcmp(argv[2], "bc") == 0; + if (argc != 1 && !thin && !flat_tail && !bc_texels) { + std::printf("usage: startup_gfx10_volume_check [--addrlib | --mutate thin | --mutate tail | --mutate bc]\n"); return 2; } check_equations(); check_block_order(); check_mip_chain(); + check_block_compressed(); check_distinct_and_round_trip(); check_descriptions(); if (failures) { @@ -430,6 +501,6 @@ int main(int argc, char** argv) return 1; } std::printf("startup_gfx10_volume: PASS (5 element sizes, block order, a mip chain, %zu volumes round-tripped mip by mip, " - "17 layouts, 8 address descriptions, 9 views)\n", sizeof(shapes) / sizeof(shapes[0])); + "17 layouts, 10 address descriptions, 9 views, 2 block-compressed volumes against their blocks)\n", sizeof(shapes) / sizeof(shapes[0])); return 0; } diff --git a/tests/startup_gfx2hlsl_compute_check.py b/tests/startup_gfx2hlsl_compute_check.py index fbd2436afd..928589a0c9 100644 --- a/tests/startup_gfx2hlsl_compute_check.py +++ b/tests/startup_gfx2hlsl_compute_check.py @@ -960,6 +960,9 @@ def expected(name): for i in range(16): out[i] = input_word(i // 8) return out + if name == 'O-loop-subset': + out[:8] = [9, 1, 2, 9, 9, 9, 9, 9] + return out if name == 'O-dword': for group in range(4): out[2 + group] = KEY ^ group @@ -1116,6 +1119,8 @@ def patch(words, old, new): words = patch(WORDS_G, '100034d804050000', '000034d804050000') words = patch(words, '0524dcd806000006', offset_bytes + 'dcd806000006') CASES[f'G-{field}-only'] = (source, words, *CASES['G'][2:]) +CASES['O-loop-subset'] = (LOOP_BREAK_SOURCE.replace('s_cbranch_scc0 6\n', 's_nop 0\n', 1), + patch(LOOP_BREAK_WORDS, '060084bf', '000080bf'), USER7 | TGID_X | tidig(1), (8, 1, 1), (1, 1, 1)) MBCNT_REFUSALS = ( @@ -1249,6 +1254,130 @@ def swap(at, new, code=EXIT_RUN_WORDS): assert any(reason in text for text, _ in refusals), refusals +def check_execz_mask_subset(): + """Pre-branch EXEC subset tracking (#2645 T1): sM <= EXEC carried into an execz block lets remasks preserve skipped bits.""" + # With the early exit branch replaced by s_nop, the counted loop still exercises s_mov_b32 exec_lo, s22 before + # s_cbranch_execz and s_andn2_b32 + s_mov_b32 exec_lo, s22 inside the skipped block. + def trace_loop(lanes, narrow_before=False): + outer = {lane for lane in lanes} + if narrow_before: + # Saving s22 before narrowing EXEC makes s22 a superset of EXEC at s_cbranch_execz, not a subset. + saved = set(outer) + exec_mask = {lane for lane in outer if lane < 1} + else: + saved = {lane for lane in outer if lane < 3} + exec_mask = set(saved) + values = dict.fromkeys(lanes, 9) + for counter in range(1, 4): + if exec_mask: + breaking = {lane for lane in exec_mask if counter > lane} + saved -= breaking + exec_mask = set(saved) # s_mov_b32 exec_lo, saved + values.update(dict.fromkeys(exec_mask, counter)) + exec_mask = set(saved) + return values + + lanes = range(8) + wave = trace_loop(lanes) + singles = [trace_loop([lane]) for lane in lanes] + assert list(wave.values()) == [s[lane] for lane, s in enumerate(singles)] == [9, 1, 2, 9, 9, 9, 9, 9] + # Near-miss wave-vs-singleton disagreement when the saved mask holds skipped lanes: lane 1 skips the block in the + # singleton model (9) while the wave enters via lane 0 and re-enables lane 1 through the stale saved mask (1). + bad_wave = trace_loop(lanes, narrow_before=True) + bad_singles = [trace_loop([lane], narrow_before=True) for lane in lanes] + assert bad_wave[1] == 1 and bad_singles[1][1] == 9 + + hlsl = translate('O-loop-subset').hlsl_cs() + assert 'exec = (s22) & 1;\n if (exec & 1) v5 = s24;' in hlsl, hlsl + # LOOP_BREAK_WORDS drops the T1 exec write refusal while keeping T2 (loop exit crosses a backward s_cbranch_scc0). + st = object.__new__(G.Stage) + st.kind = 'cs' + st.ins = G.decode(LOOP_BREAK_WORDS) + st.calculated_pc = {} + assert st.execz_refusals() == { + 0x30: 's_cbranch_scc0 inside a block s_cbranch_execz skips per lane: loop exit crosses a backward s_cbranch_scc0' + } + + # Build straight-line execz checks from llvm-mc-15 verified instructions in SPLICE / LOOP_BREAK_WORDS. + W = dict(SPLICE) + W.update({ + 's_nop 0': '000080bf', + 's_and_b32 s22, exec_lo, vcc_lo': '7e6a1687', + 's_mov_b32 s23, s22': '160397be', + 's_mov_b32 s24, 1': '810398be', + 'v_cmpx_gt_u32 s24, v0': '1800a87d', + 's_andn2_b32 s22, s22, exec_lo': '167e168a', + 's_andn2_b32 s23, s23, exec_lo': '177e178a', + 's_mov_b32 exec_lo, s22': '1603febe', + 's_mov_b32 exec_lo, s23': '1703febe', + 'v_mov_b32 v5, s24': '18020a7e', + 's_and_b32 exec_lo, exec_lo, vcc_lo': '7e6a7e87', + 's_mov_b32 s23, 0': '800397be', + 's_mov_b32 vcc_lo, -1': 'c103eabe', + }) + end = bytes.fromhex('000081bf') + def seq(*lines): + return WORDS_A[:STORE_A] + b''.join(bytes.fromhex(W[line]) for line in lines) + end + + # Accepted pre-branch subset setup without re-assigning EXEC directly before s_cbranch_execz. + pre_and_copy = seq( + 's_mov_b32 s21, exec_lo', 'v_cmp_gt_u32 vcc_lo, 3, v0', + 's_and_b32 s22, exec_lo, vcc_lo', 's_mov_b32 s23, s22', 's_mov_b32 s24, 1', + 's_cbranch_execz 4', 'v_cmpx_gt_u32 s24, v0', 's_andn2_b32 s23, s23, exec_lo', + 's_mov_b32 exec_lo, s23', 'v_mov_b32 v5, s24', 's_mov_b32 exec_lo, s21', + 'buffer_store_dword v5, v4, s[16:19], 0 offen', + ) + assert 'exec = (s23) & 1;' in translate('A', code=pre_and_copy).hlsl_cs() + pre_mov = seq( + 's_mov_b32 s21, exec_lo', 's_cbranch_execz 3', 's_mov_b32 exec_lo, s21', + 'v_mov_b32 v5, s24', 's_nop 0', 's_mov_b32 exec_lo, s21', + 'buffer_store_dword v5, v4, s[16:19], 0 offen', + ) + assert 'exec = (s21) & 1;' in translate('A', code=pre_mov).hlsl_cs() + + # Near-miss controls: each violates subset provenance and must stay refused as an exec write. + narrowed_saveexec = seq( + 's_mov_b32 s21, exec_lo', 'v_cmp_gt_u32 vcc_lo, 3, v0', 's_and_saveexec_b32 s0, vcc_lo', + 's_cbranch_execz 3', 's_mov_b32 exec_lo, s21', 'v_mov_b32 v5, s24', 's_nop 0', + 's_or_b32 exec_lo, exec_lo, s0', 'buffer_store_dword v5, v4, s[16:19], 0 offen', + ) + narrowed_cmpx = seq( + 's_mov_b32 s24, 1', 's_mov_b32 s21, exec_lo', 'v_cmpx_gt_u32 s24, v0', + 's_cbranch_execz 3', 's_mov_b32 exec_lo, s21', 's_nop 0', 's_nop 0', + 's_mov_b32 exec_lo, s21', + ) + overwritten_before = seq( + 's_mov_b32 s21, exec_lo', 's_mov_b32 exec_lo, vcc_lo', 's_mov_b32 vcc_lo, -1', + 's_cbranch_execz 3', 's_mov_b32 exec_lo, vcc_lo', 's_nop 0', 's_nop 0', + 's_mov_b32 exec_lo, s21', + ) + overwritten_inside = seq( + 's_mov_b32 s21, exec_lo', 's_mov_b32 exec_lo, vcc_lo', + 's_cbranch_execz 3', 's_mov_b32 vcc_lo, -1', 's_mov_b32 exec_lo, vcc_lo', 's_nop 0', + 's_mov_b32 exec_lo, s21', + ) + join_one_arm = seq( + 's_mov_b32 s21, exec_lo', 's_cbranch_scc1 2', 's_mov_b32 exec_lo, vcc_lo', 's_branch 2', + 's_mov_b32 vcc_lo, -1', 's_nop 0', + 's_cbranch_execz 3', 's_mov_b32 exec_lo, vcc_lo', 's_nop 0', 's_nop 0', + 's_mov_b32 exec_lo, s21', + ) + for near_miss in (narrowed_saveexec, narrowed_cmpx, overwritten_before, overwritten_inside, join_one_arm): + refused('s_mov_b32 inside a block s_cbranch_execz skips per lane: exec write', + lambda code=near_miss: translate('A', code=code).hlsl_cs()) + + # Unit checks for 64-bit moves and non-narrowing/invalidating steps in subset_after(). + assert G.subset_after('s_mov_b64', 's_mov_b64 exec, s[22:23]', {'exec', 'exec_hi', 'scc'}, G.EXEC_SUBSET) == ( + G.EXEC_SUBSET | {('s22', 0), ('s23', 1)}) + both = G.subset_after('s_mov_b64', 's_mov_b64 s[22:23], exec', {'s22', 's23', 'scc'}, G.EXEC_SUBSET) + assert both == (G.EXEC_SUBSET | {('s22', 0), ('s23', 1)}), both + assert G.subset_after('v_cmpx_gt_u32_e32', 'v_cmpx_gt_u32_e32 s24, v0', G.EXEC_KEYS, both) == G.EXEC_SUBSET + assert G.subset_after('s_movreld_b32', 's_movreld_b32 s0, s1', {'m0'}, both) == G.EXEC_SUBSET + assert G.subset_after('s_or_saveexec_b32', 's_or_saveexec_b32 s21, vcc_lo', + {'s21', 'exec', 'exec_hi', 'scc'}, {('exec', 0), ('exec_hi', 1), ('s22', 0)}) == ( + {('exec', 0), ('exec_hi', 1), ('s21', 0), ('s22', 0)}) + + def check_mbcnt(): for _, words, reason in MBCNT_REFUSALS: refused(reason, lambda: translate('D', code=bytes.fromhex(words + '000081bf'))) @@ -1802,6 +1931,7 @@ def check_controls(): check_mbcnt() check_execz_exit_run() check_execz_loop_break() + check_execz_mask_subset() check_lane_mask_data() check_lane_mask_high_word() check_lane_mask_compare_pair() @@ -2443,6 +2573,8 @@ def check_binary(llvm_mc): 'm-else-unswitched': ('M', 'exec = (s0 & ~exec) & 1;', 'exec = (s0) & 1;'), # the then lanes run the else arm 'n-unmasked': ('NM', 's23 = (vcc & exec) & 1;', 's23 = (vcc) & 1;'), # lanes 6 and 7 store with their stale vcc 'o-mask-kept': ('O', 's0 = (s0 & ~exec) & 1;', 's0 = (s0) & 1;'), # lanes 0-2 keep their bit and store + 'o-subset-remask-dropped': ('O-loop-subset', 'exec = (s22) & 1;\n if (exec & 1) v5 = s24;', + 'exec = 1u;\n if (exec & 1) v5 = s24;'), # broken lanes overwrite v5 'k-block-entered': ('K', 'pc = ((exec & 1) == 0) ? 2 : 1;', 'pc = 1; exec = 1;'), # skipped waves run it 'p-dropped-andn2': ('P', 's23 = (s23 & ~exec) & 1;', 's23 = (s23) & 1;'), # an entering lane keeps its old bit 'p-dropped-or': ('P', 's23 = (s23 | s22) & 1;', 's23 = (s23) & 1;'), # an entering lane loses its compare bit diff --git a/tests/startup_gfx2hlsl_v_dot2_check.py b/tests/startup_gfx2hlsl_v_dot2_check.py new file mode 100644 index 0000000000..1434c19028 --- /dev/null +++ b/tests/startup_gfx2hlsl_v_dot2_check.py @@ -0,0 +1,308 @@ +"""VOP3P 2-halfword integer dot products (v_dot2_i32_i16, v_dot2_u32_u16) in tools/startup/gfx2hlsl.py. + + (no arguments) VOP3P decode, on-demand helpers, value evaluation (wrapping and clamp, + including double-overflow cases), EXEC masking, refusal and mutation + controls, pure Python + draw <dxc> <offscreen_check> <warp|hardware> [fxc] + compile the translated pair with FXC ps_5_1 when given and with DXC ps_6_0, + draw one pixel per four input triples and compare the four result words + +RDNA 2 ISA, VOP3P (0x14 / 0x15): + V_DOT2_I32_I16 vD, S0, S1, S2 [clamp]: D = int16(S0.lo)*int16(S1.lo) + int16(S0.hi)*int16(S1.hi) + int32(S2) + V_DOT2_U32_U16 vD, S0, S1, S2 [clamp]: D = uint16(S0.lo)*uint16(S1.lo) + uint16(S0.hi)*uint16(S1.hi) + uint32(S2) +""" +import struct +import sys +import tempfile +from pathlib import Path + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE.parent / 'tools' / 'startup')) +sys.path.insert(0, str(HERE)) +import gfx2hlsl as G # noqa: E402 +from startup_flat_param_check import compile_hlsl, draw, root_blob # noqa: E402 +from startup_gfx2hlsl_bit_alu_check import ( # noqa: E402 + MASK, + POST_WORDS, + PRE_WORDS, + Probe, + check, + vs_words, + words_text, +) + +OPCODES = { + 'v_dot2_i32_i16': 0x14, + 'v_dot2_u32_u16': 0x15, +} + + +def vop3p(op, vdst, src0, src1, src2, *, clamp=0, op_sel=0, op_sel_hi=0b111, neg_lo=0, neg_hi=0, lit=None): + w0 = (0xcc000000 + | (op << 16) + | (clamp << 15) + | (((op_sel_hi >> 2) & 1) << 14) + | ((op_sel & 0x7) << 11) + | ((neg_hi & 0x7) << 8) + | (vdst & 0xff)) + w1 = (((neg_lo & 0x7) << 29) + | ((op_sel_hi & 0x3) << 27) + | ((src2 & 0x1ff) << 18) + | ((src1 & 0x1ff) << 9) + | (src0 & 0x1ff)) + out = struct.pack('<2I', w0, w1) + if lit is not None: + out += struct.pack('<I', lit & MASK) + return out + + +def ps_words(op, clamp=0): + code = OPCODES[op] + body = b''.join( + vop3p(code, 12 + lane, 256 + lane, 256 + 4 + lane, 256 + 8 + lane, clamp=clamp) + for lane in range(4) + ) + return PRE_WORDS + body + POST_WORDS + + +def translate(op, clamp=0): + zero = [(0, 0, 0)] * 4 + pipe = G.Pipeline(vs_words(zero), ps_words(op, clamp), root_blob()) + return pipe.hlsl_vs(), pipe.hlsl_ps() + + +def sext16(v): + v &= 0xffff + return v - 0x10000 if v >= 0x8000 else v + + +def sext32(v): + v &= MASK + return v - (1 << 32) if v >= (1 << 31) else v + + +def ref_dot2_u32_u16(a, b, c, clamp=False): + total = (c & MASK) + ((a & 0xffff) * (b & 0xffff)) + (((a >> 16) & 0xffff) * ((b >> 16) & 0xffff)) + if clamp and total > MASK: + return MASK + return total & MASK + + +def ref_dot2_i32_i16(a, b, c, clamp=False): + total = sext32(c) + (sext16(a) * sext16(b)) + (sext16(a >> 16) * sext16(b >> 16)) + if clamp: + if total > 0x7fffffff: + return 0x7fffffff + if total < -0x80000000: + return 0x80000000 + return total & MASK + + +def eval_dot2_u32_u16_hlsl(a, b, c, sat): + a, b, c = a & MASK, b & MASK, c & MASK + p0 = ((a & 0xffff) * (b & 0xffff)) & MASK + p1 = (((a >> 16) & 0xffff) * ((b >> 16) & 0xffff)) & MASK + r0 = (c + p0) & MASK + carry = 1 if r0 < c else 0 + r1 = (r0 + p1) & MASK + carry += 1 if r1 < r0 else 0 + return 0xffffffff if (sat and carry != 0) else r1 + + +def eval_dot2_i32_i16_hlsl(a, b, c, sat): + a, b, c = a & MASK, b & MASK, c & MASK + p0 = sext16(a) * sext16(b) + p1 = sext16(a >> 16) * sext16(b >> 16) + lo = c + hi = -1 if sext32(c) < 0 else 0 + t0 = (lo + (p0 & MASK)) & MASK + hi += (-1 if p0 < 0 else 0) + (1 if t0 < lo else 0) + lo = t0 + t1 = (lo + (p1 & MASK)) & MASK + hi += (-1 if p1 < 0 else 0) + (1 if t1 < lo else 0) + lo = t1 + if sat: + if hi > 0 or (hi == 0 and (lo & 0x80000000) != 0): + return 0x7fffffff + if hi < -1 or (hi == -1 and (lo & 0x80000000) == 0): + return 0x80000000 + return lo + + +def stage_refused(stage, op, line, needle=''): + try: + stage.one(op, line) + except G.Unsupported as exc: + return (not needle or needle in str(exc)) and not stage.lines + return False + + +WORDS_A = (0x00000000, 0xffffffff, 0x80008000, 0x7fff7fff, 0x80007fff, 0x00010002, 0xffff0001) +WORDS_B = (0x00000000, 0xffffffff, 0x80008000, 0x7fff7fff, 0x7fff8000, 0x00030004) +ACCUMS = (0x00000000, 0x00000001, 0x40000000, 0x7fffffff, 0x80000000, 0xc0000000, 0xffffffff) + + +def run_controls(): + # 1. Decode verification from synthetic gfx1013 VOP3P bytes via G.decode(). + check('decode v_dot2_i32_i16 plain', + G.decode(vop3p(0x14, 12, 256, 260, 264))[0][3] == 'v_dot2_i32_i16 v12, v0, v4, v8') + check('decode v_dot2_i32_i16 clamp', + G.decode(vop3p(0x14, 12, 256, 260, 264, clamp=1))[0][3] == 'v_dot2_i32_i16 v12, v0, v4, v8 clamp') + check('decode v_dot2_u32_u16 plain', + G.decode(vop3p(0x15, 12, 256, 260, 264))[0][3] == 'v_dot2_u32_u16 v12, v0, v4, v8') + check('decode v_dot2_u32_u16 clamp', + G.decode(vop3p(0x15, 12, 256, 260, 264, clamp=1))[0][3] == 'v_dot2_u32_u16 v12, v0, v4, v8 clamp') + + # 2. Exhaustive grid for both wrapping and saturating modes (including 2*2^30 = 2^31 signed & 2*0xfffe0001 unsigned). + u_ok = True + i_ok = True + for a in WORDS_A: + for b in WORDS_B: + for c in ACCUMS: + for sat in (False, True): + if eval_dot2_u32_u16_hlsl(a, b, c, sat) != ref_dot2_u32_u16(a, b, c, sat): + u_ok = False + if eval_dot2_i32_i16_hlsl(a, b, c, sat) != ref_dot2_i32_i16(a, b, c, sat): + i_ok = False + n_cases = len(WORDS_A) * len(WORDS_B) * len(ACCUMS) * 2 + check('v_dot2_u32_u16 grid (%d cases, wrap + clamp)' % n_cases, u_ok) + check('v_dot2_i32_i16 grid (%d cases, wrap + clamp)' % n_cases, i_ok) + + # 3. On-demand helper emission: each helper emitted only when its instruction is used. + _, ps_u = translate('v_dot2_u32_u16', 0) + _, ps_i = translate('v_dot2_i32_i16', 0) + check('dot2_u32_u16 emitted on demand and dot2_i32_i16 omitted', + 'uint dot2_u32_u16(' in ps_u and 'dot2_i32_i16' not in ps_u) + check('dot2_i32_i16 emitted on demand and dot2_u32_u16 omitted', + 'uint dot2_i32_i16(' in ps_i and 'dot2_u32_u16' not in ps_i) + check('dot2_i32_i16 helper uses strict unsigned carry compares', + '((t0 < lo) ? 1 : 0)' in ps_i and '((t1 < lo) ? 1 : 0)' in ps_i) + zero = [(0, 0, 0)] * 4 + unused_ps = G.Pipeline(vs_words(zero), PRE_WORDS + POST_WORDS, root_blob()).hlsl_ps() + check('both dot2 helpers omitted when unused', 'dot2_' not in unused_ps) + + # 4. EXEC masking & clamp flag propagation. + for op, helper in (('v_dot2_u32_u16', 'dot2_u32_u16'), ('v_dot2_i32_i16', 'dot2_i32_i16')): + p = Probe() + p.exec_known = False + p.one(op, '%s v12, v0, v4, v8 clamp' % op) + check('%s exec-masked + clamp' % op, + p.lines == ['if (exec & 1) v12 = %s(v0, v4, v8, true);' % helper]) + + # 5. Refusals: arity, non-clamp VOP3P modifiers, bad dst/src, source modifiers. + for op, code in OPCODES.items(): + check('%s 3 operands refused' % op, stage_refused(Probe(), op, '%s v1, v2, v3' % op, 'expected 4')) + check('%s 5 operands refused' % op, stage_refused(Probe(), op, '%s v1, v2, v3, v4, v5' % op, 'expected 4')) + for label, bad_word in ( + ('op_sel', vop3p(code, 12, 256, 260, 264, op_sel=1)), + ('op_sel_hi', vop3p(code, 12, 256, 260, 264, op_sel_hi=0)), + ('neg_lo', vop3p(code, 12, 256, 260, 264, neg_lo=1)), + ('neg_hi', vop3p(code, 12, 256, 260, 264, neg_hi=1)), + ): + asm = G.decode(bad_word)[0][3] + check('%s VOP3P %s refused' % (op, label), + stage_refused(Probe(), op, asm, 'unsupported modifiers')) + for bad_dst in ('s4', 'v[0:1]', 'v256'): + check('%s bad dst %s refused' % (op, bad_dst), + stage_refused(Probe(), op, '%s %s, v0, v4, v8' % (op, bad_dst), 'destination')) + for bad_src in ('|v0|', '-v0', 'neg(1)', 'v[0:1]', 's[0:1]', 'v256', 's106'): + check('%s bad src %s refused' % (op, bad_src), + stage_refused(Probe(), op, '%s v12, %s, v4, v8' % (op, bad_src))) + + # 6. Unlowered control: removing handlers from Stage restores refusals. + saved = {name: getattr(G.Stage, name) for name in ('op_v_dot2_i32_i16', 'op_v_dot2_u32_u16')} + try: + for name in saved: + delattr(G.Stage, name) + for op in OPCODES: + check('unlowered %s refused' % op, stage_refused(Probe(), op, '%s v12, v0, v4, v8' % op)) + try: + translate(op) + except G.Unsupported: + check('unlowered %s pipeline refused' % op, True) + else: + check('unlowered %s pipeline refused' % op, False) + finally: + for name, fn in saved.items(): + setattr(G.Stage, name, fn) + + +DRAW_CASES = ( + ('v_dot2_u32_u16', 0, [ + (0x00020003, 0x00040005, 0x3f800000), # 3*5 + 2*4 = +23 + (0x00100020, 0x01000200, 0x3f800000), # 32*512 + 16*256 = +20480 + (0x00010001, 0x00010001, 0xfffffffe), # wraps cleanly to 0x00000000 + (0x00000000, 0xffffffff, 0x40000000), # zero sum + ]), + ('v_dot2_u32_u16', 1, [ + (0x00020003, 0x00040005, 0x3f800000), # no saturation + (0xffffffff, 0xffffffff, 0x3f800000), # double overflow -> saturates to 0xffffffff + (0x80008000, 0x80008000, 0x80000000), # overflow -> saturates to 0xffffffff + (0x00000000, 0xffffffff, 0x3f800000), # zero sum + ]), + ('v_dot2_i32_i16', 0, [ + (0x00020003, 0x00040005, 0x3f800000), # +23 + (0xfffefffd, 0x00040005, 0x3f800000), # (-3)*5 + (-2)*4 = -23 + (0x80008000, 0x80008000, 0x80000000), # 2^30 + 2^30 - 2^31 = 0x00000000 + (0x00010000, 0xffff0000, 0x3f800000), # -1 + ]), + ('v_dot2_i32_i16', 1, [ + (0x80008000, 0x80008000, 0x00000000), # 2^30 + 2^30 = +2^31 -> saturates to 0x7fffffff + (0x80008000, 0x7fff7fff, 0x80000000), # negative overflow -> saturates to 0x80000000 + (0x80008000, 0x80008000, 0x80000000), # exact cancellation: 2^31 - 2^31 = 0x00000000 (NO sat!) + (0x00020003, 0x00040005, 0x3f800000), # no overflow + ]), + ('v_dot2_i32_i16', 1, [ + (0x00000003, 0x00010005, 0x3f800000), # p1 == 0: no carry, no saturation + (0x00030000, 0x00050001, 0xffffffff), # p0 == 0, c < 0: +14 + (0x00000000, 0x12345678, 0x7fffffff), # both products 0, c = INT32_MAX + (0x00000000, 0x00000000, 0x80000000), # both products 0, c = INT32_MIN + ]), +) + + +def run_draw(dxc, renderer, adapter, fxc=None): + run_controls() + compilers = ([('fxc', fxc, 'vs_5_1', 'ps_5_1')] if fxc else []) + [('dxc', dxc, 'vs_6_0', 'ps_6_0')] + with tempfile.TemporaryDirectory(prefix='x2w_v_dot2_') as tmp: + td = Path(tmp) + for kind, compiler, vs_profile, ps_profile in compilers: + first_vs = None + first_ps = None + first_exp = None + for op, clamp, triples in DRAW_CASES: + ref_fn = ref_dot2_i32_i16 if op == 'v_dot2_i32_i16' else ref_dot2_u32_u16 + _, ps_hlsl = translate(op, clamp) + ps_bin = compile_hlsl(compiler, kind, ps_hlsl, 'ps_%s_%d_%s' % (op, clamp, kind), ps_profile, td) + vs_hlsl = G.Pipeline(vs_words(triples), ps_words(op, clamp), root_blob()).hlsl_vs() + vs_bin = compile_hlsl(compiler, kind, vs_hlsl, 'vs_%s_%d_%s' % (op, clamp, kind), vs_profile, td) + raw_exp = tuple(ref_fn(a, b, c, bool(clamp)) for a, b, c in triples) + expected = words_text(raw_exp) + res = draw(renderer, adapter, vs_bin, ps_bin, expected) + if res.returncode == 77: + print('SKIP (%s): %s' % (adapter, res.stdout.strip() or res.stderr.strip())) + sys.exit(77) + if res.returncode != 0: + raise AssertionError('%s %s %s clamp=%d expected=%s\n%s\n%s' % ( + kind, adapter, op, clamp, expected, res.stdout, res.stderr)) + print('%s %s %s clamp=%d: %s' % (kind, adapter, op, clamp, expected), flush=True) + if first_vs is None: + first_vs, first_ps, first_exp = vs_bin, ps_bin, raw_exp + + bad = words_text((first_exp[0] ^ 1, first_exp[1], first_exp[2], first_exp[3])) + neg = draw(renderer, adapter, first_vs, first_ps, bad) + check('draw %s %s negative control rejects wrong expectation' % (kind, adapter), + neg.returncode != 0) + + +if __name__ == '__main__': + if len(sys.argv) == 1: + run_controls() + print('v_dot2 controls: ok') + elif len(sys.argv) in (5, 6) and sys.argv[1] == 'draw': + run_draw(sys.argv[2], sys.argv[3], sys.argv[4], sys.argv[5] if len(sys.argv) == 6 else None) + print('v_dot2 draw (%s): ok' % sys.argv[4]) + else: + print('usage: startup_gfx2hlsl_v_dot2_check.py [draw <dxc> <offscreen_check> <warp|hardware> [fxc]]', + file=sys.stderr) + sys.exit(2) diff --git a/tests/startup_image_2d_array_check.py b/tests/startup_image_2d_array_check.py index 4aaf0edc88..728971b38a 100644 --- a/tests/startup_image_2d_array_check.py +++ b/tests/startup_image_2d_array_check.py @@ -24,7 +24,7 @@ of a slice (root constant 1) at a constant mip level. They are drawn with --startup-image-2d-array-mips: a 4x4 texture of two slices with three mip levels whose cells all differ, texel (x, y) of slice s at mip m holding ((1 + x + 4y + 16s + 32m) / 128, x, y, s + 2m). The expected colours come from mip_cell() below. -Cube maps stay refused. The mip fixtures use spellings that llvm-mc 19 assembles; LLVM 15 is not known to +Cube loads stay refused (cube sampling: tests/startup_image_cube_check.py). The mip fixtures use spellings that llvm-mc 19 assembles; LLVM 15 is not known to accept them, so 'binary <llvm-mc> mip' is opt-in and CI does not pass it. """ import re @@ -261,7 +261,7 @@ def mip_controls(): G.D.MIMG_DIMS[5] = original assert G.D.MIMG_DIMS[5] == original - # Cube maps are refused as before. 2D and 3D keep their forms (same words, dim field changed). + # Cube loads are refused as before. 2D and 3D keep their forms (same words, dim field changed). cube = bytearray(MIP_IMAGE) cube[0] = 0x18 try: diff --git a/tests/startup_image_3d.cpp b/tests/startup_image_3d.cpp index 7d9b17557e..be18b7e5b7 100644 --- a/tests/startup_image_3d.cpp +++ b/tests/startup_image_3d.cpp @@ -27,6 +27,9 @@ namespace { constexpr UINT entry_constants = 4; // ud0..ud3 of the fixture's manifest constexpr UINT side = 2; constexpr UINT max_levels = 3; +// A cube fixture: six 4x4 faces, one level (dim:SQ_RSRC_IMG_CUBE, #2943). +constexpr UINT cube_faces = 6; +constexpr UINT cube_side = 4; // The value at texel (x, y) of slice s and mip level m. One level keeps the 2x2x2 fixture's values. With // several levels every (slice, mip, x, y) cell is distinct: the red channel is a dyadic fraction and @@ -68,13 +71,15 @@ ComPtr<ID3D12RootSignature> create_root(ID3D12Device* device, const x2w_startup: // comparison sampler (smpc), the texture uses DXGI_FORMAT_R32_FLOAT holding the red channel as depth. void check_startup_image_3d(ID3D12Device* device, const char* vertex_path, const char* pixel_path, float z, float color[4], const char* sampler_line, bool array, UINT levels, bool one_dimensional, - bool two_dimensional, UINT first_mip, UINT view_levels, UINT mip_base) + bool two_dimensional, UINT first_mip, UINT view_levels, UINT mip_base, bool cube) { + if (cube && (levels != 1 || array || one_dimensional || two_dimensional || view_levels)) + throw std::runtime_error("A cube image fixture has one level and no other layout"); if (levels < 1 || levels > max_levels || (levels > 1 && !array && !two_dimensional && !one_dimensional)) throw std::runtime_error("Unsupported image mip level count"); if (view_levels && ((!two_dimensional && !array) || first_mip >= levels || view_levels > levels - first_mip)) throw std::runtime_error("2D mip window exceeds the resource"); - const UINT base = levels > 1 ? mip_base : side; + const UINT base = cube ? cube_side : (levels > 1 ? mip_base : side); const auto vs = read_blob(vertex_path); const auto ps = read_blob(pixel_path); x2w_startup::TranslatedSamplers samplers; @@ -117,19 +122,19 @@ void check_startup_image_3d(ID3D12Device* device, const char* vertex_path, const D3D12_RESOURCE_DESC td{}; td.Dimension = one_dimensional ? D3D12_RESOURCE_DIMENSION_TEXTURE1D - : (array || two_dimensional) ? D3D12_RESOURCE_DIMENSION_TEXTURE2D + : (array || two_dimensional || cube) ? D3D12_RESOURCE_DIMENSION_TEXTURE2D : D3D12_RESOURCE_DIMENSION_TEXTURE3D; td.Width = base; td.Height = one_dimensional ? 1 : base; - td.DepthOrArraySize = (one_dimensional || two_dimensional) ? 1 : side; + td.DepthOrArraySize = cube ? cube_faces : (one_dimensional || two_dimensional) ? 1 : side; td.MipLevels = levels; td.Format = comparison ? DXGI_FORMAT_R32_FLOAT : DXGI_FORMAT_R32G32B32A32_FLOAT; td.SampleDesc.Count = 1; const auto texture = resource(device, td, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_STATE_COPY_DEST); // A volume is one subresource of two slices; an array is two subresources of one slice each. // The subresource of slice s and mip m is m + s * levels. - const UINT subresources = (array ? side : 1) * levels; - D3D12_PLACED_SUBRESOURCE_FOOTPRINT footprints[side * max_levels]{}; + const UINT subresources = (cube ? cube_faces : array ? side : 1) * levels; + D3D12_PLACED_SUBRESOURCE_FOOTPRINT footprints[cube_faces * max_levels]{}; UINT64 upload_size = 0; device->GetCopyableFootprints(&td, 0, subresources, 0, footprints, nullptr, nullptr, &upload_size); const D3D12_PLACED_SUBRESOURCE_FOOTPRINT& footprint = footprints[0]; @@ -142,13 +147,18 @@ void check_startup_image_3d(ID3D12Device* device, const char* vertex_path, const for (UINT tz = 0; tz < td.DepthOrArraySize; ++tz) for (UINT level = 0; level < levels; ++level) { const UINT extent = base >> level; - const auto& place = footprints[level + (array ? tz * levels : 0)]; + const auto& place = footprints[level + ((array || cube) ? tz * levels : 0)]; for (UINT ty = 0; ty < (one_dimensional ? 1u : extent); ++ty) for (UINT tx = 0; tx < extent; ++tx) { float texel[4]; texel_value(tx, ty, tz, level, levels, base, texel); if (one_dimensional) texel[3] = tx ? 0.75f : 0.5f; - auto* const slice = array ? start + place.Offset : start + place.Offset + tz * slice_pitch; + if (cube) { + // Every one of the 96 texels differs: face f, column tx and row ty. + const float face[4] = {(1.0f + tx + 4.0f * ty + 16.0f * tz) / 128.0f, float(tx), float(ty), float(tz)}; + std::memcpy(texel, face, sizeof(face)); + } + auto* const slice = (array || cube) ? start + place.Offset : start + place.Offset + tz * slice_pitch; const UINT texel_bytes = comparison ? sizeof(float) : sizeof(texel); std::memcpy(slice + ty * place.Footprint.RowPitch + tx * texel_bytes, texel, texel_bytes); } @@ -188,7 +198,15 @@ void check_startup_image_3d(ID3D12Device* device, const char* vertex_path, const view.Texture2D.MipLevels = view_levels; } } - device->CreateShaderResourceView(texture.Get(), view_levels ? &view : nullptr, views->GetCPUDescriptorHandleForHeapStart()); + if (cube) { + view.Format = td.Format; + view.ViewDimension = D3D12_SRV_DIMENSION_TEXTURECUBE; + view.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + view.TextureCube.MostDetailedMip = 0; + view.TextureCube.MipLevels = 1; + } + device->CreateShaderResourceView(texture.Get(), (view_levels || cube) ? &view : nullptr, + views->GetCPUDescriptorHandleForHeapStart()); hd = {D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 1, D3D12_DESCRIPTOR_HEAP_FLAG_NONE}; check(device->CreateDescriptorHeap(&hd, IID_PPV_ARGS(&rtvs)), "Create image 3D RTV heap"); const auto rtv = rtvs->GetCPUDescriptorHandleForHeapStart(); @@ -233,7 +251,7 @@ void check_startup_image_3d(ID3D12Device* device, const char* vertex_path, const std::memcpy(color, static_cast<std::uint8_t*>(mapped) + target_footprint.Offset, 4 * sizeof(float)); readback->Unmap(0, &none); std::printf("startup_image_%s z=%g color=(%g, %g, %g, %g)\n", - one_dimensional ? "1d" : two_dimensional ? "2d" : array ? "2d_array" : "3d", + cube ? "cube" : one_dimensional ? "1d" : two_dimensional ? "2d" : array ? "2d_array" : "3d", z, color[0], color[1], color[2], color[3]); } diff --git a/tests/startup_image_3d_check.py b/tests/startup_image_3d_check.py index 0cfc30d79e..bcc2ed62ea 100644 --- a/tests/startup_image_3d_check.py +++ b/tests/startup_image_3d_check.py @@ -107,11 +107,16 @@ def controls(): assert 'Texture1D<float4> r0' in pipe.hlsl_ps() assert 'r0.Sample(q0, F(v0))' in pipe.hlsl_ps() assert 'srv 0 tex1d table 0 0' in pipe.manifest() - unsupported = WORDS_1D.replace(bytes.fromhex('000f80f0'), bytes.fromhex('180f80f0')) + # The MIMG words carry no address count: the disassembler sizes the address from the dimension. With the cube + # dimension (field 3) the same words are a three-register cube sample, translated since #2943; the 2D MSAA + # dimension (field 6) stays an unverified dimension and must be refused. + cube = translate(WORDS_1D.replace(bytes.fromhex('000f80f0'), bytes.fromhex('180f80f0'))).hlsl_ps() + assert 'TextureCube<float4> r0' in cube and 'r0.Sample(q0, x2w_cube_dir(F(v0), F(v1), F(v2)))' in cube, cube + unsupported = WORDS_1D.replace(bytes.fromhex('000f80f0'), bytes.fromhex('300f80f0')) try: translate(unsupported) - except G.Unsupported: - pass + except G.Unsupported as error: + assert 'image dimension SQ_RSRC_IMG_2D_MSAA' in str(error), error else: raise AssertionError('unverified image dimension accepted') diff --git a/tests/startup_image_cube_check.py b/tests/startup_image_cube_check.py new file mode 100644 index 0000000000..b507e313a3 --- /dev/null +++ b/tests/startup_image_cube_check.py @@ -0,0 +1,393 @@ +"""Cube images in tools/startup/gfx2hlsl.py (dim:SQ_RSRC_IMG_CUBE, #2943). + + (no arguments) translation controls, pure Python + binary <llvm-mc> reassemble the fixture sources and compare them with the recorded words + draw <dxc> <offscreen_check> <warp|hardware> + translate, compile (DXC ps_6_0) and draw against a six-face TextureCube + +A gfx10 cube sample addresses the face coordinates s and t and then the face id. Mesa's prepare_cube_coords +(src/amd/common/nir/ac_nir_lower_tex.c) builds s = sc/|ma| + 1.5 and t = tc/|ma| + 1.5 from v_cubesc, v_cubetc +and v_cubema, and LLVM's ConstantFoldAMDGCNCubeIntrinsic defines v_cubema as twice the major coordinate, so s and +t lie in [1, 2] and s - 1, t - 1 are the position on the face. The translator rebuilds a direction from (s, t, +face) for TextureCube (x2w_cube_dir in the HLSL). + +tests/startup_image_3d.cpp, run as --startup-image-cube, binds six 4x4 R32G32B32A32_FLOAT faces as a TextureCube +whose texel (x, y) of face f holds ((1 + x + 4y + 16f) / 128, x, y, f), so all 96 texels differ. The sampler is the +all-zero inline sampler (point, wrap); every (s, t) is a texel centre (in {1.125, 1.375, 1.625, 1.875}). + +What the draws show: the literal cases feed (s, t, face) directly, without v_cube, and the reference is only the +address meaning above (x = floor(4 * (s - 1)), y = floor(4 * (t - 1))). The desktop driver selects the +face of the rebuilt direction itself, so a wrong face, sign, axis or 2.0 * (s - 1.5) / 2.0 * (t - 1.5) scale in +x2w_cube_dir reads another texel. The mutants edit one row of the emitted helper (sign of the u term flipped, u and v +exchanged, faces 2 and 3 exchanged, and dropping the 2.0 * scale on u or v) and must read the texel a D3D cube +lookup of the mutated direction gives. The end-to-end cases run the v_cube chain on six directions and must equal +both that reference and a desktop PS that samples the direction. +They do not show that the console's face order and orientation equal D3D's: that rests on LLVM's cube table +being the D3D11.3 cube face table. Only one mip is bound, so LOD and bias values are not tested; the image_sample_l +and image_sample_b draws only show that the extra address dword is not taken as a coordinate. +""" +import re +import struct +import subprocess +import sys +import tempfile +from pathlib import Path + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE.parent / 'tools' / 'startup')) +sys.path.insert(0, str(HERE)) +import gfx2hlsl as G # noqa: E402 +from startup_image_3d_check import FULLSCREEN_VS, VS_WORDS, assemble, compile_hlsl, root_blob # noqa: E402 + +INLINE_FLOATS = {0.0: 128, 0.5: 240, -0.5: 241, 1.0: 242, -1.0: 243, 2.0: 244, -2.0: 245, 4.0: 246, -4.0: 247} +PROLOGUE = bytes.fromhex('04040cf4000000fa' '800398be' '800399be' '80039abe' '80039bbe') +PROLOGUE_SOURCE = """\ +s_load_dwordx8 s[16:23], s[8:9], 0x0 +s_mov_b32 s24, 0 +s_mov_b32 s25, 0 +s_mov_b32 s26, 0 +s_mov_b32 s27, 0 +""" +EPILOGUE = bytes.fromhex('703f8cbf' '0f1800f800010203' '000081bf') +EPILOGUE_SOURCE = """\ +s_waitcnt vmcnt(0) +exp mrt0 v0, v1, v2, v3 done vm +s_endpgm +""" +WAIT = bytes.fromhex('7fc08cbf') +# First and second dword of each MIMG form on dim:SQ_RSRC_IMG_CUBE (field value 3), vdata v[0:3], vaddr v0, +# s[16:23] and s[24:27]; recorded from LLVM 15. +MIMG = { + 'sample': ('image_sample v[0:3], v[0:2], s[16:23], s[24:27] dmask:0xf dim:SQ_RSRC_IMG_CUBE', '180f80f00000c400'), + 'lz': ('image_sample_lz v[0:3], v[0:2], s[16:23], s[24:27] dmask:0xf dim:SQ_RSRC_IMG_CUBE', '180f9cf00000c400'), + 'l': ('image_sample_l v[0:3], v[0:3], s[16:23], s[24:27] dmask:0xf dim:SQ_RSRC_IMG_CUBE', '180f90f00000c400'), + 'b': ('image_sample_b v[0:3], v[0:3], s[16:23], s[24:27] dmask:0xf dim:SQ_RSRC_IMG_CUBE', '180f94f00000c400'), +} + + +def bits(value): + return struct.unpack('<I', struct.pack('<f', value))[0] + + +def v_mov(dst, value): + """v_mov_b32 vdst, value: an inline constant where LLVM uses one, else a literal.""" + if value in INLINE_FLOATS: + return struct.pack('<I', 0x7e000200 | dst << 17 | INLINE_FLOATS[value]), 'v_mov_b32 v%d, %s' % (dst, value) + return (struct.pack('<I', 0x7e0002ff | dst << 17) + struct.pack('<I', bits(value)), + 'v_mov_b32 v%d, 0x%08x' % (dst, bits(value))) + + +# image_sample_b needs a sampler with mipmapping (word 2 mip filter 1) and MAX_LOD 2 (word 1), as in +# startup_image_sample_b_check.py SAMPLER; only one mip is bound, so neither changes the texel. +B_SAMPLER = bytes.fromhex('04040cf4000000fa' '800398be' 'ff0399be00002000' 'ff039abe00000004' '80039bbe') +B_SAMPLER_SOURCE = PROLOGUE_SOURCE.replace('s_mov_b32 s25, 0', 's_mov_b32 s25, 0x200000').replace( + 's_mov_b32 s26, 0', 's_mov_b32 s26, 0x4000000') + + +def program(moves, form='lz', middle=b'', middle_source=''): + """The prologue, the given v_mov constants, an optional middle part, one cube sample and the export.""" + words, source = (bytearray(B_SAMPLER), B_SAMPLER_SOURCE) if form == 'b' else (bytearray(PROLOGUE), PROLOGUE_SOURCE) + for dst, value in moves: + w, s = v_mov(dst, value) + words += w + source += s + '\n' + words += middle + source += middle_source + text, mimg = MIMG[form] + words += WAIT + bytes.fromhex(mimg) + EPILOGUE + source += 's_waitcnt lgkmcnt(0)\n' + text + '\n' + EPILOGUE_SOURCE + return bytes(words), source + + +def texel(x, y, face): + return ','.join('%08x' % bits(c) for c in ((1 + x + 4 * y + 16 * face) / 128, x, y, face)) + + +def address_texel(s, t, face): + """The AMD cube address meaning: face-local position s - 1 and t - 1 on a 4x4 face.""" + return (min(3, max(0, int((s - 1.0) * 4))), min(3, max(0, int((t - 1.0) * 4))), face) + + +# The per-face (sc, tc) of v_cubesc and v_cubetc (LLVM ConstantFoldAMDGCNCubeIntrinsic), used here to model a D3D +# TextureCube lookup of a direction; LLVM's table is the D3D11.3 face table. +def cube_lookup(d): + x, y, z = d + ax, ay, az = abs(x), abs(y), abs(z) + if az >= ax and az >= ay: + face, sc, tc, ma = (5, -x, -y, z) if z < 0 else (4, x, -y, z) + elif ay >= ax: + face, sc, tc, ma = (3, x, -z, y) if y < 0 else (2, x, z, y) + else: + face, sc, tc, ma = (1, z, -y, x) if x < 0 else (0, -z, -y, x) + inv = 1.0 / abs(2 * ma) + return address_texel(sc * inv + 1.5, tc * inv + 1.5, face) + + +# The emitted helper rows, face 0 to 5, as (x, y, z) expressions in u and v. +ROWS = [('1.0', '-v', '-u'), ('-1.0', '-v', 'u'), ('u', '1.0', 'v'), ('u', '-1.0', '-v'), ('u', '-v', '1.0'), + ('-u', '-v', '-1.0')] + + +def row_line(face, row): + body = 'return float3(%s, %s, %s);' % row + return body if face == 5 else 'if (k == %d) %s' % (face, body) + + +def helper_dir(rows, s, t, face, su=2.0, sv=2.0): + u, v = su * (s - 1.5), sv * (t - 1.5) + return tuple(eval(c, {}, {'u': u, 'v': v}) for c in rows[face]) # noqa: S307 (fixed expressions above) + + +def flip_u(row): + return tuple(c.replace('-u', '#').replace('u', '-u').replace('#', 'u') for c in row) + + +def swap_uv(row): + return tuple(c.replace('u', '#').replace('v', 'u').replace('#', 'v') for c in row) + + +def mutants(): + """(label, edits [(old line, new line)], mutated rows, (su, sv)).""" + out = [] + for face in range(6): + for label, change in (('u sign flipped', flip_u), ('u and v exchanged', swap_uv)): + rows = list(ROWS) + rows[face] = change(ROWS[face]) + out.append(('face %d %s' % (face, label), [(row_line(face, ROWS[face]), row_line(face, rows[face]))], + rows, (2.0, 2.0))) + rows = list(ROWS) + rows[2], rows[3] = ROWS[3], ROWS[2] + out.append(('faces 2 and 3 exchanged', [(row_line(2, ROWS[2]), row_line(2, ROWS[3])), + (row_line(3, ROWS[3]), row_line(3, ROWS[2]))], rows, (2.0, 2.0))) + out.append(('u scale 2 dropped', [('clamp(2.0 * (s - 1.5), -1.0, 1.0)', 'clamp((s - 1.5), -1.0, 1.0)')], + ROWS, (1.0, 2.0))) + out.append(('v scale 2 dropped', [('clamp(2.0 * (t - 1.5), -1.0, 1.0)', 'clamp((t - 1.5), -1.0, 1.0)')], + ROWS, (2.0, 1.0))) + return out + + +# Literal (s, t, face) cases: outer-ring 4x4 texel centres so every face has x != y and dropping scale 2 moves texels. +CASES = [(1.125, 1.875, 0), (1.875, 1.125, 1), (1.125, 1.875, 2), (1.875, 1.125, 3), (1.875, 1.125, 4), (1.125, 1.875, 5), + (1.875, 1.875, 2)] +# End-to-end directions, one per face, each on a 4x4 texel centre with x != y. +DIRECTIONS = [(1.0, -0.75, 0.25), (-1.0, -0.75, -0.25), (0.75, 1.0, -0.25), (0.75, -1.0, 0.25), (0.75, 0.25, 1.0), + (-0.75, 0.25, -1.0)] +CHAIN_SOURCE = """\ +v_cubema_f32 v7, v4, v5, v6 +v_cubesc_f32 v8, v4, v5, v6 +v_cubetc_f32 v9, v4, v5, v6 +v_cubeid_f32 v2, v4, v5, v6 +v_rcp_f32_e64 v7, |v7| +v_mov_b32 v10, 0x3fc00000 +v_fma_f32 v0, v8, v7, v10 +v_fma_f32 v1, v9, v7, v10 +""" +CHAIN = bytes.fromhex('070047d5040b1a04' '080045d5040b1a04' '090046d5040b1a04' '020044d5040b1a04' + '0701aad507010000' 'ff02147e0000c03f' '00004bd5080f2a04' '01004bd5090f2a04') + + +def literal_program(s, t, face, form='lz'): + if form in ('lz', 'sample'): + return program([(0, s), (1, t), (2, float(face))], form) + if form == 'l': + return program([(0, s), (1, t), (2, float(face)), (3, 0.0)], form) + return program([(0, 0.0), (1, s), (2, t), (3, float(face))], form) # b: bias first + + +def chain_program(d): + return program([(4, d[0]), (5, d[1]), (6, d[2])], 'lz', CHAIN, CHAIN_SOURCE) + + +def desktop_ps(d): + return ('TextureCube<float4> r0 : register(t0);\nSamplerState q0 : register(s0);\n' + 'float4 main() : SV_Target { return r0.SampleLevel(q0, float3(%r, %r, %r), 0); }\n' % d) + + +def translate(words): + return G.Pipeline(VS_WORDS, words, root_blob()) + + +def expect_refused(call, needle): + try: + call() + except G.Unsupported as error: + assert needle in str(error), (needle, str(error)) + return str(error) + raise AssertionError('accepted, expected refusal containing %r' % needle) + + +def bare_image(how, mods, kind='ps'): + stage = G.Stage.__new__(G.Stage) + stage.kind = kind + return lambda: stage.image(['v[0:3]', 'v[0:2]', 's[16:23]', 's[24:27]'], mods, how) + + +def model_controls(): + values = {texel(x, y, f) for f in range(6) for y in range(4) for x in range(4)} + assert len(values) == 96, len(values) + for s, t, face in CASES: + # The helper rebuilds a direction that a D3D lookup maps back to the address texel. + assert cube_lookup(helper_dir(ROWS, s, t, face)) == address_texel(s, t, face), (s, t, face) + assert {f for s, t, f in CASES if address_texel(s, t, f)[0] != address_texel(s, t, f)[1]} == set(range(6)) + for d in DIRECTIONS: + x, y, face = cube_lookup(d) + assert x != y, d + assert sorted(cube_lookup(d)[2] for d in DIRECTIONS) == list(range(6)) + for label, _, rows, scale in mutants(): + assert any(cube_lookup(helper_dir(rows, s, t, f, *scale)) != address_texel(s, t, f) + for s, t, f in CASES), label + print('model: 96 distinct texels; helper rows invert a D3D lookup on %d cases; %d mutants each change a case' + % (len(CASES), len(mutants()))) + + +def controls(): + model_controls() + words, _ = literal_program(1.875, 1.125, 1) + pipe = translate(words) + ps, manifest = pipe.hlsl_ps(), pipe.manifest() + assert 'TextureCube<float4> r0 : register(t0);' in ps and 'Texture2DArray' not in ps, ps + assert 'r0.SampleLevel(q0, x2w_cube_dir(F(v0), F(v1), F(v2)), 0)' in ps, ps + assert 'float u = clamp(2.0 * (s - 1.5), -1.0, 1.0);' in ps, ps + assert 'float v = clamp(2.0 * (t - 1.5), -1.0, 1.0);' in ps, ps + for face, row in enumerate(ROWS): + assert row_line(face, row) in ps, (face, ps) + assert ps.count('float3 x2w_cube_dir(') == 1, ps + assert 'srv 0 texcube table 0 0' in manifest.splitlines(), manifest + for form, call in (('sample', 'r0.Sample(q0, x2w_cube_dir(F(v0), F(v1), F(v2)))'), + ('l', 'r0.SampleLevel(q0, x2w_cube_dir(F(v0), F(v1), F(v2)), F(v3))'), + ('b', 'r0.SampleBias(q0, x2w_cube_dir(F(v1), F(v2), F(v3)), F(v0))')): + ps = translate(literal_program(1.875, 1.125, 1, form)[0]).hlsl_ps() + assert call in ps, (form, ps) + # Other dimensions keep their declarations and calls. + from startup_image_2d_array_check import SAMPLE_WORDS, SAMPLE_CALL # noqa: E402 + ps = translate(SAMPLE_WORDS).hlsl_ps() + assert SAMPLE_CALL in ps and 'x2w_cube_dir' not in ps and 'TextureCube' not in ps, ps + print('translation: TextureCube r0 with x2w_cube_dir for sample, lz, l and b; manifest srv 0 texcube') + refusals = [ + (bare_image('load', ['dim:SQ_RSRC_IMG_CUBE', 'dmask:0xf']), 'image dimension SQ_RSRC_IMG_CUBE: Load'), + (bare_image('load_mip', ['dim:SQ_RSRC_IMG_CUBE', 'dmask:0xf']), 'image dimension SQ_RSRC_IMG_CUBE: Load'), + (bare_image('d', ['dim:SQ_RSRC_IMG_CUBE', 'dmask:0xf']), 'image_sample_d on SQ_RSRC_IMG_CUBE'), + (bare_image('get_lod', ['dim:SQ_RSRC_IMG_CUBE', 'dmask:0x3']), 'image_get_lod on SQ_RSRC_IMG_CUBE'), + (bare_image('lz', ['dim:SQ_RSRC_IMG_CUBE', 'dmask:0xf', 'a16']), 'image_sample_lz on SQ_RSRC_IMG_CUBE with a16'), + (bare_image('sample', ['dim:SQ_RSRC_IMG_CUBE', 'dmask:0xf', 'd16']), + 'image_sample on SQ_RSRC_IMG_CUBE with d16'), + (bare_image('l', ['dim:SQ_RSRC_IMG_CUBE', 'dmask:0xf'], kind='cs'), 'cube image in a compute program'), + ] + for call, needle in refusals: + expect_refused(call, needle) + # A constant sampler with DISABLE_CUBE_WRAP (word 0 bit 28) is refused; the bit clear is accepted above. + wrap = bytes.fromhex('ff0398be00000010') + words = literal_program(1.75, 1.25, 1)[0].replace(bytes.fromhex('800398be'), wrap, 1) + expect_refused(lambda: translate(words), 'DISABLE_CUBE_WRAP') + print('refused: cube load and load_mip, sample_d, get_lod, a16, d16, compute, DISABLE_CUBE_WRAP') + + +def check_binary(llvm_mc): + fixtures = [('literal %s' % (case,), *reversed(literal_program(*case))) for case in CASES] + fixtures += [('%s' % form, *reversed(literal_program(1.875, 1.125, 1, form))) for form in ('sample', 'l', 'b')] + fixtures += [('chain %s' % (d,), *reversed(chain_program(d))) for d in DIRECTIONS] + for name, source, words in fixtures: + built = assemble(llvm_mc, source) + if built != words: + raise AssertionError('%s fixture: assembled %s, recorded %s' % (name, built.hex(), words.hex())) + print('fixture words match llvm-mc (%d programs)' % len(fixtures)) + + +def check_draw(dxc, renderer, adapter): + with tempfile.TemporaryDirectory() as tmp: + directory = Path(tmp) + vs = compile_hlsl(dxc, 'dxc', FULLSCREEN_VS, 'fullscreen', 'vs_6_0', directory) + count = [0, 0] # reference draws that matched, controls and mutants that failed as predicted + + def draw(shader, expected, label, fail_reads=None, sampler=None): + run = subprocess.run([renderer, adapter, '--startup-image-cube', str(vs), str(shader), '0', expected] + + ([sampler] if sampler else []), capture_output=True, text=True) + if run.returncode == 77: + print(run.stdout + run.stderr) + sys.exit(77) + if not any(count): + for line in run.stdout.splitlines(): + if line.startswith(('backend=', 'adapter=', 'driver=')): + print(line) + if 'debug_layer=enabled' in run.stdout: + assert 'debug_errors=0 debug_warnings=0' in run.stdout, (run.stdout, run.stderr) + if fail_reads is None: + if run.returncode: + raise AssertionError('%s\n%s\n%s' % (label, run.stdout, run.stderr)) + print('%s: %s' % (label, expected), flush=True) + count[0] += 1 + else: + if run.returncode == 0 or 'actual=%s' % fail_reads not in run.stderr: + raise AssertionError('%s: control did not read %s\n%s\n%s' + % (label, fail_reads, run.stdout, run.stderr)) + print('%s: fails as expected, reads %s' % (label, fail_reads), flush=True) + count[1] += 1 + + def build(words, name): + return compile_hlsl(dxc, 'dxc', translate(words).hlsl_ps(), name, 'ps_6_0', directory) + + def sampler_line(words): + lines = [line for line in translate(words).manifest().splitlines() if line.startswith(('smp ', 'smpl '))] + assert len(lines) == 1, lines + return lines[0] + + for i, (s, t, face) in enumerate(CASES): + draw(build(literal_program(s, t, face)[0], 'lit%d' % i), texel(*address_texel(s, t, face)), + 'image_sample_lz s=%g t=%g face=%d' % (s, t, face)) + case = (1.875, 1.125, 1) + for form in ('sample', 'l', 'b'): + words = literal_program(*case, form)[0] + draw(build(words, 'form_%s' % form), texel(*address_texel(*case)), + 'image_sample%s s=%g t=%g face=%d' % ('' if form == 'sample' else '_' + form, *case), + sampler=sampler_line(words)) + # Guest-input controls: the face one higher and s, t exchanged must read those texels. + s, t, face = case + draw(build(literal_program(s, t, face + 1)[0], 'face_plus'), texel(*address_texel(*case)), + 'control face + 1', texel(*address_texel(s, t, face + 1))) + draw(build(literal_program(t, s, face)[0], 'swap_st'), texel(*address_texel(*case)), + 'control s and t exchanged', texel(*address_texel(t, s, face))) + # l and b with the face in the slot the translator reads as LOD or bias: another texel. + draw(build(program([(0, s), (1, t), (2, 0.0), (3, float(face))], 'l')[0], 'l_swapped'), + texel(*address_texel(*case)), 'control image_sample_l face and lod exchanged', + texel(*address_texel(s, t, 0))) + words = program([(0, float(face)), (1, s), (2, t), (3, 0.0)], 'b')[0] + draw(build(words, 'b_swapped'), texel(*address_texel(*case)), 'control image_sample_b face and bias exchanged', + texel(*address_texel(s, t, 0)), sampler=sampler_line(words)) + # Translator mutants: each edits the emitted helper and must read the texel a D3D lookup of its direction gives. + for index, (label, edits, rows, scale) in enumerate(mutants()): + hit = next((c for c in CASES if cube_lookup(helper_dir(rows, *c, *scale)) != address_texel(*c))) + source = translate(literal_program(*hit)[0]).hlsl_ps() + mutated = source + for old, new in edits: + assert mutated.count(old) == 1, (label, old) + mutated = mutated.replace(old, new) + assert mutated != source, label + shader = compile_hlsl(dxc, 'dxc', mutated, 'mutant%d' % index, 'ps_6_0', directory) + draw(shader, texel(*address_texel(*hit)), 'mutant %s (case %s)' % (label, hit), + texel(*cube_lookup(helper_dir(rows, *hit, *scale)))) + # End to end: the v_cube chain on six directions, against the reference and a desktop TextureCube draw. + for i, d in enumerate(DIRECTIONS): + expected = texel(*cube_lookup(d)) + draw(build(chain_program(d)[0], 'chain%d' % i), expected, 'v_cube chain d=%s' % (d,)) + native = compile_hlsl(dxc, 'dxc', desktop_ps(d), 'native%d' % i, 'ps_6_0', directory) + draw(native, expected, 'desktop TextureCube d=%s' % (d,)) + print('%d cube draws matched their references; %d controls and mutants read the texel they predict' + % tuple(count)) + + +def main(): + if len(sys.argv) == 1: + controls() + return + mode, *args = sys.argv[1:] + if mode == 'binary': + check_binary(args[0]) + elif mode == 'draw': + controls() + check_draw(*args) + else: + raise SystemExit(__doc__) + + +if __name__ == '__main__': + main() diff --git a/tests/startup_image_sample_b_check.py b/tests/startup_image_sample_b_check.py index 1842919cdd..3be4b1cc0b 100644 --- a/tests/startup_image_sample_b_check.py +++ b/tests/startup_image_sample_b_check.py @@ -529,7 +529,9 @@ def controls(): refused('c_b', 'image_sample_c_b') refused('offset', 'image_sample_b_o') refused('gather', 'image_gather4_b') - refused('cube', 'image dimension SQ_RSRC_IMG_CUBE') + # Since #2943 a cube lowers to TextureCube; the bias dword comes before the face address. + cube = stage('cube').hlsl_ps() + assert 'TextureCube<float4>' in cube and 'SampleBias(' in cube and 'x2w_cube_dir(F(v1), F(v2), F(v3)), F(v0))' in cube, cube refused('msaa', 'image dimension SQ_RSRC_IMG_') refused('dim1d', 'unverified 1D image b address or modifiers') refused('unorm', 'image_sample_b modifier unorm') @@ -543,7 +545,8 @@ def controls(): refused(name, 'image_sample_b modifier reserved') refused('sampler bias', 'image_sample_b with a sampler LOD bias (word 2 0x4000001)') refused('sampler bias sec', 'image_sample_b with a sampler LOD bias (word 2 0x4004000)') - print('refused: b_cl, c_b, offset, gather4_b, cube, MSAA, 1D, a16, d16, tfe, lwe, unorm, r128, dmask 0, ' + print('cube: TextureCube SampleBias with x2w_cube_dir') + print('refused: b_cl, c_b, offset, gather4_b, MSAA, 1D, a16, d16, tfe, lwe, unorm, r128, dmask 0, ' 'reserved bits, sampler LOD bias') # Guest sampler limits: carried over for a constant descriptor, refused where they cannot be shown irrelevant. diff --git a/tests/startup_image_sample_l_check.py b/tests/startup_image_sample_l_check.py index 72d4a0fffa..c5b83c2fa5 100644 --- a/tests/startup_image_sample_l_check.py +++ b/tests/startup_image_sample_l_check.py @@ -243,7 +243,9 @@ def controls(): refused('offset', 'image_sample_l_o') refused('compare', 'image_sample_c_l') refused('gather', 'image_gather4_l') - refused('cube', 'image dimension SQ_RSRC_IMG_CUBE') + # Since #2943 a cube lowers to TextureCube with the face address rebuilt as a direction, level after it. + cube = stage('cube') + assert 'TextureCube<float4>' in cube and 'x2w_cube_dir(F(v0), F(v1), F(v2)), F(v3))' in cube, cube refused('unorm', 'image_sample_l modifier unorm') refused('tfe', 'image_sample_l modifier tfe') # the extra status register is not modelled refused('a16', 'image_sample_l modifier a16') # packed 16-bit address: v[0:1] holds u, v and the level as halves @@ -259,7 +261,8 @@ def controls(): refused('msaa', 'image dimension SQ_RSRC_IMG_') for name in RESERVED: refused(name, 'image_sample_l modifier reserved') # bits LLVM ignores must not be silently accepted - print('refused: offset, compare, gather, cube, MSAA, unorm, a16, tfe, lwe, d16, r128, dmask 0, reserved bits') + print('cube: TextureCube SampleLevel with x2w_cube_dir') + print('refused: offset, compare, gather, MSAA, unorm, a16, tfe, lwe, d16, r128, dmask 0, reserved bits') # Cache-policy bits do not change the sampled value: same lowering as the plain form. for name in ('glc', 'slc', 'dlc'): diff --git a/tests/startup_indirect_draw_indexed.cpp b/tests/startup_indirect_draw_indexed.cpp index 943ee8ccff..563e9ab30b 100644 --- a/tests/startup_indirect_draw_indexed.cpp +++ b/tests/startup_indirect_draw_indexed.cpp @@ -993,7 +993,7 @@ bool run(ID3D12Device* device, ID3D12Device* guest, ID3D12RootSignature* writer_ std::memcpy(allocation, contents, vertex_bytes); const UINT bytes = vertex_bytes + (refusal == Refusal::indexed_vertex_range ? 4 : 0); const D3D12_VERTEX_BUFFER_VIEW vertex{reinterpret_cast<UINT64>(allocation), bytes, - rect ? sizeof(RectVertex) : sizeof(std::uint32_t)}; + static_cast<UINT>(rect ? sizeof(RectVertex) : sizeof(std::uint32_t))}; slot<VertexBuffer>(wrapped, 48)(wrapped, 0, 1, &vertex); } if (index_buffer) { diff --git a/tests/startup_local_log_check.cpp b/tests/startup_local_log_check.cpp index e59677c5f8..f2f5ec2a0e 100644 --- a/tests/startup_local_log_check.cpp +++ b/tests/startup_local_log_check.cpp @@ -7,6 +7,8 @@ // unmapped range is refused by the probe and the guarded copies with zero first-chance exceptions. #include "startup_stubs/local_log.h" +#include <intrin.h> + #include <atomic> #include <cstdint> #include <cstdio> @@ -713,11 +715,21 @@ void test_protected_prefix_not_counted() check(judged, "one round kept the free tail free to be judged"); } -// Without a debugger and without X2W_PROBE_PRECHECK the pre-check is off: a free range is still refused, but by -// the touch / __try path (nothing counted in faults_avoided) and the touch is a real first-chance fault. -int precheck_off_child() +// With X2W_PROBE_PRECHECK=0 the pre-check is off: a free range is still refused, but by the touch / __try path +// (nothing counted in faults_avoided) and the touch is a real first-chance fault. simulate_debugger sets the PEB's +// BeingDebugged byte first, which is what IsDebuggerPresent reads, so the explicit 0 must win over an attached +// debugger (title runs always start under debug_launch.py); no real debugger is attached, so faults still reach +// the vectored handler. +int precheck_off_child(bool simulate_debugger) { - if (IsDebuggerPresent()) return 0; // a debugger turns the pre-check on by design + auto* const being_debugged = reinterpret_cast<volatile unsigned char*>(__readgsqword(0x60) + 2); + const unsigned char was = *being_debugged; + if (simulate_debugger) { + *being_debugged = 1; + check(IsDebuggerPresent() != FALSE, "precheck off: the simulated debugger is visible to IsDebuggerPresent"); + } else if (IsDebuggerPresent()) { + return 0; // unset-style run under a real debugger: nothing to judge here + } constexpr std::size_t kPage = 0x1000; counted_thread = static_cast<LONG>(GetCurrentThreadId()); void* const handler = AddVectoredExceptionHandler(1, count_first_chance); @@ -740,11 +752,13 @@ int precheck_off_child() if (faults != 0) ++faulted; } RemoveVectoredExceptionHandler(handler); + *being_debugged = was; check(judged >= 5, "precheck off: enough rounds judged"); check(refused == judged, "precheck off: a free range is still not readable"); check(counted_rounds == 0, "precheck off: no refusal is counted as an avoided fault"); check(faulted == judged, "precheck off: the free range is found by the touch, one first-chance fault each"); - std::printf("startup_local_log precheck off: %d of %d FAILED\n", failures, cases); + std::printf("startup_local_log precheck off%s: %d of %d FAILED\n", simulate_debugger ? " (debugger)" : "", + failures, cases); return failures ? 1 : 0; } @@ -754,7 +768,8 @@ int main(int argc, char** argv) { const bool two_args = argc == 3; if (two_args && std::strcmp(argv[1], "--phase") == 0) { - if (std::strcmp(argv[2], "precheck-off") == 0) return precheck_off_child(); + if (std::strcmp(argv[2], "precheck-off") == 0) return precheck_off_child(false); + if (std::strcmp(argv[2], "precheck-off-debugger") == 0) return precheck_off_child(true); if (std::strcmp(argv[2], "concurrency") == 0) return concurrency_child(false); if (std::strcmp(argv[2], "concurrency-reopen") == 0) return concurrency_child(true); if (std::strcmp(argv[2], "recovery-missing") == 0) return recovery_child(Recovery::missing); diff --git a/tests/startup_map_drive_check.py b/tests/startup_map_drive_check.py new file mode 100644 index 0000000000..b62b00e49f --- /dev/null +++ b/tests/startup_map_drive_check.py @@ -0,0 +1,154 @@ +"""Check the launcher's --map-drive option (#1158). + +usage: startup_map_drive_check.py <consumer.exe> <debug_launch.py> <scratch dir> [overlap] + +A console executable opens its package at a fixed drive letter. The option rewrites an open on a +mapped letter to a real folder, in the caller's own path structure, so the package can live on any +volume. + +1. Mapped letter: the consumer opens a file through a letter that is not a real volume and reads it, + and the trace shows the rewrite. +2. Negative control: without the option the same open fails. +3. Unmapped letter: with the option, an open on a letter that is not mapped is left alone. +4. Reuse: one caller-owned name over 32 serial opens is restored after every return. +5. (overlap argument) Two threads, 32 opens each, with their own caller-owned names in flight at once: + all 64 opens must see the mapped name and succeed, every caller string must be back as built, and + the debugger must report no unprotected step window; three times. The control runs the same case + with --suspend-others 0 (the other thread is not held): it must lose at least one open in 8 runs. +""" +import os +import re +import shutil +import subprocess +import sys + +consumer, launcher, scratch = sys.argv[1:4] +python = sys.executable +# The serial and the overlap check run as two CTests that may run at the same time: each owns its folders. +overlap_mode = len(sys.argv) > 4 and sys.argv[4] == "overlap" +tag = "overlap" if overlap_mode else "serial" +failures = [] + + +def free_letter(): + """A letter that is not a mounted volume, so only the rewrite can make the open succeed.""" + for letter in "ZYXWVUTSRQPONMLKJIHG": + if not os.path.exists(letter + ":\\"): + return letter + return None + + +def run(letter, map_spec, log_name, mode="", extra=()): + log = os.path.join(scratch, f"map_drive_{tag}_{log_name}") + shutil.rmtree(log, ignore_errors=True) + env = dict(os.environ, X2W_PROBE_DRIVE=letter) + if mode: + env["X2W_PROBE_MODE"] = mode + command = [python, "-B", launcher, consumer, scratch, log, "--timeout", "15", "--memory-gib", "2", + "--trace-files", "1", "--continue-asserts", "0"] + command += list(extra) + if map_spec: + command += ["--map-drive", map_spec] + launcher_out = subprocess.run(command, capture_output=True, text=True, env=env, timeout=120).stdout + stdout_path = os.path.join(log, "stdout.txt") + files_path = os.path.join(log, "files.txt") + stdout = open(stdout_path, encoding="utf-8", errors="replace").read() if os.path.exists(stdout_path) else "" + trace = open(files_path, encoding="utf-8", errors="replace").read() if os.path.exists(files_path) else "" + return stdout, trace, launcher_out + + +letter = free_letter() +if not letter: + print("no free drive letter to map; skipping") + sys.exit(77) + +package = os.path.join(scratch, f"map_drive_pkg_{tag}") +shutil.rmtree(package, ignore_errors=True) +os.makedirs(package) +with open(os.path.join(package, "map_drive_probe.txt"), "w", encoding="ascii", newline="") as handle: + handle.write("mapped ok") +if overlap_mode: + # The second thread's file has a longer name; the contents tell the files apart in the trace-free case. + with open(os.path.join(package, "map_drive_probe_second_longer_name.txt"), "w", encoding="ascii", newline="") as handle: + handle.write("second file") + +if not overlap_mode: + # The launcher exits 0 whether or not the child succeeded, so the child's own output is the signal. + stdout, trace, _ = run(letter, f"{letter}={package}", "map_on") + ok = "mapped ok" in stdout and "MAP " in trace and "map_drive_pkg" in trace + print(f"mapped letter {letter}: {'ok' if ok else 'MISMATCH'} ({stdout.strip()!r})") + if not ok: + failures.append(f"mapped letter: stdout {stdout.strip()!r}, trace has MAP: {'MAP ' in trace}") + + stdout, trace, _ = run(letter, "", "map_off") + ok = "open failed" in stdout and "mapped ok" not in stdout + print(f"negative control without the option: {'ok' if ok else 'MISMATCH'} ({stdout.strip()!r})") + if not ok: + failures.append(f"negative control did not fail as expected: stdout {stdout.strip()!r}") + + stdout, trace, _ = run("C", f"{letter}={package}", "map_unmapped") + ok = "MAP " not in trace + print(f"unmapped letter C: {'ok' if ok else 'MISMATCH'}") + if not ok: + failures.append("an open on an unmapped letter was rewritten") + + # One caller-owned UNICODE_STRING through many opens: the borrowed name has to be given back after + # every return, and the backing allocation must be reused rather than grown per open. + stdout, trace, _ = run(letter, f"{letter}={package}", "map_reuse", mode="reuse") + name_buffers = trace.count("NAMEBUF alloc") + ok = "reuse ok" in stdout and name_buffers <= 1 and trace.count("MAP ") >= 32 + print(f"reused caller name over 32 opens: {'ok' if ok else 'MISMATCH'} " + f"(name allocations={name_buffers}, rewrites={trace.count('MAP ')})") + if not ok: + failures.append(f"reuse: stdout {stdout.strip()!r}, name allocations {name_buffers}, " + f"rewrites {trace.count('MAP ')}") + + +OPENS = 64 # two threads, 32 opens each + + +def overlap(label, extra): + """One two-thread run: (every open mapped and succeeded and every caller name restored, text, unprotected).""" + stdout, trace, launcher_out = run(letter, f"{letter}={package}", label, mode="overlap", extra=extra) + def mapped_opens(name): + return sum(1 for line in trace.splitlines() if " NtCreateFile " in line and "(mapped from " in line + and line.rstrip().endswith("-> 0x00000000") and f"\\{name} from " in line) + first, second = mapped_opens("map_drive_probe.txt"), mapped_opens("map_drive_probe_second_longer_name.txt") + mapped_ok = first + second + rewrites = trace.count("MAP ") + summary = re.search(r"hook windows: entries=\d+ windows=\d+ unprotected=(\d+)", launcher_out + trace) + unprotected = int(summary.group(1)) if summary else -1 + good = f"overlap ok: {OPENS} opens across two threads, both caller names intact" in stdout \ + and first == second == OPENS // 2 and rewrites == OPENS + return good, f"{stdout.strip()!r} (mapped opens traced {first} + {second}, rewrites {rewrites})", unprotected + + +if overlap_mode: + # With the other threads held for each step, every one of the 64 opens is rewritten, succeeds and gets + # its own caller-owned name back; the debugger reports no unprotected window. Three times. + for attempt in range(3): + good, text, unprotected = overlap(f"held{attempt}", []) + print(f"two overlapping threads, attempt {attempt}: {'ok' if good else 'MISMATCH'} {text} unprotected={unprotected}") + if not good or unprotected != 0: + failures.append(f"overlap attempt {attempt}: {text}, unprotected={unprotected}") + # Control (the broken copy): the same case without holding the other thread loses opens, and the + # debugger says so. If it never does in 8 runs the overlap was not exercised and the case above proves nothing. + lost = None + for attempt in range(8): + good, text, unprotected = overlap(f"free{attempt}", ["--suspend-others", "0"]) + if not good: + if unprotected <= 0: + failures.append(f"control attempt {attempt} lost opens but reported no unprotected window: {text}") + lost = text + break + print(f"control without holding the other thread: {'lost opens: ' + lost if lost else 'NEVER LOST'}") + if lost is None: + failures.append("the control never lost an open in 8 runs: the overlap was not exercised") + +shutil.rmtree(package, ignore_errors=True) +if failures: + print("FAIL") + for text in failures: + print(" " + text) + sys.exit(1) +print("PASS") diff --git a/tests/startup_map_drive_consumer.cpp b/tests/startup_map_drive_consumer.cpp new file mode 100644 index 0000000000..37c25b9f3d --- /dev/null +++ b/tests/startup_map_drive_consumer.cpp @@ -0,0 +1,229 @@ +// Source-built consumer for the launcher's --map-drive option (#1158). +// +// A console executable opens its package at a fixed drive letter. The letter comes from +// X2W_PROBE_DRIVE (default Z) because the launcher passes no program arguments. +// +// Two modes, chosen with X2W_PROBE_MODE: +// (default) one open of "<letter>:\map_drive_probe.txt" through CreateFileW, printing what it read. +// Under the launcher with --map-drive the open is rewritten and succeeds; without it, it +// fails, which is the negative control. +// reuse a caller-owned UNICODE_STRING is passed to NtCreateFile many times. After every return +// its length, buffer pointer and contents must be the ones the caller built, and every +// open must still succeed: the rewritten name is only borrowed for the duration of each +// call, and one backing buffer is reused rather than one allocation per open. +#include <windows.h> +#include <winternl.h> + +#include <cstdio> +#include <cwchar> + +namespace { +constexpr int reuse_opens = 32; + +// ntdll's declarations in <winternl.h> differ across SDK versions, so resolve the two entry points +// at run time: the fixture only needs to make the call, not to link against a signature. +using NtCreateFileFn = NTSTATUS(NTAPI*)(PHANDLE, ACCESS_MASK, POBJECT_ATTRIBUTES, PIO_STATUS_BLOCK, + PLARGE_INTEGER, ULONG, ULONG, ULONG, ULONG, PVOID, ULONG); +using NtCloseFn = NTSTATUS(NTAPI*)(HANDLE); + +bool resolve(HMODULE ntdll, NtCreateFileFn& create, NtCloseFn& close) +{ + create = reinterpret_cast<NtCreateFileFn>(GetProcAddress(ntdll, "NtCreateFile")); + close = reinterpret_cast<NtCloseFn>(GetProcAddress(ntdll, "NtClose")); + return create && close; +} + +wchar_t probe_letter() +{ + wchar_t letter = L'Z'; + wchar_t from_env[8]{}; + if (GetEnvironmentVariableW(L"X2W_PROBE_DRIVE", from_env, 8) == 1) letter = from_env[0]; + return letter; +} + +// One open through CreateFileW; the mapped letter has no volume of its own. +int single_open() +{ + wchar_t path[64]; + _snwprintf_s(path, 64, _TRUNCATE, L"%c:\\map_drive_probe.txt", probe_letter()); + HANDLE file = CreateFileW(path, GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, 0, nullptr); + if (file == INVALID_HANDLE_VALUE) { + std::printf("open failed: %lu\n", static_cast<unsigned long>(GetLastError())); + return 2; + } + char text[64]{}; + DWORD got = 0; + const BOOL ok = ReadFile(file, text, sizeof(text) - 1, &got, nullptr); + CloseHandle(file); + if (!ok) return 3; + std::printf("read %lu bytes: %s\n", static_cast<unsigned long>(got), text); + return 0; +} + +int reused_string() +{ + HMODULE ntdll = GetModuleHandleW(L"ntdll.dll"); + NtCreateFileFn create = nullptr; + NtCloseFn close = nullptr; + if (!ntdll || !resolve(ntdll, create, close)) { + std::printf("ntdll entry points not resolved\n"); + return 1; + } + wchar_t name[64]; + // NtCreateFile takes the NT form of the name; CreateFileW would add this prefix itself. + _snwprintf_s(name, 64, _TRUNCATE, L"\\??\\%c:\\map_drive_probe.txt", probe_letter()); + wchar_t built[64]; + wcscpy_s(built, name); + + UNICODE_STRING string{}; + string.Buffer = name; + string.Length = static_cast<USHORT>(std::wcslen(name) * sizeof(wchar_t)); + string.MaximumLength = string.Length; // exactly the caller's size, so a longer name must borrow + OBJECT_ATTRIBUTES attributes{}; + InitializeObjectAttributes(&attributes, &string, OBJ_CASE_INSENSITIVE, nullptr, nullptr); + + const USHORT length = string.Length, maximum = string.MaximumLength; + PWSTR buffer = string.Buffer; + for (int index = 0; index < reuse_opens; ++index) { + HANDLE handle = nullptr; + IO_STATUS_BLOCK status{}; + const NTSTATUS result = create(&handle, GENERIC_READ | SYNCHRONIZE, &attributes, &status, nullptr, + FILE_ATTRIBUTE_NORMAL, FILE_SHARE_READ, FILE_OPEN, + FILE_NON_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT, nullptr, 0); + if (result < 0) { + std::printf("reuse open %d failed: 0x%08lx\n", index, static_cast<unsigned long>(result)); + return 1; + } + close(handle); + // The launcher borrows the caller's name for the call only; it must be back exactly as built. + if (string.Length != length || string.MaximumLength != maximum || string.Buffer != buffer || + std::wcscmp(string.Buffer, built) != 0) { + std::printf("caller name changed after open %d: length=%u maximum=%u buffer_moved=%d text=%ls\n", + index, string.Length, string.MaximumLength, string.Buffer != buffer ? 1 : 0, + string.Buffer ? string.Buffer : L"(null)"); + return 1; + } + } + std::printf("reuse ok: %d opens, caller name intact after every return\n", reuse_opens); + return 0; +} +// Two threads open through the mapped letter at the same time with their own caller-owned names. +// Each rewritten name must stay valid for the call that is still in flight, so both threads must see +// their own mapped file and get their own UNICODE_STRING back. +struct Overlap { + HANDLE start; + wchar_t letter; + int opens; + LONG completed; + LONG broken; + LONG wrong_file; // an open that reached a file other than the one its own thread named +}; + +// The two threads name DIFFERENT files of DIFFERENT lengths, so a name buffer shared between the calls in +// flight would hand one thread the other's name (or a cut-off one) instead of its own file. +struct Worker { + Overlap* shared; + int index; +}; +const wchar_t* const overlap_file[2] = {L"map_drive_probe.txt", L"map_drive_probe_second_longer_name.txt"}; + + +DWORD WINAPI overlap_thread(LPVOID parameter) +{ + auto* worker = static_cast<Worker*>(parameter); + Overlap* shared = worker->shared; + const wchar_t* const file_name = overlap_file[worker->index]; + wchar_t name[96]; + _snwprintf_s(name, 96, _TRUNCATE, L"\\??\\%c:\\%ls", shared->letter, file_name); + wchar_t built[96]; + wcscpy_s(built, name); + + UNICODE_STRING string{}; + string.Buffer = name; + string.Length = static_cast<USHORT>(std::wcslen(name) * sizeof(wchar_t)); + string.MaximumLength = string.Length; + OBJECT_ATTRIBUTES attributes{}; + InitializeObjectAttributes(&attributes, &string, OBJ_CASE_INSENSITIVE, nullptr, nullptr); + const USHORT length = string.Length, maximum = string.MaximumLength; + PWSTR buffer = string.Buffer; + + HMODULE ntdll = GetModuleHandleW(L"ntdll.dll"); + NtCreateFileFn create = nullptr; + NtCloseFn close = nullptr; + if (!ntdll || !resolve(ntdll, create, close)) return 1; + const size_t file_length = std::wcslen(file_name); + + WaitForSingleObject(shared->start, INFINITE); + for (int index = 0; index < shared->opens; ++index) { + HANDLE handle = nullptr; + IO_STATUS_BLOCK status{}; + const NTSTATUS result = create(&handle, GENERIC_READ | SYNCHRONIZE, &attributes, &status, nullptr, + FILE_ATTRIBUTE_NORMAL, FILE_SHARE_READ, FILE_OPEN, + FILE_NON_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT, nullptr, 0); + if (result < 0) return 1; + // Which file did the call open? It has to be this thread's own, not the other thread's. + wchar_t final_path[MAX_PATH * 2]{}; + const DWORD got = GetFinalPathNameByHandleW(handle, final_path, MAX_PATH * 2, FILE_NAME_NORMALIZED); + const bool own_file = got > file_length && got < MAX_PATH * 2 && + _wcsicmp(final_path + got - file_length, file_name) == 0 && final_path[got - file_length - 1] == L'\\'; + close(handle); + if (!own_file) { + InterlockedIncrement(&shared->wrong_file); + return 1; + } + if (string.Length != length || string.MaximumLength != maximum || string.Buffer != buffer || + std::wcscmp(string.Buffer, built) != 0) { + InterlockedIncrement(&shared->broken); + return 1; + } + InterlockedIncrement(&shared->completed); + SwitchToThread(); // give the other thread a chance to be inside its own call + } + return 0; +} + +int overlapping_names() +{ + Overlap shared{}; + shared.start = CreateEventW(nullptr, TRUE, FALSE, nullptr); + shared.letter = probe_letter(); + shared.opens = 32; + if (!shared.start) return 1; + Worker workers[2] = {{&shared, 0}, {&shared, 1}}; + HANDLE threads[2] = {CreateThread(nullptr, 0, overlap_thread, &workers[0], 0, nullptr), + CreateThread(nullptr, 0, overlap_thread, &workers[1], 0, nullptr)}; + if (!threads[0] || !threads[1]) return 1; + SetEvent(shared.start); + WaitForMultipleObjects(2, threads, TRUE, 30000); + const DWORD first = WaitForSingleObject(threads[0], 0), second = WaitForSingleObject(threads[1], 0); + for (HANDLE thread : threads) CloseHandle(thread); + CloseHandle(shared.start); + if (first != WAIT_OBJECT_0 || second != WAIT_OBJECT_0) { + std::printf("overlap threads did not finish\n"); + return 1; + } + if (shared.wrong_file) { + std::printf("overlap: %ld opens reached another thread's file (a name was shared between calls)\n", shared.wrong_file); + return 1; + } + if (shared.broken) { + std::printf("overlap: a caller name was changed while its call was in flight\n"); + return 1; + } + if (shared.completed != 2 * shared.opens) { + std::printf("overlap incomplete: %ld of %d opens succeeded\n", shared.completed, 2 * shared.opens); + return 1; + } + std::printf("overlap ok: %ld opens across two threads, both caller names intact\n", shared.completed); + return 0; +} +} // namespace + +int main() +{ + wchar_t mode[16]{}; + const DWORD len = GetEnvironmentVariableW(L"X2W_PROBE_MODE", mode, 16); + if (len == 5 && _wcsicmp(mode, L"reuse") == 0) return reused_string(); + if (len == 7 && _wcsicmp(mode, L"overlap") == 0) return overlapping_names(); + return single_open(); +} \ No newline at end of file diff --git a/tests/startup_native_graphics_draw_check.py b/tests/startup_native_graphics_draw_check.py new file mode 100644 index 0000000000..b70a6ec9db --- /dev/null +++ b/tests/startup_native_graphics_draw_check.py @@ -0,0 +1,87 @@ +"""Exercise first-use native graphics translation and a fresh-process cache hit.""" +import os +import subprocess +import sys +import tempfile +from pathlib import Path + +from native_direct_container_check import patched_pixel, vertex +from startup_stream_draw_check import vop1, vop2 + + +def triangle(): + code = [vop2(0x1a, 1, 129, 0), vop2(0x1b, 1, 130, 1), vop2(0x1b, 2, 130, 0)] + for v in (1, 2): + code.extend([vop1(6, v, 256 + v), vop2(8, v, 244, v), vop2(3, v, 243, v)]) + code.extend([vop1(1, 3, 128), vop1(1, 4, 242), 0xf80008cf, 0x04030201, 0xbf810000]) + return vertex(program=code) + + +def check(folder, consumer, cli, sdk, adapter): + cache = folder / "cache" + cache.mkdir() + vs, ps, root, pixels = [folder / name for name in ("vs", "ps", "root", "pixels")] + vs.write_bytes(triangle()) + ps.write_bytes(patched_pixel(2, [vop1(1, 0, 128), vop1(1, 1, 242)], export=(0xf800180f, 0x01000001))) + env = dict(os.environ, X2W_SHADER_CACHE=str(cache), X2W_NATIVE_SHADERS=sdk, + X2W_D3D12_DEBUG="1", X2W_D3D12_RENDER="1", X2W_D3D12_PERMISSIVE="1", X2W_D3D12_LIST_NOOP="1") + env.pop("X2W_TEST_NATIVE_GRAPHICS_BAD_MANIFEST", None) + clear = bytes((0, 0, 255, 255)) + red = bytes((255, 0, 0, 255)) + args = [consumer, vs, ps, root, adapter, pixels] + for name, hits in (("cold", "0,0,0"), ("hot", "1,1,1")): + run = subprocess.run(args, env=env, capture_output=True, text=True, timeout=45) + if run.returncode == 77: + return 77 + if run.returncode or f"ready=1 cache(frontend,vs,ps)={hits}" not in run.stderr or "-> drawn;" not in run.stderr: + raise RuntimeError(run.stderr[-8000:]) + for line in run.stderr.splitlines(): + if "x2w-d3d12-debug " in line: + assert " sev=0 " not in line and " sev=1 " not in line, line + if "debug layer:" in line: + print(line) + print(run.stdout.strip()) + assert pixels.read_bytes() == (red * 4 + clear * 4) * 4 + print(f"{adapter} {name}: cache={hits}, 16 red and 16 clear pixels") + # A published disk pair must be used without attempting native compilation. + offline = subprocess.run([cli, "--watch", sdk, folder / "offline", cache, "--once"], + capture_output=True, text=True, timeout=45) + assert offline.returncode == 0 and "compiled graphics" in offline.stdout, (offline.stdout, offline.stderr) + key = next(cache.glob("req_*.a")).stem.removeprefix("req_") + published = [cache / f"{key}{suffix}" for suffix in (".txt", ".vs.cso", ".ps.cso")] + contents = [path.read_bytes() for path in published] + run = subprocess.run(args, env=env, capture_output=True, text=True, timeout=45) + assert run.returncode == 0 and "-> drawn;" in run.stderr, run.stderr + assert "native graphics " not in run.stderr, run.stderr + assert pixels.read_bytes() == (red * 4 + clear * 4) * 4 + assert [path.read_bytes() for path in published] == contents + print(f"{adapter} published disk pair: 16 red and 16 clear pixels, cache files unchanged") + + manifest = published[0] + retries = ( + ("unavailable DXC", {"X2W_NATIVE_SHADERS": str(folder / "missing-sdk")}, + (f"native graphics {key} refused:",)), + ("invalid native manifest", {"X2W_TEST_NATIVE_GRAPHICS_BAD_MANIFEST": "1"}, + (f"unsupported manifest version for {key}", f"native graphics {key} ready=0")), + ) + for failure, override, diagnostics in retries: + manifest.rename(Path(str(manifest) + ".pending")) + retry_env = dict(env, X2W_TEST_PUBLISH_MANIFEST=str(manifest), **override) + run = subprocess.run(args, env=retry_env, capture_output=True, text=True, timeout=45) + assert run.returncode == 0 and all(text in run.stderr for text in diagnostics), run.stderr + assert Path(str(pixels) + ".first").read_bytes() == clear * 32 + assert pixels.read_bytes() == (red * 4 + clear * 4) * 4 + assert [path.read_bytes() for path in published] == contents + print(f"{adapter} {failure}: disk publication recovers the next draw in the same process") + + ps.write_bytes(patched_pixel(1, [0xffffffff], export=(0xf800180f, 0x01000001))) + run = subprocess.run(args, env=env, capture_output=True, text=True, timeout=45) + assert run.returncode == 0 and "refused:" in run.stderr and "-> drawn;" not in run.stderr, run.stderr + assert pixels.read_bytes() == clear * 32 + print("unsupported stage: all 32 pixels retain the clear color") + return 0 + + +if __name__ == "__main__": + with tempfile.TemporaryDirectory() as directory: + sys.exit(check(Path(directory), *sys.argv[1:])) diff --git a/tests/startup_resource_retire_title.cpp b/tests/startup_resource_retire_title.cpp index 75b638474b..9645bda5f5 100644 --- a/tests/startup_resource_retire_title.cpp +++ b/tests/startup_resource_retire_title.cpp @@ -292,7 +292,9 @@ struct Context { upload->Unmap(0, nullptr); if (!require(own_allocator->Reset(), "own allocator") || !require(own_list->Reset(own_allocator.Get(), nullptr), "own list")) return false; - own_list->CopyTextureRegion(&footprint_tex(real.Get()), 0, 0, 0, &footprint(upload.Get()), nullptr); + D3D12_TEXTURE_COPY_LOCATION tex_dst = footprint_tex(real.Get()); + D3D12_TEXTURE_COPY_LOCATION tex_src = footprint(upload.Get()); + own_list->CopyTextureRegion(&tex_dst, 0, 0, 0, &tex_src, nullptr); D3D12_RESOURCE_BARRIER b{D3D12_RESOURCE_BARRIER_TYPE_TRANSITION, D3D12_RESOURCE_BARRIER_FLAG_NONE, {}}; b.Transition = {real.Get(), D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_COMMON}; @@ -314,7 +316,9 @@ struct Context { b.Transition = {real.Get(), D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_COPY_SOURCE}; own_list->ResourceBarrier(1, &b); - own_list->CopyTextureRegion(&footprint(readback.Get(), fmt, width), 0, 0, 0, &footprint_tex(real.Get()), nullptr); + D3D12_TEXTURE_COPY_LOCATION tex_dst = footprint(readback.Get(), fmt, width); + D3D12_TEXTURE_COPY_LOCATION tex_src = footprint_tex(real.Get()); + own_list->CopyTextureRegion(&tex_dst, 0, 0, 0, &tex_src, nullptr); b.Transition.StateBefore = D3D12_RESOURCE_STATE_COPY_SOURCE; b.Transition.StateAfter = D3D12_RESOURCE_STATE_COMMON; own_list->ResourceBarrier(1, &b); diff --git a/tests/startup_resource_retire_views.cpp b/tests/startup_resource_retire_views.cpp index 263dd96dcd..25842a0e23 100644 --- a/tests/startup_resource_retire_views.cpp +++ b/tests/startup_resource_retire_views.cpp @@ -226,7 +226,9 @@ struct Context { upload->Unmap(0, nullptr); if (!require(own_allocator->Reset(), "own allocator") || !require(own_list->Reset(own_allocator.Get(), nullptr), "own list")) return false; - own_list->CopyTextureRegion(&footprint_tex(real.Get()), 0, 0, 0, &footprint(upload.Get()), nullptr); + D3D12_TEXTURE_COPY_LOCATION tex_dst = footprint_tex(real.Get()); + D3D12_TEXTURE_COPY_LOCATION tex_src = footprint(upload.Get()); + own_list->CopyTextureRegion(&tex_dst, 0, 0, 0, &tex_src, nullptr); D3D12_RESOURCE_BARRIER b{D3D12_RESOURCE_BARRIER_TYPE_TRANSITION, D3D12_RESOURCE_BARRIER_FLAG_NONE, {}}; b.Transition = {real.Get(), D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_COMMON}; @@ -243,7 +245,9 @@ struct Context { b.Transition = {real.Get(), D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_COPY_SOURCE}; own_list->ResourceBarrier(1, &b); - own_list->CopyTextureRegion(&footprint(readback.Get()), 0, 0, 0, &footprint_tex(real.Get()), nullptr); + D3D12_TEXTURE_COPY_LOCATION tex_dst = footprint(readback.Get()); + D3D12_TEXTURE_COPY_LOCATION tex_src = footprint_tex(real.Get()); + own_list->CopyTextureRegion(&tex_dst, 0, 0, 0, &tex_src, nullptr); b.Transition.StateBefore = D3D12_RESOURCE_STATE_COPY_SOURCE; b.Transition.StateAfter = D3D12_RESOURCE_STATE_COMMON; own_list->ResourceBarrier(1, &b); diff --git a/tests/startup_run_ps1_check.py b/tests/startup_run_ps1_check.py index 3d0bc80b5f..f1d5b83ec0 100644 --- a/tests/startup_run_ps1_check.py +++ b/tests/startup_run_ps1_check.py @@ -20,6 +20,7 @@ RUN_PS1 = Path(__file__).resolve().parent.parent / "tools" / "startup" / "run.ps1" DLLS = ["xmem", "d3d12_xs", "AcpHal", "XCRDAPI", "chad", "xapu", "xg_xs", "GameInput"] STUB_LINES = [f"stub debugger line {n}" for n in range(1, 8)] +STUB_ERROR = "synthetic debugger error" HEAD_LINES = 5 # run.ps1 prints this many lines of "<LogDir>.out" # The stub stands in for tools/startup/debug_launch.py: it records its arguments, # prints seven lines and exits with the code under test. @@ -50,6 +51,8 @@ time.sleep(0.05) for n in range(1, 8): print("stub debugger line", n) +if {emit_stderr}: + print("synthetic debugger error", file=sys.stderr) sys.exit({code}) """ # Stands in for tools/startup/gfx2hlsl.py under -Translate: starts a child process, as the parallel @@ -79,7 +82,7 @@ WATCH_CLEANUP = re.compile( r"if\s*\(\s*\$translator\s+-and\s+-not\s+\$translator\.HasExited\s*\)\s*\{\s*&\s*\{\s*" r"""\$ErrorActionPreference\s*=\s*['"]Continue['"]\s+&\s+taskkill\.exe\b[^|#\n]*\s/T\b""", re.I) -CAPTURE = re.compile(r"\$(\w+)\s*=\s*\$LASTEXITCODE", re.I) +CAPTURE = re.compile(r"\$(?:script:)?(\w+)\s*=\s*\$LASTEXITCODE", re.I) EXIT = re.compile(r"exit\s+\$(\w+)", re.I) HEAD = 'Get-Content "$LogDir.out" -TotalCount 5' # Without -FakeUser, user APIs hit the host runtime; run.ps1 must warn (docs/startup-runtime.md). @@ -146,8 +149,8 @@ def alive(pid): def run_case(shell, script, code, work, translate=False, switches=(), passed=(), fake_user_env=False, - early_exit=False, trace_api_env=None, absolute_build=False, missing_build=False, - native=False, manifest="absent", cache_files=None): + early_exit=False, trace_api_env=None, absolute_build=False, missing_build=False, emit_stderr=False, + missing_python=False, real_log_error=False, native=False, manifest="absent", cache_files=None): """Run one copy of the script on a stub that exits with `code`; return what is wrong. `switches` are extra run.ps1 switches and `passed` the debugger arguments they must add. @@ -160,7 +163,11 @@ def run_case(shell, script, code, work, translate=False, switches=(), passed=(), startup = root / "tools" / "startup" startup.mkdir(parents=True) (startup / "run.ps1").write_bytes(script.encode("utf-8")) - (startup / "debug_launch.py").write_text(STUB.format(code=code, early_exit=early_exit), encoding="utf-8") + if real_log_error: + for name in ("debug_launch.py", "launch.py", "host_cpu.py", "hook_window.py", "window_capture.py"): + shutil.copyfile(RUN_PS1.parent / name, startup / name) + else: + (startup / "debug_launch.py").write_text(STUB.format(code=code, early_exit=early_exit, emit_stderr=emit_stderr), encoding="utf-8") (startup / "gfx2hlsl.py").write_text(WATCH_STUB.format(early_exit=early_exit), encoding="utf-8") shutil.copyfile(RUN_PS1.with_name("shader_cache_revision.py"), startup / "shader_cache_revision.py") if cache_files is not None: # a shader cache left by an earlier run @@ -175,6 +182,8 @@ def run_case(shell, script, code, work, translate=False, switches=(), passed=(), exe.parent.mkdir() exe.write_bytes(b"") data.mkdir() + if real_log_error: + (log / "events.txt").mkdir(parents=True) if manifest in ("normal", "bracket"): (data / "MicrosoftGame.config").write_text("<TitleId>1234</TitleId><SizeMB>42</SizeMB>", encoding="utf-8") if manifest.startswith("bracket"): @@ -197,13 +206,15 @@ def run_case(shell, script, code, work, translate=False, switches=(), passed=(), # In this tree run.ps1 finds `python` through PATH. This interpreter's directory # goes first so the stub runs under the Python that runs this check. env["PATH"] = os.path.dirname(sys.executable) + os.pathsep + env.get("PATH", "") + if missing_python: + env["PATH"] = str(Path(os.environ["SystemRoot"]) / "System32") build_arg = str(build) if absolute_build else "bld" if missing_build: build_arg = str(root / "missing build") command = [shell, "-NoProfile", "-ExecutionPolicy", "Bypass", "-File", str(startup / "run.ps1"), "-Exe", str(exe), "-DataDir", str(data), "-LogDir", str(log), "-BuildDir", build_arg, - "-Seconds", "9", "-MemoryGiB", "3", "-ContinueAsserts", "4", *switches] + "-Seconds", "9", "-MemoryGiB", "3", "-ContinueAsserts", "4", "-AssertSites", "2", *switches] sdk = root / "dxc" if native: sdk.mkdir() @@ -223,13 +234,23 @@ def run_case(shell, script, code, work, translate=False, switches=(), passed=(), stderr.seek(0) printed = [line.strip() for line in stdout if line.strip()] error_text = stderr.read().strip() + if missing_python: + return (["missing Python returned success"] if out.returncode == 0 else []) + ( + ["missing Python launched debugger"] if (startup / "debugger.json").exists() else []) + if real_log_error: + summary = Path(str(log) + ".out") + text = decode(summary.read_bytes()) if summary.is_file() else "" + return ([f"real debugger log error returned {out.returncode}, expected 1"] if out.returncode != 1 else []) + ( + ["real debugger log error was not captured in the summary"] if "PermissionError" not in text else []) found = [] for dll in DLLS: if not (exe.parent / f"{dll}.dll").is_file(): found.append(f"stand-in {dll}.dll was not copied") if out.returncode != code: found.append(f"stub debugger exited {code}, run.ps1 exited {out.returncode}") - want_output = STUB_LINES[:HEAD_LINES] + summary = Path(str(log) + ".out") + summary_lines = [line.strip() for line in decode(summary.read_bytes()).splitlines() if line.strip()] if summary.is_file() else [] + want_output = summary_lines[:HEAD_LINES] if emit_stderr else STUB_LINES[:HEAD_LINES] if cache_files is not None: # One warning with both revisions and the fixes; PowerShell may wrap it, so compare without whitespace. flat = re.sub(r"\s", "", " ".join(printed)) @@ -243,13 +264,15 @@ def run_case(shell, script, code, work, translate=False, switches=(), passed=(), if printed != want_output: found.append(f"stub exit {code}: printed {printed}, expected {want_output} " f"(stderr: {error_text!r})") - summary = Path(str(log) + ".out") if not summary.is_file(): found.append(f"stub exit {code}: {summary.name} was not written") - elif [line.strip() for line in decode(summary.read_bytes()).splitlines() if line.strip()] != STUB_LINES: + elif emit_stderr and ([line for line in summary_lines if line in STUB_LINES] != STUB_LINES or + not any(STUB_ERROR in line for line in summary_lines)): + found.append(f"stub exit {code}: {summary.name} does not hold stdout and stderr") + elif not emit_stderr and summary_lines != STUB_LINES: found.append(f"stub exit {code}: {summary.name} does not hold the debugger's output") want = [str(exe), str(data), str(log), "--timeout", "9", "--memory-gib", "3", - "--trace-files", "1", "--continue-asserts", "4", *passed] + "--trace-files", "1", "--continue-asserts", "4", "--assert-sites", "2", *passed] record = startup / "debugger.json" got = json.loads(record.read_text(encoding="utf-8")) if record.is_file() else None expected = [want, "1" if "-TraceApi" in switches else trace_api_env, @@ -284,6 +307,13 @@ def run_problems(shell, script, work, first_only): found += run_case(shell, script, 7, work, absolute_build=True) for manifest in ("normal", "bracket", "bracket_missing"): found += run_case(shell, script, 0, work, manifest=manifest) + if found and first_only: + return found + for code in (0, 7): + found += run_case(shell, script, code, work, emit_stderr=True) + if found and first_only: + return found + found += run_case(shell, script, 7, work, translate=True, emit_stderr=True) if found and first_only: return found found += run_case(shell, script, 0, work, switches=["-FakeUser"]) @@ -381,6 +411,8 @@ def shell_failures(shell, script, tmp): if mutant is None or not run_problems(shell, mutant, tmp, True): failures.append(f"{name}: mutant '{label}' was not detected") if shell: + failures += [f"{name}: {item}" for item in run_case(shell, script, 7, tmp, real_log_error=True)] + failures += [f"{name}: {item}" for item in run_case(shell, script, 7, tmp, missing_python=True)] missing = run_case(shell, script, 7, tmp, missing_build=True) if not any("debugger [argv" in item and "was None" in item for item in missing): failures.append(f"{name}: missing build directory did not prevent debugger startup") diff --git a/tests/startup_run_sh_check.py b/tests/startup_run_sh_check.py index 3198db2ace..f34b7b2425 100644 --- a/tests/startup_run_sh_check.py +++ b/tests/startup_run_sh_check.py @@ -216,7 +216,7 @@ def run_case(script, code, work, switches=(), passed=(), env_extra=None, drive_d log = data / "logs" command = ["bash", str(startup / "run.sh"), "--exe", str(exe), "--data", "G:\\" if drive_data else str(data), "--log", log_arg, "--build-dir", "bld", "--seconds", "9", "--memory-gib", "3", - "--continue-asserts", "4", *switches] + "--continue-asserts", "4", "--assert-sites", "2", *switches] if translate: command += ["--render", "--translate", "--shader-cache", "cache"] (startup / "translate.flag").write_bytes(b"") @@ -292,7 +292,7 @@ def run_case(script, code, work, switches=(), passed=(), env_extra=None, drive_d if missing: found.append(f"{label}: stand-in DLLs not copied next to the executable: {missing}") want = [win(exe), "G:\\" if drive_data else win(data), log_win, "--timeout", "9", "--memory-gib", "3", - "--trace-files", "1", "--continue-asserts", "4", *passed] + "--trace-files", "1", "--continue-asserts", "4", "--assert-sites", "2", *passed] got = read_json(startup / "argv.json") if got != want: found.append(f"{label}: the debugger received {got}, expected {want}") diff --git a/tests/startup_stage_package_check.py b/tests/startup_stage_package_check.py index a3ca4a7d18..a08145f767 100644 --- a/tests/startup_stage_package_check.py +++ b/tests/startup_stage_package_check.py @@ -1,4 +1,5 @@ """Exercise safe startup staging using synthetic files; no game package is needed.""" +import ctypes import os from pathlib import Path import subprocess @@ -93,6 +94,73 @@ def main(): assert not (location / "new-run").exists() finally: junction.rmdir() + + # The package can be named through an alias while the destination uses its real path. + # Both spellings must refer to the same tree for the separation check. + alias = root / "package-alias" + result = subprocess.run(["cmd.exe", "/c", "mklink", "/J", str(alias), str(package)], + capture_output=True, errors="replace", timeout=30) + assert result.returncode == 0, result.stdout + result.stderr + try: + nested = package / "new" / "run" + result = call(powershell, alias, exe.name, nested) + assert result.returncode != 0 and "separate from PackageDir" in result.stderr, result.stdout + result.stderr + assert not nested.exists() + safe = root / "alias-safe-run" + result = call(powershell, alias, exe.name, safe) + assert result.returncode == 0, result.stdout + result.stderr + assert (safe / exe.name).read_bytes() == original[exe.name] + finally: + alias.rmdir() + + # A path spelled inside the package can also lead outside through a junction. + outside_dir = root / "outside-dir" + outside_dir.mkdir() + (outside_dir / "outside.exe").write_bytes(b"outside executable") + escape = package / "escape" + result = subprocess.run(["cmd.exe", "/c", "mklink", "/J", str(escape), str(outside_dir)], + capture_output=True, errors="replace", timeout=30) + assert result.returncode == 0, result.stdout + result.stderr + try: + refused = root / "escape-run" + result = call(powershell, package, "escape/outside.exe", refused) + assert result.returncode != 0 and "inside PackageDir" in result.stderr, result.stdout + result.stderr + assert not refused.exists() + finally: + escape.rmdir() + + # A junction whose target stays inside the package remains usable. + inside = package / "inside" + result = subprocess.run(["cmd.exe", "/c", "mklink", "/J", str(inside), str(bin_dir)], + capture_output=True, errors="replace", timeout=30) + assert result.returncode == 0, result.stdout + result.stderr + try: + safe = root / "inside-run" + result = call(powershell, package, "inside/child.exe", safe) + assert result.returncode == 0, result.stdout + result.stderr + assert (safe / "child.exe").read_bytes() == b"child" + assert (safe / "side.DLL").read_bytes() == b"beside child" + finally: + inside.rmdir() + + # Volume GUID paths are returned as provider-qualified paths by PowerShell. + # Staging to a sibling must work, while the underlying package is still protected. + volume = ctypes.create_unicode_buffer(1024) + kernel = ctypes.WinDLL("kernel32", use_last_error=True) + kernel.GetVolumeNameForVolumeMountPointW.argtypes = [ctypes.c_wchar_p, ctypes.c_wchar_p, ctypes.c_uint32] + kernel.GetVolumeNameForVolumeMountPointW.restype = ctypes.c_int + if kernel.GetVolumeNameForVolumeMountPointW(package.anchor, volume, len(volume)): + volume_package = volume.value + str(package)[len(package.anchor):] + nested = package / "volume-nested" + result = call(powershell, volume_package, exe.name, nested) + assert result.returncode != 0 and "separate from PackageDir" in result.stderr, result.stdout + result.stderr + assert not nested.exists() + safe = root / "volume-safe" + result = call(powershell, volume_package, exe.name, safe) + assert result.returncode == 0, result.stdout + result.stderr + assert (safe / exe.name).read_bytes() == original[exe.name] + else: + print("volume GUID control skipped: temporary volume has no GUID path") print("safe startup staging: isolated executable/DLL copy, package preservation and overwrite/path guards passed") diff --git a/tests/startup_stream_consumer.cpp b/tests/startup_stream_consumer.cpp index 4b5f44da20..e0a7f665fd 100644 --- a/tests/startup_stream_consumer.cpp +++ b/tests/startup_stream_consumer.cpp @@ -7,6 +7,7 @@ #include <cstring> #include <wrl/client.h> +#include <algorithm> #include <array> #include <fstream> #include <iterator> @@ -171,7 +172,7 @@ static void* desktop_pipeline(void* device) // code-zero, data-zero, no-root, code-unreadable, code-past-end, data-unreadable, state-unreadable, // stateb-unreadable, desc-unreadable // dispatch, dispatch-swapped, dispatch-none, dispatch-records32, dispatch-sampled, dispatch-sampled-unbound, dispatch-sampled-2x1, dispatch-sampled-depth, dispatch-heap, -// dispatch-heap-outside, dispatch-heap-word*, dispatch-input-*: one creation, then dispatch_slot67 below +// dispatch-heap-outside, dispatch-heap-word*, dispatch-input-*, dispatch-output-*: one creation, then dispatch_slot67 below // texture-store and texture-array modes: one creation, then texture_slot67 below // The unreadable cases point at a PAGE_NOACCESS page; code-past-end ends the code on the last byte before one. static void* slot67_pipeline; @@ -219,22 +220,39 @@ static void* make_committed(void* device, D3D12_HEAP_TYPE type, const D3D12_RESO // Input descriptors the dispatch refuses, one reason each: dispatch-input-empty has zero records (a nonzero base, // word 3 zero), dispatch-input-past ends 16 bytes past the input buffer, dispatch-input-unplaced names memory between // the two buffers, dispatch-input-copied a third buffer placed there at an offset the desktop cannot alias, and +// dispatch-input-null (all four words zero, an unbound buffer) is not refused and reads zeros; // dispatch-input-token writes the token of a texture view where the input descriptor was. +// Output descriptors the dispatch refuses, one reason each: dispatch-output-texture-token, -unplaced and -copied do +// to the output what dispatch-input-token, -unplaced and -copied do to the input, dispatch-output-unaligned starts +// the output 8 bytes into its buffer and dispatch-output-state places the output buffer in the unordered access state. // For any mode, X2W_TEST_DISPATCH_IN names 1280 bytes that replace the input words, and X2W_TEST_DISPATCH_FIELDS // names six words that replace, for the input and then the output descriptor, the stride (word 1 bits 16-31), the // record count (word 2) and word 3, which are otherwise 4, 320 and 0. +// (The long case puts its input at 0x28000, not at a 64 KiB multiple like 0x20000: there the placed buffer would alias title memory +// and the input would be read in place, never snapshotted, which is how an earlier version of this case passed without a snapshot.) +// dispatch-input-snapshot-long: dispatch-input-snapshot with an 8 MiB input range (the descriptor declares 2M records; the program +// reads the first 320 words) dispatched in 48 frames, 384 MiB of snapshots in all, with the queue completed between frames. The +// snapshot pool holds 128 MiB, so every frame after the sixteenth reuses chunks the GPU is done with; a pool that is not recycled +// refuses them. Every frame must translate and give the first frame's words. // Table controls bind away from the heap start or change the root/view heap after slot 35 without rebinding. static int dispatch_slot67(IDXGIAdapter* adapter, void* device, const std::string& mode) { constexpr UINT words = 320; + const bool keep_closed = mode == "dispatch-input-snapshot-long-keep"; + const bool long_run = keep_closed || mode == "dispatch-input-snapshot-long"; + constexpr UINT long_records = 2u << 20, long_frames = 48; const bool shared_uav = mode == "dispatch-read-write-uav"; + const bool typed_output_offset = mode == "dispatch-records32-output-offset"; const bool indirect = mode.rfind("dispatch-indirect-", 0) == 0; + const bool heap_waterfall = mode.rfind("dispatch-heap-waterfall", 0) == 0; const bool pixel = mode.rfind("dispatch-indirect-pixel-", 0) == 0; const bool write_zero = mode == "dispatch-indirect-pixel-zero"; const bool root_srv = mode.rfind("dispatch-root-srv", 0) == 0; const UINT groups = mode == "dispatch-indirect-zero" || write_zero || mode == "dispatch-indirect-pixel-omit" ? 0u : mode == "dispatch-indirect-2" || mode == "dispatch-indirect-pixel-2" ? 2u : 5u; - auto* memory = static_cast<UINT*>(VirtualAlloc(nullptr, (indirect || root_srv) ? 0x30000 : 0x20000, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)); + const SIZE_T mem_bytes = heap_waterfall ? 0x60000 : long_run ? 0x28000 + long_records * sizeof(UINT) : + (indirect || root_srv) ? 0x30000 : 0x20000; + auto* memory = static_cast<UINT*>(VirtualAlloc(nullptr, mem_bytes, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)); if (!memory) return 70; UINT* const buffers[2] = {memory, memory + 0x10000 / sizeof(UINT)}; UINT* const buffer2 = memory + 0x20000 / sizeof(UINT); @@ -242,7 +260,7 @@ static int dispatch_slot67(IDXGIAdapter* adapter, void* device, const std::strin buffers[0][i] = 0x8b02a7f1u + i * 0x413b1u; buffers[1][i] = 0xc5c5c5c5u; } - UINT fields[2][3] = {{4, words, 0}, {4, words, 0}}; + UINT fields[2][3] = {{4, long_run ? long_records : words, 0}, {4, words, 0}}; const auto from_file = [](const char* variable, void* data, std::streamsize bytes) { char path[MAX_PATH]; const DWORD n = GetEnvironmentVariableA(variable, path, MAX_PATH); @@ -259,13 +277,29 @@ static int dispatch_slot67(IDXGIAdapter* adapter, void* device, const std::strin for (int i = 0; i < 2; ++i) { const D3D12_RESOURCE_DESC desc{D3D12_RESOURCE_DIMENSION_BUFFER, 0, words * sizeof(UINT), 1, 1, 1, DXGI_FORMAT_UNKNOWN, {1, 0}, D3D12_TEXTURE_LAYOUT_ROW_MAJOR, i ? D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS : D3D12_RESOURCE_FLAG_NONE}; - if (FAILED(static_cast<HRESULT>(invoke(device, 133, word(buffers[i]), word(&desc), D3D12_RESOURCE_STATE_COMMON, 0, + const auto state = i && mode == "dispatch-output-state" ? D3D12_RESOURCE_STATE_UNORDERED_ACCESS : D3D12_RESOURCE_STATE_COMMON; + if (FAILED(static_cast<HRESULT>(invoke(device, 133, word(buffers[i]), word(&desc), state, 0, word(&__uuidof(ID3D12Resource)), word(&placed[i]))))) return 71; const UINT64 address = reinterpret_cast<UINT64>(buffers[mode == "dispatch-same-buffer" ? 1 : i]); const UINT view[4] = {static_cast<UINT>(address), static_cast<UINT>(address >> 32) | fields[i][0] << 16, fields[i][1], fields[i][2]}; std::memcpy(descriptors[mode == "dispatch-swapped" ? 1 - i : i], view, sizeof(view)); } - const UINT64 between = reinterpret_cast<UINT64>(memory) + 0x8000; + UINT record_descs[4][4]{}; + if (heap_waterfall) { + for (UINT rec = 0; rec < 4; ++rec) { + UINT* const rec_buf = memory + (0x20000 + rec * 0x10000) / sizeof(UINT); + for (UINT i = 0; i < words; ++i) rec_buf[i] = 1000u * (rec + 1u) + 17u * i; + const D3D12_RESOURCE_DESC rdesc{D3D12_RESOURCE_DIMENSION_BUFFER, 0, words * sizeof(UINT), 1, 1, 1, + DXGI_FORMAT_UNKNOWN, {1, 0}, D3D12_TEXTURE_LAYOUT_ROW_MAJOR, D3D12_RESOURCE_FLAG_NONE}; + void* rec_res = nullptr; + if (FAILED(static_cast<HRESULT>(invoke(device, 133, word(rec_buf), word(&rdesc), D3D12_RESOURCE_STATE_COMMON, + 0, word(&__uuidof(ID3D12Resource)), word(&rec_res))))) return 71; + const UINT64 address = reinterpret_cast<UINT64>(rec_buf); + const UINT view[4] = {static_cast<UINT>(address), static_cast<UINT>(address >> 32) | (4u << 16), words, 0}; + std::memcpy(record_descs[rec], view, sizeof(view)); + } + } + const UINT64 between = reinterpret_cast<UINT64>(memory) + (long_run ? 0x28000 : 0x8000); void* placed2 = nullptr; if (root_srv) { for (UINT i = 0; i < words; ++i) buffer2[i] = 0x3c6ef372u + i * 0x19660du; @@ -278,8 +312,13 @@ static int dispatch_slot67(IDXGIAdapter* adapter, void* device, const std::strin if (FAILED(static_cast<HRESULT>(invoke(device, 133, word(buffer2), word(&desc), D3D12_RESOURCE_STATE_COMMON, 0, word(&__uuidof(ID3D12Resource)), word(&placed2))))) return 71; } - if (mode == "dispatch-input-copied" || mode == "dispatch-root-srv-copied") { - const D3D12_RESOURCE_DESC desc{D3D12_RESOURCE_DIMENSION_BUFFER, 0, words * sizeof(UINT), 1, 1, 1, DXGI_FORMAT_UNKNOWN, {1, 0}, + // dispatch-input-snapshot: the input words are written into the memory the third buffer is placed over, so they + // exist only in title memory (the desktop copy of a buffer that does not alias holds zeros); dispatch-input-copied + // leaves that memory zero. + if (mode == "dispatch-input-snapshot" || long_run) std::memcpy(reinterpret_cast<void*>(between), input, sizeof(input)); + if (mode == "dispatch-input-copied" || mode == "dispatch-input-snapshot" || long_run || mode == "dispatch-root-srv-copied" || + mode == "dispatch-output-copied") { + const D3D12_RESOURCE_DESC desc{D3D12_RESOURCE_DIMENSION_BUFFER, 0, long_run ? long_records * sizeof(UINT) : words * sizeof(UINT), 1, 1, 1, DXGI_FORMAT_UNKNOWN, {1, 0}, D3D12_TEXTURE_LAYOUT_ROW_MAJOR}; void* copied = nullptr; if (FAILED(static_cast<HRESULT>(invoke(device, 133, word(reinterpret_cast<void*>(between)), word(&desc), D3D12_RESOURCE_STATE_COMMON, 0, @@ -288,16 +327,30 @@ static int dispatch_slot67(IDXGIAdapter* adapter, void* device, const std::strin if (mode == "dispatch-input-empty") { const UINT view[4] = {0x32c, 0, 0, 0}; std::memcpy(descriptors[0], view, sizeof(view)); + } else if (mode == "dispatch-input-null") { + std::memset(descriptors[0], 0, sizeof(descriptors[0])); // an unbound buffer: all four words zero } else if (mode == "dispatch-input-past") { descriptors[0][2] = words + 4; - } else if (mode == "dispatch-input-unplaced" || mode == "dispatch-input-copied") { + } else if (mode == "dispatch-input-unplaced" || mode == "dispatch-input-copied" || mode == "dispatch-input-snapshot" || long_run) { descriptors[0][0] = static_cast<UINT>(between); descriptors[0][1] = static_cast<UINT>(between >> 32) | 4u << 16; + } else if (mode == "dispatch-output-unplaced" || mode == "dispatch-output-copied") { + descriptors[1][0] = static_cast<UINT>(between); + descriptors[1][1] = static_cast<UINT>(between >> 32) | 4u << 16; + } else if (mode == "dispatch-output-unaligned") { + descriptors[1][0] += 8; // still inside the buffer: 318 records + descriptors[1][2] = words - 2; + } else if (typed_output_offset) { + const UINT64 address = reinterpret_cast<UINT64>(buffers[1]) + 8; + descriptors[1][0] = static_cast<UINT>(address); + descriptors[1][1] = static_cast<UINT>(address >> 32) | fields[1][0] << 16; } + const bool heap_short = mode == "dispatch-heap-waterfall-short"; const struct { D3D12_DESCRIPTOR_HEAP_DESC desc; UINT64 backing, bytes; - } heap_desc{{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 4, D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE}, 0, 0}; + } heap_desc{{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, heap_waterfall ? (heap_short ? 3u : 5u) : 4u, + D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE}, 0, 0}; void *heap = nullptr, *queue = nullptr, *allocator = nullptr, *list = nullptr, *fence = nullptr; // dispatch-sampled-compute records the same calls on a compute list and queue. const D3D12_COMMAND_LIST_TYPE list_type = mode == "dispatch-sampled-compute" ? D3D12_COMMAND_LIST_TYPE_COMPUTE : D3D12_COMMAND_LIST_TYPE_DIRECT; @@ -330,7 +383,7 @@ static int dispatch_slot67(IDXGIAdapter* adapter, void* device, const std::strin } else { std::memcpy(reinterpret_cast<void*>(cpu), descriptors, sizeof(descriptors)); } - if (mode == "dispatch-records32" || shared_uav) { // the output's descriptor at table byte 32, none at byte 16 + if (mode == "dispatch-records32" || typed_output_offset || shared_uav) { // output at byte 32, none at byte 16 std::memset(reinterpret_cast<void*>(cpu + sizeof(descriptors[0])), 0, sizeof(descriptors[1])); std::memcpy(reinterpret_cast<void*>(cpu + 32), descriptors[1], sizeof(descriptors[1])); } @@ -338,12 +391,29 @@ static int dispatch_slot67(IDXGIAdapter* adapter, void* device, const std::strin if (change_table_heap && (FAILED(static_cast<HRESULT>(invoke(device, 14, word(&heap_desc), word(&__uuidof(ID3D12DescriptorHeap)), word(&other_heap)))) || !other_heap || other_heap == heap)) return 72; - const bool heap_record = mode.rfind("dispatch-heap", 0) == 0; + const bool heap_record = mode.rfind("dispatch-heap", 0) == 0 && !heap_waterfall; if (heap_record) for (const UINT at : {0u, 32u, 64u}) std::memcpy(reinterpret_cast<void*>(cpu + at), descriptors[at != 64], sizeof(descriptors[0])); + if (heap_waterfall) { + if (heap_short) { + std::memcpy(reinterpret_cast<void*>(cpu + 32), record_descs[1], sizeof(record_descs[1])); + std::memcpy(reinterpret_cast<void*>(cpu + 64), record_descs[2], sizeof(record_descs[2])); + } else { + for (UINT rec = 0; rec < 4; ++rec) + std::memcpy(reinterpret_cast<void*>(cpu + rec * 32u), record_descs[rec], sizeof(record_descs[rec])); + std::memcpy(reinterpret_cast<void*>(cpu + 128), descriptors, sizeof(descriptors)); + } + } const bool heap_word = mode.rfind("dispatch-heap-word", 0) == 0; - const UINT constants[3] = {0x01234567, 0x9e3779b9, mode == "dispatch-heap-outside" ? 0x07ffffffu : heap_word ? 1u : 2u}; + UINT active_lanes = 4u; + if (heap_waterfall) { + char buf[32]; + const DWORD len = GetEnvironmentVariableA("X2W_TEST_DISPATCH_ACTIVE", buf, sizeof(buf)); + if (len && len < sizeof(buf)) active_lanes = static_cast<UINT>(std::strtoul(buf, nullptr, 10)); + } + const UINT constants[3] = {heap_waterfall ? active_lanes : 0x01234567u, 0x9e3779b9u, + mode == "dispatch-heap-outside" ? 0x07ffffffu : heap_word ? 1u : 2u}; const UINT graphics[2] = {0xdeadbeef, 0xfeedface}; const auto bind = [&] { invoke(list, 32, 1, word(&heap)); @@ -383,7 +453,7 @@ static int dispatch_slot67(IDXGIAdapter* adapter, void* device, const std::strin if (FAILED(static_cast<HRESULT>(invoke(list, 139, word(allocator))))) return 74; } bind(); - if (mode.rfind("dispatch-sampled", 0) == 0 || mode == "dispatch-input-token") { + if (mode.rfind("dispatch-sampled", 0) == 0 || mode == "dispatch-input-token" || mode == "dispatch-output-texture-token") { const bool depth = mode == "dispatch-sampled-depth"; const UINT width = depth || mode == "dispatch-sampled-2x1" ? 2 : 1; const DXGI_FORMAT format = depth ? DXGI_FORMAT_R32_FLOAT : DXGI_FORMAT_R8G8B8A8_UNORM; @@ -408,6 +478,67 @@ static int dispatch_slot67(IDXGIAdapter* adapter, void* device, const std::strin D3D12_SHADER_RESOURCE_VIEW_DESC view{format, D3D12_SRV_DIMENSION_TEXTURE2D, D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING}; view.Texture2D.MipLevels = 1; if (mode != "dispatch-sampled-unbound") invoke(device, 18, word(texture), word(&view), cpu + (mode == "dispatch-input-token" ? 0 : 64)); + // Byte 16 is not a descriptor of the heap: the token's words are copied there, as a title copies descriptors. + if (mode == "dispatch-output-texture-token") std::memcpy(reinterpret_cast<void*>(cpu + 16), reinterpret_cast<const void*>(cpu + 64), 16); + } + if (mode.rfind("dispatch-texdim-", 0) == 0) { + // dispatch-texdim-<1d|2da|3d>[-mismatch|-undescribed|-clamped]: the sampled input is a described R32_FLOAT texture + // of that dimension in the SRV at table byte 64, texel (x + y * 4 + slice * 16) holding 0.25 * (index + 1): + // 1d is 8 texels wide, 2da is 4x4 with six slices (the view starts at slice 1 and spans four), 3d is 4x4x4. + // Each subresource is uploaded by its own copy. -mismatch views a plain 2D texture instead (a view dimension + // that is not the manifest's), -undescribed creates the view without a description, -clamped sets + // ResourceMinLODClamp 1.0 (a valid desktop view that is not a view of the texels as stored; a view outside the + // texture would remove the device when it is created). + const std::string rest = mode.substr(16); + const std::string kind = rest.substr(0, rest.find('-')); + const std::string control = rest.find('-') == std::string::npos ? "" : rest.substr(rest.find('-') + 1); + const bool one = kind == "1d", array = kind == "2da", volume = kind == "3d"; + if (!one && !array && !volume) return 2; + const bool plain = control == "mismatch"; + constexpr DXGI_FORMAT format = DXGI_FORMAT_R32_FLOAT; + const UINT width = one && !plain ? 8 : 4, height = one && !plain ? 1 : 4; + const UINT depth = plain || one ? 1 : array ? 6 : 4; + const D3D12_RESOURCE_DIMENSION dimension = plain || array ? D3D12_RESOURCE_DIMENSION_TEXTURE2D : + one ? D3D12_RESOURCE_DIMENSION_TEXTURE1D : D3D12_RESOURCE_DIMENSION_TEXTURE3D; + const D3D12_RESOURCE_DESC texture_desc{dimension, 0, width, height, static_cast<UINT16>(depth), 1, format, {1, 0}}; + constexpr UINT pitch = D3D12_TEXTURE_DATA_PITCH_ALIGNMENT, slice_bytes = pitch * 4; + const D3D12_RESOURCE_DESC upload_desc{D3D12_RESOURCE_DIMENSION_BUFFER, 0, 8192, 1, 1, 1, DXGI_FORMAT_UNKNOWN, {1, 0}, + D3D12_TEXTURE_LAYOUT_ROW_MAJOR}; + void* const texture = make_committed(device, D3D12_HEAP_TYPE_DEFAULT, texture_desc, D3D12_RESOURCE_STATE_COMMON); + void* const upload = make_committed(device, D3D12_HEAP_TYPE_UPLOAD, upload_desc, D3D12_RESOURCE_STATE_GENERIC_READ); + void* texel = nullptr; + if (!texture || !upload || FAILED(static_cast<HRESULT>(invoke(upload, 8, 0, 0, word(&texel)))) || !texel) return 80; + std::memset(texel, 0, 8192); + for (UINT z = 0; z < depth; ++z) + for (UINT y = 0; y < height; ++y) + for (UINT x = 0; x < width; ++x) { + const float value = 0.25f * static_cast<float>(x + y * 4 + z * 16 + 1); + std::memcpy(static_cast<char*>(texel) + z * slice_bytes + y * pitch + x * 4, &value, sizeof(value)); + } + invoke(upload, 9, 0, 0); + // A 3D texture is one subresource whose footprint spans its depth; a 2D one has a subresource per slice. + const UINT copies = volume ? 1 : depth; + for (UINT i = 0; i < copies; ++i) { + D3D12_TEXTURE_COPY_LOCATION image{static_cast<ID3D12Resource*>(texture), D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX}; + image.SubresourceIndex = i; + D3D12_TEXTURE_COPY_LOCATION source{static_cast<ID3D12Resource*>(upload), D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT}; + source.PlacedFootprint = {UINT64{i} * slice_bytes, {format, width, height, volume ? depth : 1, pitch}}; + invoke(list, 16, word(&image), 0, 0, 0, word(&source), 0); + } + D3D12_SHADER_RESOURCE_VIEW_DESC view{format, D3D12_SRV_DIMENSION_TEXTURE2D, D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING}; + const float clamp = control == "clamped" ? 1.0f : 0.0f; + if (plain) view.Texture2D.MipLevels = 1; + else if (one) { + view.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE1D; + view.Texture1D = {0, 1, clamp}; + } else if (array) { + view.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2DARRAY; + view.Texture2DArray = {0, 1, 1, 4, 0, clamp}; + } else { + view.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE3D; + view.Texture3D = {0, 1, clamp}; + } + invoke(device, 18, word(texture), control == "undescribed" ? 0 : word(&view), cpu + 64); } if (mode == "dispatch-input-memory-view") { // The input is a buffer view (device slot 70) of memory no buffer is placed over, 16 bytes in; its token @@ -470,7 +601,7 @@ static int dispatch_slot67(IDXGIAdapter* adapter, void* device, const std::strin if (FAILED(static_cast<HRESULT>(invoke(list, 9))) || FAILED(static_cast<HRESULT>(invoke(list, 139, word(allocator))))) return 74; bind(); } - if (heap_record || root_srv) invoke(list, 39, 0, 1, word(&constants[2]), 2); + if (heap_record || root_srv || heap_waterfall) invoke(list, 39, 0, 1, word(&constants[2]), 2); if (heap_word) { // The index buffer of table byte 96, in this recording's upload memory (list slot 148). Byte 288 + 336 * 1 // holds the index, 2; every other word names record 0 or 1, the output's descriptor. @@ -485,7 +616,7 @@ static int dispatch_slot67(IDXGIAdapter* adapter, void* device, const std::strin mode == "dispatch-heap-word-past" ? at : mode == "dispatch-heap-word-placed" ? words * 4 : bytes, 0}; std::memcpy(reinterpret_cast<void*>(cpu + 96), view, sizeof(view)); } - invoke(list, 35, 1, table_gpu); + invoke(list, 35, 1, table_gpu + (heap_waterfall && !heap_short ? 128u : 0u)); if (change_table_root) { invoke(list, 33, word(slot67_other_root)); invoke(list, 33, word(slot67_root)); @@ -500,6 +631,7 @@ static int dispatch_slot67(IDXGIAdapter* adapter, void* device, const std::strin if (pixel) record.capture_before_consumer(adapter, device, list); if (indirect) record.execute(list, mode == "dispatch-indirect-multi" ? 2 : 1, mode == "dispatch-indirect-counted", mode == "dispatch-indirect-outside"); + else if (heap_waterfall) invoke(list, 14, 1, 1, 1); else if (mode == "dispatch-reference-2" || mode == "dispatch-reference-5") invoke(list, 14, mode == "dispatch-reference-2" ? 2 : 5, 1, 1); else if (mode != "dispatch-none" && mode != "dispatch-root-srv-none") invoke(list, 14, 3, 2, 2); @@ -513,6 +645,34 @@ static int dispatch_slot67(IDXGIAdapter* adapter, void* device, const std::strin if (indirect && !pixel && !record.check_record(groups)) return 80; for (UINT i = 0; i < words; ++i) if (buffers[0][i] != input[i]) return 79; // the input must stay as written + if (long_run) { + UINT first[words]; + std::memcpy(first, buffers[1], sizeof(first)); + for (UINT frame = 1; frame < long_frames; ++frame) { + std::fill_n(buffers[1], words, 0xc5c5c5c5u); + if (FAILED(static_cast<HRESULT>(invoke(allocator, 8)))) return 84; + // Keep each submitted list alive and closed so only fenced submit can drop its snapshot hold. + if (keep_closed && FAILED(static_cast<HRESULT>(invoke(device, 73, word(list_desc), word(allocator), 0, + word(&__uuidof(ID3D12GraphicsCommandList)), word(&list))))) return 72; + if (FAILED(static_cast<HRESULT>(invoke(list, 139, word(allocator))))) return 74; + bind(); + invoke(list, 37, 0, constants[0], 0); + invoke(list, 40, 0, 2, word(graphics), 0); + invoke(list, 39, 0, 1, word(&constants[1]), 1); + invoke(list, 35, 1, gpu); + invoke(list, 14, 3, 2, 2); + if (FAILED(static_cast<HRESULT>(invoke(list, 9)))) return 75; + invoke(queue, 10, 1, word(&list)); + if (FAILED(static_cast<HRESULT>(invoke(queue, 14, word(fence), frame + 1)))) return 76; + for (const ULONGLONG deadline = GetTickCount64() + 10000; invoke(fence, 8) < frame + 1;) { + if (GetTickCount64() >= deadline) return 78; + Sleep(1); + } + if (std::memcmp(first, buffers[1], sizeof(first)) != 0) return 85; // a frame gave other words than the first + for (UINT i = 0; i < words; ++i) + if (buffers[0][i] != input[i]) return 79; + } + } x2w_d3d12_compute_census(); char path[MAX_PATH]; const DWORD n = GetEnvironmentVariableA("X2W_TEST_DISPATCH_OUT", path, MAX_PATH); @@ -530,21 +690,23 @@ static int dispatch_slot67(IDXGIAdapter* adapter, void* device, const std::strin // and its view RGBA16_UINT; texture-store-occupied then asks for a view of a texture without unordered access at the same // handle, which keeps the first view; texture-store-self also creates a shader resource view of the texture at table byte 0. // texture-store-mips adds a second UAV of the same texture. The swapped mode reverses the two mip views. -static int texture_slot67(void* device, const std::string& mode) +static int texture_slot67(IDXGIAdapter* adapter, void* device, const std::string& mode) { constexpr UINT width = 32; - const bool volume = mode == "texture-volume" || mode == "texture-volume-bad-w"; + const bool exact = mode.rfind("texture-exact-", 0) == 0; + const bool volume = mode == "texture-volume" || mode == "texture-volume-bad-w" || mode == "texture-exact-volume"; const bool line = mode == "texture-line" || mode == "texture-line-bad-mip"; const UINT first_mip = volume || line ? 1 : 0; const UINT height = line ? 1 : 8; const bool fp32 = volume || line || mode == "texture-array" || mode == "texture-array-2d"; const bool atomic_uint = mode == "texture-store-atomic"; - const UINT layers = volume || mode == "texture-array" || mode == "texture-array-d16" ? 6 : 1; + const UINT layers = volume || mode == "texture-array" || mode == "texture-array-d16" || + mode == "texture-exact-array" ? 6 : 1; const UINT subresources = volume ? 1 : layers; const bool swapped = mode == "texture-store-mips-swapped"; const bool dual = swapped || mode == "texture-store-mips"; const UINT mips = dual ? 2 : 1; - const UINT pixel_bytes = atomic_uint ? 4 : fp32 ? 16 : 8; + const UINT pixel_bytes = exact ? (mode == "texture-exact-rg" ? 8 : 4) : atomic_uint ? 4 : fp32 ? 16 : 8; const UINT pitch = (std::max)(width * pixel_bytes, UINT{D3D12_TEXTURE_DATA_PITCH_ALIGNMENT}); const UINT slice_bytes = pitch * (height + (dual ? height / 2 : 0)), bytes = slice_bytes * layers; const auto offset = [&](UINT layer, UINT mip) { return UINT64{layer} * slice_bytes + (mip ? pitch * height : 0); }; @@ -552,8 +714,23 @@ static int texture_slot67(void* device, const std::string& mode) const auto make = [&](D3D12_HEAP_TYPE type, const D3D12_RESOURCE_DESC& desc, D3D12_RESOURCE_STATES state) { return make_committed(device, type, desc, state); }; - const DXGI_FORMAT format = atomic_uint ? DXGI_FORMAT_R32_UINT : fp32 ? DXGI_FORMAT_R32G32B32A32_FLOAT : + const DXGI_FORMAT format = mode == "texture-exact-r" ? DXGI_FORMAT_R32_FLOAT : + mode == "texture-exact-rg" ? DXGI_FORMAT_R32G32_FLOAT : + mode == "texture-exact-rgba" ? DXGI_FORMAT_R8G8B8A8_UNORM : + exact ? DXGI_FORMAT_R11G11B10_FLOAT : + atomic_uint ? DXGI_FORMAT_R32_UINT : fp32 ? DXGI_FORMAT_R32G32B32A32_FLOAT : mode == "texture-store-uint" ? DXGI_FORMAT_R16G16B16A16_UINT : DXGI_FORMAT_R16G16B16A16_FLOAT; + if (exact) { + ComPtr<ID3D12Device> desktop; + D3D12_FEATURE_DATA_FORMAT_SUPPORT support{format}; + if (FAILED(D3D12CreateDevice(adapter, D3D_FEATURE_LEVEL_11_0, IID_PPV_ARGS(&desktop))) || + FAILED(desktop->CheckFeatureSupport(D3D12_FEATURE_FORMAT_SUPPORT, &support, sizeof(support))) || + !(support.Support2 & D3D12_FORMAT_SUPPORT2_UAV_TYPED_STORE) || + (volume && !(support.Support1 & D3D12_FORMAT_SUPPORT1_TEXTURE3D))) { + std::printf("exact-width image store format %u unavailable\n", static_cast<unsigned>(format)); + return 77; + } + } const auto dimension = volume ? D3D12_RESOURCE_DIMENSION_TEXTURE3D : line ? D3D12_RESOURCE_DIMENSION_TEXTURE1D : D3D12_RESOURCE_DIMENSION_TEXTURE2D; const D3D12_RESOURCE_DESC texture_desc{dimension, 0, width << first_mip, line ? 1 : height << first_mip, @@ -567,7 +744,15 @@ static int texture_slot67(void* device, const std::string& mode) void* const readback = make(D3D12_HEAP_TYPE_READBACK, buffer_desc, D3D12_RESOURCE_STATE_COPY_DEST); void* memory = nullptr; if (!texture || !upload || !readback || FAILED(static_cast<HRESULT>(invoke(upload, 8, 0, 0, word(&memory)))) || !memory) return 71; - if (atomic_uint) { + if (exact) { + for (UINT layer = 0; layer < layers; ++layer) + for (UINT y = 0; y < height; ++y) { + auto* row = reinterpret_cast<UINT*>(static_cast<char*>(memory) + offset(layer, 0) + y * pitch); + const UINT row_words = width * pixel_bytes / sizeof(UINT); + for (UINT x = 0; x < row_words; ++x) + row[x] = 0x30000000u + (layer * height + y) * row_words + x; + } + } else if (atomic_uint) { auto* words = static_cast<UINT*>(memory); for (UINT y = 0; y < height; ++y) for (UINT x = 0; x < width; ++x) @@ -808,7 +993,7 @@ int main(int argc, char** argv) return dispatch_slot67(adapter.Get(), device, argv[8]); } if (argc == 9 && std::strcmp(argv[4], "slot67") == 0 && std::strncmp(argv[8], "texture", 7) == 0) - return create_slot67(device, argv[5], argv[6], argv[7], argv[8]) ? texture_slot67(device, argv[8]) : 10; + return create_slot67(device, argv[5], argv[6], argv[7], argv[8]) ? texture_slot67(adapter.Get(), device, argv[8]) : 10; if ((argc == 8 || argc == 9) && std::strcmp(argv[4], "slot67") == 0) return create_slot67(device, argv[5], argv[6], argv[7], argc == 9 ? argv[8] : "valid") ? 0 : 10; if (GetEnvironmentVariableW(L"X2W_TEST_TRUNCATED_ONLY", nullptr, 0)) return 0; diff --git a/tests/startup_stub_check.py b/tests/startup_stub_check.py index f2e39ccfa5..1398c34630 100644 --- a/tests/startup_stub_check.py +++ b/tests/startup_stub_check.py @@ -102,7 +102,7 @@ run.stderr) requests_by_format = {int(f): int(n) for f, n in re.findall(r"(\d+):(\d+)", summary.group(1))} if summary else {} blank_by_format = {int(f): int(n) for f, n in re.findall(r"(\d+):(\d+)", summary.group(2))} if summary else {} -bcpack_ok = (requests_by_format.get(6) == 1 and blank_by_format.get(6) == 1 +bcpack_ok = (requests_by_format.get(6) == 1 and blank_by_format.get(6, 0) == 0 and requests_by_format.get(1) == 2 and blank_by_format.get(1, 0) == 0 and requests_by_format.get(3) == 3 and blank_by_format.get(3, 0) == 0 and requests_by_format.get(4) == 4 and blank_by_format.get(4, 0) == 0 diff --git a/tests/startup_stub_consumer.cpp b/tests/startup_stub_consumer.cpp index 3951fa93a8..722f7f4b2f 100644 --- a/tests/startup_stub_consumer.cpp +++ b/tests/startup_stub_consumer.cpp @@ -24,6 +24,8 @@ #include <fstream> #include <cstring> #include <vector> +#include "bcpack_format_fixtures.h" +#include "bcpack_storage_goldens.h" using u64 = std::uint64_t; @@ -1964,39 +1966,40 @@ bool dstorage_checks() { std::memcpy(bc1_packed_trailing, bc1_packed, sizeof(bc1_packed)); bc1_packed_trailing[515] = 0x01; + // GDK 1.2603.3.0 output for the unchanged synthetic_11 input above. const unsigned char bc1_expected[512] = { - 0x85, 0x31, 0x64, 0xd5, 0xaf, 0xbe, 0xff, 0xbf, 0x50, 0x84, 0xc7, 0x6b, 0xba, 0xa5, 0xbf, 0xbf, - 0x50, 0x84, 0x27, 0xc9, 0x56, 0x06, 0x5e, 0x5f, 0x25, 0x6a, 0x43, 0xaa, 0x5e, 0xee, 0xf5, 0xf5, - 0xe8, 0x72, 0xa0, 0x91, 0x5e, 0x5e, 0xfb, 0xfb, 0x2a, 0x3b, 0x83, 0xf1, 0x9a, 0xa5, 0x7a, 0xfa, - 0x81, 0x08, 0xcc, 0xa2, 0x9a, 0x9d, 0xbb, 0xff, 0x28, 0x73, 0x20, 0xbe, 0x8a, 0x8f, 0x05, 0x05, - 0x41, 0x00, 0x8c, 0xda, 0xfa, 0x5f, 0xfa, 0xdb, 0xfe, 0x8a, 0x7a, 0x5a, 0x72, 0x3a, 0xfa, 0xba, - 0x41, 0xf8, 0x8c, 0x32, 0x0f, 0xff, 0xfa, 0xba, 0xec, 0x5a, 0xa6, 0xa9, 0x6b, 0x5f, 0xaf, 0xaf, - 0x50, 0x84, 0x26, 0x89, 0x5a, 0x5f, 0x5f, 0x5f, 0x44, 0x21, 0x23, 0xb1, 0xaf, 0x5d, 0xaf, 0xab, - 0x0d, 0x6b, 0x24, 0x52, 0xaf, 0xf7, 0xbf, 0xfd, 0x0c, 0x5b, 0x26, 0x7c, 0xbe, 0x9e, 0x05, 0x05, - 0x3e, 0x83, 0x7a, 0x39, 0xd5, 0x95, 0xaa, 0x5a, 0x61, 0x10, 0x6e, 0x68, 0x5b, 0x0f, 0xff, 0xbd, - 0x8a, 0x9b, 0x65, 0x51, 0x2f, 0xaa, 0xaa, 0x5a, 0xb8, 0xc6, 0xd3, 0x4a, 0x4f, 0x45, 0xf0, 0xb0, - 0x1e, 0xb6, 0x1e, 0x6d, 0x5b, 0x5f, 0xba, 0xba, 0x50, 0x84, 0x27, 0xe4, 0xfa, 0x5a, 0xaa, 0xaf, - 0x65, 0x52, 0x45, 0xd2, 0x5e, 0x0f, 0xaf, 0xef, 0xaf, 0x73, 0x06, 0x55, 0xae, 0x8f, 0xae, 0x5f, - 0x89, 0x52, 0xa1, 0x80, 0x0f, 0x0b, 0xa5, 0xa5, 0x03, 0x21, 0xe2, 0xe8, 0x7b, 0x5f, 0x0a, 0x0a, - 0xa5, 0x39, 0x23, 0x99, 0xd0, 0xd0, 0xaa, 0xff, 0x2c, 0x8b, 0xca, 0x0a, 0x20, 0xa0, 0xaf, 0xfb, - 0x28, 0x6b, 0xc1, 0x08, 0x0a, 0x5a, 0xff, 0xaa, 0x4a, 0x4a, 0x45, 0x09, 0xba, 0xab, 0x5e, 0x5e, - 0x0c, 0x7a, 0x40, 0xaa, 0x7f, 0x7e, 0x0e, 0x0f, 0x20, 0x48, 0x9d, 0x3b, 0x5f, 0x5f, 0x00, 0x00, - 0x4b, 0xd6, 0xc4, 0xd4, 0x60, 0x60, 0xfb, 0xef, 0x45, 0x3a, 0x41, 0xa9, 0xba, 0x9f, 0xa7, 0xf7, - 0x0d, 0x5b, 0x37, 0x4a, 0xdb, 0x2b, 0xef, 0xaa, 0x20, 0x48, 0x8e, 0x0b, 0x8e, 0xaa, 0xaf, 0xaf, - 0xd8, 0xcd, 0x75, 0x6d, 0x0e, 0x0a, 0xba, 0xff, 0xbc, 0xa3, 0xf8, 0x3e, 0xbf, 0xdf, 0x5a, 0xfa, - 0x9f, 0x08, 0xd2, 0x9a, 0x25, 0x5f, 0xff, 0xba, 0x09, 0x94, 0xc3, 0x82, 0xff, 0xfe, 0xba, 0xba, - 0x21, 0x79, 0x3c, 0x31, 0xaf, 0xfe, 0xaf, 0x5a, 0xbf, 0x53, 0xe1, 0xd1, 0xbf, 0xab, 0x5f, 0x5b, - 0x26, 0x6b, 0xc3, 0xd8, 0x2a, 0xb5, 0xfb, 0xbf, 0x89, 0x42, 0x5f, 0xe1, 0xaf, 0xff, 0xb5, 0xb5, - 0x0a, 0x94, 0x8b, 0xfb, 0xa5, 0xd5, 0x0f, 0x0f, 0xa8, 0x52, 0xc7, 0x01, 0x9f, 0xab, 0x55, 0x55, - 0x29, 0xf8, 0x86, 0x7a, 0xfa, 0xfa, 0xff, 0xaa, 0x40, 0x00, 0x9a, 0x7a, 0xbe, 0xfe, 0xfa, 0xfa, - 0x54, 0x8c, 0x29, 0xc4, 0x0a, 0x0a, 0xaf, 0xab, 0x6c, 0x6b, 0x08, 0x0a, 0xa0, 0xd0, 0xf0, 0xf0, - 0x6b, 0x7c, 0xd9, 0x51, 0xa5, 0xd5, 0xf5, 0xe5, 0x82, 0x21, 0x00, 0x32, 0x00, 0x50, 0xa0, 0xa0, - 0x42, 0x19, 0x35, 0x99, 0xbf, 0xe7, 0xaf, 0xff, 0x46, 0x7b, 0x60, 0x42, 0x60, 0x45, 0x0f, 0x0f, - 0xd4, 0x31, 0x33, 0x99, 0xda, 0xaa, 0xa5, 0xaf, 0x1a, 0xd7, 0xe9, 0x80, 0xba, 0xba, 0x0a, 0x0f, - 0xc6, 0x08, 0x97, 0xe0, 0xff, 0xfa, 0xba, 0xba, 0x51, 0xd6, 0xdf, 0xec, 0x65, 0x65, 0x5f, 0x5a, - 0xbb, 0xbe, 0xda, 0x22, 0x2e, 0xaa, 0xf0, 0xf0, 0x6c, 0x63, 0x1d, 0x72, 0xeb, 0xeb, 0x5f, 0x5f, - 0xce, 0x31, 0x36, 0x91, 0x70, 0x70, 0xaa, 0xf2, 0x57, 0x8c, 0x27, 0xb4, 0x8f, 0xab, 0xf0, 0xb0, - 0x49, 0x7b, 0x6a, 0x42, 0xef, 0xfb, 0xa5, 0xb5, 0x7f, 0x6b, 0x2a, 0x3a, 0x75, 0x75, 0x5a, 0x5f + 0x8d, 0x73, 0x0a, 0x07, 0xea, 0xb8, 0xfa, 0xbe, 0x91, 0x84, 0x04, 0x53, 0xd8, 0xa7, 0x2a, 0x4a, + 0xc3, 0x18, 0xe2, 0x75, 0xa9, 0xf9, 0xa1, 0xa0, 0xef, 0x83, 0x6d, 0xd4, 0xf8, 0x8e, 0xa0, 0xb5, + 0x48, 0x4a, 0x63, 0xaa, 0xd7, 0xd7, 0xbd, 0xb9, 0x8c, 0x6c, 0xc2, 0xf9, 0x3b, 0x05, 0xe0, 0xa0, + 0x90, 0x84, 0xc5, 0x60, 0x30, 0x33, 0xb2, 0x5f, 0x2f, 0x84, 0xed, 0xf8, 0xba, 0xbc, 0xb4, 0x5a, + 0x3e, 0x71, 0x3e, 0xa0, 0x2e, 0x08, 0xdf, 0x9d, 0x82, 0x18, 0xa1, 0xe9, 0xec, 0x20, 0x70, 0xb8, + 0x91, 0x7c, 0x04, 0xab, 0xf7, 0x71, 0x5a, 0xc0, 0xe1, 0x07, 0x40, 0x88, 0xea, 0xdf, 0x25, 0x2f, + 0xb2, 0x94, 0x6c, 0x2b, 0xf0, 0xfa, 0x5f, 0x5f, 0xc1, 0x10, 0xa1, 0xa0, 0x5f, 0xa4, 0x00, 0x04, + 0xad, 0x8b, 0x88, 0x83, 0x2a, 0xae, 0x2b, 0xfd, 0x43, 0x29, 0x62, 0xf3, 0x2f, 0x3a, 0x7b, 0x7b, + 0x68, 0x42, 0xe1, 0xd0, 0x40, 0xc5, 0xe0, 0x10, 0xad, 0x8b, 0x46, 0x57, 0x0d, 0xa5, 0x55, 0xd4, + 0xa2, 0x18, 0x01, 0xd1, 0x14, 0xa0, 0x7a, 0x0a, 0x4b, 0x53, 0x87, 0xe7, 0xda, 0xdf, 0xa4, 0xb0, + 0xe5, 0x39, 0x22, 0xe9, 0xda, 0x5e, 0xde, 0xda, 0x03, 0x19, 0xc5, 0xa1, 0x58, 0x08, 0xe0, 0xee, + 0x0f, 0x84, 0x21, 0x88, 0x0e, 0xae, 0xaa, 0xc0, 0x69, 0x52, 0x46, 0x65, 0xe8, 0x92, 0x08, 0xdf, + 0x4b, 0x63, 0x03, 0x99, 0xd8, 0xd0, 0xdb, 0xd3, 0x99, 0xce, 0xa6, 0xf9, 0xc2, 0xff, 0x50, 0x50, + 0xbf, 0x53, 0xfd, 0xa9, 0x4a, 0xd2, 0x02, 0xaa, 0xeb, 0x62, 0x64, 0xb9, 0xca, 0x0e, 0x41, 0x2d, + 0xb9, 0xd6, 0xa6, 0x21, 0xef, 0xb5, 0xda, 0xb5, 0x8b, 0x52, 0xa6, 0x19, 0x3a, 0x2a, 0xf8, 0xf8, + 0xb9, 0xac, 0x25, 0x42, 0xc2, 0xea, 0x27, 0xa5, 0x6b, 0xac, 0xd3, 0xc1, 0xe2, 0xea, 0x54, 0x42, + 0xc2, 0x7b, 0x9d, 0x82, 0xe1, 0xe0, 0xbd, 0xaf, 0xb0, 0x54, 0xc3, 0xc0, 0x4e, 0xd1, 0xf7, 0x4e, + 0x4c, 0x53, 0x54, 0x00, 0xb2, 0x43, 0x8d, 0x0b, 0x91, 0x84, 0x15, 0x23, 0xb5, 0xa0, 0x7f, 0xff, + 0xcc, 0x6a, 0xec, 0x22, 0x4e, 0x4a, 0x22, 0x8b, 0xb7, 0xde, 0xa2, 0xe9, 0x65, 0x30, 0x02, 0x4a, + 0xcc, 0x73, 0xc9, 0x10, 0x67, 0x46, 0xd6, 0xb8, 0xfa, 0x9b, 0x7a, 0xa5, 0xc5, 0xd7, 0x4e, 0x4e, + 0xee, 0x62, 0x62, 0xb1, 0x00, 0x5a, 0xaf, 0x52, 0xbf, 0x7a, 0x03, 0xfd, 0x3f, 0xab, 0xff, 0xfb, + 0xa0, 0x18, 0x03, 0x91, 0x4b, 0x30, 0x5d, 0xd7, 0x67, 0x5a, 0x01, 0x1a, 0x90, 0x54, 0x4a, 0x42, + 0x26, 0x4a, 0x43, 0x90, 0xa0, 0xd5, 0x5a, 0x72, 0xec, 0x52, 0xc6, 0xe0, 0x22, 0x03, 0x40, 0x00, + 0x79, 0x84, 0x9c, 0xb0, 0xb0, 0xb8, 0xba, 0xa8, 0x8c, 0x73, 0x8f, 0xb0, 0xd7, 0xaa, 0x80, 0xa2, + 0x07, 0x21, 0xc7, 0x81, 0x0a, 0x0a, 0xaf, 0xab, 0x40, 0x08, 0xe4, 0xe8, 0x35, 0xe0, 0xf2, 0xba, + 0x37, 0x5b, 0x60, 0x11, 0x28, 0x37, 0x0e, 0xa8, 0xa1, 0x39, 0x7d, 0x39, 0x5d, 0x55, 0xa0, 0xa0, + 0xff, 0xff, 0x52, 0x70, 0x97, 0xdc, 0xa1, 0x57, 0x1d, 0x41, 0xba, 0x18, 0xea, 0x94, 0x0d, 0xa5, + 0x73, 0x21, 0x30, 0x70, 0xce, 0x91, 0xa8, 0xf7, 0xb7, 0xce, 0xa8, 0x49, 0x37, 0x3f, 0x2b, 0x84, + 0x68, 0x19, 0x56, 0xd8, 0x5f, 0x20, 0x2f, 0x0b, 0x29, 0x29, 0x05, 0x7b, 0x30, 0x64, 0xfb, 0xf0, + 0x85, 0x08, 0x08, 0xd8, 0x17, 0xbf, 0x08, 0x08, 0x01, 0xf8, 0x15, 0x68, 0x37, 0xfb, 0xef, 0x27, + 0xa4, 0x52, 0x6c, 0x42, 0xe5, 0x71, 0xbe, 0xf2, 0xc4, 0x10, 0xbf, 0x90, 0x05, 0x49, 0xf2, 0xda, + 0x33, 0x7c, 0x53, 0x42, 0x8d, 0xa9, 0xa5, 0xd5, 0x7f, 0x6b, 0xa9, 0x31, 0xae, 0x10, 0x1a, 0x0d, }; void* status_ptr = nullptr; @@ -2019,7 +2022,7 @@ bool dstorage_checks() { std::vector<unsigned char> dest_truncated(32, 0xCC); std::vector<unsigned char> dest_bc1_valid(512, 0xEE); std::vector<unsigned char> dest_bc1_trailing(512, 0xDD); - std::vector<unsigned char> dest_bc6h_blank(64, 0xAA); + std::vector<unsigned char> dest_bc6h_invalid(64, 0xAA); std::vector<unsigned char> dest_bc4_wrong_size(8, 0x5A); std::vector<unsigned char> dest_bc4_non_mult(7, 0x5B); std::vector<unsigned char> dest_bc5_wrong_size(16, 0x5C); @@ -2097,11 +2100,11 @@ bool dstorage_checks() { *reinterpret_cast<unsigned*>(req5 + 0x30) = sizeof(bc1_packed_trailing); *reinterpret_cast<unsigned*>(req5 + 0x38) = 512; - // Request 6: BCPack format 6 (BC6H) is not decoded yet; it must be zero-filled and counted. + // Request 6: malformed BC6H must fail without publishing partial output. static const unsigned char bc6h_packed[] = {0x00, 0x01, 0x02, 0x03}; unsigned char req6[0x48] = {}; *reinterpret_cast<u64*>(req6 + 0x00) = (6ull << 1) | 0x400000; - *reinterpret_cast<void**>(req6 + 0x08) = dest_bc6h_blank.data(); + *reinterpret_cast<void**>(req6 + 0x08) = dest_bc6h_invalid.data(); *reinterpret_cast<u64*>(req6 + 0x10) = 0; *reinterpret_cast<unsigned*>(req6 + 0x18) = 64; *reinterpret_cast<const unsigned char**>(req6 + 0x20) = bc6h_packed; @@ -2187,9 +2190,9 @@ bool dstorage_checks() { for (unsigned char b : dest_bc1_trailing) { if (b != 0xDD) return false; } - if (hrs[6] != 0) return false; - for (unsigned char b : dest_bc6h_blank) { - if (b != 0) return false; + if (hrs[6] == 0) return false; + for (unsigned char b : dest_bc6h_invalid) { + if (b != 0xAA) return false; } if (hrs[7] == 0) return false; for (unsigned char b : dest_bc4_wrong_size) { @@ -2340,6 +2343,8 @@ bool dstorage_file_information_checks() return ok; } +#include "bcpack_storage_checks.inl" + } // namespace int main(int argc, char** argv) @@ -2347,6 +2352,7 @@ int main(int argc, char** argv) if (argc != 2) return 2; const char* which = argv[1]; if (!std::strcmp(which, "none")) return 0; + if (!std::strcmp(which, "bcpack-storage")) return bcpack_storage_checks() ? 0 : 11; if (!std::strcmp(which, "chad")) return static_cast<int>(XDspActivate(0x11, 0x22, 0x33, 0x44)); if (!std::strcmp(which, "xg_xs")) return static_cast<int>(XGSuggestSwizzleMode(0x55, 0, 0, 0)); if (!std::strcmp(which, "physical")) { diff --git a/tests/startup_triage_run_check.py b/tests/startup_triage_run_check.py index 9b46c1a7da..494d0f40be 100644 --- a/tests/startup_triage_run_check.py +++ b/tests/startup_triage_run_check.py @@ -59,6 +59,11 @@ def check_aggregation_and_redaction(failures: list[str]) -> None: # A device slot 67 compute request with the same reason is counted in its own class. (cache_dir / "0000000000000004.fail").write_text("image_load_mip tfe\n", encoding="utf-8") (cache_dir / "req_0000000000000004.c67").write_bytes(b"\0" * 4) + # A compute runtime manifest reason is a fixed category; text outside its allowlist is not copied. + for key, line in ((5, "unsupported startup runtime manifest bindings: UAV kind texture_uav cube"), + (6, "unsupported startup runtime manifest bindings: SRV kind /home/alice/x")): + (cache_dir / f"{key:016x}.fail").write_text(line + "\n", encoding="utf-8") + (cache_dir / f"req_{key:016x}.c67").write_bytes(b"\0" * 4) report = triage_run.triage_run(logdir, shader_cache=cache_dir, max_items=16) @@ -77,6 +82,8 @@ def check_aggregation_and_redaction(failures: list[str]) -> None: "| 1 | `persistent_local_storage` | `0x80070005` |", "| 2 | `image_load_mip tfe` |", "| 1 | `compute: image_load_mip tfe` |", + "| 1 | `compute: runtime manifest: UAV kind texture_uav cube` |", + f"| 1 | `compute: {triage_run.OTHER}` |", f"| 1 | `{triage_run.OTHER}` |", ] for snippet in expected_snippets: @@ -503,6 +510,9 @@ def check_every_shader_reason_entry_is_reachable(failures: list[str]) -> None: ("native compute +0x14: unsupported instruction v_add3_u32 0xd76d0002u", "v_* instruction"), ("native compute +0x8: unsupported opcode 0xdeadbeefu", "unsupported opcode"), ("native compute +0x10: unsupported pixel entry VGPR 2", "unsupported pixel entry VGPR"), + ("unsupported startup runtime manifest bindings: SRV kind texture_srv 2d array", + "runtime manifest: SRV kind texture_srv 2d array"), + ("unsupported startup runtime manifest bindings: more than 8 UAVs", "runtime manifest: more than 8 UAVs"), ("native compute +0x1c: unproven resource descriptor s12", "unproven resource descriptor"), ("native compute +0x20: unbound numeric SGPR s0", "unbound numeric SGPR"), ("unknown gfx1013 instruction format at byte 24", "undecodable word"), diff --git a/tests/texture_bc_volume_check.py b/tests/texture_bc_volume_check.py index d15e58f91c..cc9f361f10 100644 --- a/tests/texture_bc_volume_check.py +++ b/tests/texture_bc_volume_check.py @@ -90,7 +90,7 @@ def test_table(self) -> None: "BC1_UNORM": (71, (4, 4, 1), 8, 2), "BC2_UNORM": (74, (4, 4, 1), 16, 2), "BC3_UNORM": (77, (4, 4, 1), 16, 2), - "BC4_UNORM": (79, (4, 4, 1), 8, 2), + "BC4_UNORM": (80, (4, 4, 1), 8, 2), "BC5_UNORM": (83, (4, 4, 1), 16, 2), "BC6H_UF16": (95, (4, 4, 1), 16, 2), "BC7_UNORM": (98, (4, 4, 1), 16, 2), diff --git a/tests/texture_blocks_check.py b/tests/texture_blocks_check.py index 685e6e6e7a..24ead3e516 100644 --- a/tests/texture_blocks_check.py +++ b/tests/texture_blocks_check.py @@ -21,7 +21,7 @@ ("BC1_UNORM", 71, 8), ("BC2_UNORM", 74, 16), ("BC3_UNORM", 77, 16), - ("BC4_UNORM", 79, 8), + ("BC4_UNORM", 80, 8), ("BC5_UNORM", 83, 16), ("BC6H_UF16", 95, 16), ("BC7_UNORM", 98, 16), diff --git a/tests/ttpf_batch_export_check.py b/tests/ttpf_batch_export_check.py index cb209a608d..5cd1bb9126 100644 --- a/tests/ttpf_batch_export_check.py +++ b/tests/ttpf_batch_export_check.py @@ -404,6 +404,74 @@ def test_manifest_generation(self): finally: batch.load_tools = orig_load + def test_manifest_cannot_replace_a_requested_dds(self): + for index in (0, 1, 2): + for existing in (False, True): + with self.subTest(index=index, existing=existing), tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + pool = root / "pool.ttpf" + pool.write_bytes(b"DUMMY_POOL") + out_dir = root / "out" + dds = out_dir / f"tex_{index:05d}.dds" + if existing: + out_dir.mkdir() + dds.write_bytes(b"previous dds") + with patch.object(batch, "load_tools", return_value=MockTtpfModule), \ + patch.object(MockTtpfModule, "export", wraps=MockTtpfModule.export) as export: + with self.assertRaisesRegex(ValueError, "manifest path collides with DDS"): + batch.batch_export(pool, out_dir, indices=[index], manifest_path=dds) + export.assert_not_called() + self.assertEqual(pool.read_bytes(), b"DUMMY_POOL") + if existing: + self.assertEqual(dds.read_bytes(), b"previous dds") + else: + self.assertFalse(out_dir.exists()) + + def test_manifest_dds_name_in_a_different_directory_is_allowed(self): + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + pool = root / "pool.ttpf" + pool.write_bytes(b"DUMMY_POOL") + out_dir = root / "out" + manifest = root / "tex_00000.dds" + with patch.object(batch, "load_tools", return_value=MockTtpfModule): + summary = batch.batch_export(pool, out_dir, indices=[0], manifest_path=manifest) + self.assertEqual(summary["stats"]["strict"], 1) + row, = json.loads(manifest.read_text()) + dds = out_dir / row["file"] + self.assertEqual(dds.read_bytes(), b"DDS_STRICT_BC1_DATA") + self.assertEqual(row["sha256"], hashlib.sha256(dds.read_bytes()).hexdigest()) + + def test_manifest_cannot_replace_a_history_or_calibration_input(self): + for option in ("history", "calibration"): + with self.subTest(option=option), tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + pool = root / "pool.ttpf" + pool.write_bytes(b"DUMMY_POOL") + profile = root / "profile.json" + original = b'{"version": 1}' + profile.write_bytes(original) + out_dir = root / "out" + tools = SimpleNamespace( + __file__=str(root / "ttpf_mips.py"), Pool=MockTtpfModule.Pool, + analyze=MockTtpfModule.analyze, export=MockTtpfModule.export, + BC_FORMATS=MockTtpfModule.BC_FORMATS, + ) + calibrated = SimpleNamespace( + __file__=str(root / "calibrated_texture.py"), ttpf=tools, + native=Mock(), LocalDecoder=Mock(), + ) + kwargs = ({"history_path": profile, "allow_provisional": True} if option == "history" + else {"calibration_path": profile}) + with patch.object(batch, "load_tools", return_value=tools) as load, patch.dict( + sys.modules, {"calibrated_texture": calibrated} + ): + with self.assertRaisesRegex(ValueError, f"manifest path collides with --{option}"): + batch.batch_export(pool, out_dir, indices=[0], manifest_path=profile, **kwargs) + load.assert_not_called() + self.assertEqual(profile.read_bytes(), original) + self.assertFalse(out_dir.exists()) + def test_export_fitted_then_strict_reused_directory(self): """A failed strict export keeps the prior DDS outside the current manifest.""" with tempfile.TemporaryDirectory() as tmp: diff --git a/tests/upload_reservation_check.cpp b/tests/upload_reservation_check.cpp index 075e38f685..0eaa3c6661 100644 --- a/tests/upload_reservation_check.cpp +++ b/tests/upload_reservation_check.cpp @@ -64,6 +64,33 @@ void check_ring_reuse() check(!reuse_upload_chunk(chunk, 0, bytes, queues).mapped, "untracked submit prevents reuse"); } +void check_snapshot_pool() +{ + // The snapshot pool's chunks are numbered after the ring's in the same recording mask and the same per-queue table. + check(snapshot_chunk_base == max_upload_chunks && max_snapshot_chunks == 8 && upload_chunk_bits == 40, "pool numbering"); + unsigned char storage[4 * kAlign]; + std::array<UploadRingChunk, 2> ring{}; + std::array<UploadRingChunk, 2> snap{}; + UploadRingChunk& chunk = snap[1]; + chunk = {nullptr, storage, sizeof(storage), sizeof(storage)}; + UploadChunkMask recording = 0; + ring[1].hold(recording, 1); + snap[0].hold(recording, snapshot_chunk_base + 0); + snap[1].hold(recording, snapshot_chunk_base + 1); + check(ring[1].recordings == 1 && snap[0].recordings == 1 && snap[1].recordings == 1 && ring[0].recordings == 0, "holds land in their pool"); + TestFence fence; + std::map<unsigned, UploadQueue<TestFence>> queues{{0, {&fence, 1}}}; + queues[0].submitted(recording, true); + check(!queues[0].completed(snapshot_chunk_base + 1), "a snapshot chunk in flight is not complete"); + fence.value = 1; + check(queues[0].completed(snapshot_chunk_base + 1) && queues[0].completed(snapshot_chunk_base + 7), "completed, or never used"); + check(!reuse_upload_chunk(chunk, snapshot_chunk_base + 1, kAlign, queues).mapped, "a held chunk is not reused"); + discard_upload_chunks(recording, ring.data(), snap.data()); + check(recording == 0 && ring[1].recordings == 0 && snap[0].recordings == 0 && snap[1].recordings == 0, "discard releases both pools"); + const auto again = reuse_upload_chunk(chunk, snapshot_chunk_base + 1, kAlign, queues); + check(again.mapped == storage && again.generation == 1, "a finished, unheld snapshot chunk is reused"); +} + // X2W_D3D12_RING_RELEASE_AT_SUBMIT=1 bookkeeping: a closed list stops holding its chunks once its submit is fenced, // the fence alone then guards the chunks, and a later submit of the same list before its Reset fences the intact // chunks again and reports the reused ones. @@ -95,7 +122,7 @@ void check_release_at_submit() const auto reused = reuse_upload_chunk(chunks[0], 0, bytes, queues); check(reused.mapped == storage[0] && reused.generation == 1, "release: chunk reused after the fence"); - UploadChunkMask recycled = UINT32_MAX; + UploadChunkMask recycled = UINT64_MAX; const auto intact = resubmitted_upload_chunks(released, chunks.data(), recycled); check(intact == 2 && recycled == 1, "release: a resubmit finds chunk 1 intact and chunk 0 reused"); @@ -109,6 +136,50 @@ void check_release_at_submit() "release: both chunks reported once reused"); } +void check_snapshot_release_at_submit() +{ + constexpr unsigned ring_index = max_upload_chunks - 1; + constexpr unsigned snapshot_index = upload_chunk_bits - 1; + constexpr auto ring_bit = UploadChunkMask{1} << ring_index; + constexpr auto snapshot_bit = UploadChunkMask{1} << snapshot_index; + constexpr auto both = ring_bit | snapshot_bit; + unsigned char storage[2][kAlign]; + std::array<UploadRingChunk, max_upload_chunks> ring{}; + std::array<UploadRingChunk, max_snapshot_chunks> snapshots{}; + auto& ring_chunk = ring.back(); + auto& snapshot = snapshots.back(); + ring_chunk = {nullptr, storage[0], kAlign, kAlign, 2}; + snapshot = {nullptr, storage[1], kAlign, kAlign, 3}; + UploadChunkMask recording = 0; + ring_chunk.hold(recording, ring_index); + snapshot.hold(recording, snapshot_index); + check(recording == both, "snapshot release: both boundary bits are recorded"); + + TestFence first, second; + std::map<unsigned, UploadQueue<TestFence>> queues{{0, {&first, 1}}, {1, {&second, 1}}}; + queues[0].submitted(recording, true); + ReleasedUploadChunks released; + release_upload_chunks_at_submit(recording, ring.data(), released, snapshots.data()); + check(!recording && !ring_chunk.recordings && !snapshot.recordings, "snapshot release: both holds dropped"); + check(released.chunks == both && released.generation[ring_index] == 2 && released.generation[snapshot_index] == 3, + "snapshot release: both generations saved"); + check(!reuse_upload_chunk(snapshot, snapshot_index, kAlign, queues).mapped, + "snapshot release: first fence guards the snapshot after release"); + + UploadChunkMask recycled = UINT64_MAX; + const auto intact = resubmitted_upload_chunks(released, ring.data(), recycled, snapshots.data()); + check(intact == both && !recycled, "snapshot release: intact resubmit includes both pools"); + queues[1].submitted(intact, true); + first.value = 1; + check(!reuse_upload_chunk(snapshot, snapshot_index, kAlign, queues).mapped, + "snapshot release: the other queue's resubmit fence still guards reuse"); + second.value = 1; + const auto reused = reuse_upload_chunk(snapshot, snapshot_index, kAlign, queues); + check(reused.mapped == storage[1] && reused.generation == 4, "snapshot release: reuse after both fences"); + check(resubmitted_upload_chunks(released, ring.data(), recycled, snapshots.data()) == ring_bit && + recycled == snapshot_bit, "snapshot release: a recycled snapshot alone invalidates the recording"); +} + } // namespace int main() @@ -156,7 +227,9 @@ int main() "existing reservations survive exhaustion"); check_ring_reuse(); + check_snapshot_pool(); check_release_at_submit(); + check_snapshot_release_at_submit(); std::puts("upload_reservation_check: all checks passed"); return 0; } diff --git a/tools/_bcpack_rans/THIRD_PARTY_NOTICES.md b/tools/_bcpack_rans/THIRD_PARTY_NOTICES.md index 8b16a91595..5e9550ce8a 100644 --- a/tools/_bcpack_rans/THIRD_PARTY_NOTICES.md +++ b/tools/_bcpack_rans/THIRD_PARTY_NOTICES.md @@ -34,12 +34,12 @@ SOFTWARE ## Ahmet Dedeler bcpack-rs -`src/startup_stubs/bcpack_tables.h` and `src/startup_stubs/bcpack_tables_bcn.inl` contain BC1, BC3, BC4, BC5, and BC7 -codebook, rank, window, and dictionary tables (`BC7_CONTROL_TABLE`, `BC7_DICTIONARY`, `BC1_WINDOW`, `BC1_QUAD_MASKS`, +`src/startup_stubs/bcpack_tables.h` and `src/startup_stubs/bcpack_tables_bcn.inl` contain BC3, BC4, BC5, and BC7 +codebook, rank, and dictionary tables (`BC7_CONTROL_TABLE`, `BC7_DICTIONARY`, `RANK_PAIR_BC4`, `BC4_DICTIONARY`, `RANK_PAIR_BC5`, `BC5_DICTIONARY`, `RANK_PAIR_BC3_ALPHA`, `RANK_QUAD_BC3_COLOUR`, `BC3_DICTIONARY`) adapted from https://github.com/Ahmet-Dedeler/bcpack-rs (pinned revision c55c5fad539644b8cf5a705051df214291763fc0). -The BC1, BC3, BC4, BC5, and BC7 block reconstruction routines in `src/startup_stubs/bcpack_decoder.h` are adapted from +The BC3, BC4, BC5, and BC7 block reconstruction routines in `src/startup_stubs/bcpack_decoder.h` are adapted from the same repository. Used under the MIT License: ``` @@ -65,3 +65,35 @@ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ``` + +## Microsoft DirectXTex + +The `BC6_WIRE` descriptors in `src/startup_stubs/bcpack_tables_extra.inl` adapt +the BC6H bit layout in `DirectXTex/BC6HBC7.cpp` at revision +[`a8e5dbf42909aeeb9fcf9c2ae399ae3c06737379`](https://github.com/microsoft/DirectXTex/tree/a8e5dbf42909aeeb9fcf9c2ae399ae3c06737379). +The BCPack-specific bit ordering is described in +[the implementation notes](../../docs/experiments/bcpack-standalone.md). + +```text +MIT License + + Copyright (c) Microsoft Corporation. + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in all + copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE +``` diff --git a/tools/bcpack_recover_constants.py b/tools/bcpack_recover_constants.py new file mode 100644 index 0000000000..3fab7e05f2 --- /dev/null +++ b/tools/bcpack_recover_constants.py @@ -0,0 +1,228 @@ +"""Reproduce BCPack format constants with chosen synthetic lane streams. + +SPDX-License-Identifier: MIT + +The GDK is a development oracle only. No DLL bytes or memory tables are read here. +BC6H wire bit descriptors are parsed from the public MIT DirectXTex source. +""" +import ctypes as c +import json +import argparse +import hashlib +from pathlib import Path +import re + +parser = argparse.ArgumentParser(description=__doc__) +parser.add_argument("--sdk", type=Path, required=True, help="Installed BCPack.dll, development oracle only") +parser.add_argument("--bridge", type=Path, required=True, help="Source-built bcpack_oracle_bridge.dll") +parser.add_argument("--bc6-reference", type=Path, required=True, help="Pinned public DirectXTex BC6HBC7.cpp") +parser.add_argument("--output", type=Path, required=True, help="Generated .inl (normally under out/)") +parser.add_argument("--storage-goldens", type=Path, help="Also regenerate the source-built storage fixture's expected blocks") +args = parser.parse_args() +sdk = c.CDLL(str(args.sdk.resolve())) +dec = sdk.BCPackDecompress +dec.argtypes = [c.c_size_t, c.c_void_p, c.c_size_t, c.c_void_p, c.c_size_t] +dec.restype = c.c_int32 +encoder = c.CDLL(str(args.bridge.resolve())) +enc = encoder.encode_symbols +enc.argtypes = [c.c_uint, c.POINTER(c.c_uint16), c.c_size_t, c.c_void_p, c.c_size_t] +enc.restype = c.c_size_t +N = {1:12, 2:15, 3:12, 4:12, 5:12, 6:16, 7:16} +PER = {b:1 if b in (1,4) else 2 for b in N} +LINE = [0, 3, 1, 2] +BC6_BITS = [[0]*4,[10,5,5,5],[7,6,6,6],[11,5,4,4],[11,4,5,4], + [11,4,4,5],[9,5,5,5],[8,6,5,5],[8,5,6,5],[8,5,5,6], + [6,6,6,6],[10,10,10,10],[11,9,9,9],[12,8,8,8],[16,4,4,4]] + + +def wire_descriptors(): + source = args.bc6_reference.read_bytes() + if hashlib.sha256(source).hexdigest() != "187434fab12351df0f875ae09390981034e8479159a6f4aaaf0904f007182b8a": + raise ValueError("DirectXTex reference does not match pinned a8e5dbf42909aeeb9fcf9c2ae399ae3c06737379") + text = source.decode("utf-8-sig") + text = text.split('const D3DX_BC6H::ModeDescriptor D3DX_BC6H::ms_aDesc',1)[1] + text = text.split('// Mode, Partitions, Transformed, IndexPrec',1)[0] + desc = [[]] + for mode, body in re.findall(r'\{\s*// Mode (\d+)[^\n]*\n(.*?)\n\s*\},',text,re.S): + mode = int(mode) + pairs = [(f,int(b)) for f,b in re.findall(r'\{\s*(\w+),\s*(\d+)\s*\}',body)] + assert len(pairs) == 82 and mode == len(desc) + # BCPack's packer writes the high base bits ascending in modes 13/14. + if mode in (13,14): + for f in ['RW','GW','BW']: + positions = [i for i,(field,bit) in enumerate(pairs) if field == f and bit >= 10] + for i,b in zip(positions,sorted(pairs[i][1] for i in positions)): + pairs[i] = (f,b) + desc.append(pairs[:82 if mode <= 10 else 65]) + assert len(desc) == 15 + return desc + + +DESC = wire_descriptors() + + +def interleave(a,b): + return sum(((a>>k&1)<<(2*k)) | ((b>>k&1)<<(2*k+1)) for k in range(4)) + + +def split(v): + return [sum((v>>(2*k+j)&1)<<k for k in range(4)) for j in range(2)] + + +def query(fmt, ep=0, ix=0, mode=11, rank=0): + per = PER[fmt] + s = [0] * (N[fmt] * per) + delta = (ep - ix + 128) % 256 - 128 + zz = 2*delta if delta >= 0 else -2*delta-1 + s[:per] = split(zz) if per == 2 else [zz] + s[per:2*per] = split(ix) if per == 2 else [ix] + if fmt == 1: + s[8:] = [rank]*4 + elif fmt == 2: + s[26:] = [rank]*4 + elif fmt == 6: + s[30] = mode-1 + v = (c.c_uint16*len(s))(*s) + packed = c.create_string_buffer(65536) + n = enc(fmt,v,per,packed,len(packed)) + assert n, (fmt,ep,ix,mode,rank,'encode') + size = 8*per + out = c.create_string_buffer(b'\xa5'*(size+32),size+32) + hr = dec(fmt,c.addressof(out)+16,size,packed,n) + assert hr >= 0, (fmt,ep,ix,mode,rank,hex(hr&0xffffffff)) + assert out.raw[:16] == b'\xa5'*16 and out.raw[-16:] == b'\xa5'*16 + return out.raw[16:-16] + + +def colour(raw): + a,b = int.from_bytes(raw[:2],'little'),int.from_bytes(raw[2:4],'little') + ep = [a>>11,a>>5&63,a&31,b>>11,b>>5&63,b&31] + word = int.from_bytes(raw[4:8],'little') + ix = [LINE[word>>(2*p)&3] for p in range(16)] + return ep,ix + + +def unpack6(raw,mode): + word = int.from_bytes(raw,'little') + fields = {f:0 for f in ['RW','RX','RY','RZ','GW','GX','GY','GZ','BW','BX','BY','BZ']} + for i,(f,bit) in enumerate(DESC[mode]): + if f in fields: fields[f] |= ((word>>i)&1)<<bit + ep = [[0]*3 for _ in range(4)] + for k,e in enumerate('WXYZ'): + if mode > 10 and k > 1: continue + for channel,ch in enumerate('RGB'): + bits = BC6_BITS[mode][0 if k == 0 else channel+1] + ep[k][channel] = (fields[ch+e] << (16-bits)) ^ 0x8000 + at = 82 if mode <= 10 else 65 + bits = 3 if mode <= 10 else 4 + ix = [] + for p in range(16): + width = bits - int(p == 0 or mode <= 10 and p == 15) + value = (word>>at)&((1<<width)-1) + ix.append(((value-(1<<(bits-1))) << (16-bits))&65535) + at += width + assert at == 128 + return ep,ix + + +def main(): + tables = {'method':'Synthetic BCPack lane streams -> decoder API -> public BC block fields; no SDK binary-table extraction', + 'bc6_wire':DESC, 'bc6_bits':BC6_BITS} + for fmt in (1,2): + ranks=[] + for rank in range(256): + _, ix = colour(query(fmt,rank=rank)[0 if fmt == 1 else 8:]) + ranks.append([ix[p] for p in (0,1,4,5)]) + zero = ranks.index([0]*4) + rows=[] + for r in range(1,256): + raw = query(fmt,ep=r,ix=r,rank=zero) + ep,ix=colour(raw[0 if fmt == 1 else 8:]) + row={'ep':ep,'ix':ix} + if fmt == 2: + a=int.from_bytes(raw[:8],'little') + row['alpha']=[((a>>(4*p))&15)^8 for p in range(16)] + rows.append(row) + tables[f'bc{fmt}_ranks']=ranks + tables[f'bc{fmt}_dictionary']=rows + print(f'BC{fmt}: {len(ranks)} quadrant ranks and {len(rows)} predictor entries recovered',flush=True) + rows=[] + for r in range(1,256): + a,_=unpack6(query(6,ep=r,mode=14),14) + b,_=unpack6(query(6,ep=r,mode=11),11) + c,_=unpack6(query(6,ep=r,mode=2),2) + _,ix=unpack6(query(6,ix=r,mode=11),11) + rows.append({'ep':[a[0],b[1],c[2],c[3]],'ix':ix}) + tables['bc6_dictionary']=rows + write_tables(tables, args.output) + if args.storage_goldens: + storage_goldens(args.storage_goldens) + print(f'BC6H: {len(rows)} predictor entries recovered',flush=True) + + +def initializer(values): + return '{ ' + ', '.join(initializer(v) if isinstance(v,list) else str(v) for v in values) + ' }' + + +def storage_goldens(out): + build = encoder.storage_symbols + build.argtypes = [c.c_uint, c.POINTER(c.c_uint16), c.c_size_t] + build.restype = c.c_size_t + lines = ["// GDK 1.2603.3.0 golden BC blocks from random_symbols(fmt,4,0x7700+fmt).", + "// Entirely synthetic input, no SDK or title bytes. SPDX-License-Identifier: MIT", "#pragma once"] + for fmt in (2, 6): + symbols = (c.c_uint16 * 128)() + assert build(fmt, symbols, 128) + packed = c.create_string_buffer(65536) + size = enc(fmt, symbols, 8, packed, len(packed)) + assert size + output = c.create_string_buffer(64) + assert dec(fmt, output, 64, packed, size) >= 0 + lines.append(f"inline constexpr unsigned char BC{fmt}_STORAGE_EXPECTED[64] = {{") + for at in range(0, 64, 16): + lines.append(" " + ", ".join(f"0x{v:02x}" for v in output.raw[at:at+16]) + ",") + lines.append("};") + out.write_text("\n".join(lines) + "\n", encoding="utf-8", newline="\n") + + +def write_tables(t, out): + lines=['// BCPack format constants reconstructed with synthetic lane streams.', + '// No SDK binaries or title data are embedded. See docs/experiments/bcpack-standalone.md.', + '// BC6H wire descriptors adapt the MIT-licensed Microsoft DirectXTex BC6HBC7.cpp.', + '// Copyright (c) Microsoft Corporation. All rights reserved.', + '// SPDX-License-Identifier: MIT', '', + 'struct Bc1FullState { uint8_t ep[6]; uint8_t ix[16]; };', + 'struct Bc2State { uint8_t alpha[16]; uint8_t ep[6]; uint8_t ix[16]; };', + 'struct Bc6State { uint16_t ep[4][3]; uint16_t ix[16]; };', + 'struct Bc6WireBit { uint8_t field; uint8_t bit; };',''] + for fmt in (1,2): + lines.append(f'inline constexpr uint8_t BC{fmt}_POSITION_RANK[256][4] = {{') + lines.extend(' '+initializer(row)+',' for row in t[f'bc{fmt}_ranks']) + lines.extend(['};','']) + typ='Bc1FullState' if fmt==1 else 'Bc2State' + lines.append(f'inline constexpr {typ} BC{fmt}_FULL_DICTIONARY[255] = {{') + fields=['ep','ix'] if fmt==1 else ['alpha','ep','ix'] + lines.extend(' '+initializer([row[f] for f in fields])+',' for row in t[f'bc{fmt}_dictionary']) + lines.extend(['};','']) + lines.append('inline constexpr Bc6State BC6_DICTIONARY[255] = {') + lines.extend(' '+initializer([row['ep'],row['ix']])+',' for row in t['bc6_dictionary']) + lines.extend(['};','','inline constexpr uint8_t BC6_ENDPOINT_BITS[15][4] = {']) + lines.extend(' '+initializer(row)+',' for row in t['bc6_bits']) + lines.extend(['};','','// 0 = mode bit, 1 = partition bit; 2 + 3 * endpoint + channel = endpoint bit.', + 'inline constexpr Bc6WireBit BC6_WIRE[14][82] = {']) + for mode,row in enumerate(t['bc6_wire'][1:],1): + vals=[] + for f,b in row: + field = 0 if f in ('M','NA') else 1 if f=='D' else 2+3*'WXYZ'.index(f[1])+'RGB'.index(f[0]) + vals.append([field,b]) + lines.append(' { // Mode '+str(mode)) + for pos in range(0,len(vals),10): + lines.append(' '+', '.join(initializer(v) for v in vals[pos:pos+10])+',') + lines.append(' },') + lines.extend(['};','']) + out.write_text('\n'.join(lines),encoding='utf-8',newline='\n') + print(out, out.stat().st_size) + + +if __name__ == "__main__": + main() diff --git a/tools/gdk_abi_probe.py b/tools/gdk_abi_probe.py new file mode 100644 index 0000000000..656a9f06f9 --- /dev/null +++ b/tools/gdk_abi_probe.py @@ -0,0 +1,163 @@ +#!/usr/bin/env python3 +"""Generate and compare C++ ABI probes from parsed GDK layouts. + +The layout JSON comes from tools/gdk_layouts.py. The generated probe can either +assert sizes and offsets at compile time or print them for a GRDK/GXDK diff. +Only names, sizes and offsets are used; private members and non-standard-layout +classes need an explicit review before offsetof is enabled. + +Commands: + generate --layouts <json> --out <cpp> [--include H]... [--print] [--offsetof] + parse <log> [--json <out>] + diff <left.json> <right.json> +""" + +import argparse +import json +import re +import sys +from pathlib import Path + + +IDENTIFIER = re.compile(r"^[A-Za-z_]\w*$") +CLASS_NAME = re.compile(r"^(?:::)?[A-Za-z_]\w*(?:::[A-Za-z_]\w*)*$") + + +def load_classes(path): + document = json.loads(Path(path).read_text(encoding="utf-8")) + return document, document.get("classes", []) + + +def member_offsets(block): + has_dynamic_layout = bool(block.get("bases")) or any( + item.get("kind") == "vftable" for item in block.get("members", []) + ) + if has_dynamic_layout: + return [] + offsets = [] + for item in block.get("members", []): + if item.get("kind") != "field" or item.get("bits") is not None: + continue + name = item.get("name", "") + if IDENTIFIER.fullmatch(name): + offsets.append((name, item["offset"])) + return offsets + + +def generate_command(args): + document, classes = load_classes(args.layouts) + if args.prefix: + classes = [ + block + for block in classes + if any(block["name"].startswith(prefix) for prefix in args.prefix) + ] + skipped = [block["name"] for block in classes if not CLASS_NAME.fullmatch(block["name"])] + classes = [block for block in classes if CLASS_NAME.fullmatch(block["name"])] + lines = [ + "// Generated by tools/gdk_abi_probe.py; do not edit.", + f"// module: {document.get('module', '')}", + f"// source: {document.get('header', '')}", + "", + ] + lines += [f"#include <{header}>" if not header.startswith('"') else f"#include {header}" for header in args.include] + lines.append("#include <cstddef>") + if args.print: + lines.append("#include <cstdio>") + lines.append("") + for block in classes: + name = block["name"] + lines.append(f'static_assert(sizeof({name}) == {block["size"]}, "sizeof({name})");') + if args.offsetof: + for member, offset in member_offsets(block): + lines.append( + f'static_assert(offsetof({name}, {member}) == {offset}, "offsetof({name}, {member})");' + ) + if args.print: + lines += ["", "int main()", "{"] + for block in classes: + name = block["name"] + lines.append(f' std::printf("sizeof({name})=%zu\\n", sizeof({name}));') + if args.offsetof: + for member, _ in member_offsets(block): + lines.append( + f' std::printf("offsetof({name}, {member})=%zu\\n", offsetof({name}, {member}));' + ) + lines += [" return 0;", "}"] + Path(args.out).parent.mkdir(parents=True, exist_ok=True) + Path(args.out).write_text("\n".join(lines) + "\n", encoding="utf-8") + print( + json.dumps( + { + "classes": len(classes), + "skipped": len(skipped), + "offsetof": bool(args.offsetof), + "print": bool(args.print), + } + ) + ) + return 0 + + +def parse_command(args): + facts = {} + for line in Path(args.log).read_text(encoding="utf-8", errors="replace").splitlines(): + if "=" not in line: + continue + key, value = line.split("=", 1) + try: + facts[key.strip()] = int(value.strip(), 0) + except ValueError: + facts[key.strip()] = value.strip() + document = {"facts": facts} + if args.json: + Path(args.json).parent.mkdir(parents=True, exist_ok=True) + Path(args.json).write_text(json.dumps(document, indent=2) + "\n", encoding="utf-8") + print(json.dumps({"facts": len(facts)})) + return 0 + + +def diff_command(args): + left = json.loads(Path(args.left).read_text(encoding="utf-8")).get("facts", {}) + right = json.loads(Path(args.right).read_text(encoding="utf-8")).get("facts", {}) + changes = [] + for key in sorted(set(left) | set(right)): + if left.get(key) != right.get(key): + changes.append({"key": key, "left": left.get(key), "right": right.get(key)}) + if not changes: + print("no ABI differences") + return 0 + for change in changes: + print(json.dumps(change, sort_keys=True)) + return 1 + + +def main(argv=None): + parser = argparse.ArgumentParser(description=__doc__) + sub = parser.add_subparsers(dest="command", required=True) + + generate = sub.add_parser("generate", help="emit a C++ probe") + generate.add_argument("--layouts", required=True) + generate.add_argument("--out", required=True) + generate.add_argument("--include", action="append", default=[]) + generate.add_argument("--prefix", action="append", default=[]) + generate.add_argument("--offsetof", action="store_true") + generate.add_argument("--print", action="store_true") + generate.set_defaults(func=generate_command) + + parse = sub.add_parser("parse", help="parse a probe log") + parse.add_argument("log") + parse.add_argument("--json") + parse.set_defaults(func=parse_command) + + diff = sub.add_parser("diff", help="compare two parsed probe logs") + diff.add_argument("left") + diff.add_argument("right") + diff.set_defaults(func=diff_command) + + args = parser.parse_args(argv) + return args.func(args) + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/gdk_knowledge_report.py b/tools/gdk_knowledge_report.py new file mode 100644 index 0000000000..33e9b17935 --- /dev/null +++ b/tools/gdk_knowledge_report.py @@ -0,0 +1,1676 @@ +#!/usr/bin/env python3 +"""Merge GDK knowledge facts, report conflicts and count coverage. + +The tool reads only JSON metadata. It never loads a GDK binary, header or SDK +file. Inputs are optional directories under a knowledge root: + + layouts/*.json layout classes with a size and members + abi/*.json ABI facts (structs, enums, constants, GUIDs) + exports/*.json export rows, or a root exports-all.json + behavior/*.json runtime observations + platform/*.json build defines, includes, libraries and flags + shaders/corpus.json shader corpus cases + +Normalised facts carry module, kind, name, value, source, confidence and +targets. Conflicts are grouped by fact identity and by type name. The report is +deterministic: facts, conflicts, modules and shims are sorted before writing. +""" + +from __future__ import annotations + +import argparse +import json +from pathlib import Path +import re +import sys +from collections import defaultdict + + +SCHEMA = "xbox2windows.gdk_knowledge/1" +TOOL = "gdk_knowledge_report" +VERSION = 1 +CATEGORIES = ("layouts", "abi", "exports", "behavior", "platform", "shaders") +TYPE_KINDS = frozenset( + {"layout", "class", "struct", "union", "type", "typedef", "sizeof"} +) +ENUM_KINDS = frozenset({"enum", "enumerator", "enumeration", "enum-value"}) +CONFLICT_ORDER = {"value": 0, "size": 1, "ordinal": 2, "enum": 3, "type-size": 4} +FACT_FIELDS = ("module", "kind", "name", "value", "source", "confidence", "targets") +DEFAULT_CONFIDENCE = { + "layouts": "header", + "abi": "compiled", + "exports": "export-table", + "behavior": "runtime", + "platform": "build-profile", + "shaders": "shader-corpus", +} +LEFTOVER_KEYS = frozenset( + {"module", "kind", "name", "value", "source", "confidence", "targets"} +) +METHOD_SOURCES = frozenset( + { + "msvc-layout", + "compiled-probe", + "dumpbin", + "runtime-oracle", + "header-msvc-layout", + } +) + + +class InputError(Exception): + """A malformed input or unusable path. The CLI maps this to exit code 2.""" + + +def _canonical(value): + return json.dumps(value, sort_keys=True, ensure_ascii=False, separators=(",", ":")) + + +def _as_int(value): + if isinstance(value, bool) or value is None: + return None + if isinstance(value, int): + return value + if isinstance(value, str): + text = value.strip() + if not text: + return None + try: + if text.lower().startswith(("0x", "-0x")): + return int(text, 16) + return int(text, 10) + except ValueError: + return None + return None + + +def _display_source(source): + if isinstance(source, str): + return source + return _canonical(source) + + +def _value_sort_key(value): + if isinstance(value, bool): + return (0, int(value), "") + if isinstance(value, (int, float)): + return (1, value, "") + if isinstance(value, str): + return (2, 0, value) + return (3, 0, _canonical(value)) + + +def _relative(path, root): + path = Path(path) + root = Path(root) + try: + return path.resolve().relative_to(root.resolve()).as_posix() + except (OSError, ValueError): + return path.name + + +def _read_json(path): + path = Path(path) + try: + text = path.read_text(encoding="utf-8-sig") + except OSError as exc: + raise InputError("cannot read {}: {}".format(path, exc)) from exc + try: + return json.loads(text) + except json.JSONDecodeError as exc: + raise InputError( + "invalid JSON in {} at line {} column {}: {}".format( + path, exc.lineno, exc.colno, exc.msg + ) + ) from exc + + +def _require_object(value, where): + if not isinstance(value, dict): + raise InputError("{} must be a JSON object".format(where)) + return value + + +def _require_list(value, where): + if not isinstance(value, list): + raise InputError("{} must be a JSON array".format(where)) + return value + + +def _require_name(item, where, keys=("name",)): + for key in keys: + value = item.get(key) + if isinstance(value, str) and value.strip(): + return value.strip() + raise InputError("{} has no non-empty {}".format(where, "/".join(keys))) + + +def _normalise_targets(value, where): + if value is None: + return [] + if isinstance(value, str): + return [value] + if not isinstance(value, list): + raise InputError("{} targets must be a string or an array".format(where)) + targets = [] + for target in value: + if not isinstance(target, str): + raise InputError("{} targets must contain strings".format(where)) + if target: + targets.append(target) + return sorted(set(targets)) + + +def _source_and_confidence(item, meta, default_source, default_confidence): + item = item if isinstance(item, dict) else {} + meta = meta if isinstance(meta, dict) else {} + source = None + method = None + for candidate in (item.get("source"), meta.get("source")): + if isinstance(candidate, str) and candidate.strip(): + text = candidate.strip() + if text.casefold() in METHOD_SOURCES: + if method is None: + method = text + elif source is None: + source = text + elif candidate is not None and source is None: + source = candidate + confidence = ( + item.get("confidence") + or meta.get("confidence") + or method + or default_confidence + ) + return source or default_source, confidence + + +def _module_from_stem(stem): + text = Path(stem).stem + lowered = text.casefold() + suffixes = ( + "-all-layout", + "-interesting-layout", + "-layout-report", + "-layout", + "_layout", + "-vtables", + "-facts", + "-exports", + ) + for suffix in suffixes: + if lowered.endswith(suffix) and len(text) > len(suffix): + return text[: -len(suffix)] + return text + + +def _module_from_library(path): + name = Path(path).name + lowered = name.casefold() + for suffix in (".lib", ".dll"): + if lowered.endswith(suffix): + return name[: -len(suffix)] + return _module_from_stem(name) + + +def _module_from_def_stem(stem): + module = _module_from_stem(stem) + lowered = module.casefold() + for suffix in ("_shim", "-shim"): + if lowered.endswith(suffix) and len(module) > len(suffix): + return module[: -len(suffix)] + return module + + +def _make_fact(module, kind, name, value, source, confidence, targets): + if not isinstance(module, str) or not module.strip(): + raise InputError("fact {} has no module".format(name)) + if not isinstance(kind, str) or not kind.strip(): + raise InputError("fact {} has no kind".format(name)) + if not isinstance(name, str) or not name.strip(): + raise InputError("fact has no non-empty name") + if confidence is None: + confidence = "" + if not isinstance(confidence, str): + confidence = str(confidence) + return { + "module": module.strip(), + "kind": kind.strip(), + "name": name.strip(), + "value": value, + "source": source, + "confidence": confidence, + "targets": list(targets), + } + + +def _fact_sort_key(fact): + return ( + fact["module"].casefold(), + fact["module"], + fact["kind"].casefold(), + fact["kind"], + fact["name"].casefold(), + fact["name"], + _canonical(fact["value"]), + _canonical(fact["source"]), + ) + + +def _dedupe_facts(facts): + seen = set() + result = [] + for fact in facts: + key = _canonical(fact) + if key in seen: + continue + seen.add(key) + result.append(fact) + result.sort(key=_fact_sort_key) + return result + + +def _canonicalise_modules(facts): + counts = defaultdict(lambda: defaultdict(int)) + for fact in facts: + counts[fact["module"].casefold()][fact["module"]] += 1 + canonical = {} + for key, variants in counts.items(): + if len(variants) == 1: + canonical[key] = next(iter(variants)) + continue + canonical[key] = sorted( + variants, + key=lambda name: ( + -variants[name], + name != name.lower(), + name.casefold(), + name, + ), + )[0] + for fact in facts: + fact["module"] = canonical[fact["module"].casefold()] + return facts + + +def _is_type_kind(kind): + return kind.casefold() in TYPE_KINDS + + +def _is_enum_kind(kind): + lowered = kind.casefold().replace("_", "-") + return lowered in ENUM_KINDS or lowered.startswith("enum-") + + +def _is_anonymous_name(name): + lowered = name.casefold() + return "<unnamed" in lowered or "<anonymous" in lowered + + +def _size_of(fact): + if not _is_type_kind(fact["kind"]): + return None + value = fact["value"] + if isinstance(value, bool): + return None + if isinstance(value, int): + return value + if isinstance(value, dict): + for key in ("size", "sizeof", "bytes", "size_bytes"): + if key in value: + number = _as_int(value[key]) + if number is not None: + return number + return None + + +def _ordinal_of(fact): + value = fact["value"] + if isinstance(value, dict): + return _as_int(value.get("ordinal")) + return _as_int(value) + + +def _json_files(directory): + directory = Path(directory) + if not directory.is_dir(): + return [] + return sorted( + (path for path in directory.iterdir() if path.is_file() and path.suffix.lower() == ".json"), + key=lambda path: path.name.casefold(), + ) + + +def _load_layouts(path, root): + data = _read_json(path) + where = _relative(path, root) + meta = data if isinstance(data, dict) else {} + if isinstance(data, list): + classes = data + elif isinstance(data, dict): + classes = data.get("classes") + if classes is None and "name" in data: + classes = [data] + if classes is None: + raise InputError("{} has no classes array".format(where)) + _require_list(classes, where + " classes") + else: + raise InputError("{} must contain an object or an array".format(where)) + + fallback_module = _module_from_stem(path.stem) + top_module = meta.get("module") + facts = [] + for index, item in enumerate(classes): + item_where = "{} classes[{}]".format(where, index) + item = _require_object(item, item_where) + name = _require_name(item, item_where) + size = _as_int(item.get("size")) + if size is None: + size = _as_int(item.get("bytes")) + if size is None or size < 0: + raise InputError("{} has no non-negative integer size".format(item_where)) + members = item.get("members", []) + if members is None: + members = [] + _require_list(members, item_where + " members") + module = item.get("module") or top_module or fallback_module + kind = item.get("kind") or "layout" + source, confidence = _source_and_confidence( + item, meta, where, DEFAULT_CONFIDENCE["layouts"] + ) + targets = _normalise_targets( + item["targets"] if "targets" in item else meta.get("targets"), + item_where, + ) + facts.append( + _make_fact( + module, + kind, + name, + {"size": size, "members": members}, + source, + confidence, + targets, + ) + ) + return facts + + +def _load_abi(path, root): + data = _read_json(path) + where = _relative(path, root) + if isinstance(data, list): + facts_data = data + meta = {} + elif isinstance(data, dict): + meta = data + facts_data = data.get("facts") + if facts_data is None: + raise InputError("{} has no facts array".format(where)) + _require_list(facts_data, where + " facts") + else: + raise InputError("{} must contain an object or an array".format(where)) + + fallback_module = _module_from_stem(path.stem) + top_module = meta.get("module") + facts = [] + for index, item in enumerate(facts_data): + item_where = "{} facts[{}]".format(where, index) + item = _require_object(item, item_where) + name = _require_name(item, item_where) + kind = item.get("kind") or meta.get("kind") + if not isinstance(kind, str) or not kind.strip(): + raise InputError("{} has no non-empty kind".format(item_where)) + if "value" in item: + value = item["value"] + else: + value = {key: val for key, val in item.items() if key not in LEFTOVER_KEYS} + module = item.get("module") or top_module or fallback_module + source, confidence = _source_and_confidence( + item, meta, where, DEFAULT_CONFIDENCE["abi"] + ) + targets = _normalise_targets( + item["targets"] if "targets" in item else meta.get("targets"), + item_where, + ) + facts.append( + _make_fact(module, kind.strip(), name, value, source, confidence, targets) + ) + return facts + + +def _export_groups(data, where): + if isinstance(data, list): + if not data: + return [] + if all(isinstance(item, dict) and isinstance(item.get("exports"), list) for item in data): + return data + if all(isinstance(item, dict) and "name" in item for item in data): + return [{"exports": data}] + raise InputError("{} export array has an unsupported shape".format(where)) + + data = _require_object(data, where) + if isinstance(data.get("modules"), list): + return _require_list(data["modules"], where + " modules") + if isinstance(data.get("modules"), dict): + groups = [] + for module, rows in data["modules"].items(): + if not isinstance(rows, list): + raise InputError( + "{} module {} must have an exports array".format(where, module) + ) + groups.append({"module": module, "exports": rows}) + return groups + if "exports" in data: + return [data] + + metadata = { + "schema", + "generated", + "sdk", + "module", + "source", + "confidence", + "targets", + "kind", + "file", + } + groups = [] + for module, rows in data.items(): + if module in metadata: + continue + if not isinstance(rows, list): + raise InputError("{} mapping entry {} must be an array".format(where, module)) + groups.append({"module": module, "exports": rows}) + if not groups: + raise InputError("{} has no exports array".format(where)) + return groups + + +def _load_exports(path, root): + data = _read_json(path) + where = _relative(path, root) + groups = _export_groups(data, where) + meta = data if isinstance(data, dict) else {} + fallback_module = _module_from_stem(path.stem) + fallback_source = where + top_module = meta.get("module") + + facts = [] + for group_index, group in enumerate(groups): + group_where = "{} exports[{}]".format(where, group_index) + group = _require_object(group, group_where) + rows = group.get("exports", []) + _require_list(rows, group_where + " exports") + + module = group.get("module") or top_module + if not module and group.get("file"): + module = _module_from_library(group["file"]) + if not module: + module = fallback_module + + source, confidence = _source_and_confidence( + group, meta, fallback_source, DEFAULT_CONFIDENCE["exports"] + ) + if group.get("file"): + origin = Path(str(group["file"])).name + if origin: + source = "{}#{}".format(source, origin) + targets = _normalise_targets( + group["targets"] if "targets" in group else meta.get("targets"), + group_where, + ) + + for row_index, row in enumerate(rows): + row_where = "{} row {}".format(group_where, row_index) + if isinstance(row, str): + row = {"name": row} + row = _require_object(row, row_where) + name = _require_name(row, row_where) + ordinal = _as_int(row.get("ordinal")) + rva = row.get("rva") + parsed_rva = _as_int(rva) + if parsed_rva is not None: + rva = parsed_rva + row_module = row.get("module") or module + row_source = row.get("source") or source + row_confidence = row.get("confidence") or confidence + row_targets = _normalise_targets( + row["targets"] if "targets" in row else targets, + row_where, + ) + facts.append( + _make_fact( + row_module, + "export", + name, + {"ordinal": ordinal, "rva": rva}, + row_source, + row_confidence, + row_targets, + ) + ) + return facts + + +def _observation_value(item): + payload = { + key: value + for key, value in item.items() + if key not in {"module", "kind", "name", "source", "confidence", "targets"} + } + observation_kind = item.get("kind") + if isinstance(observation_kind, str): + lowered = observation_kind.casefold() + if lowered not in {"behavior", "runtime", "observation", "value", ""}: + payload["observation"] = observation_kind + if not payload: + return None + if set(payload) == {"value"}: + return payload["value"] + return payload + + +def _load_behavior(path, root): + data = _read_json(path) + where = _relative(path, root) + if isinstance(data, list): + observations = data + meta = {} + elif isinstance(data, dict): + meta = data + observations = data.get("observations") + if observations is None: + raise InputError("{} has no observations array".format(where)) + _require_list(observations, where + " observations") + else: + raise InputError("{} must contain an object or an array".format(where)) + + fallback_module = _module_from_stem(path.stem) + top_module = meta.get("module") + facts = [] + for index, item in enumerate(observations): + item_where = "{} observations[{}]".format(where, index) + item = _require_object(item, item_where) + name = _require_name(item, item_where) + module = item.get("module") or top_module or fallback_module + source, confidence = _source_and_confidence( + item, meta, where, DEFAULT_CONFIDENCE["behavior"] + ) + targets = _normalise_targets( + item["targets"] if "targets" in item else meta.get("targets"), + item_where, + ) + facts.append( + _make_fact( + module, + "behavior", + name, + _observation_value(item), + source, + confidence, + targets, + ) + ) + return facts + + +def _load_platform(path, root): + data = _read_json(path) + where = _relative(path, root) + if isinstance(data, list): + items = data + meta = {} + elif isinstance(data, dict): + meta = data + platforms = data.get("platforms") + if platforms is not None: + _require_list(platforms, where + " platforms") + items = platforms + else: + items = [data] + else: + raise InputError("{} must contain an object or an array".format(where)) + + fallback_module = _module_from_stem(path.stem) + top_module = meta.get("module") + facts = [] + for index, item in enumerate(items): + item_where = "{} platforms[{}]".format(where, index) + item = _require_object(item, item_where) + values = {} + has_values = False + for key in ("defines", "includes", "libs", "flags"): + rows = item.get(key, []) + if rows is None: + rows = {} if key == "flags" else [] + if isinstance(rows, str): + rows = [rows] + if not isinstance(rows, (list, dict)): + raise InputError( + "{} {} must be an array or object".format(item_where, key) + ) + values[key] = rows + has_values = has_values or bool(rows) + name = item.get("platform") or item.get("name") or item.get("id") + if not name and not has_values and not item.get("module"): + raise InputError("{} has no platform name or build facts".format(item_where)) + module = item.get("module") or top_module or name or fallback_module + if not name: + name = module + if not isinstance(name, str) or not name.strip(): + raise InputError("{} has no non-empty platform name".format(item_where)) + source, confidence = _source_and_confidence( + item, meta, where, DEFAULT_CONFIDENCE["platform"] + ) + targets = _normalise_targets( + item["targets"] if "targets" in item else meta.get("targets"), + item_where, + ) + facts.append( + _make_fact( + module, + "platform", + name, + values, + source, + confidence, + targets, + ) + ) + return facts + + +def _load_shaders(path, root): + data = _read_json(path) + where = _relative(path, root) + if isinstance(data, list): + cases = data + meta = {} + elif isinstance(data, dict): + meta = data + cases = data.get("cases") + if cases is None: + raise InputError("{} has no cases array".format(where)) + _require_list(cases, where + " cases") + else: + raise InputError("{} must contain an object or an array".format(where)) + + fallback_module = meta.get("module") or meta.get("platform") or path.parent.name + facts = [] + for index, item in enumerate(cases): + item_where = "{} cases[{}]".format(where, index) + item = _require_object(item, item_where) + name = None + for key in ("name", "id", "case"): + value = item.get(key) + if isinstance(value, str) and value.strip(): + name = value.strip() + break + if name is None: + name = "case-{:04d}".format(index) + value = { + key: val + for key, val in item.items() + if key not in {"module", "name", "id", "case", "source", "confidence", "targets"} + } + module = item.get("module") or fallback_module + source, confidence = _source_and_confidence( + item, meta, where, DEFAULT_CONFIDENCE["shaders"] + ) + targets = _normalise_targets( + item["targets"] if "targets" in item else meta.get("targets"), + item_where, + ) + facts.append( + _make_fact(module, "shader", name, value, source, confidence, targets) + ) + return facts + + +def load_knowledge(root): + root = Path(root) + if not root.exists(): + raise InputError("knowledge root does not exist: {}".format(root)) + if not root.is_dir(): + raise InputError("knowledge root is not a directory: {}".format(root)) + + category_files = {category: [] for category in CATEGORIES} + category_facts = {category: 0 for category in CATEGORIES} + facts = [] + + for category in ("layouts", "abi", "behavior", "platform"): + loader = { + "layouts": _load_layouts, + "abi": _load_abi, + "behavior": _load_behavior, + "platform": _load_platform, + }[category] + files = _json_files(root / category) + for path in files: + loaded = loader(path, root) + facts.extend(loaded) + category_facts[category] += len(loaded) + category_files[category] = [_relative(path, root) for path in files] + + export_files = _json_files(root / "exports") + if not export_files: + root_exports = root / "exports-all.json" + if root_exports.is_file(): + export_files = [root_exports] + for path in export_files: + loaded = _load_exports(path, root) + facts.extend(loaded) + category_facts["exports"] += len(loaded) + category_files["exports"] = [_relative(path, root) for path in export_files] + + shader_corpus = root / "shaders" / "corpus.json" + if not shader_corpus.is_file(): + shader_corpus = root / "shaders" / "corpus" / "corpus.json" + if shader_corpus.is_file(): + loaded = _load_shaders(shader_corpus, root) + facts.extend(loaded) + category_facts["shaders"] = len(loaded) + category_files["shaders"] = [_relative(shader_corpus, root)] + + return facts, category_files, category_facts + + +def _unique_value_entries(entries): + chosen = {} + for fact, value in entries: + key = _canonical(value) + source = _display_source(fact["source"]) + candidate = (fact["module"], value, source) + previous = chosen.get(key) + if previous is None or (source.casefold(), source) < ( + previous[2].casefold(), + previous[2], + ): + chosen[key] = candidate + return [ + {"module": module, "value": value, "source": source} + for module, value, source in sorted( + chosen.values(), + key=lambda item: ( + item[0].casefold(), + item[0], + _value_sort_key(item[1]), + item[2].casefold(), + item[2], + ), + ) + ] + + +def _fact_value_entries(items): + return _unique_value_entries([(fact, fact["value"]) for fact in items]) + + +def _conflict(kind, module, name, values, message, modules=None): + sources = sorted({_display_source(item["source"]) for item in values}) + conflict = { + "kind": kind, + "module": module, + "name": name, + "values": values, + "sources": sources, + "message": message, + } + if modules is not None: + conflict["modules"] = sorted(modules) + return conflict + + +def detect_conflicts(facts): + grouped = defaultdict(list) + type_by_module_name = defaultdict(list) + type_by_name = defaultdict(lambda: defaultdict(list)) + enum_by_name = defaultdict(list) + export_by_name = defaultdict(list) + + for fact in facts: + grouped[(fact["module"], fact["kind"], fact["name"])].append(fact) + kind = fact["kind"] + anonymous_type = _is_type_kind(kind) and _is_anonymous_name(fact["name"]) + if _is_type_kind(kind) and not anonymous_type: + size = _size_of(fact) + if size is not None: + type_by_module_name[(fact["module"], fact["name"])].append((fact, size)) + type_by_name[fact["name"]][fact["module"]].append((fact, size)) + if _is_enum_kind(kind) and not _is_anonymous_name(fact["name"]): + enum_by_name[(fact["module"], fact["name"])].append(fact) + if kind.casefold() == "export": + export_by_name[(fact["module"], fact["name"])].append(fact) + + conflicts = [] + size_conflict_keys = set() + for (module, name), entries in sorted(type_by_module_name.items()): + sizes = {size for _, size in entries} + if len(sizes) <= 1: + continue + values = _unique_value_entries(entries) + conflicts.append( + _conflict( + "size", + module, + name, + values, + "type {} has conflicting sizes in module {}: {}".format( + name, module, ", ".join(str(size) for size in sorted(sizes)) + ), + ) + ) + size_conflict_keys.add((module, name)) + + enum_conflict_keys = set() + for (module, name), items in sorted(enum_by_name.items()): + values = _fact_value_entries(items) + if len(values) <= 1: + continue + conflicts.append( + _conflict( + "enum", + module, + name, + values, + "enum {} has conflicting values in module {}".format(name, module), + ) + ) + enum_conflict_keys.add((module, name)) + + for (module, name), items in sorted(export_by_name.items()): + ordinals = sorted({_ordinal_of(fact) for fact in items if _ordinal_of(fact) is not None}) + if len(ordinals) <= 1: + continue + values = [ + { + "module": module, + "value": ordinal, + "source": _display_source( + next( + fact["source"] + for fact in items + if _ordinal_of(fact) == ordinal + ) + ), + } + for ordinal in ordinals + ] + conflicts.append( + _conflict( + "ordinal", + module, + name, + values, + "export {} has conflicting ordinals: {}".format( + name, ", ".join(str(ordinal) for ordinal in ordinals) + ), + ) + ) + + for (module, kind, name), items in sorted(grouped.items()): + values = _fact_value_entries(items) + if len(values) <= 1: + continue + if kind.casefold() == "export": + continue + if (_is_type_kind(kind) or _is_enum_kind(kind)) and _is_anonymous_name(name): + continue + if _is_type_kind(kind) and (module, name) in size_conflict_keys: + continue + if _is_enum_kind(kind) and (module, name) in enum_conflict_keys: + continue + conflicts.append( + _conflict( + "value", + module, + name, + values, + "{} {} has {} distinct values in module {}".format( + kind, name, len(values), module + ), + ) + ) + + for name in sorted(type_by_name, key=lambda text: (text.casefold(), text)): + modules = type_by_name[name] + if len(modules) < 2: + continue + all_sizes = {size for entries in modules.values() for _, size in entries} + if len(all_sizes) <= 1: + continue + values = [] + for module in sorted(modules, key=lambda text: (text.casefold(), text)): + unique_sizes = {} + for fact, size in modules[module]: + key = _canonical(size) + source = _display_source(fact["source"]) + previous = unique_sizes.get(key) + if previous is None or (source.casefold(), source) < ( + previous[0].casefold(), + previous[0], + ): + unique_sizes[key] = (source, size) + for source, size in sorted( + unique_sizes.values(), key=lambda item: (_value_sort_key(item[1]), item[0]) + ): + values.append({"module": module, "value": size, "source": source}) + module_summary = ", ".join( + "{}={}".format( + module, + "/".join( + str(size) + for size in sorted( + {size for _, size in modules[module]} + ) + ), + ) + for module in sorted(modules, key=lambda text: (text.casefold(), text)) + ) + conflicts.append( + _conflict( + "type-size", + "*", + name, + values, + "type {} has incompatible sizes across modules: {}".format( + name, module_summary + ), + modules=modules, + ) + ) + + conflicts.sort( + key=lambda item: ( + CONFLICT_ORDER.get(item["kind"], 99), + item["kind"], + item["module"].casefold(), + item["module"], + item["name"].casefold(), + item["name"], + _canonical(item["values"]), + ) + ) + return conflicts + + +def _is_internal_shim(name): + return name.casefold().startswith("x2w") + + +def _clean_export_name(name): + text = name.strip().strip('"') + match = re.match(r"^(.*?)@\d+$", text) + if match: + text = match.group(1) + return text.strip() + + +def _parse_def(path, root): + text = path.read_text(encoding="utf-8-sig", errors="replace") + module = None + in_exports = False + entries = [] + source = _relative(path, root) + + for raw in text.splitlines(): + line = raw.split(";", 1)[0].strip() + if not line: + continue + upper = line.upper() + if upper.startswith("LIBRARY"): + rest = line[len("LIBRARY"):].strip() + module = rest.strip().strip('"') or None + continue + if upper.startswith("EXPORTS"): + in_exports = True + continue + if not in_exports: + continue + + token = line.split()[0] + alias = None + if "=" in token: + token, alias = token.split("=", 1) + export_name = _clean_export_name(token) + if alias: + alias = _clean_export_name(alias) + if not export_name or export_name.startswith(";"): + continue + entries.append( + { + "module": module or _module_from_def_stem(path.stem), + "name": export_name, + "alias": alias, + "source": source, + } + ) + return entries + + +def _load_shim_mapping(path): + data = _read_json(path) + source = path.name + entries = [] + default_module = data.get("module") if isinstance(data, dict) else None + + def add(module, item): + if isinstance(item, str): + name = item.strip() + alias = None + elif isinstance(item, dict): + name = item.get("name") + alias = item.get("alias") + else: + raise InputError("{} shim entry must be a string or object".format(source)) + if not isinstance(name, str) or not name.strip(): + raise InputError("{} shim entry has no non-empty name".format(source)) + if alias is not None: + if not isinstance(alias, str): + raise InputError("{} shim alias must be a string".format(source)) + alias = alias.strip() or None + entries.append( + { + "module": module or "shims", + "name": name.strip(), + "alias": alias, + "source": source, + } + ) + + def add_mapping(mapping): + for module, rows in mapping.items(): + if not isinstance(rows, list): + raise InputError("{} mapping {} must be an array".format(source, module)) + for item in rows: + add(module, item) + + def add_rows(module, rows): + if not isinstance(rows, list): + raise InputError("{} group {} must be an array".format(source, module)) + for item in rows: + add(module, item) + + metadata = { + "schema", + "generated", + "sdk", + "module", + "source", + "confidence", + "targets", + "note", + "version", + } + + if isinstance(data, dict): + if isinstance(data.get("modules"), dict): + add_mapping(data["modules"]) + elif isinstance(data.get("modules"), list): + for group in data["modules"]: + group = _require_object(group, source + " module group") + module = group.get("module") or default_module + rows = group.get("exports", group.get("shims")) + if rows is None: + raise InputError("{} module group has no exports".format(source)) + add_rows(module, rows) + elif isinstance(data.get("shims"), list): + for item in data["shims"]: + if isinstance(item, dict) and item.get("module"): + add(item["module"], item) + else: + add(default_module, item) + elif isinstance(data.get("shims"), dict): + add_mapping(data["shims"]) + elif isinstance(data.get("exports"), list): + add_rows(default_module, data["exports"]) + else: + mapping = {} + for key, value in data.items(): + if key in metadata: + continue + if not isinstance(value, list): + raise InputError( + "{} mapping {} must be an array".format(source, key) + ) + mapping[key] = value + if mapping: + add_mapping(mapping) + elif not data: + return [] + else: + raise InputError("{} has no shim mapping".format(source)) + elif isinstance(data, list): + for item in data: + if isinstance(item, dict) and isinstance(item.get("exports"), list): + module = item.get("module") or default_module + add_rows(module, item["exports"]) + elif isinstance(item, dict) and item.get("module"): + add(item["module"], item) + else: + add(default_module, item) + else: + raise InputError("{} must contain a shim mapping".format(source)) + return entries + + +def load_shims(path): + if path is None: + return { + "source": None, + "exports": 0, + "covered": 0, + "without_fact": [], + "internal": 0, + } + path = Path(path) + if not path.exists(): + raise InputError("defs path does not exist: {}".format(path)) + + entries = [] + if path.is_file(): + if path.suffix.lower() == ".json": + entries = _load_shim_mapping(path) + elif path.suffix.lower() == ".def": + entries = _parse_def(path, path.parent) + else: + raise InputError("defs file must be .def or .json: {}".format(path)) + elif path.is_dir(): + files = sorted( + ( + item + for item in path.rglob("*") + if item.is_file() and item.suffix.lower() == ".def" + ), + key=lambda item: item.as_posix().casefold(), + ) + for item in files: + entries.extend(_parse_def(item, path)) + else: + raise InputError("defs path is not a file or directory: {}".format(path)) + + merged = {} + internal = 0 + for entry in entries: + if _is_internal_shim(entry["name"]): + internal += 1 + continue + key = (entry["module"].casefold(), entry["name"].casefold()) + if key not in merged: + merged[key] = entry + elif not merged[key].get("alias") and entry.get("alias"): + merged[key]["alias"] = entry["alias"] + + result = [] + for entry in sorted( + merged.values(), + key=lambda item: ( + item["module"].casefold(), + item["module"], + item["name"].casefold(), + item["name"], + ), + ): + result.append( + { + "module": entry["module"], + "name": entry["name"], + "alias": entry.get("alias"), + "source": entry["source"], + } + ) + return { + "source": str(path), + "exports": len(result), + "covered": 0, + "without_fact": result, + "internal": internal, + } + + +def _associate_shims(shims, facts): + if not shims["without_fact"]: + return shims + exact = {fact["name"] for fact in facts} + folded = {fact["name"].casefold() for fact in facts} + covered = 0 + missing = [] + for entry in shims["without_fact"]: + names = [entry["name"]] + if entry.get("alias"): + names.append(entry["alias"]) + if any(name in exact or name.casefold() in folded for name in names): + covered += 1 + else: + missing.append(entry) + shims["covered"] = covered + shims["without_fact"] = missing + return shims + + +def _module_rows(facts): + rows = {} + for fact in facts: + module = fact["module"] + row = rows.setdefault( + module, + { + "module": module, + "types": set(), + "exports": set(), + "runtime_facts": 0, + "shader_facts": 0, + "platform_facts": 0, + "facts": 0, + }, + ) + row["facts"] += 1 + kind = fact["kind"] + if _is_type_kind(kind): + row["types"].add(fact["name"]) + elif kind.casefold() == "export": + row["exports"].add(fact["name"]) + elif kind.casefold() == "behavior": + row["runtime_facts"] += 1 + elif kind.casefold() == "shader": + row["shader_facts"] += 1 + elif kind.casefold() == "platform": + row["platform_facts"] += 1 + + result = [] + for module in sorted(rows, key=lambda text: (text.casefold(), text)): + row = rows[module] + result.append( + { + "module": row["module"], + "types": len(row["types"]), + "exports": len(row["exports"]), + "runtime_facts": row["runtime_facts"], + "shader_facts": row["shader_facts"], + "platform_facts": row["platform_facts"], + "facts": row["facts"], + } + ) + return result + + +def _count_unique_types(facts): + return len( + { + (fact["module"], fact["name"]) + for fact in facts + if _is_type_kind(fact["kind"]) + } + ) + + +def _count_unique_exports(facts): + return len( + { + (fact["module"], fact["name"]) + for fact in facts + if fact["kind"].casefold() == "export" + } + ) + + +def build_report(root, defs=None, required=()): + facts, category_files, category_facts = load_knowledge(root) + facts = _canonicalise_modules(facts) + facts = _dedupe_facts(facts) + conflicts = detect_conflicts(facts) + shims = _associate_shims(load_shims(defs), facts) + + categories = {} + missing = [] + for category in CATEGORIES: + files = category_files[category] + present = bool(files) + if not present: + missing.append(category) + categories[category] = { + "present": present, + "files": files, + "facts": category_facts[category], + } + + required = list(required) + required_missing = [category for category in required if category in missing] + + modules = _module_rows(facts) + runtime_facts = sum(fact["kind"].casefold() == "behavior" for fact in facts) + shader_facts = sum(fact["kind"].casefold() == "shader" for fact in facts) + platforms = len( + {fact["name"] for fact in facts if fact["kind"].casefold() == "platform"} + ) + summary = { + "modules": len(modules), + "types": _count_unique_types(facts), + "classes_types": _count_unique_types(facts), + "exports": _count_unique_exports(facts), + "export_rows": category_facts["exports"], + "runtime_facts": runtime_facts, + "shader_facts": shader_facts, + "platforms": platforms, + "facts": len(facts), + "conflicts": len(conflicts), + "shims_without_fact": len(shims["without_fact"]), + "shims": shims["exports"], + } + + return { + "schema": SCHEMA, + "generated_by": {"tool": TOOL, "version": VERSION}, + "inputs": { + "root": str(root), + "defs": str(defs) if defs is not None else None, + }, + "summary": summary, + "categories": categories, + "missing": missing, + "required": required, + "required_missing": required_missing, + "modules": modules, + "conflicts": conflicts, + "shims": shims, + "facts": facts, + } + + +def _md_cell(value): + return ( + str(value) + .replace("|", "\\|") + .replace("\r", " ") + .replace("\n", " ") + ) + + +def _md_value(value): + if isinstance(value, str): + return value + return _canonical(value) + + +def _md_values(values): + parts = [] + for item in values: + value = item.get("value") + if isinstance(value, dict) and "size" in value and "members" in value: + shown = "size={} members={}".format(value["size"], len(value["members"])) + else: + shown = _md_value(value) + if len(shown) > 160: + shown = shown[:157] + "..." + parts.append( + "{}={} ({})".format( + item.get("module", ""), + shown, + _md_cell(item.get("source", "")), + ) + ) + return "; ".join(parts) + + +def render_markdown(report): + summary = report["summary"] + lines = [ + "# GDK knowledge coverage", + "", + "- Schema: {}".format(report["schema"]), + "- Tool: {} version {}".format( + report["generated_by"]["tool"], report["generated_by"]["version"] + ), + "- Knowledge root: {}".format(_md_cell(report["inputs"]["root"])), + "", + "The report merges metadata facts from the knowledge root. It does not read", + "or execute SDK binaries, and it does not infer a fact from a missing category.", + "", + "## Summary", + "", + "| Metric | Value |", + "| --- | ---: |", + "| Modules | {} |".format(summary["modules"]), + "| Classes/types | {} |".format(summary["types"]), + "| Exports | {} |".format(summary["exports"]), + "| Export rows | {} |".format(summary["export_rows"]), + "| Runtime facts | {} |".format(summary["runtime_facts"]), + "| Shader facts | {} |".format(summary["shader_facts"]), + "| Platforms | {} |".format(summary["platforms"]), + "| Normalised facts | {} |".format(summary["facts"]), + "| Conflicts | {} |".format(summary["conflicts"]), + "| Shim exports | {} |".format(summary["shims"]), + "| Shims without fact | {} |".format(summary["shims_without_fact"]), + "", + "## Categories", + "", + "| Category | State | Files | Facts |", + "| --- | --- | ---: | ---: |", + ] + for category in CATEGORIES: + info = report["categories"][category] + files = ", ".join(info["files"]) if info["files"] else "-" + lines.append( + "| {} | {} | {} | {} |".format( + category, + "present" if info["present"] else "missing", + _md_cell(files), + info["facts"], + ) + ) + lines.append("") + if report["missing"]: + lines.append( + "Missing categories: {}.".format(", ".join(report["missing"])) + ) + else: + lines.append("All six categories are present.") + if report["required"]: + if report["required_missing"]: + lines.append( + "Required categories missing: {}.".format( + ", ".join(report["required_missing"]) + ) + ) + else: + lines.append( + "Required categories present: {}.".format( + ", ".join(report["required"]) + ) + ) + + lines.extend(["", "## Conflicts", ""]) + if report["conflicts"]: + lines.extend( + [ + "| Kind | Module | Name | Values | Sources |", + "| --- | --- | --- | --- | --- |", + ] + ) + for conflict in report["conflicts"]: + lines.append( + "| {} | {} | {} | {} | {} |".format( + conflict["kind"], + _md_cell(conflict["module"]), + _md_cell(conflict["name"]), + _md_cell(_md_values(conflict["values"])), + _md_cell(", ".join(conflict["sources"])), + ) + ) + else: + lines.append("No conflicts detected.") + + lines.extend( + [ + "", + "## Coverage by module", + "", + "| Module | Classes/types | Exports | Runtime facts | Shader facts | Platform facts | Facts |", + "| --- | ---: | ---: | ---: | ---: | ---: | ---: |", + ] + ) + for module in report["modules"]: + lines.append( + "| {} | {} | {} | {} | {} | {} | {} |".format( + _md_cell(module["module"]), + module["types"], + module["exports"], + module["runtime_facts"], + module["shader_facts"], + module["platform_facts"], + module["facts"], + ) + ) + + lines.extend(["", "## Shims without associated fact", ""]) + if report["inputs"]["defs"] is None: + lines.append("Shim coverage was not checked; pass --defs or a mapping JSON.") + elif report["shims"]["without_fact"]: + lines.extend( + [ + "| Module | Shim export | Alias | Def |", + "| --- | --- | --- | --- |", + ] + ) + for shim in report["shims"]["without_fact"]: + lines.append( + "| {} | {} | {} | {} |".format( + _md_cell(shim["module"]), + _md_cell(shim["name"]), + _md_cell(shim["alias"] or "-"), + _md_cell(shim["source"]), + ) + ) + else: + lines.append( + "All {} shim exports match a fact.".format(report["shims"]["exports"]) + ) + + lines.extend( + [ + "", + "## Limits", + "", + "A header fact does not prove the runtime. Layout and ABI rows only describe", + "the header or compile-time probe that produced them; runtime observations are", + "separate facts with their own source and confidence. An absent category is", + "reported as missing and is not treated as a zero-valued fact. Ordinals are", + "compared only when both sources report one, and RVA differences between", + "debug, release, import-library and DLL records are not conflicts. Anonymous", + "MSVC tags are counted as types but are not compared by display name because", + "several distinct anonymous records can share the same text.", + ] + ) + return "\n".join(lines) + "\n" + + +def _write_text(path, text): + path = Path(path) + try: + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(text, encoding="utf-8") + except OSError as exc: + raise InputError("cannot write {}: {}".format(path, exc)) from exc + + +def _parse_required(value): + if value is None: + return [] + result = [] + for token in value.split(","): + category = token.strip().casefold() + if not category: + raise InputError("--require contains an empty category") + if category not in CATEGORIES: + raise InputError( + "--require has unknown category {}; expected one of {}".format( + category, ", ".join(CATEGORIES) + ) + ) + if category not in result: + result.append(category) + return result + + +def _run_report(args): + root = Path(args.root) + json_path = Path(args.json) + markdown_path = Path(args.markdown) + if json_path.resolve() == markdown_path.resolve(): + raise InputError("--json and --markdown must be different paths") + required = _parse_required(args.require) + report = build_report(root, args.defs, required) + + _write_text( + json_path, + json.dumps(report, indent=2, sort_keys=True, ensure_ascii=False) + "\n", + ) + _write_text(markdown_path, render_markdown(report)) + + summary = report["summary"] + print( + "{}: {} facts, {} conflicts, {} shims without fact".format( + TOOL, + summary["facts"], + summary["conflicts"], + summary["shims_without_fact"], + ) + ) + + if args.check: + failures = [] + if report["conflicts"]: + failures.append("{} conflict(s)".format(len(report["conflicts"]))) + if report["required_missing"]: + failures.append( + "missing required categories: {}".format( + ", ".join(report["required_missing"]) + ) + ) + if failures: + print("error: " + "; ".join(failures), file=sys.stderr) + return 1 + return 0 + + +def _build_parser(): + parser = argparse.ArgumentParser( + description="Merge GDK knowledge facts and report coverage and conflicts." + ) + subparsers = parser.add_subparsers(dest="command", required=True) + report = subparsers.add_parser("report", help="write coverage JSON and Markdown") + report.add_argument("--root", required=True, help="knowledge root directory") + report.add_argument("--json", required=True, help="coverage JSON output") + report.add_argument("--markdown", required=True, help="Markdown report output") + report.add_argument( + "--defs", + help="repository src directory, one .def file, or a shim-mapping JSON", + ) + report.add_argument( + "--require", + help="comma-separated categories that must be present (with --check)", + ) + report.add_argument( + "--check", + action="store_true", + help="exit 1 on conflicts or missing categories listed by --require", + ) + return parser + + +def main(argv=None): + parser = _build_parser() + args = parser.parse_args(argv) + try: + if args.command == "report": + return _run_report(args) + parser.error("unknown command") + except InputError as exc: + print("error: {}".format(exc), file=sys.stderr) + return 2 + return 2 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/gdk_layouts.py b/tools/gdk_layouts.py new file mode 100644 index 0000000000..1ab95b588e --- /dev/null +++ b/tools/gdk_layouts.py @@ -0,0 +1,263 @@ +#!/usr/bin/env python3 +"""Parse MSVC /d1reportAllClassLayout logs and compare two layout sets. + +The logs are produced outside the repository from GDK headers. This tool keeps +only sizes, offsets and member names, so the JSON can live in the local +knowledge base without copying header text. + +Commands: + parse <log>... --json <out> [--module M] [--platform P] [--header H] + [--header-sha256 SHA] [--msvc VERSION] [--prefix P]... + compare <left.json> <right.json> [--json <out>] + +compare exits 1 when a class size or a named member offset differs. +""" + +import argparse +import hashlib +import json +import re +import sys +from pathlib import Path + + +HEADER_RE = re.compile(r"^(?:class|struct|union)\s+(.+?)\s+size\((\d+)\):") +MEMBER_RE = re.compile(r"^\s*(\d+)\s*\|\s*(.*?)\s*$") +ALIGNMENT_RE = re.compile(r"^\s*\|\s*<alignment member> \(size=(\d+)\)") +BASE_RE = re.compile(r"\+---\s*\(base class\s+(.+?)\)") +BITS_RE = re.compile(r":\s*(\d+)\s*$") +ARRAY_RE = re.compile(r"^(.*?)\s+([A-Za-z_]\w*)\s*\[(\d+)\]$") +NAMED_RE = re.compile(r"^(?P<type>.+?)\s+(?P<name>[A-Za-z_]\w*)$") +VFTABLE = "{vfptr}" + + +def sha256(path): + digest = hashlib.sha256() + digest.update(Path(path).read_bytes()) + return digest.hexdigest().upper() + + +def parse_member(offset, text): + if BASE_RE.search(text): + return { + "offset": offset, + "type": "", + "name": BASE_RE.search(text).group(1).strip(), + "bits": None, + "kind": "base", + } + if VFTABLE in text: + return {"offset": offset, "type": "void*", "name": VFTABLE, "bits": None, "kind": "vftable"} + + rest = text + bits = None + match = BITS_RE.search(rest) + if match: + bits = int(match.group(1)) + rest = rest[: match.start()].rstrip() + + array = None + match = ARRAY_RE.match(rest) + if match: + rest, count = match.group(1).strip(), int(match.group(3)) + array = count + name = match.group(2) + return { + "offset": offset, + "type": rest, + "name": name, + "bits": bits, + "kind": "field", + "array": array, + } + + match = NAMED_RE.match(rest) + if match: + return { + "offset": offset, + "type": match.group("type").strip(), + "name": match.group("name"), + "bits": bits, + "kind": "field", + } + if re.fullmatch(r"[A-Za-z_]\w*", rest): + return { + "offset": offset, + "type": "unknown", + "name": rest, + "bits": bits, + "kind": "field", + } + return { + "offset": offset, + "type": rest.strip(), + "name": "", + "bits": bits, + "kind": "unnamed", + } + + +def parse_log(path): + classes = [] + current = None + alignment = 0 + for line in Path(path).read_text(encoding="utf-8", errors="replace").splitlines(): + header = HEADER_RE.match(line) + if header: + if current is not None: + current["alignment"] = alignment + name = header.group(1).strip() + current = { + "name": name, + "size": int(header.group(2)), + "bases": [], + "members": [], + "alignment": 0, + "nested_in": name.rsplit("::", 1)[0] if "::" in name else None, + } + alignment = 0 + classes.append(current) + continue + if current is None: + continue + if line.strip().startswith("+---"): + continue + align = ALIGNMENT_RE.match(line) + if align: + alignment = int(align.group(1)) + current["members"].append( + { + "offset": current["size"] - alignment, + "type": "", + "name": "<alignment>", + "bits": None, + "kind": "alignment", + } + ) + continue + member = MEMBER_RE.match(line) + if not member: + continue + text = re.sub(r"^(?:\|\s*)+", "", member.group(2)) + if not text.strip(): + continue + parsed = parse_member(int(member.group(1)), text) + if parsed["kind"] == "base": + current["bases"].append({"offset": parsed["offset"], "name": parsed["name"]}) + else: + current["members"].append(parsed) + if current is not None: + current["alignment"] = alignment + for block in classes: + seen = set() + unique = [] + for member in block["members"]: + key = (member["offset"], member["name"], member["kind"]) + if key not in seen: + seen.add(key) + unique.append(member) + block["members"] = unique + return classes + + +def parse_command(args): + classes = [] + sources = [] + for path in args.logs: + block = parse_log(path) + classes.extend(block) + sources.append({"log": str(path), "sha256": sha256(path), "classes": len(block)}) + if args.prefix: + classes = [item for item in classes if any(item["name"].startswith(prefix) for prefix in args.prefix)] + document = { + "sdk": args.sdk, + "module": args.module, + "platform": args.platform, + "header": args.header, + "header_sha256": args.header_sha256 or (sha256(args.header) if args.header else ""), + "msvc": args.msvc, + "source": "msvc-layout", + "logs": sources, + "classes": classes, + "stats": {"classes": len(classes), "bytes": sum(item["size"] for item in classes)}, + } + Path(args.json).parent.mkdir(parents=True, exist_ok=True) + Path(args.json).write_text(json.dumps(document, indent=2) + "\n", encoding="utf-8") + print(json.dumps(document["stats"])) + return 0 + + +def index_classes(document): + return {item["name"]: item for item in document.get("classes", [])} + + +def compare_command(args): + left = json.loads(Path(args.left).read_text(encoding="utf-8")) + right = json.loads(Path(args.right).read_text(encoding="utf-8")) + left_classes = index_classes(left) + right_classes = index_classes(right) + changes = [] + for name in sorted(set(left_classes) | set(right_classes)): + old = left_classes.get(name) + new = right_classes.get(name) + if old is None: + changes.append({"class": name, "kind": "added", "right_size": new["size"]}) + continue + if new is None: + changes.append({"class": name, "kind": "removed", "left_size": old["size"]}) + continue + if old["size"] != new["size"]: + changes.append( + {"class": name, "kind": "size", "left_size": old["size"], "right_size": new["size"]} + ) + old_members = {item["name"]: item["offset"] for item in old["members"] if item.get("name") and item["kind"] == "field"} + new_members = {item["name"]: item["offset"] for item in new["members"] if item.get("name") and item["kind"] == "field"} + for member in sorted(set(old_members) | set(new_members)): + if old_members.get(member) != new_members.get(member): + changes.append( + { + "class": name, + "member": member, + "kind": "offset", + "left_offset": old_members.get(member), + "right_offset": new_members.get(member), + } + ) + if args.json: + Path(args.json).write_text(json.dumps(changes, indent=2) + "\n", encoding="utf-8") + if not changes: + print("no layout differences") + return 0 + for change in changes: + print(json.dumps(change, sort_keys=True)) + return 1 + + +def main(argv=None): + parser = argparse.ArgumentParser(description=__doc__) + sub = parser.add_subparsers(dest="command", required=True) + + parse = sub.add_parser("parse", help="parse MSVC layout logs") + parse.add_argument("logs", nargs="+") + parse.add_argument("--json", required=True) + parse.add_argument("--sdk", default="261000") + parse.add_argument("--module", default="") + parse.add_argument("--platform", default="") + parse.add_argument("--header", default="") + parse.add_argument("--header-sha256", default="") + parse.add_argument("--msvc", default="") + parse.add_argument("--prefix", action="append", default=[]) + parse.set_defaults(func=parse_command) + + compare = sub.add_parser("compare", help="compare two layout JSON files") + compare.add_argument("left") + compare.add_argument("right") + compare.add_argument("--json") + compare.set_defaults(func=compare_command) + + args = parser.parse_args(argv) + return args.func(args) + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/gdk_platform_profiles.py b/tools/gdk_platform_profiles.py new file mode 100644 index 0000000000..0bc98d22dc --- /dev/null +++ b/tools/gdk_platform_profiles.py @@ -0,0 +1,308 @@ +#!/usr/bin/env python3 +"""Extract GDK MSBuild platform properties into JSON. + +The GDK installation stays outside the repository. This reads the canonical +VS2022/flatDeployment platform files, keeps the MSBuild conditions and resolves +the simple variables defined in the same files. Unresolved variables remain +visible instead of being guessed. + +Commands: + list --root <GDK_ROOT> [--vs v170] [--sdk 261000] + scan --root <GDK_ROOT> --platform <name> --json <out> [--vs v170] [--sdk 261000] +""" + +import argparse +import hashlib +import json +import re +import sys +import xml.etree.ElementTree as ET +from pathlib import Path + + +NS = "{http://schemas.microsoft.com/developer/msbuild/2003}" +VARIABLE = re.compile(r"\$\(([A-Za-z_][A-Za-z0-9_]*)\)") +PROPERTY_NAMES = ("PropertyGroup", "ItemDefinitionGroup", "ItemGroup") + + +def tag(element): + return element.tag.rsplit("}", 1)[-1] + + +def sha256(path): + digest = hashlib.sha256() + digest.update(Path(path).read_bytes()) + return digest.hexdigest().upper() + + +def platform_dirs(root): + root = Path(root) + found = {} + for candidate in root.rglob("Platform.props"): + directory = candidate.parent + found[str(directory).lower()] = directory + return list(found.values()) + + +def score(directory, vs, sdk): + parts = [part.lower() for part in directory.parts] + value = 0 + if "vs2022" in parts: + value += 20 + if vs.lower() in parts: + value += 10 + if "flatdeployment" in parts: + value += 5 + if sdk in parts: + value += 3 + if (directory / sdk).is_dir(): + value += 15 + return value + + +def choose(root, platform, vs, sdk): + matches = [item for item in platform_dirs(root) if item.name.lower() == platform.lower()] + if not matches: + return None + versioned = [item for item in matches if (item / sdk).is_dir()] + if not versioned: + return None + return max(versioned, key=lambda item: (score(item, vs, sdk), -len(str(item)))) + + +def list_command(args): + rows = [] + by_name = {} + for directory in platform_dirs(args.root): + candidate = { + "platform": directory.name, + "path": str(directory), + "score": score(directory, args.vs, args.sdk), + } + key = directory.name.lower() + if key not in by_name or candidate["score"] > by_name[key]["score"]: + by_name[key] = candidate + rows = list(by_name.values()) + rows.sort(key=lambda item: item["platform"].lower()) + for row in rows: + print(f"{row['platform']}\t{row['path']}") + return 0 + + +def parse_file(path, properties, items, sources): + sources.append({"path": str(path), "sha256": sha256(path)}) + tree = ET.parse(path) + root = tree.getroot() + for group in root: + name = tag(group) + condition = group.get("Condition", "") + if name == "PropertyGroup": + for child in group: + key = tag(child) + value = (child.text or "").strip() + properties.setdefault(key, []).append( + { + "value": value, + "condition": child.get("Condition", condition), + "file": Path(path).name, + } + ) + elif name == "ItemDefinitionGroup": + for item in group: + item_name = tag(item) + bucket = items.setdefault(item_name, {}) + for child in item: + key = tag(child) + bucket.setdefault(key, []).append( + { + "value": (child.text or "").strip(), + "condition": child.get("Condition", condition), + } + ) + + +def table(properties): + result = {} + for key, entries in properties.items(): + value = entries[-1]["value"] + if f"$({key})" in value: + continue + result[key] = value + return result + + +def resolve(text, variables, depth=0, seen=None): + if depth > 8 or not text: + return text + seen = set() if seen is None else seen + + def replace(match): + name = match.group(1) + if name in seen: + return match.group(0) + value = variables.get(name) + if value is None: + return match.group(0) + return resolve(value, variables, depth + 1, seen | {name}) + + replaced = VARIABLE.sub(replace, text) + if len(replaced) > 16384: + return replaced[:16384] + if replaced == text: + return text + return resolve(replaced, variables, depth + 1, seen) + + +def split_list(text): + if not text: + return [] + values = [] + for item in text.split(";"): + item = item.strip() + if not item or item.startswith("%("): + continue + values.append(item) + return values + + +def last_item(items, group, key): + entries = items.get(group, {}).get(key, []) + return entries[-1]["value"] if entries else "" + + +def combined(items, group, key, separator): + entries = items.get(group, {}).get(key, []) + return separator.join(entry["value"] for entry in entries if entry["value"]) + + +def scan_command(args): + directory = choose(args.root, args.platform, args.vs, args.sdk) + if directory is None: + print( + f"platform not found for SDK {args.sdk}: {args.platform}", + file=sys.stderr, + ) + return 2 + sources = [] + properties = {} + items = {} + edition = directory / args.sdk + files = [ + directory / "Platform.default.props", + edition / "Platform.Common.props", + edition / "Platform.Edition.default.props", + edition / "Platform.Edition.props", + edition / "Platform.Edition.targets", + edition / "Platform.Commandline.targets", + directory / "Platform.props", + directory / "Platform.targets", + ] + toolset_root = directory / "PlatformToolsets" + if toolset_root.exists(): + files += sorted(toolset_root.glob("*/Toolset.props")) + for path in files: + if path.exists(): + parse_file(path, properties, items, sources) + variables = table(properties) + + def resolved(value): + return resolve(value, variables) + + defines = split_list(resolved(combined(items, "ClCompile", "PreprocessorDefinitions", ";"))) + includes = split_list( + resolved(combined(items, "ClCompile", "AdditionalIncludeDirectories", ";")) + ) + if not includes: + includes = split_list(resolved(variables.get("Console_EndpointIncludeRoot", ""))) + libs = split_list(resolved(combined(items, "Link", "AdditionalLibraryDirectories", ";"))) + if not libs: + libs = split_list(resolved(variables.get("Console_EndpointLibRoot", ""))) + dependencies = split_list( + resolved(combined(items, "Link", "AdditionalDependencies", ";")) + ) + if not dependencies: + dependencies = split_list(resolved(variables.get("Console_Libs", ""))) + + document = { + "sdk": args.sdk, + "platform": directory.name, + "toolset": args.vs, + "root": str(directory), + "sources": sources, + "defines": defines, + "includes": includes, + "libs": libs, + "dependencies": dependencies, + "console": { + "endpoint_include_root": resolved(variables.get("Console_EndpointIncludeRoot", "")), + "endpoint_lib_root": resolved(variables.get("Console_EndpointLibRoot", "")), + "libs": split_list(resolved(variables.get("Console_Libs", ""))), + "tool_path": resolved(variables.get("Console_SdkToolPath", "")), + "sdk_root": resolved(variables.get("Console_SdkRoot", "")), + }, + "flags": { + "additional_options": split_list( + resolved(combined(items, "ClCompile", "AdditionalOptions", " ")) + ), + "ignore_specific_default_libraries": split_list( + resolved(last_item(items, "Link", "IgnoreSpecificDefaultLibraries")) + ), + "runtime_library": resolved(last_item(items, "ClCompile", "RuntimeLibrary")), + "exception_handling": resolved(last_item(items, "ClCompile", "ExceptionHandling")), + "language_standard": resolved(last_item(items, "ClCompile", "LanguageStandard")), + "floating_point_model": resolved( + last_item(items, "ClCompile", "FloatingPointModel") + ), + "enable_enhanced_instruction_set": resolved( + last_item(items, "ClCompile", "EnableEnhancedInstructionSet") + ), + "target_machine": resolved(last_item(items, "Link", "TargetMachine")), + "use_debug_libraries": resolved(variables.get("UseDebugLibraries", "")), + "character_set": resolved(variables.get("CharacterSet", "")), + }, + "properties": { + key: [ + {"value": entry["value"], "condition": entry["condition"], "file": entry["file"]} + for entry in entries + ] + for key, entries in properties.items() + }, + "items": items, + } + Path(args.json).parent.mkdir(parents=True, exist_ok=True) + Path(args.json).write_text(json.dumps(document, indent=2) + "\n", encoding="utf-8") + print( + json.dumps( + { + "platform": document["platform"], + "sources": len(sources), + "defines": len(document["defines"]), + "includes": len(document["includes"]), + "libs": len(document["libs"]), + "dependencies": len(document["dependencies"]), + } + ) + ) + return 0 + + +def main(argv=None): + parser = argparse.ArgumentParser(description=__doc__) + sub = parser.add_subparsers(dest="command", required=True) + for name in ("list", "scan"): + command = sub.add_parser(name) + command.add_argument("--root", required=True) + command.add_argument("--vs", default="v170") + command.add_argument("--sdk", default="261000") + if name == "scan": + command.add_argument("--platform", required=True) + command.add_argument("--json", required=True) + command.set_defaults(func=scan_command) + else: + command.set_defaults(func=list_command) + args = parser.parse_args(argv) + return args.func(args) + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/gdk_runtime_oracle.py b/tools/gdk_runtime_oracle.py new file mode 100644 index 0000000000..107bd0d4ed --- /dev/null +++ b/tools/gdk_runtime_oracle.py @@ -0,0 +1,279 @@ +#!/usr/bin/env python3 +"""Compare one GDK runtime fixture against the GRDK and the Xbox2Windows shim. + +The reference executable links the installed gaming runtime and is run with the +inbox xgameruntime.dll. The candidate links the shim's import library and runs +with that library next to it. Both print one observation per line. Only the +normalized lines are compared: handles, console ids and per-user temp paths are +masked so two runs can be diffed. + +Commands: + run --gdk-root <GRDK> --shim-dir <dir> --fixture <cpp> --out <dir> + normalize <log> + diff <reference.txt> <candidate.txt> + +run returns 77 when cl.exe or a required path is missing, so CI can skip a host +without the GDK. The normalization and diff commands need no SDK. +""" + +import argparse +import difflib +import json +import os +import re +import shutil +import subprocess +import sys +from pathlib import Path + + +ROOT = Path(__file__).resolve().parents[1] +SKIP = 77 + +HANDLE_RE = re.compile( + r"\b(queue_handle|xpackage_mount_handle)=(?:0x)?[0-9A-Fa-f]+\b" +) +CONSOLE_RE = re.compile(r"\b(console_value=)[0-9A-Fa-f.]+") +PATH_RE = re.compile( + r"\b(pls_path_value=|xpackage_path_value=)" + r"(?:[A-Za-z]:\\[^\r\n]*?)\\Temp\\(xbox-recomp-(?:pls|packages))\\([^\\\s]+)" +) + + +def normalize_line(line): + """Mask volatile handles, console ids and per-user temp paths.""" + line = HANDLE_RE.sub(lambda m: m.group(1) + "=<handle>", line) + line = CONSOLE_RE.sub(lambda m: m.group(1) + "<console-id>", line) + line = PATH_RE.sub( + lambda m: m.group(1) + "<localappdata>\\Temp\\" + m.group(2) + "\\" + m.group(3), + line, + ) + return line + + +def normalize(lines): + return [normalize_line(str(line).rstrip("\r\n")) for line in lines] + + +def diff_lines(reference, candidate): + """Return a unified diff of two normalized logs, without file timestamps.""" + return list( + difflib.unified_diff( + list(reference), + list(candidate), + fromfile="reference", + tofile="candidate", + lineterm="", + n=2, + ) + ) + + +def read_lines(path): + return Path(path).read_text(encoding="utf-8", errors="replace").splitlines() + + +def grdk_version(include_dir): + header = Path(include_dir) / "GRDK.h" + if not header.exists(): + return "unknown" + match = re.search( + r"#define _GRDKVER_PRODUCTBUILDVER_FULL\s+([0-9.]+)", + header.read_text(encoding="utf-8", errors="replace"), + ) + return match.group(1) if match else "unknown" + + +def file_version(path): + path = Path(path) + if not path.exists(): + return "missing" + if sys.platform != "win32": + return "unavailable" + command = [ + "powershell", + "-NoProfile", + "-Command", + "(Get-Item -LiteralPath '" + str(path).replace("'", "''") + "').VersionInfo.FileVersion", + ] + try: + result = subprocess.run(command, capture_output=True, text=True, timeout=30) + except (OSError, subprocess.TimeoutExpired): + return "unknown" + value = result.stdout.strip() + return value or "unknown" + + +def build_command(cl, fixture, include, output, lib, shim_dir=None): + command = [str(cl), "/nologo", "/std:c++17", "/EHsc", "/W4"] + if shim_dir is not None: + command.append("/DX2W_SHIM") + command += ["/I" + str(include), str(fixture), "/link"] + command.append("/LIBPATH:" + str(shim_dir if shim_dir is not None else lib)) + command += ["advapi32.lib", "/OUT:" + str(output)] + return command + + +def run_fixture(executable, cwd, timeout): + result = subprocess.run( + [str(executable)], + cwd=str(cwd), + capture_output=True, + text=True, + timeout=timeout, + ) + lines = (result.stdout + result.stderr).splitlines() + return result.returncode, lines + + +def msvc_environment(vcvars): + """Return os.environ plus the variables vcvars64.bat sets, or (None, log).""" + command = 'call "' + str(vcvars) + '" >nul && set' + result = subprocess.run(command, shell=True, capture_output=True, text=True, timeout=120) + if result.returncode != 0: + return None, result.stdout + result.stderr + environment = os.environ.copy() + for line in result.stdout.splitlines(): + key, separator, value = line.partition("=") + if separator: + for existing in [name for name in environment if name.lower() == key.lower()]: + del environment[existing] + environment[key] = value + return environment, "" + + +def run_build(command, environment): + return subprocess.run( + command, capture_output=True, text=True, timeout=120, env=environment + ) + + +def command_run(args): + gdk_root = Path(args.gdk_root) + include = gdk_root / "GameKit" / "Include" + lib = gdk_root / "GameKit" / "Lib" / "amd64" + shim_dir = Path(args.shim_dir) + fixture = Path(args.fixture) + for path in (include, lib, shim_dir, fixture): + if not path.exists(): + print(f"missing required path: {path}", file=sys.stderr) + return 2 + + environment = None + if args.vcvars: + environment, error = msvc_environment(args.vcvars) + if environment is None: + print("vcvars failed: " + error, file=sys.stderr) + return 2 + path = next((value for key, value in environment.items() if key.lower() == "path"), "") + cl = args.cl or shutil.which("cl", path=path) + if cl is None: + print("cl.exe not found in the vcvars environment", file=sys.stderr) + return 2 + else: + cl = args.cl or shutil.which("cl") + if cl is None or not Path(cl).exists(): + print("cl.exe not found; skipping the GDK runtime oracle", file=sys.stderr) + return SKIP + + out = Path(args.out) + reference_dir = out / "reference" + candidate_dir = out / "candidate" + reference_dir.mkdir(parents=True, exist_ok=True) + candidate_dir.mkdir(parents=True, exist_ok=True) + + reference_exe = reference_dir / "fixture.exe" + candidate_exe = candidate_dir / "fixture.exe" + builds = ( + ("reference", build_command(cl, fixture, include, reference_exe, lib)), + ("candidate", build_command(cl, fixture, include, candidate_exe, lib, shim_dir)), + ) + for name, command in builds: + result = run_build(command, environment) + (out / f"build-{name}.log").write_text( + result.stdout + result.stderr, encoding="utf-8" + ) + if result.returncode != 0: + print(f"{name} fixture build failed; see {out / f'build-{name}.log'}", file=sys.stderr) + return 2 + + runtime_dll = shim_dir / "xgameruntime.dll" + if runtime_dll.exists(): + shutil.copy2(runtime_dll, candidate_dir / runtime_dll.name) + + reference_exit, reference_lines = run_fixture(reference_exe, reference_dir, args.timeout) + candidate_exit, candidate_lines = run_fixture(candidate_exe, candidate_dir, args.timeout) + reference_normalized = normalize(reference_lines) + candidate_normalized = normalize(candidate_lines) + differences = diff_lines(reference_normalized, candidate_normalized) + + (out / "reference.txt").write_text("\n".join(reference_lines) + "\n", encoding="utf-8") + (out / "candidate.txt").write_text("\n".join(candidate_lines) + "\n", encoding="utf-8") + (out / "diff.txt").write_text("\n".join(differences) + "\n", encoding="utf-8") + report = { + "sdk": grdk_version(include), + "fixture": str(fixture), + "reference": { + "exit": reference_exit, + "runtime": file_version(Path("C:/Windows/System32/xgameruntime.dll")), + "normalized": reference_normalized, + }, + "candidate": { + "exit": candidate_exit, + "shim": str(shim_dir), + "normalized": candidate_normalized, + }, + "differences": differences, + } + (out / "report.json").write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8") + print(f"reference exit={reference_exit}; candidate exit={candidate_exit}") + print("\n".join(differences) if differences else "no normalized differences") + if args.fail_on_difference and differences: + return 1 + return 0 + + +def command_normalize(args): + lines = normalize(read_lines(args.log)) + print("\n".join(lines)) + return 0 + + +def command_diff(args): + reference = normalize(read_lines(args.reference)) + candidate = normalize(read_lines(args.candidate)) + differences = diff_lines(reference, candidate) + print("\n".join(differences) if differences else "no normalized differences") + return 1 if differences else 0 + + +def main(argv=None): + parser = argparse.ArgumentParser(description=__doc__) + sub = parser.add_subparsers(dest="command", required=True) + + run = sub.add_parser("run", help="build and run the reference and shim fixtures") + run.add_argument("--gdk-root", required=True, help="GRDK root (contains GameKit)") + run.add_argument("--shim-dir", required=True, help="directory with the shim import library") + run.add_argument("--fixture", required=True, help="C++ fixture source") + run.add_argument("--out", required=True, help="output directory") + run.add_argument("--cl", help="explicit cl.exe path") + run.add_argument("--vcvars", help="Visual Studio vcvars64.bat; runs cl in its environment") + run.add_argument("--timeout", type=int, default=120) + run.add_argument("--fail-on-difference", action="store_true") + run.set_defaults(func=command_run) + + normalize_command = sub.add_parser("normalize", help="print a normalized log") + normalize_command.add_argument("log") + normalize_command.set_defaults(func=command_normalize) + + diff = sub.add_parser("diff", help="compare two normalized logs") + diff.add_argument("reference") + diff.add_argument("candidate") + diff.set_defaults(func=command_diff) + + args = parser.parse_args(argv) + return args.func(args) + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/gdk_shader_corpus.py b/tools/gdk_shader_corpus.py new file mode 100644 index 0000000000..783131666f --- /dev/null +++ b/tools/gdk_shader_corpus.py @@ -0,0 +1,215 @@ +#!/usr/bin/env python3 +"""Compile an original HLSL corpus with the GDK dxc and retarget it. + +The Xbox container and the desktop container stay outside the repository. The +HLSL sources are original and versioned; only SHA-256 values and sizes are +recorded in the manifest. + +Commands: + build --gdk-root <GXDK> --corpus <dir> --out <dir> [--dxc <path>] [--require] + verify --manifest <corpus.json> [--root <dir>] + +build returns 77 when dxc is missing, unless --require is set. verify needs no +SDK and checks the recorded hashes and the DXIL triples. +""" + +import argparse +import hashlib +import json +import shutil +import subprocess +import sys +from pathlib import Path + + +ROOT = Path(__file__).resolve().parents[1] +SKIP = 77 + + +def sha256(path): + digest = hashlib.sha256() + digest.update(Path(path).read_bytes()) + return digest.hexdigest().upper() + + +def load_cases(corpus): + corpus = Path(corpus) + manifest = corpus / "cases.json" + document = json.loads(manifest.read_text(encoding="utf-8")) + cases = document.get("cases", []) + names = set() + for case in cases: + name = case["name"] + if name in names: + raise ValueError("duplicate corpus case: " + name) + names.add(name) + source = corpus / case["source"] + if not source.exists(): + raise ValueError("missing corpus source: " + str(source)) + return cases + + +def find_dxc(gdk_root, explicit): + if explicit: + return Path(explicit) if Path(explicit).exists() else None + for relative in ("GXDK/bin/Scarlett/dxc.exe", "bin/Scarlett/dxc.exe", "dxc.exe", "dxc"): + candidate = Path(gdk_root) / relative + if candidate.exists(): + return candidate + found = shutil.which("dxc") + return Path(found) if found else None + + +def dxc_version(dxc): + result = subprocess.run([str(dxc), "--version"], capture_output=True, text=True, timeout=60) + return (result.stdout + result.stderr).strip() + + +def compile_case(case, corpus, out, dxc): + directory = out / case["name"] + directory.mkdir(parents=True, exist_ok=True) + source = (corpus / case["source"]).resolve() + xbox = directory / "xbox.cso" + desktop = directory / "desktop.cso" + args = [ + str(dxc), + "-noprecompile", + "-T", + case["profile"], + "-E", + case["entry"], + ] + list(case.get("args", [])) + [str(source), "-Fo", str(xbox)] + result = subprocess.run(args, capture_output=True, text=True, timeout=300) + if result.returncode != 0: + return {"name": case["name"], "error": (result.stdout + result.stderr).strip()} + retarget = subprocess.run( + [sys.executable, str(ROOT / "tools" / "dxil_retarget.py"), str(xbox), str(desktop)], + capture_output=True, + text=True, + timeout=300, + ) + if retarget.returncode != 0: + return {"name": case["name"], "error": (retarget.stdout + retarget.stderr).strip()} + try: + dxil = json.loads(retarget.stdout) + except json.JSONDecodeError: + dxil = {"raw": retarget.stdout.strip()} + return { + "name": case["name"], + "source": case["source"], + "source_sha256": sha256(source), + "profile": case["profile"], + "entry": case["entry"], + "args": list(case.get("args", [])), + "xbox": { + "file": str(xbox.relative_to(out)), + "bytes": xbox.stat().st_size, + "sha256": sha256(xbox), + }, + "desktop": { + "file": str(desktop.relative_to(out)), + "bytes": desktop.stat().st_size, + "sha256": sha256(desktop), + }, + "dxil": dxil.get("dxil", dxil), + } + + +def build_command(args): + corpus = Path(args.corpus) + out = Path(args.out) + out.mkdir(parents=True, exist_ok=True) + cases = load_cases(corpus) + dxc = find_dxc(args.gdk_root, args.dxc) + if dxc is None: + print("dxc not found; skipping the GDK shader corpus", file=sys.stderr) + return 2 if args.require else SKIP + version = dxc_version(dxc) + results = [] + failures = [] + for case in cases: + result = compile_case(case, corpus, out, dxc) + results.append(result) + if "error" in result: + failures.append(result) + print(f"{case['name']}: failed", file=sys.stderr) + if not args.keep_going: + break + else: + print(f"{case['name']}: {result['xbox']['bytes']} -> {result['desktop']['bytes']} bytes") + document = { + "sdk": "261000", + "dxc": version, + "cases": results, + } + (out / "corpus.json").write_text(json.dumps(document, indent=2) + "\n", encoding="utf-8") + print(json.dumps({"cases": len(results), "failures": len(failures)})) + return 2 if failures else 0 + + +def verify_command(args): + manifest = Path(args.manifest) + root = Path(args.root) if args.root else manifest.parent + document = json.loads(manifest.read_text(encoding="utf-8")) + errors = [] + for case in document.get("cases", []): + if "error" in case: + errors.append(case["name"] + ": build error recorded") + continue + for kind in ("xbox", "desktop"): + record = case.get(kind) + if not record: + errors.append(f"{case['name']}: missing {kind} record") + continue + path = root / record["file"] + if not path.exists(): + errors.append(f"{case['name']}: missing {path}") + continue + if sha256(path) != record["sha256"]: + errors.append(f"{case['name']}: {kind} hash mismatch") + if path.stat().st_size != record["bytes"]: + errors.append(f"{case['name']}: {kind} size mismatch") + dxil = case.get("dxil", {}) + if dxil.get("original_triple") != "dxil-ms-xb2": + errors.append(f"{case['name']}: source triple {dxil.get('original_triple')!r}") + if dxil.get("target_triple") != "dxil-ms-dx": + errors.append(f"{case['name']}: target triple {dxil.get('target_triple')!r}") + removed = dxil.get("removed_named_metadata", []) + if "xbox.compiler.options" not in removed: + errors.append(f"{case['name']}: xbox.compiler.options not removed") + if errors: + for error in errors: + print(error, file=sys.stderr) + return 1 + print(f"verified {len(document.get('cases', []))} cases") + return 0 + + +def main(argv=None): + parser = argparse.ArgumentParser(description=__doc__) + sub = parser.add_subparsers(dest="command", required=True) + + build = sub.add_parser("build") + build.add_argument("--gdk-root", required=True) + build.add_argument("--corpus", required=True) + build.add_argument("--out", required=True) + build.add_argument("--dxc") + build.add_argument("--require", action="store_true") + build.add_argument("--keep-going", action="store_true") + build.set_defaults(func=build_command) + + verify = sub.add_parser("verify") + verify.add_argument("--manifest", required=True) + verify.add_argument("--root") + verify.set_defaults(func=verify_command) + + args = parser.parse_args(argv) + try: + return args.func(args) + except (OSError, ValueError, json.JSONDecodeError) as error: + print(str(error), file=sys.stderr) + return 2 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/patch_manifest.py b/tools/patch_manifest.py index 3ff82090ce..b57bb465f2 100644 --- a/tools/patch_manifest.py +++ b/tools/patch_manifest.py @@ -14,9 +14,20 @@ expect_sha256 = "<sha256 of the len(bytes) original bytes at rva>" bytes = "90c3" # the replacement, lowercase hex + [[patch]] + id = "s001" + kind = "shader" # the translation files of one shader cache key + why = "<issue or root cause>" + remove_when = "<condition>" + key = "0123456789abcdef" # the cache key, 16 lowercase hex digits + pipeline = "compute" # graphics, compute or mesh86 + revision = "x2w-startup-shader-29cs" + files = [{ ext = ".txt", file = "s001.txt", sha256 = "<sha256>" }, + { ext = ".cs.cso", file = "s001.cs.cso", sha256 = "<sha256>" }] + The whole manifest is validated and the input's SHA-256 compared before anything is returned, so -a manifest that fails any check applies nothing. Only the memory kind is defined so far, and -nothing applies it yet. +a manifest that fails any check applies nothing. The memory and shader kinds are defined, checked +for shape only; nothing applies them yet. """ import argparse @@ -28,9 +39,26 @@ SHA256 = re.compile(r"[0-9a-f]{64}") HEX = re.compile(r"(?:[0-9a-f]{2})+") +KEY = re.compile(r"[0-9a-f]{16}") +# Names Windows opens as a device instead of a file in the directory, alone or before an extension (Microsoft, +# "Naming Files, Paths, and Namespaces"). Matched against the part before the first dot, trailing spaces dropped. +DEVICE = re.compile(r"(?:con|prn|aux|nul|com[0-9\u00b9\u00b2\u00b3]|lpt[0-9\u00b9\u00b2\u00b3]|conin\$|conout\$)", + re.IGNORECASE) COMMON = {"id", "kind", "why", "remove_when"} # Every key of a kind is required. hook and data get their tables with their stages. -KINDS = {"memory": {"rva", "expect_sha256", "bytes"}} +KINDS = {"memory": {"rva", "expect_sha256", "bytes"}, "shader": {"key", "pipeline", "revision", "files"}} +# Shader patches, per pipeline: the form of the runtime's key revision (src/startup_stubs/d3d12_draw.inl and +# mesh86_cache.inl; <n> is the number each revision bump raises), the translation files the runtime reads for one +# key, and the ones without which it has no translation. A later consumer must check which is current. compute +# also needs .cs.hlsl when its .txt has no native line, and mesh86 reads .ps.cso only for a request with a pixel +# shader; this loader reads neither, so both stay optional. +PIPELINES = { + "graphics": ("x2w-startup-shader-<n>", (".txt", ".vs.cso", ".ps.cso"), (".txt", ".vs.cso", ".ps.cso")), + "compute": ("x2w-startup-shader-<n>cs", (".txt", ".cs.cso", ".cs.hlsl"), (".txt", ".cs.cso")), + "mesh86": ("x2w-startup-mesh-86-<n>", (".mesh86.txt", ".ms.cso", ".ps.cso"), (".mesh86.txt", ".ms.cso")), +} +REVISIONS = {name: re.compile(re.escape(form).replace("<n>", "[1-9][0-9]*")) + for name, (form, _, _) in PIPELINES.items()} def _keys(table, keys, where): @@ -54,9 +82,60 @@ def _sha256(value, where): return value +def _file_name(value, where): + """A bare file name, for a later consumer to resolve in the manifest's directory. + + That consumer is the runtime, which runs on Windows, so a name that Windows would not resolve to a file of that + name in the directory is refused too: one it cannot hold, one whose trailing dot or space it drops, a device. + """ + name = _text(value, where) + if any(c in name for c in "/\\:") or name in (".", ".."): + raise ValueError(f"{where} {name!r} must be a bare file name, without a directory, drive or '..'") + if any(c in '<>"|?*' for c in name) or any(ord(c) < 32 for c in name): + raise ValueError(f"{where} {name!r} has a character a Windows file name cannot hold") + if name.endswith((".", " ")): + raise ValueError(f"{where} {name!r} ends in a dot or a space, which Windows drops") + if DEVICE.fullmatch(name.split(".", 1)[0].rstrip(" ")): + raise ValueError(f"{where} {name!r} is a Windows device name") + return name + + +def _shader(entry, where): + """The key, pipeline, revision and files of a shader patch, checked for shape only.""" + key = entry["key"] + if not isinstance(key, str) or not KEY.fullmatch(key): + raise ValueError(f"{where} key must be 16 lowercase hex digits") + pipeline = entry["pipeline"] + if not isinstance(pipeline, str) or pipeline not in PIPELINES: + raise ValueError(f"{where} pipeline must be one of: {', '.join(PIPELINES)}") + form, extensions, required = PIPELINES[pipeline] + revision = entry["revision"] + if not isinstance(revision, str) or not REVISIONS[pipeline].fullmatch(revision): + raise ValueError(f"{where} revision {revision!r} is not a {pipeline} key revision ({form})") + if not isinstance(entry["files"], list) or not entry["files"]: + raise ValueError(f"{where} files must be a non-empty array of tables") + files = {} + for index, item in enumerate(entry["files"]): + at = f"{where} files[{index}]" + _keys(item, {"ext", "file", "sha256"}, at) + ext = item["ext"] + if not isinstance(ext, str) or ext not in extensions: + raise ValueError(f"{at} ext {ext!r} is not a {pipeline} translation file ({', '.join(extensions)})") + if ext in files: + raise ValueError(f"{where} lists {ext} twice") + files[ext] = {"ext": ext, "file": _file_name(item["file"], f"{at} file"), + "sha256": _sha256(item["sha256"], f"{at} sha256")} + if missing := [ext for ext in required if ext not in files]: + raise ValueError(f"{where} {pipeline} override is missing: {', '.join(missing)}") + return {"key": key, "pipeline": pipeline, "revision": revision, "files": list(files.values())} + + def parse(text): """Return (input_sha256, patches) from manifest text, or raise ValueError.""" - data = tomllib.loads(text) + try: + data = tomllib.loads(text) + except RecursionError: # tomllib recurses once per nested array or inline table + raise ValueError("manifest is nested too deeply to parse") from None _keys(data, {"target", "patch"}, "manifest") _keys(data["target"], {"input_sha256"}, "[target]") target = _sha256(data["target"]["input_sha256"], "input_sha256") @@ -73,6 +152,13 @@ def parse(text): if any(p["id"] == pid for p in patches): raise ValueError(f"duplicate patch id: {pid}") where = f"patch {pid}" + if kind == "shader": + patch = {"id": pid, "kind": kind, "why": _text(entry["why"], f"{where} why"), + "remove_when": _text(entry["remove_when"], f"{where} remove_when"), **_shader(entry, where)} + if other := next((p["id"] for p in patches if p.get("key") == patch["key"]), None): + raise ValueError(f"patches {other} and {pid} override the same key {patch['key']}") + patches.append(patch) + continue rva = entry["rva"] if type(rva) is not int or not 0 <= rva < 1 << 32: raise ValueError(f"{where} rva must be an integer in [0, 2^32)") @@ -105,6 +191,18 @@ def load(manifest_path, input_path): target, patches = parse(raw.decode("utf-8")) with open(input_path, "rb") as handle: digest = hashlib.file_digest(handle, "sha256").hexdigest() + return _bound(raw, target, patches, digest) + + +def load_data(manifest_path, data): + """load() for an input the caller has already read: data is hashed, so the bytes that pass the gate are + the bytes the caller goes on to use, even if the file on disk changes in between.""" + raw = Path(manifest_path).read_bytes() + target, patches = parse(raw.decode("utf-8")) + return _bound(raw, target, patches, hashlib.sha256(data).hexdigest()) + + +def _bound(raw, target, patches, digest): if digest != target: raise ValueError(f"manifest is for another input: manifest input_sha256 {target}, input sha256 {digest}") return {"manifest_sha256": hashlib.sha256(raw).hexdigest(), "input_sha256": digest, "patches": patches} diff --git a/tools/probe_root_devices.py b/tools/probe_root_devices.py index 696c178e45..9aa37697e7 100644 --- a/tools/probe_root_devices.py +++ b/tools/probe_root_devices.py @@ -32,8 +32,13 @@ def main(argv=None): backends.append("hardware") result = {"windows": sys.getwindowsversion().build, "controls": {}, "images": {}} try: + if not args.bin.is_dir(): + raise NotADirectoryError(f"--bin path is not a directory: {args.bin}") for name in ("compute_root", "compute_tables"): - rows = measure(command, (args.bin / (name + ".cso")).read_bytes()) + control_path = args.bin / (name + ".cso") + if not control_path.is_file(): + raise FileNotFoundError(f"Control shader is missing or not a file: {control_path}") + rows = measure(command, control_path.read_bytes()) if (len(rows) != 1 or not isinstance(rows[0], dict) or rows[0].get("cleared") != 0 or rows[0].get("remaining_flags") != 0 or any(rows[0].get(key) != "0x00000000" for key in ["serialize", *backends])): @@ -45,7 +50,16 @@ def main(argv=None): dest = PROJECT / "out/calls" / ("root-devices-warp.json" if args.warp_only else "root-devices.json") if dest.resolve().is_relative_to(args.build.resolve()): parser.error("Choose an input directory separate from the report directory") - inventory = json.loads((dest.parent / "six-apis.json").read_bytes()) + if not args.build.is_dir(): + raise NotADirectoryError(f"Build directory is not a directory: {args.build}") + if dest.parent.is_file(): + raise NotADirectoryError(f"Output parent is not a directory: {dest.parent}") + if dest.is_dir(): + raise IsADirectoryError(f"Output path is a directory: {dest}") + inventory_path = dest.parent / "six-apis.json" + if not inventory_path.is_file(): + raise FileNotFoundError(f"Inventory file is missing or not a file: {inventory_path}") + inventory = json.loads(inventory_path.read_bytes()) if not isinstance(inventory, dict): raise ValueError("Invalid six-apis.json inventory") for name in NAMES: @@ -58,7 +72,10 @@ def main(argv=None): container_specs = [(int(item["rva"], 16), item["bytes"], item["rva"]) for item in containers] except (KeyError, TypeError) as exc: raise ValueError(f"Invalid six-apis.json entry for {name}: {exc}") from exc - image = (args.build / name).read_bytes() + image_path = args.build / name + if not image_path.is_file(): + raise FileNotFoundError(f"Build image is missing or not a file: {image_path}") + image = image_path.read_bytes() if hashlib.sha256(image).hexdigest() != expected_sha256: raise ValueError(f"Regenerate six-apis.json for {name}") layouts = {} diff --git a/tools/startup/compile_dxil.cpp b/tools/startup/compile_dxil.cpp index 51c6b01aa8..7728f227e6 100644 --- a/tools/startup/compile_dxil.cpp +++ b/tools/startup/compile_dxil.cpp @@ -1,5 +1,7 @@ #include "shader_dxil_compiler.h" #include "direct_compute_cache.h" +#include "native_compute_output.h" +#include "shader_compute_request.h" #include "gfx1013_pixel.h" #include "gfx1013_sampled_pixel.h" #include "gfx1013_vertex_id.h" @@ -102,7 +104,7 @@ static std::optional<std::string> compile_one(x2w::ShaderDxilCompiler& compiler, const fs::path& input_path, const fs::path& destination, const fs::path& cache, std::ostream& report, const x2w::NativeComputeShader *linked=nullptr, - bool emit_manifest=false) { + bool emit_manifest=false, std::string *manifest_reason=nullptr) { Clock::time_point start; std::string source; std::optional<std::string> manifest; @@ -148,7 +150,7 @@ static std::optional<std::string> compile_one(x2w::ShaderDxilCompiler& compiler, } report<<"global_srv select="<<views.request.selected<<" need="<<x2w_startup::global_srv_type_name(views.request.needed)<<'\n'; } - if (emit_manifest && !container) manifest = x2w::format_compute_runtime_manifest(program); + if (emit_manifest && !container) manifest = x2w::format_compute_runtime_manifest(program, manifest_reason); source=direct?std::move(program.dxil_ir):std::move(program.hlsl);profile=L"cs_6_6"; } else if (profile.compare(0,clear_prefix.size(),clear_prefix)==0) { auto offset=profile.substr(clear_prefix.size()); @@ -322,6 +324,11 @@ static std::string format_fail_line(std::string_view message) { return out; } +// A compute program that translates but has no runtime manifest: the runtime cannot dispatch it translated. +static std::string manifest_refusal(const std::string &reason) { + return "unsupported startup runtime manifest bindings: " + reason; +} + static bool is_ident_char(unsigned char c) { return std::isalnum(c) != 0 || c == '_'; } static std::string normalize_refusal_reason(std::string_view raw) { @@ -565,7 +572,9 @@ static int run_refusals(int argc, wchar_t** argv) { try { if (task.compute) { auto req = x2w::read_compute_request(compute_inputs[task.index]); - (void)x2w::translate_compute(req, 0, true); + std::string reason; + if (!x2w::format_compute_runtime_manifest(x2w::translate_compute(req, 0, true), &reason)) + throw std::runtime_error(manifest_refusal(reason)); } else { auto input = x2w::read_graphics_request(graphics_inputs[task.index]); bool hit = false; @@ -728,6 +737,8 @@ static bool is_watch_request_pending(const fs::path& request_dir, const WatchReq const fs::path psdep_path = fs::path(stem) += L".psdep"; std::optional<fs::file_time_type> psin_mtime; + bool dependency_changed = false; + bool lost = false; bool sidecar_changed = false; if (!req.compute) { if (const auto psin_path = graphics_psin_path(req.marker)) { @@ -753,10 +764,24 @@ static bool is_watch_request_pending(const fs::path& request_dir, const WatchReq } } } + lost = !psin_mtime.has_value() && fs::is_regular_file(psdep_path, ec); } const bool has_manifest = fs::is_regular_file(manifest_path, ec); - if (has_manifest && !sidecar_changed) { + if (has_manifest && !sidecar_changed && !lost && !dependency_changed) { + if (req.compute) { + // A native manifest from another revision, or an unmarked one without the Python translator's + // <key>.cs.hlsl, is stale. Other outputs, and a manifest that cannot be read, go on to the usual + // timestamp and bytecode checks. + if (std::ifstream file{manifest_path, std::ios::binary}) { + const std::string manifest((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>()); + const auto output = x2w::native_compute_output(manifest); + const bool python = fs::is_regular_file(fs::path(stem) += L".cs.hlsl", ec); + if (output == x2w::NativeComputeOutput::incompatible || + (output == x2w::NativeComputeOutput::unmarked && !python)) + return true; + } + } const auto manifest_mtime = fs::last_write_time(manifest_path, ec); if (!ec && !(psin_mtime.has_value() && *psin_mtime > manifest_mtime)) { if (req.compute) { @@ -827,11 +852,15 @@ static const char* compile_watch_item(x2w::ShaderDxilCompiler& compiler, const f fs::remove(manifest_path, ignored); std::ostringstream sink; if (req.compute) { + // A Python translation's sidecar must not outlive its manifest: the stand-in reads an unmarked manifest + // next to a <key>.cs.hlsl as the Python translator's output. + fs::remove(fs::path(stem) += L".cs.hlsl", ignored); bool hit = false; auto program = x2w::prepare_direct_compute(req.marker, 0, false, cache_dir, hit, x2w::HeapViewContract::none); - auto manifest = x2w::format_compute_runtime_manifest(program); + std::string reason; + auto manifest = x2w::format_compute_runtime_manifest(program, &reason); if (!manifest) - throw std::runtime_error("unsupported startup runtime manifest bindings"); + throw std::runtime_error(manifest_refusal(reason)); auto cs_dxil = compile_to_dxil(compiler, program.dxil_ir, L"cs_6_6", cache_dir, true, sink); publish_atomic(fs::path(stem) += L".cs.cso", cs_dxil.data(), cs_dxil.size()); publish_atomic(manifest_path, manifest->data(), manifest->size()); @@ -979,7 +1008,390 @@ static int run_watch(int argc, wchar_t** argv) { } } +static std::string format_key16(uint64_t key) { + char buf[20]; + std::snprintf(buf, sizeof(buf), "%016llx", static_cast<unsigned long long>(key)); + return std::string(buf); +} + +static fs::path rekey_request_path(const fs::path& dir, const std::string& hex16, const char* ext) { + return dir / ("req_" + hex16 + ext); +} + +static bool read_rekey_bytes(const fs::path& path, size_t max_bytes, std::string& out, std::string& error) { + std::error_code ec; + if (!fs::is_regular_file(path, ec)) { + error = "unreadable " + path.filename().string() + ": not a regular file"; + return false; + } + const auto file_bytes = fs::file_size(path, ec); + if (ec || file_bytes > max_bytes) { + error = "unreadable " + path.filename().string() + ": " + (ec ? ec.message() : "oversized file"); + return false; + } + std::ifstream file(path, std::ios::binary); + if (!file) { + error = "unreadable " + path.filename().string() + ": cannot open"; + return false; + } + out.assign(static_cast<size_t>(file_bytes), '\0'); + if (file_bytes && !file.read(out.data(), static_cast<std::streamsize>(file_bytes))) { + error = "unreadable " + path.filename().string() + ": short read"; + return false; + } + return true; +} + +static void publish_rekey_file(const fs::path& dst_file, const void* data, size_t size, + size_t& written, size_t& kept) { + std::error_code ec; + if (fs::exists(dst_file, ec)) { + ++kept; + return; + } + if (ec) + throw fs::filesystem_error("cannot inspect destination file", dst_file, ec); + publish_atomic(dst_file, data, size); + ++written; +} + +static int run_rekey(int argc, wchar_t** argv) { + fs::path src_dir, dst_dir; + int positional = 0; + unsigned hw_threads = std::thread::hardware_concurrency(); + int jobs = static_cast<int>((std::min)(64u, (std::max)(1u, hw_threads))); + auto usage = []() { + std::cerr << "usage: compile_dxil --rekey OLD_CACHE_DIR NEW_REQUEST_DIR [--jobs N]\n"; + return 2; + }; + for (int i = 2; i < argc; ++i) { + const std::wstring_view arg = argv[i]; + if (arg == L"--jobs") { + if (i + 1 >= argc) + return usage(); + try { + jobs = parse_jobs_count(argv[++i]); + } catch (const std::exception& error) { + std::cerr << "error: " << error.what() << '\n'; + return 2; + } + } else if (!arg.empty() && arg.front() == L'-') { + return usage(); + } else { + if (positional == 0) src_dir = fs::path(arg); + else if (positional == 1) dst_dir = fs::path(arg); + else return usage(); + ++positional; + } + } + if (positional != 2) + return usage(); + + std::error_code ec; + if (!fs::is_directory(src_dir, ec)) { + std::cerr << "error: " << src_dir.string() << " is not a directory\n"; + return 2; + } + if (fs::exists(dst_dir, ec)) { + if (!fs::is_directory(dst_dir, ec)) { + std::cerr << "error: " << dst_dir.string() << " is not a directory\n"; + return 2; + } + if (fs::equivalent(src_dir, dst_dir, ec)) { + std::cerr << "error: the new request dir must not be the old cache\n"; + return 2; + } + } else if (ec) { + std::cerr << "error: cannot inspect " << dst_dir.string() << ": " << ec.message() << '\n'; + return 2; + } + + enum class Kind { graphics, compute, m57 }; + struct Marker { + Kind kind; + uint64_t old_key = 0; + std::string old_hex; + }; + struct RtvMarker { + uint64_t old_key = 0; + std::string old_hex; + }; + + std::vector<Marker> graphics_markers, compute_markers, m57_markers; + std::vector<RtvMarker> rtv_markers; + size_t m86_count = 0; + + try { + for (const auto& entry : fs::directory_iterator(src_dir)) { + if (!entry.is_regular_file(ec)) { + ec.clear(); + continue; + } + const fs::path path = entry.path(); + const std::wstring wname = path.filename().wstring(); + if (wname.size() < 22 || wname.rfind(L"req_", 0) != 0) + continue; + const std::wstring wstem = path.stem().wstring(); + if (wstem.size() != 20) + continue; + const std::wstring_view whex = std::wstring_view(wstem).substr(4); + if (!is_lower_hex16(whex)) + continue; + std::string hex16; + hex16.reserve(16); + for (wchar_t ch : whex) + hex16.push_back(static_cast<char>(ch)); + uint64_t old_key = 0; + const auto parsed = std::from_chars(hex16.data(), hex16.data() + hex16.size(), old_key, 16); + if (parsed.ec != std::errc{} || parsed.ptr != hex16.data() + hex16.size()) + continue; + const std::wstring ext = path.extension().wstring(); + if (ext == L".a") + graphics_markers.push_back({Kind::graphics, old_key, std::move(hex16)}); + else if (ext == L".c67") + compute_markers.push_back({Kind::compute, old_key, std::move(hex16)}); + else if (ext == L".m57") + m57_markers.push_back({Kind::m57, old_key, std::move(hex16)}); + else if (ext == L".rtv") + rtv_markers.push_back({old_key, std::move(hex16)}); + else if (ext == L".m86") + ++m86_count; + } + } catch (const fs::filesystem_error& error) { + std::cerr << "error: cannot list " << src_dir.string() << ": " << error.what() << '\n'; + return 1; + } + + auto by_old_key = [](const auto& a, const auto& b) { return a.old_key < b.old_key; }; + std::sort(graphics_markers.begin(), graphics_markers.end(), by_old_key); + std::sort(compute_markers.begin(), compute_markers.end(), by_old_key); + std::sort(m57_markers.begin(), m57_markers.end(), by_old_key); + std::sort(rtv_markers.begin(), rtv_markers.end(), by_old_key); + + std::vector<Marker> work; + work.reserve(graphics_markers.size() + compute_markers.size() + m57_markers.size()); + work.insert(work.end(), graphics_markers.begin(), graphics_markers.end()); + work.insert(work.end(), compute_markers.begin(), compute_markers.end()); + work.insert(work.end(), m57_markers.begin(), m57_markers.end()); + + struct WorkResult { + uint64_t new_key = 0; + bool has_ia = false; + bool has_psin = false; + std::string rewritten_psin; + std::string error; + }; + std::vector<WorkResult> results(work.size()); + + auto hash_item = [&](size_t idx) { + const Marker& m = work[idx]; + WorkResult& res = results[idx]; + std::string err; + try { + if (m.kind == Kind::graphics) { + std::string a, b, root, ia, psin_raw; + if (!read_rekey_bytes(rekey_request_path(src_dir, m.old_hex, ".b"), 64ull << 20, b, err) || + !read_rekey_bytes(rekey_request_path(src_dir, m.old_hex, ".root"), 16ull << 20, root, err) || + !read_rekey_bytes(rekey_request_path(src_dir, m.old_hex, ".a"), 64ull << 20, a, err)) { + res.error = std::move(err); + return; + } + const fs::path ia_path = rekey_request_path(src_dir, m.old_hex, ".ia"); + std::error_code file_ec; + if (fs::is_regular_file(ia_path, file_ec)) { + if (!read_rekey_bytes(ia_path, 1ull << 20, ia, err)) { + res.error = std::move(err); + return; + } + res.has_ia = true; + } + const fs::path psin_path = rekey_request_path(src_dir, m.old_hex, ".psin"); + std::string psin_entry; + if (fs::is_regular_file(psin_path, file_ec)) { + if (!read_rekey_bytes(psin_path, 128, psin_raw, err)) { + res.error = std::move(err); + return; + } + auto parsed_psin = x2w::parse_pixel_input_description(psin_raw, m.old_key); + psin_entry = std::move(parsed_psin.entry); + res.has_psin = true; + res.new_key = x2w::graphics_request_key(a, b, root, ia, psin_entry); + res.rewritten_psin = x2w::format_pixel_input_description(res.new_key, parsed_psin.ena, parsed_psin.addr); + } else { + res.new_key = x2w::graphics_request_key(a, b, root, ia); + } + } else if (m.kind == Kind::compute) { + std::string desc, sa, sb, data, root, c67; + constexpr size_t limit = 64ull << 20; + if (!read_rekey_bytes(rekey_request_path(src_dir, m.old_hex, ".desc"), limit, desc, err) || + !read_rekey_bytes(rekey_request_path(src_dir, m.old_hex, ".sa"), limit, sa, err) || + !read_rekey_bytes(rekey_request_path(src_dir, m.old_hex, ".sb"), limit, sb, err) || + !read_rekey_bytes(rekey_request_path(src_dir, m.old_hex, ".data"), limit, data, err) || + !read_rekey_bytes(rekey_request_path(src_dir, m.old_hex, ".root"), limit, root, err) || + !read_rekey_bytes(rekey_request_path(src_dir, m.old_hex, ".c67"), limit, c67, err)) { + res.error = std::move(err); + return; + } + res.new_key = x2w::compute_request_key(c67, data, root, desc, sa, sb); + } else { + std::string ps57, root, m57; + constexpr size_t limit = 64ull << 20; + if (!read_rekey_bytes(rekey_request_path(src_dir, m.old_hex, ".ps57"), limit, ps57, err) || + !read_rekey_bytes(rekey_request_path(src_dir, m.old_hex, ".root"), limit, root, err) || + !read_rekey_bytes(rekey_request_path(src_dir, m.old_hex, ".m57"), limit, m57, err)) { + res.error = std::move(err); + return; + } + res.new_key = x2w::mesh57_request_key(m57, ps57, root); + } + } catch (const std::exception& ex) { + res.error = ex.what(); + } + }; + + if (!work.empty()) { + const int worker_count = (std::min)(jobs, static_cast<int>(work.size())); + if (worker_count <= 1) { + for (size_t i = 0; i < work.size(); ++i) + hash_item(i); + } else { + std::atomic<size_t> next{}; + std::vector<std::future<void>> workers; + workers.reserve(worker_count); + for (int w = 0; w < worker_count; ++w) { + workers.emplace_back(std::async(std::launch::async, [&]() { + for (size_t i = next++; i < work.size(); i = next++) + hash_item(i); + })); + } + for (auto& w : workers) + w.get(); + } + } + + std::vector<std::string> bad; + std::map<uint64_t, uint64_t> new_graphics_map; + for (size_t i = 0; i < work.size(); ++i) { + if (!results[i].error.empty()) { + bad.push_back("req_" + work[i].old_hex + ": " + results[i].error); + } else if (work[i].kind == Kind::graphics) { + new_graphics_map[work[i].old_key] = results[i].new_key; + } + } + + std::map<uint64_t, std::string> rtv_rewritten; + for (const auto& rm : rtv_markers) { + std::string raw, err; + if (!read_rekey_bytes(rekey_request_path(src_dir, rm.old_hex, ".rtv"), 256, raw, err)) { + bad.push_back("req_" + rm.old_hex + ".rtv: " + err); + continue; + } + try { + const auto parsed = x2w::parse_rtv_variant_text(raw, rm.old_key); + const auto it = new_graphics_map.find(parsed.base_key); + if (it == new_graphics_map.end()) { + bad.push_back("req_" + rm.old_hex + ".rtv: .rtv base request " + format_key16(parsed.base_key) + + " is not a complete graphics request"); + continue; + } + std::string rewritten = x2w::format_rtv_variant_text(it->second, parsed.formats); + const uint64_t new_rtv_key = x2w::fnv1a_64(rewritten); + rtv_rewritten.try_emplace(new_rtv_key, std::move(rewritten)); + } catch (const std::exception& ex) { + bad.push_back("req_" + rm.old_hex + ".rtv: " + ex.what()); + } + } + + if (!bad.empty()) { + std::cerr << "error: " << bad.size() << " of " << (work.size() + rtv_markers.size()) + << " requests are incomplete or unreadable; nothing written\n"; + const size_t limit = (std::min)(bad.size(), size_t{10}); + for (size_t i = 0; i < limit; ++i) + std::cerr << " " << bad[i] << '\n'; + return 1; + } + + try { + fs::create_directories(dst_dir); + size_t written = 0, kept = 0; + + const size_t gfx_end = graphics_markers.size(); + const size_t cmp_end = gfx_end + compute_markers.size(); + const size_t m57_end = cmp_end + m57_markers.size(); + + auto publish_group = [&](size_t begin, size_t end, const char* label) { + std::set<uint64_t> done_keys; + size_t already_current = 0; + for (size_t i = begin; i < end; ++i) { + const Marker& m = work[i]; + const WorkResult& res = results[i]; + if (m.old_key == res.new_key) + ++already_current; + if (!done_keys.insert(res.new_key).second) + continue; + const std::string new_hex = format_key16(res.new_key); + auto copy_part = [&](const char* ext, size_t max_bytes) { + const fs::path dst_file = rekey_request_path(dst_dir, new_hex, ext); + std::error_code file_ec; + if (fs::exists(dst_file, file_ec)) { + ++kept; + return; + } + if (file_ec) + throw fs::filesystem_error("cannot inspect destination file", dst_file, file_ec); + std::string bytes, err; + if (!read_rekey_bytes(rekey_request_path(src_dir, m.old_hex, ext), max_bytes, bytes, err)) + throw std::runtime_error(err); + publish_atomic(dst_file, bytes.data(), bytes.size()); + ++written; + }; + if (m.kind == Kind::graphics) { + copy_part(".b", 64ull << 20); + copy_part(".root", 16ull << 20); + if (res.has_ia) + copy_part(".ia", 1ull << 20); + if (res.has_psin) + publish_rekey_file(rekey_request_path(dst_dir, new_hex, ".psin"), + res.rewritten_psin.data(), res.rewritten_psin.size(), written, kept); + copy_part(".a", 64ull << 20); + } else if (m.kind == Kind::compute) { + constexpr size_t limit = 64ull << 20; + copy_part(".desc", limit); + copy_part(".sa", limit); + copy_part(".sb", limit); + copy_part(".data", limit); + copy_part(".root", limit); + copy_part(".c67", limit); + } else { + constexpr size_t limit = 64ull << 20; + copy_part(".ps57", limit); + copy_part(".root", limit); + copy_part(".m57", limit); + } + } + std::cout << label << ": " << (end - begin) << " requests, " << already_current + << " already current -> " << done_keys.size() << " keys\n"; + }; + + publish_group(0, gfx_end, "graphics"); + publish_group(gfx_end, cmp_end, "compute"); + publish_group(cmp_end, m57_end, "m57"); + for (const auto& [new_key, text] : rtv_rewritten) + publish_rekey_file(rekey_request_path(dst_dir, format_key16(new_key), ".rtv"), + text.data(), text.size(), written, kept); + std::cout << "rtv variants: " << rtv_markers.size() << " requests -> " << rtv_rewritten.size() << " keys\n"; + std::cout << "not re-keyed (own key strings): m86 " << m86_count << '\n'; + std::cout << "files: " << written << " written, " << kept << " already present in " << dst_dir.string() << '\n'; + return 0; + } catch (const std::exception& error) { + std::cerr << "error: failed writing " << dst_dir.string() << ": " << error.what() << '\n'; + return 1; + } +} + int wmain(int argc, wchar_t** argv) { + if (argc >= 2 && std::wstring_view(argv[1]) == L"--rekey") + return run_rekey(argc, argv); if (argc >= 2 && std::wstring_view(argv[1]) == L"--watch") return run_watch(argc, argv); if (argc >= 2 && std::wstring_view(argv[1]) == L"--refusals") @@ -1030,6 +1442,7 @@ int wmain(int argc, wchar_t** argv) { "gfx1013-container-rect also emits the rectangle geometry stage.\n" "Use --refusals REQUEST_DIRECTORY [--jobs N] [--json] for a read-only refusal summary.\n" "Use --watch SDK_DIRECTORY CACHE_DIRECTORY REQUEST_DIRECTORY [--jobs N] [--interval MS] [--once] to translate pending requests.\n" + "Use --rekey OLD_CACHE_DIR NEW_REQUEST_DIR [--jobs N] to copy requests under the current cache revision keys.\n" "Use --index-graphics-interfaces REVIEWED_DIRECTORY CACHE_DIRECTORY to index native graphics interfaces.\n" "Use --prepare-compute-pack REQUEST_DIRECTORY CACHE_DIRECTORY ENTRY_BYTE_OFFSET for captured compute.\n"; return 2; @@ -1139,8 +1552,13 @@ int wmain(int argc, wchar_t** argv) { const fs::path manifest_path = fs::path(stems[i]) += L".txt"; std::error_code ignored; fs::remove(manifest_path, ignored); - auto manifest = compile_one(compiler, job_profile(i), inputs[i], outputs[i], argv[2], report, nullptr, true); + fs::remove(fs::path(stems[i]) += L".cs.hlsl", ignored); // see compile_watch_item + std::string reason; + auto manifest = compile_one(compiler, job_profile(i), inputs[i], outputs[i], argv[2], report, nullptr, true, &reason); if (manifest) publish_atomic(manifest_path, manifest->data(), manifest->size()); + // Not a .fail: that file is the watchers' retry marker, and this compile succeeded. + if (!manifest && !reason.empty()) + report << "no_manifest input=" << inputs[i].filename().string() << ' ' << manifest_refusal(reason) << '\n'; fs::remove(fs::path(stems[i]) += L".fail", ignored); return; } diff --git a/tools/startup/compile_lds_request.py b/tools/startup/compile_lds_request.py index ace21c37f9..621323f88c 100644 --- a/tools/startup/compile_lds_request.py +++ b/tools/startup/compile_lds_request.py @@ -8,8 +8,12 @@ import shutil import struct import subprocess +import sys from tempfile import TemporaryDirectory +_STARTUP_DIR = str(Path(__file__).resolve().parent) +if _STARTUP_DIR not in sys.path: + sys.path.insert(0, _STARTUP_DIR) import gfx2hlsl as gfx @@ -92,8 +96,12 @@ def body(self): elif term[0] == 'end': dest = [] elif term[0] == 'jump': + if term[1] not in index: + raise gfx.Unsupported(f'branch target {term[1]} is outside the compute stage') dest = [index[term[1]]] elif term[0] == 'branch': + if term[2] not in index: + raise gfx.Unsupported(f'branch target {term[2]} is outside the compute stage') dest = [i+1,index[term[2]]] else: raise gfx.Unsupported('unsupported compute branch') @@ -130,6 +138,15 @@ def body(self): return lines +class CompileLdsRequestError(ValueError): + """Error raised by this tool's own CLI and artifact guards. + + Only this type (plus gfx.Unsupported and subprocess.CalledProcessError) + is caught in main(); anything else keeps its traceback, so a real + translator bug is never mistaken for a deliberate refusal. + """ + + class ComputePipeline(gfx.ComputePipeline): stage_type = ComputeStage @@ -138,7 +155,44 @@ def __init__(self, *args, feedback, **kwargs): super().__init__(*args, **kwargs) -def main(): +def _validate_regular_file(path: Path, label: str) -> None: + if path.is_dir(): + raise CompileLdsRequestError(f'{label} path is a directory: {path}') + if not path.exists(): + raise CompileLdsRequestError(f'{label} file not found: {path}') + if not path.is_file(): + raise CompileLdsRequestError(f'{label} path is not a regular file: {path}') + + +def _validate_writable_dir(path: Path, label: str) -> None: + """Reject paths that are files or whose parents are files or dangling links. + + A symlink component is allowed: the bundle is written through a + TemporaryDirectory inside the output and moved into place with an atomic + rename, so a symlinked output or cache is simply the caller's chosen + location. Only a component that is not a directory at all is refused. + """ + if path.is_file() or (path.exists() and not path.is_dir()): + raise CompileLdsRequestError(f'{label} path is not a directory: {path}') + for parent in path.parents: + if parent.is_file() or ((parent.exists() or parent.is_symlink()) and not parent.is_dir()): + raise CompileLdsRequestError(f'{label} parent is not a directory: {parent}') + + +def _validate_paths(args: argparse.Namespace) -> None: + _validate_regular_file(args.marker, 'request marker') + for ext in ('.root', '.data', '.desc', '.sa', '.sb'): + _validate_regular_file(args.marker.with_suffix(ext), f'companion {ext}') + _validate_regular_file(args.compiler, 'compiler') + if not args.sdk.exists(): + raise CompileLdsRequestError(f'SDK directory not found: {args.sdk}') + if not args.sdk.is_dir(): + raise CompileLdsRequestError(f'SDK path is not a directory: {args.sdk}') + _validate_writable_dir(args.output, 'output') + _validate_writable_dir(args.cache, 'cache') + + +def main(argv=None) -> int: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('marker',type=Path) parser.add_argument('output',type=Path) @@ -147,7 +201,7 @@ def main(): parser.add_argument('--cache',required=True,type=Path) parser.add_argument('--rw-image',required=True,nargs=2,type=int,metavar=('PARAM','BYTE_OFFSET')) parser.add_argument('--wave-size',required=True,type=int,choices=[32,64]) - args = parser.parse_args() + args = parser.parse_args(argv) name = args.marker.name if not re.fullmatch(r'req_[0-9a-f]{16}\.c67',name): parser.error('expected req_<16 hex digits>.c67') @@ -155,41 +209,58 @@ def main(): param,off = args.rw_image if param < 0 or off < 0 or off%32: parser.error('expected a nonnegative parameter and a 32-byte-aligned descriptor offset') - args.output.mkdir(parents=True,exist_ok=True) - with TemporaryDirectory(dir=args.output) as temp: - bundle = Path(temp)/'bundle' - request = bundle/'request' - request.mkdir(parents=True) - for ext in ('.c67','.root','.data','.desc','.sa','.sb'): - path = args.marker.with_suffix(ext) - shutil.copyfile(path,request/path.name) - pipeline = gfx.load_compute_request(str(request),key, - pipeline_type=partial(ComputePipeline,feedback=(('table',param),off))) - source = pipeline.hlsl_cs().replace('[numthreads(',f'[WaveSize({args.wave_size})]\n[numthreads(') - stage = bundle/f'{key:016x}.cs.hlsl' - stage.write_text(source,encoding='utf-8') - bytecode = stage.with_suffix('.cso') - subprocess.run([args.compiler,args.sdk,args.cache,'cs_6_6',stage,bytecode],check=True) - manifest = bundle/f'{key:016x}.txt' - manifest.write_text(pipeline.manifest(),encoding='utf-8') - metadata = {'schema':1,'request':f'request/{name}','profile':'cs_6_6','rw_image':[param,off], - 'wave_size':args.wave_size,'sha256':{}} - for path in sorted(bundle.rglob('*')): - if path.is_file(): - metadata['sha256'][path.relative_to(bundle).as_posix()] = hashlib.sha256(path.read_bytes()).hexdigest() - replay = json.dumps(metadata,indent=2,sort_keys=True)+'\n' - (bundle/'replay.json').write_bytes(replay.encode()) - dest = args.output/f'{key:016x}-{hashlib.sha256(replay.encode()).hexdigest()}' - try: - bundle.rename(dest) - except OSError: - if not dest.is_dir() or (dest/'replay.json').read_bytes()!=replay.encode(): - raise - for relative,digest in metadata['sha256'].items(): - if hashlib.sha256((dest/relative).read_bytes()).hexdigest()!=digest: - raise RuntimeError(f'damaged replay artifact {relative}') - print(dest) + try: + _validate_paths(args) + args.output.mkdir(parents=True, exist_ok=True) + with TemporaryDirectory(dir=args.output) as temp: + bundle = Path(temp) / 'bundle' + request = bundle / 'request' + request.mkdir(parents=True) + for ext in ('.c67', '.root', '.data', '.desc', '.sa', '.sb'): + path = args.marker.with_suffix(ext) + shutil.copyfile(path, request / path.name) + pipeline = gfx.load_compute_request( + str(request), key, + pipeline_type=partial(ComputePipeline, feedback=(('table', param), off)), + ) + source = pipeline.hlsl_cs().replace('[numthreads(', f'[WaveSize({args.wave_size})]\n[numthreads(') + stage = bundle / f'{key:016x}.cs.hlsl' + stage.write_text(source, encoding='utf-8') + bytecode = stage.with_suffix('.cso') + subprocess.run([args.compiler, args.sdk, args.cache, 'cs_6_6', stage, bytecode], check=True) + manifest = bundle / f'{key:016x}.txt' + manifest.write_text(pipeline.manifest(), encoding='utf-8') + metadata = { + 'schema': 1, 'request': f'request/{name}', 'profile': 'cs_6_6', + 'rw_image': [param, off], 'wave_size': args.wave_size, 'sha256': {}, + } + for path in sorted(bundle.rglob('*')): + if path.is_file(): + metadata['sha256'][path.relative_to(bundle).as_posix()] = hashlib.sha256(path.read_bytes()).hexdigest() + replay = json.dumps(metadata, indent=2, sort_keys=True) + '\n' + (bundle / 'replay.json').write_bytes(replay.encode()) + dest = args.output / f'{key:016x}-{hashlib.sha256(replay.encode()).hexdigest()}' + try: + bundle.rename(dest) + except OSError as error: + if not dest.is_dir(): + raise CompileLdsRequestError(f'cannot move replay bundle to {dest}: {error}') from error + replay_path = dest / 'replay.json' + if not replay_path.is_file() or replay_path.read_bytes() != replay.encode(): + raise CompileLdsRequestError(f'damaged replay artifact replay.json in {dest}') from error + for relative, digest in metadata['sha256'].items(): + try: + data = (dest / relative).read_bytes() + except OSError: + raise CompileLdsRequestError(f'damaged replay artifact {relative}') from None + if hashlib.sha256(data).hexdigest() != digest: + raise CompileLdsRequestError(f'damaged replay artifact {relative}') + print(dest) + except (gfx.Unsupported, subprocess.CalledProcessError, CompileLdsRequestError) as error: + print(f'error: {error}', file=sys.stderr) + return 1 + return 0 if __name__ == '__main__': - main() + raise SystemExit(main()) diff --git a/tools/startup/debug_launch.py b/tools/startup/debug_launch.py index 5bffa1820b..c5f794f77e 100644 --- a/tools/startup/debug_launch.py +++ b/tools/startup/debug_launch.py @@ -2,11 +2,16 @@ usage: debug_launch.py <exe> <cwd> <logdir> [--timeout S] [--memory-gib N] [--stop-first-chance 1] [--suspend-others 0] [--capture-every S] + [--continue-asserts N] [--assert-sites N] Records module loads, every exception (code, address as module+offset, first/second chance) and, for the stopping exception, the integer registers, the stack words and the code bytes around RIP. Stops at a second-chance exception, an uncontinued main-image breakpoint, or the timeout. A timeout of zero disables the timer. An assertion continuation limit of -1 removes that limit. +--continue-asserts N steps over the first N main-image int3 hits in total. --assert-sites N instead +steps over every hit at up to N distinct main-image int3 sites, so a site that repeats does not use +the budget up however long the run lasts; the first hit at one more site stops the run. A hit is +stepped over when either budget allows it. A file named `stop` created in <logdir> during the run ends it as the timeout does (checked twice a second; a stop file left from an earlier run is removed at start). """ @@ -131,8 +136,10 @@ def print(*args, **kwargs): timeout = float(opts.get("--timeout", 15)) # zero leaves the session running until exit or a debug stop memory_gib = float(opts.get("--memory-gib", 16)) skip_asserts = int(opts.get("--continue-asserts", "0")) # -1 continues all diagnostic assertions + assert_sites = int(opts.get("--assert-sites", "0")) # distinct sites whose every hit is continued except ValueError: - print("expected numeric --timeout and --memory-gib values and an integer --continue-asserts value") + print("expected numeric --timeout and --memory-gib values and integer --continue-asserts and " + "--assert-sites values") return 2 stop_first = opts.get("--stop-first-chance") == "1" try: @@ -145,12 +152,20 @@ def print(*args, **kwargs): if timeout < 0 or not timeout < float("inf") or skip_asserts < -1: print("expected a finite nonnegative timeout and an assertion limit of -1 or greater") return 2 + if assert_sites < 0: + print("expected an --assert-sites value of 0 or greater") + return 2 # The job always sets JOB_MEMORY (0x200), so a limit of 0 would deny the process any commit. if not 1 <= memory_gib * 2**30 < 2**(8 * ctypes.sizeof(ctypes.c_size_t)): print("expected a finite --memory-gib that is at least one byte and fits the Windows size_t limit") return 2 memory = int(memory_gib * 2**30) asserts_seen = {} + # The two assert budgets keep their own books, so a hit one of them covers never uses up the other: + # assert_sites_admitted holds the sites --assert-sites covers (the first assert_sites distinct ones), + # asserts_counted the hits --continue-asserts stepped over. + assert_sites_admitted = set() + asserts_counted = 0 # X2W_NOP_SOFT_ASSERTS=1: after the first hit of a main-image int3 that is continued, replace the # trap byte with NOP. DBG_CONTINUE already bypasses the title's handler, so the visible behavior is # unchanged, but a long mapping that traps once per chunk then runs at native speed. @@ -366,6 +381,97 @@ def oa_name(addr): # OBJECT_ATTRIBUTES* text = ustr(name) if name else "" return (f"[root {root:#x}]" if root else "") + text + def oa_string(addr): # the UNICODE_STRING* inside OBJECT_ATTRIBUTES, for rewriting it + raw = read(addr, 24) + return struct.unpack_from("<Q", raw, 16)[0] if len(raw) >= 24 else 0 + + # --map-drive G=C:\folder[;S=D:\folder]: a console executable opens its package at a fixed drive + # letter, so a package that sits on another volume never mounts. The file hooks rewrite the path + # of an open on a mapped letter to the real folder, in the caller's own UNICODE_STRING. + drive_map = {} + # Rewritten names live in buffers borrowed for the duration of one hooked call, so two calls that + # overlap on different threads cannot overwrite or free each other's name. A buffer goes back to + # the pool when that call's name is restored, so a serial run reuses one buffer instead of + # allocating per open and the allocation count does not follow the number of opens. + name_pool = {"free": [], "allocations": 0} + for item in filter(None, opts.get("--map-drive", "").split(";")): + letter, _, folder = item.partition("=") + letter = letter.strip().rstrip(":").upper() + # Letters are ASCII A-Z: isalpha() alone also accepts non-ASCII letters, which no NT path has. + if len(letter) == 1 and letter.isascii() and letter.isalpha() and folder.strip(): + # NT paths take backslashes; the option may arrive with either separator. + drive_map[letter] = folder.strip().rstrip("\\/").replace("/", "\\") + + def map_drive(text, string_address): + """Makes the call's name temporary: returns (new text, restore) or (None, None). + + The caller's UNICODE_STRING is changed only for the duration of the hooked call; restore() + puts back its length, buffer pointer and contents when the call returns.""" + if not drive_map or not string_address: + return None, None + body = text + # oa_name() marks a root-relative name with a "[root 0x...]" tag for the log. That tag is not + # part of the name, so it is dropped here and never written into the caller's UNICODE_STRING. + if body.startswith("[root ") and "]" in body: + body = body[body.index("]") + 1:] + prefix = "" + for candidate in ("\\??\\", "\\\\.\\", "\\\\?\\"): + if body.upper().startswith(candidate): + prefix, body = body[:len(candidate)], body[len(candidate):] + break + if len(body) < 2 or body[1] != ":" or body[0].upper() not in drive_map: + return None, None + replacement = prefix + drive_map[body[0].upper()] + body[2:] + raw = read(string_address, 16) + if len(raw) < 16: + return None, None + _, maximum, buffer = struct.unpack_from("<HH4xQ", raw) + encoded = replacement.encode("utf-16-le") + # A UNICODE_STRING length is a USHORT, so a longer name cannot be expressed at all. + if not 0 < len(encoded) <= 0xFFFF: + return None, None + if len(encoded) <= maximum: + original = read(buffer, len(encoded)) + if len(original) != len(encoded) or not write(buffer, encoded): + return None, None + if not write(string_address, struct.pack("<H", len(encoded))): + write(buffer, original) + return None, None + return replacement, lambda: (write(buffer, original), write(string_address, raw)) + # The replacement is longer than the caller's buffer, which is the common case: a folder path + # against a single letter. Borrow a buffer from the pool for this call only; it is returned + # when the name is restored, so serial opens reuse one buffer but overlapping calls get their + # own. + address, capacity = 0, 0 + for index, (candidate, room) in enumerate(name_pool["free"]): + if room >= len(encoded): + address, capacity = name_pool["free"].pop(index) + break + if not address: + k32.VirtualAllocEx.restype = ctypes.c_void_p + k32.VirtualAllocEx.argtypes = [wt.HANDLE, ctypes.c_void_p, ctypes.c_size_t, wt.DWORD, wt.DWORD] + fresh = k32.VirtualAllocEx(wt.HANDLE(pi.hProcess), None, len(encoded), 0x3000, 0x04) + if not fresh: + return None, None + address, capacity = fresh, len(encoded) + name_pool["allocations"] += 1 + if file_log: + file_log.write(f"{time.time() - start:7.3f} NAMEBUF alloc {len(encoded)} bytes at {fresh:#x} " + f"(live {name_pool['allocations']})\n") + file_log.flush() + if not write(address, encoded): + name_pool["free"].append((address, capacity)) + return None, None + if not write(string_address, struct.pack("<HH4xQ", len(encoded), len(encoded), address)): + name_pool["free"].append((address, capacity)) + return None, None + + def restore(): + write(string_address, raw) + name_pool["free"].append((address, capacity)) + + return replacement, restore + trace = opts.get("--trace-files") == "1" or opts.get("--offline", "1") == "1" # offline mode needs the hooks # --trace-calls 1: also break on gaming-runtime and movie-player calls. Every hit stops the whole # process, so these hooks are off by default; the movie-player report (bink_report) needs them. @@ -556,7 +662,11 @@ def handle_breakpoint(tid, addr): if addr in hooks: hook_entries[0] += 1 name, arg = hooks[addr] - ret = read_qword(read, rsp) or 0 + ret = struct.unpack("<Q", read(rsp, 8) or b"\0" * 8)[0] + # Every kind of trace reaches the common "if desc:" below, so the restore callback is + # initialised here: leaving it to the file-name branch would let a non-name trace see an + # unbound name or carry over the previous call's callback. + restore = None if arg == "valloc": # NtAllocateVirtualMemory(process, &base, zero bits, &size, type, protect) and # NtAllocateVirtualMemoryEx(process, &base, &size, type, protect, ...). @@ -604,10 +714,29 @@ def guid(address): desc = bink_call(name, regs, ret) else: if arg.startswith("ustr:"): - target = ustr(regs[arg[5:].capitalize()]) + string_address = regs[arg[5:].capitalize()] + target = ustr(string_address) else: - target = oa_name(regs[arg.capitalize()] if arg != 'r8' else regs['R8']) - desc = f"{name} {target} from {where(ret)}" + oa_address = regs['R8'] if arg == 'r8' else regs[arg.capitalize()] + target = oa_name(oa_address) + string_address = oa_string(oa_address) + if offline and any(pattern in target.lower() for pattern in OFFLINE_DENY): + # Offline mode: the call never runs, so the caller's name is left untouched. + denied[target] = denied.get(target, 0) + 1 + file_log.write(f"{time.time() - start:7.3f} DENIED (offline) {name} {target} " + f"from {where(ret)}\n") + file_log.flush() + struct.pack_into("<Q", ctx, 0x78, 0xC0000022) # rax + struct.pack_into("<Q", ctx, 0x98, rsp + 8) # rsp: pop the return address + struct.pack_into("<Q", ctx, 0xF8, ret) # rip + set_ctx(thread) + return True + mapped, restore = map_drive(target, string_address) + desc = f"{name} {mapped or target} from {where(ret)}" + if mapped: + desc += " (mapped from " + target + ")" + file_log.write(f"{time.time() - start:7.3f} MAP {target} -> {mapped}\n") + file_log.flush() if offline and any(pattern in target.lower() for pattern in OFFLINE_DENY): # Offline mode: the call never runs. Return STATUS_ACCESS_DENIED to the caller. denied[target] = denied.get(target, 0) + 1 @@ -627,7 +756,9 @@ def guid(address): chain = [c for c in chain if not c.lower().startswith(("ntdll", "kernelbase", "kernel32"))] desc += " callers: " + " ".join(chain[:8]) if desc: - returns.add(ret, tid, rsp + 8, desc, addr) + # The name is temporary: take() puts the caller's own UNICODE_STRING back (restore) when the + # call returns, before anything else runs, so a failure or a retry sees the name it built. + returns.add(ret, tid, rsp + 8, desc, addr, restore) arm(ret) for description in returns.take(addr, tid, rsp): file_log.write(f"{time.time() - start:7.3f} {description} -> {regs['Rax'] & 0xFFFFFFFF:#010x}\n") @@ -937,8 +1068,13 @@ def capture_loop(): log(f"X2W_LOG_AT ignored {rva:#x}: cannot arm a main-image instruction breakpoint") del log_at[rva] elif (ex_code == 0x80000003 and first and main_base and main_base <= ex_addr < main_base + 0x10000000 - and (skip_asserts == -1 or sum(asserts_seen.values()) < skip_asserts) + and (ex_addr in assert_sites_admitted or len(assert_sites_admitted) < assert_sites + or skip_asserts == -1 or asserts_counted < skip_asserts) and (ex_addr - main_base) not in stop_at): + if ex_addr in assert_sites_admitted or len(assert_sites_admitted) < assert_sites: + assert_sites_admitted.add(ex_addr) + else: + asserts_counted += 1 asserts_seen[ex_addr] = asserts_seen.get(ex_addr, 0) + 1 if nop_soft_asserts and ex_addr not in nop_sites and read(ex_addr, 1) == b"\xcc" and write(ex_addr, b"\x90"): nop_sites[ex_addr] = 1 diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index bedd84bb45..4100044215 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -790,6 +790,41 @@ def clear_after(name, asm, may, clear): return out | {(word, h) for word, held in writes for h in held} +EXEC_SUBSET = frozenset({('exec', 0), ('exec_hi', 1)}) + + +def subset_after(name, asm, may, clear): + """Forward step before an s_cbranch_execz: scalar words known to have bit 0 wherever current EXEC has bit 0. + + When EXEC is unchanged, bitwise mask instructions propagate those subset facts via clear_after and non-mask + writes drop them. When EXEC is written, facts on the written wave half are dropped unless a move assigns EXEC + from a scalar mask word (so that word equals the new EXEC) or an OR widens EXEC with an existing bitmask. + Indirect scalar writes (s_movrel*) drop all non-EXEC facts.""" + base = re.sub(r'_e(32|64)$', '', name) + if base.startswith('s_movrel'): + return EXEC_SUBSET + if not (may & EXEC_KEYS): + return frozenset(clear_after(name, asm, may, clear)) | EXEC_SUBSET + kept = ({0} if 'exec' not in may else set()) | ({1} if 'exec_hi' not in may else set()) + shape = clear_shape(name, asm) + if shape and shape != 'cmpx': + op, saving, count, words = shape + if op == 'or' and (saving == '_saveexec' or any( + all(src[p] == ('exec', 'exec_hi')[p] for p in range(count)) for src in words[1:])): + return frozenset(clear_after(name, asm, may, clear)) | EXEC_SUBSET + out = {fact for fact in clear if fact[1] in kept and fact[0] not in may - EXEC_KEYS} + if op == 'mov' and saving is None: + dest, src = words + for p, dw in enumerate(dest): + if dw in EXEC_KEYS: + h = 0 if dw == 'exec' else 1 + sw = src[p] + if re.fullmatch(r's\d+|vcc(_hi)?', sw): + out.add((sw, h)) + return frozenset(out) | EXEC_SUBSET + return frozenset(fact for fact in clear if fact[1] in kept and fact[0] not in may - EXEC_KEYS) | EXEC_SUBSET + + def mask_lanes(name, asm): """(operation, destination words, source word lists) of a bitwise scalar mask instruction, or None. Word p of every operand holds the same lanes: wave half p of a 64-bit form.""" @@ -2332,6 +2367,111 @@ def region_walk(lo, hi): return out +RESHEAP_RANGE_SPACE = 2 +RESHEAP_RANGE_MAX = 1024 + + +def _lit_u32(tok): + if re.fullmatch(r'-?(?:0[xX][0-9a-fA-F]+|\d+)', tok) and tok not in FLOATS: + return int(tok, 0) & 0xffffffff + return None + + +def _join_vbound(a, b): + if a is None or b is None or a[0] != b[0]: + return None + return (a[0], max(a[1], b[1])) + + +def vgpr_heap_bounds(ins, succ): + """Forward CFG dataflow: map each instruction index to ({vreg: ('idx' | 'off5', max_idx)}, exec_is_entry). + + A bound enters only while every active lane that can reach a waterfall head executes the bounding write + (proven before any EXEC change, or joined with the prior bound on every path after EXEC changes).""" + if not ins: + return [] + before = [None] * len(ins) + before[0] = ({}, True) + work = [0] + for i in work: + regs, exec_entry = before[i] + _off, _n, name, asm = ins[i] + base, ops, mods = parse(asm) + base = re.sub(r'_e(32|64)$', '', base) + nxt_regs = dict(regs) + nxt_exec = exec_entry and not writes_exec(name, ops) + dst_v = set() + for tok in destinations(name, ops): + r = reg_range(tok) + if r and r[0] == 'v': + dst_v.update(range(r[1], r[2] + 1)) + if 'movrel' in name: + nxt_regs.clear() + elif dst_v: + new_val = None + r0 = reg_range(ops[0]) if ops else None + single = r0 and r0[0] == 'v' and r0[1] == r0[2] and r0[1] <= 255 and dst_v == {r0[1]} + if single and not mods: + def src_idx_max(tok): + k = _lit_u32(tok) + if k is not None: + return k + rs = reg_range(tok) + if rs and rs[0] == 'v' and rs[1] == rs[2] and regs.get(rs[1], ('',))[0] == 'idx': + return regs[rs[1]][1] + return None + + if base in ('v_and_b32', 'v_min_u32') and len(ops) == 3: + bounds = [b for b in (src_idx_max(ops[1]), src_idx_max(ops[2])) if b is not None] + if bounds and min(bounds) < RESHEAP_RANGE_MAX: + new_val = ('idx', min(bounds)) + elif base == 'v_bfe_u32' and len(ops) == 4: + width = _lit_u32(ops[3]) + if width is not None and width < 16 and ((1 << width) - 1) < RESHEAP_RANGE_MAX: + new_val = ('idx', (1 << width) - 1) + elif base == 'v_lshrrev_b32' and len(ops) == 3: + shift = _lit_u32(ops[1]) + if shift is not None: + shift &= 31 + rs = reg_range(ops[2]) + if rs and rs[0] == 'v' and rs[1] == rs[2] and regs.get(rs[1], ('',))[0] == 'idx': + new_val = ('idx', regs[rs[1]][1] >> shift) + elif (0xffffffff >> shift) < RESHEAP_RANGE_MAX: + new_val = ('idx', 0xffffffff >> shift) + elif base == 'v_lshlrev_b32' and len(ops) == 3: + shift = _lit_u32(ops[1]) + rs = reg_range(ops[2]) + if (shift is not None and (shift & 31) == 5 and rs and rs[0] == 'v' and rs[1] == rs[2] + and regs.get(rs[1], ('',))[0] == 'idx'): + new_val = ('off5', regs[rs[1]][1]) + elif base == 'v_mov_b32' and len(ops) == 2: + k = _lit_u32(ops[1]) + rs = reg_range(ops[1]) + if k is not None and k < RESHEAP_RANGE_MAX: + new_val = ('idx', k) + elif rs and rs[0] == 'v' and rs[1] == rs[2] and rs[1] in regs: + new_val = regs[rs[1]] + for v in dst_v: + merged = new_val if (single and exec_entry) else (_join_vbound(regs.get(v), new_val) if single else None) + if merged is not None: + nxt_regs[v] = merged + else: + nxt_regs.pop(v, None) + for s in succ[i]: + if before[s] is None: + before[s] = (nxt_regs, nxt_exec) + work.append(s) + else: + old_regs, old_exec = before[s] + m_exec = old_exec and nxt_exec + m_regs = {k: j for k, v in old_regs.items() if k in nxt_regs + for j in (_join_vbound(v, nxt_regs[k]),) if j is not None} + if (m_regs, m_exec) != before[s]: + before[s] = (m_regs, m_exec) + work.append(s) + return before + + def adjacent_address_carries(ins, targets): """Map each candidate low add to its high-word carry read in the same basic block.""" pairs = {} @@ -3110,13 +3250,27 @@ def execz_refusals(self): value = reads | (out - writes) if value != live_in[i]: live_in[i], changed = value, True + vbounds = vgpr_heap_bounds(self.ins, succ) self.waterfall_reads = {} + self.waterfall_heap_bounds = {} for close, target in jumps: head = index.get(target) if (head is not None and head + 3 < close and self.ins[close][2] == 's_cbranch_scc1' and self.ins[head][2] == 'v_readfirstlane_b32' and self.ins[close - 1][2] == 's_andn2_wrexec_b32'): - self.waterfall_reads[target] = self.waterfall_refusal(head, close, effects, live_in, jumps) + self.waterfall_reads[target] = self.waterfall_refusal(head, close, effects, live_in, jumps, vbounds) + pre_sub = [EXEC_SUBSET] + [None] * (len(self.ins) - 1) + changed = bool(self.ins) + while changed: + changed = False + for i in range(len(self.ins)): + if pre_sub[i] is None: + continue + after = subset_after(*self.ins[i][2:], effects[i][2], pre_sub[i]) + for s in succ[i]: + if pre_sub[s] is None or not pre_sub[s] <= after: + pre_sub[s] = after if pre_sub[s] is None else (pre_sub[s] & after) + changed = True refused, into = {}, {} for k, target in jumps: into.setdefault(index.get(target), []).append(k) @@ -3129,7 +3283,7 @@ def execz_refusals(self): continue live = live_in[t] | {'m0'} # m0 is also read implicitly; treat it as live # Facts before each instruction the wave can reach from the branch: the largest sets every path keeps. - entry = frozenset({('exec', 0), ('exec_hi', 1)}) + entry = pre_sub[b] or EXEC_SUBSET before = {b + 1: entry} if b + 1 < t else {} entered = any(index.get(target) in range(b + 1, t) for k, target in jumps if not b < k < t) changed = not entered @@ -3137,7 +3291,7 @@ def execz_refusals(self): changed = False for i in range(b + 1, t): if i in before: - after = frozenset(clear_after(*self.ins[i][2:], effects[i][2], before[i])) | entry + after = frozenset(clear_after(*self.ins[i][2:], effects[i][2], before[i])) | EXEC_SUBSET for s in succ[i]: if b < s < t and before.get(s, after) & after != before.get(s): before[s], changed = before.get(s, after) & after, True @@ -3177,7 +3331,7 @@ def quiet(j): # exec unchanged since the join on every path to j: a straight ru self.execz_scalar_exit(b, i, t, exit_index, effects, live_in, into)): reason = 'branch out of the block' elif may & EXEC_KEYS and (entered or i in before and - not entry <= clear_after(inner, inner_asm, may, before[i])): + not EXEC_SUBSET <= clear_after(inner, inner_asm, may, before[i])): reason = 'exec write' elif words := [word for word in sorted((may - EXEC_KEYS - ok_masks) & live) if self.execz_live_read(t, word, kept[word], effects, succ, quiet, unread) is not None]: @@ -3296,7 +3450,109 @@ def execz_live_read(self, t, word, halves, effects, succ, quiet, unread): unread[word] = None return None - def waterfall_refusal(self, head, close, effects, live_in, jumps): + def compute_resheap_sgpr(self): + pipe = getattr(self, 'pipe', None) + root = getattr(pipe, 'root', None) + if not root or not (root['flags'] & 0x400): + return None + reg = 4 if getattr(self, 'kind', None) == 'cs' else 8 + for p in root['params']: + reg += 1 if p['type'] == 0 else p['count'] if p['type'] == 1 else 2 + return reg + + def waterfall_heap_check(self, head, close, effects, key, key_vtok, body_writes, numeric_writes, + buffer_descriptors, vbounds): + """Return ('idx' | 'off5', max_idx) when every key-dependent descriptor selection in the waterfall + body reads a resource heap record at a proven bounded per-lane index, else None.""" + if buffer_descriptors & numeric_writes: + return None + resheap_reg = self.compute_resheap_sgpr() + if resheap_reg is None or ('s%d' % resheap_reg) in body_writes or not vbounds: + return None + binfo = vbounds[head] + k_reg = int(key_vtok[1:]) + key_bound = binfo[0].get(k_reg) if binfo else None + if not key_bound: + return None + ins = self.ins + local_idx = {key} if key_bound[0] == 'idx' else set() + local_off5 = {key} if key_bound[0] == 'off5' else set() + local_ptrs = set() + heap_aliases = {'s%d' % resheap_reg} + local_descs = set() + pending_carry = None + for j in range(head + 2, close - 1): + base, ops, mods = parse(ins[j][3]) + base = re.sub(r'_e(32|64)$', '', base) + reads, _writes, may_write = effects[j] + if pending_carry is not None: + carry_d, want_j = pending_carry + pending_carry = None + hi_tok = 's%d' % (carry_d + 1) + carry_ok = (j == want_j and not mods and ( + (base == 's_add_u32' and ops == [hi_tok, '0', 'src_scc']) or + (base == 's_addc_u32' and len(ops) == 3 and ops[0] == hi_tok and ops[2] == '0' + and ops[1] not in body_writes))) + if not carry_ok: + return None + local_ptrs.add(('s%d' % carry_d, hi_tok)) + for w in may_write: + local_idx.discard(w) + local_off5.discard(w) + heap_aliases.discard(w) + local_descs = {tup for tup in local_descs if w not in tup} + continue + idx_hit = (base == 's_lshl_b32' and not mods and len(ops) == 3 and ops[1] in local_idx and ops[2] == '5') + mov_idx = base == 's_mov_b32' and not mods and len(ops) == 2 and ops[1] in local_idx + mov_off5 = base == 's_mov_b32' and not mods and len(ops) == 2 and ops[1] in local_off5 + mov_heap = base == 's_mov_b32' and not mods and len(ops) == 2 and ops[1] in heap_aliases + add_hit = (base == 's_add_u32' and not mods and len(ops) == 3 and ( + (ops[1] in heap_aliases and ops[2] in local_off5) or + (ops[2] in heap_aliases and ops[1] in local_off5))) + load_hit = False + if base == 's_load_dwordx4' and (reads & body_writes): + if mods or len(ops) != 3: + return None + br, dr = reg_range(ops[1]), reg_range(ops[0]) + if not br or br[0] != 's' or br[2] - br[1] != 1 or not dr or dr[0] != 's' or dr[2] - dr[1] != 3: + return None + b_lo, b_hi = 's%d' % br[1], 's%d' % br[2] + off_tok = smem_offset(ops[2]) + if not ((b_lo in heap_aliases and b_hi not in body_writes and off_tok in local_off5) or + ((b_lo, b_hi) in local_ptrs and _lit_u32(off_tok) == 0)): + return None + load_hit = tuple('s%d' % k for k in range(dr[1], dr[2] + 1)) + elif base == 'buffer_load_dword' and (reads & body_writes): + br = reg_range(ops[2]) if len(ops) >= 3 else None + dtup = tuple('s%d' % k for k in range(br[1], br[2] + 1)) if br and br[0] == 's' and br[2] - br[1] == 3 else None + if dtup not in local_descs or any(tok in body_writes and tok not in dtup for tok in scalar_tokens(ops[2])): + return None + for w in may_write: + local_idx.discard(w) + local_off5.discard(w) + heap_aliases.discard(w) + local_ptrs = {pair for pair in local_ptrs if w not in pair} + local_descs = {tup for tup in local_descs if w not in tup} + if idx_hit: + local_off5.add(ops[0]) + elif mov_idx: + local_idx.add(ops[0]) + elif mov_off5: + local_off5.add(ops[0]) + elif mov_heap: + heap_aliases.add(ops[0]) + elif add_hit: + dr = reg_range(ops[0]) + if not dr or dr[0] != 's' or dr[1] != dr[2] or dr[1] >= 105: + return None + pending_carry = (dr[1], j + 1) + elif load_hit: + local_descs.add(load_hit) + if pending_carry is not None: + return None + return key_bound + + def waterfall_refusal(self, head, close, effects, live_in, jumps, vbounds=None): """Return None when the lane can pick its own key at the head of the waterfall. CMPX selects all remaining lanes with the first lane's key. WREXEC removes those lanes, @@ -3344,7 +3600,7 @@ def waterfall_refusal(self, head, close, effects, live_in, jumps): for j in range(head + 2, close - 1): base, ops, mods = parse(ins[j][3]) base = re.sub(r'_e(32|64)$', '', base) - if base not in ('s_add_u32', 's_mov_b32', 's_and_b32', 's_or_b32', 's_lshl_b32', 's_waitcnt', + if base not in ('s_add_u32', 's_addc_u32', 's_mov_b32', 's_and_b32', 's_or_b32', 's_lshl_b32', 's_waitcnt', 'v_mov_b32', 'v_xor_b32', 'v_add_nc_u32', 's_load_dwordx4', 'buffer_load_dword'): return 'body instruction %s is not proven lane-local' % base if mods and not (base == 'buffer_load_dword' and mods == ['offen']): @@ -3365,6 +3621,8 @@ def waterfall_refusal(self, head, close, effects, live_in, jumps): buffer_descriptors.update(scalar_tokens(ops[2])) reads_before_write.update(reads - defined) defined.update(writes) + if base in ('s_add_u32', 's_addc_u32', 's_and_b32', 's_or_b32', 's_lshl_b32'): + defined.add('scc') body_writes.update(may_write) if (reads & keyed) or base == 'buffer_load_dword': keyed.update(may_write) @@ -3375,7 +3633,11 @@ def waterfall_refusal(self, head, close, effects, live_in, jumps): # The data byte offset can use the key. Loading or modifying the resource descriptor # with the key needs a separate proof that the runtime binds the whole range. if descriptor_inputs & body_writes or buffer_descriptors & numeric_writes: - return 'per-lane descriptor selection requires a proven bound heap range' + bound = self.waterfall_heap_check(head, close, effects, key, key_ops[1], body_writes, numeric_writes, + buffer_descriptors, vbounds) + if bound is None: + return 'per-lane descriptor selection requires a proven bound heap range' + self.waterfall_heap_bounds[ins[head][0]] = bound # The close leaves EXEC and SCC zero. The last physical pass's other scalar # values can differ per lane in this model and must be dead on every successor. # A scalar written from loop-invariant inputs only (no read of the key or of a key-dependent scalar, no @@ -3866,6 +4128,10 @@ def translate(self): self.spill_writes = {} # instruction index of a v_writelane_b32 translated in this pass -> (sym, uniform, proven, mask) self.heap_index = {} # SGPR -> what its word is for a resource-heap s_load (see heap_record) self.heap_index_was = {} # the marks the current instruction's destinations held before it + self.per_lane_index = {} # SGPR -> (expr, max_idx) from bounded waterfall v_readfirstlane_b32 + self.per_lane_index_was = {} + self.resheap_low_add = None + self.resheap_index_temps = [] self.since_join = None # SGPRs proven uniform since the last branch target (None: none reached) self.defined_uniform_s = set(init_entry_uniform) self.bad_sgprs = set() @@ -3906,6 +4172,7 @@ def translate(self): self.scc_def = None if not falls: self.scc_verified = False + self.resheap_low_add = None self.align4_v.clear() self.align4_s.clear() # Before the first branch target or terminator every path has run exactly the instructions above, so @@ -3914,6 +4181,8 @@ def translate(self): self.past_entry = bool(self.blocks) or 0 in targets if off in targets: self.heap_index.clear() # another path into the join may hold a different word + self.per_lane_index.clear() + self.resheap_low_add = None self.align4_v.clear() self.align4_s.clear() pre_uniform = { @@ -4612,8 +4881,11 @@ def one(self, name, asm): if hasattr(self, 'heap_index'): # unit probes build a Stage without the tracking state # Any write ends a register's mark; the lowering below sets the new one, if any. wrote = scalar_destinations(name, asm) - wrote = set(self.heap_index) if 'any' in wrote else wrote & set(self.heap_index) - self.heap_index_was = {r: self.heap_index.pop(r) for r in wrote} + wrote_h = set(self.heap_index) if 'any' in wrote else wrote & set(self.heap_index) + self.heap_index_was = {r: self.heap_index.pop(r) for r in wrote_h} + pl = getattr(self, 'per_lane_index', {}) + wrote_p = set(pl) if 'any' in wrote else wrote & set(pl) + self.per_lane_index_was = {r: pl.pop(r) for r in wrote_p} try: term = self.lower(base, asm, ops, mods) finally: @@ -5162,6 +5434,8 @@ def _lower(self, base, asm, ops, mods): hi = reg_range(ops[1]) if len(ops) == 3 else None if hasattr(self, 'scc_uniform') and self.tracks_uniformity(): self.scc_uniform = False + if self._complete_resheap_carry(base, ops, mods): + return None if hi and hi[0] == 's' and self.pointer_add(base, ops[0], ops[1:], [self.sym.get(hi[1]), None]): return None raise Unsupported(base) @@ -5604,6 +5878,26 @@ def exec_absorbed_source(self, base, srcs): return i return None + def _complete_resheap_carry(self, base, ops, mods): + if getattr(self, 'resheap_low_add', None) is None: + return False + low_d, expect_pc, per_lane_info = self.resheap_low_add + self.resheap_low_add = None + hi_tok = 's%d' % (low_d + 1) + hi_carry_ok = (self.pc == expect_pc and not mods and ( + (base == 's_add_u32' and ops == [hi_tok, '0', 'src_scc']) or + (base == 's_addc_u32' and len(ops) == 3 and ops[0] == hi_tok and ops[2] == '0' + and reg_range(ops[1]) and reg_range(ops[1])[0] == 's' + and self.sym.get(reg_range(ops[1])[1]) == ('const', 0)))) + if not hi_carry_ok: + return False + self.sym[low_d + 1] = ('ptrhi', ('resheap',), per_lane_info) + getattr(self, 'ptr_open_pairs', set()).discard(low_d) + self.__dict__.setdefault('ptr_addc_pcs', set()).add(self.pc) + self.scc_effect = 'emitted' + self.scc_verified = False + return True + def scalar(self, base, ops, mods=()): # Every SALU form in SCA is dst, src (the two templates below use {0} and {1}); a short list would # index past the end and leave `translator crash in <op>: IndexError` in the census instead of a @@ -5614,6 +5908,8 @@ def scalar(self, base, ops, mods=()): raise Unsupported('s_movk_i32 with %d operands, expected 2' % len(ops)) text, scc = SCA[base] dst = reg_range(ops[0]) + if self._complete_resheap_carry(base, ops, mods): + return None if base == 's_add_u32' and self.address_carry_reader is not None and self.pc == self.address_carry_reader: if not dst or dst[0] != 's' or dst[1] != dst[2] or dst[1] > 105: raise Unsupported('s_add_u32 destination %s' % ops[0]) @@ -5725,6 +6021,24 @@ def src_sym(t): getattr(self, 'mask_high', set()).discard(reg) if self.pointer_add(base, dname, srcs, syms): return None + if (base == 's_add_u32' and not mods and len(srcs) == 2 and dst and dst[0] == 's' + and dst[1] == dst[2] and dst[1] < 105 and hasattr(self, 'heap_index')): + for i in (0, 1): + if syms[i] == ('ptr', ('resheap',)): + off_r = reg_range(srcs[1 - i]) + heap_mark = ({**self.heap_index, **self.heap_index_was}.get(off_r[1]) + if off_r and off_r[0] == 's' and off_r[1] == off_r[2] else None) + if heap_mark and heap_mark[0] == 'per_lane': + ptr_r = reg_range(srcs[i]) + if self.sym.get(ptr_r[1] + 1) != ('const', 0): + raise Unsupported('s_load of a resource heap record through a pointer whose high ' + 'word is not a constant zero') + size = next((n for off, n, _name, _asm in getattr(self, 'ins', ()) if off == self.pc), 0) + self.sym[dst[1]] = ('ptr', ('resheap',), heap_mark) + self.__dict__.setdefault('ptr_open_pairs', set()).add(dst[1]) + self.resheap_low_add = (dst[1], self.pc + size, heap_mark) + self.scc_verified = True + return None if dname == 'm0': if scc: raise Unsupported('scc from descriptor data') @@ -5962,10 +6276,22 @@ def mark_heap_index(self, base, d, srcs, syms): r = reg_range(srcs[0]) if base == 's_lshl_b32' and lit[1:] == [5]: word = {**self.heap_index, **self.heap_index_was}.get(r[1]) if r and r[0] == 's' else None + per_lane = {**getattr(self, 'per_lane_index', {}), **getattr(self, 'per_lane_index_was', {})}.get(r[1]) \ + if r and r[0] == 's' else None if syms[0] and syms[0][0] == 'ud' and self.pipe.uds[syms[0][1]][0] == 'rootconst': self.heap_index[d] = self.pipe.uds[syms[0][1]] elif word and word[0] == 'bufword': self.heap_index[d] = ('buffer',) + word[1:] + elif per_lane is not None: + expr, bound = per_lane + self.heap_index[d] = ('per_lane', ('(s%d >> 5)' % d) if d == r[1] else expr, bound) + elif base == 's_mov_b32' and len(srcs) == 1 and r and r[0] == 's' and r[1] == r[2]: + word = {**self.heap_index, **self.heap_index_was}.get(r[1]) + per_lane = {**getattr(self, 'per_lane_index', {}), **getattr(self, 'per_lane_index_was', {})}.get(r[1]) + if word and word[0] == 'per_lane': + self.heap_index[d] = word + elif per_lane is not None: + self.per_lane_index[d] = ('s%d' % d, per_lane[1]) elif base in ('s_add_u32', 's_add_i32', 's_mul_i32') and len(srcs) == 2: for i in (0, 1): k = lit[1 - i] @@ -6502,6 +6828,14 @@ def op_s_load_dwordx4(self, ops, mods, count=4): p = self.sym.get(base[1]) if not p or p[0] != 'ptr': raise Unsupported('s_load through s%d holding %s' % (base[1], p)) + if len(p) > 2 and p[1] == ('resheap',) and isinstance(p[2], tuple) and p[2][0] == 'per_lane': + if (getattr(self, 'kind', None) != 'cs' or count != 4 or into_vcc or imm is not None + or _lit_u32(smem_offset(ops[2])) != 0): + raise Unsupported('s_load of a resource heap record through %s' % (p,)) + if (base[1] in getattr(self, 'ptr_open_pairs', ()) + or self.sym.get(base[2]) != ('ptrhi', ('resheap',), p[2])): + raise Unsupported('s_load through s%d: its high word is not the matching advanced pair' % base[1]) + return self._capture_resheap_desc(dst, p[2][1], p[2][2]) if len(p) > 2 and not isinstance(p[2], int): # The 'added' mark (an add whose offset is not tracked, as in a program with branches): no byte offset. raise Unsupported('s_load through s%d: the pointer was advanced by an untracked offset' % base[1]) @@ -6580,20 +6914,30 @@ def op_s_load_dwordx4(self, ops, mods, count=4): return self.heap_record(dst, base, token, imm, count) raise Unsupported('s_load with a register offset through %s' % (p[1],)) + def _capture_resheap_desc(self, dst, expr, bound): + if not hasattr(self, 'resheap_index_temps'): + self.resheap_index_temps = [] + temp = 'h%d' % len(self.resheap_index_temps) + self.resheap_index_temps.append(temp) + self.emit('%s = %s;' % (temp, expr)) + source = ('resheap', 'per_lane', temp, bound) + for i in range(4): + self.sym[dst[1] + i] = ('desc', source, 0, i) + def heap_record(self, dst, base, token, imm, count): """s_load_dwordx4 D, <resource heap pointer>, R in a compute program, where R is an index shifted left by 5 with no later write of R and no branch target in between: D is the buffer descriptor in the 32-byte heap record that the index names. The index is a root constant word, or a word an s_buffer_load read from an unmodified table buffer at a literal byte offset or at a root constant word times a literal plus a literal - (the marks, see mark_heap_index, end at a branch target). The manifest names the root constant or where the - word is; the dispatch reads the word and the record. Only these exact forms are modelled.""" + (the marks, see mark_heap_index, end at a branch target), or a bounded per-lane index in a proven waterfall + loop. Only these exact forms are modelled.""" what = 's_load of a resource heap record' r = reg_range(token) index = getattr(self, 'heap_index', {}).get(r[1]) if r and r[0] == 's' and r[1] == r[2] else None if index == ('buffer',): raise Unsupported('%s whose index is read from a buffer other than a table buffer at a dispatch-constant ' 'offset' % what) - if not index or index[0] not in ('rootconst', 'buffer'): + if not index or index[0] not in ('rootconst', 'buffer', 'per_lane'): raise Unsupported('%s whose offset is not a root constant shifted left by 5 since the last branch target' % what) if count != 4: raise Unsupported('%s of %d dwords' % (what, count)) @@ -6601,6 +6945,8 @@ def heap_record(self, dst, base, token, imm, count): raise Unsupported('%s with offset:%#x' % (what, imm)) if self.sym.get(base[2]) != ('const', 0): raise Unsupported('%s through a pointer whose high word is not a constant zero' % what) + if index[0] == 'per_lane': + return self._capture_resheap_desc(dst, index[1], index[2]) source = ('resheap',) + index[1:] if index[0] == 'rootconst' else ('resheap', 'word') + index[1:] for i in range(count): self.sym[dst[1] + i] = ('desc', source, 0, i) @@ -6882,6 +7228,8 @@ def buffer_address(self, ops, mods, *, is_formatted=False): key = self.load_descriptor(ops[2], what, stride0_ok=not idxen, raw_conversion_ok=not idxen) else: key = self.descriptor(ops[2]) + if isinstance(key[0], tuple) and key[0][:2] == ('resheap', 'per_lane') and idxen: + raise Unsupported('indexed load through a per-lane resource heap descriptor') buf = self.pipe.resource(key, 'buf') soffset = None if re.fullmatch(r'0x[0-9a-f]+|\d+', ops[3]): @@ -7718,13 +8066,33 @@ def image(self, ops, mods, how): raise Unsupported('image instruction without %s' % ('dim:' if not dims else 'dmask:')) dim = dims[0][4:] dmask = int(dmasks[0][6:], 0) - kinds = {'SQ_RSRC_IMG_1D': 'tex1d', 'SQ_RSRC_IMG_2D': 'tex2d', 'SQ_RSRC_IMG_3D': 'tex3d', 'SQ_RSRC_IMG_2D_ARRAY': 'tex2da'} + kinds = {'SQ_RSRC_IMG_1D': 'tex1d', 'SQ_RSRC_IMG_2D': 'tex2d', 'SQ_RSRC_IMG_3D': 'tex3d', 'SQ_RSRC_IMG_2D_ARRAY': 'tex2da', + 'SQ_RSRC_IMG_CUBE': 'texcube'} if dim not in kinds: raise Unsupported('image dimension %s' % dim) + # A cube sample addresses the face coordinates s and t and then the face id (#2943). The face coordinates + # are sc/|ma| + 1.5 and tc/|ma| + 1.5 with ma the v_cubema value, twice the major coordinate (Mesa + # ac_nir_lower_tex.c prepare_cube_coords; LLVM ConstantFoldAMDGCNCubeIntrinsic), so both lie in [1, 2]. + # The lowering rebuilds a direction for TextureCube (x2w_cube_dir). Loads, derivative and LOD queries, + # packed addresses and compute stages have no TextureCube equivalent here and are refused by name. + cube = dim == 'SQ_RSRC_IMG_CUBE' + if cube: + if how in ('load', 'load_mip'): + raise Unsupported('image dimension SQ_RSRC_IMG_CUBE: Load is not defined on a TextureCube') + if how == 'd': + raise Unsupported('image_sample_d on SQ_RSRC_IMG_CUBE: cube derivatives are not converted') + if how == 'get_lod': + raise Unsupported('image_get_lod on SQ_RSRC_IMG_CUBE') + for flag in ('a16', 'd16'): + if flag in mods: + raise Unsupported('image_sample%s on SQ_RSRC_IMG_CUBE with %s' + % ('' if how == 'sample' else '_' + how, flag)) + if getattr(self, 'kind', None) == 'cs': + raise Unsupported('cube image in a compute program (no texcube SRV binding)') # A 2D array takes the slice as its third address component, where a volume takes z. Sample and # Load on a Texture2DArray take it in the same place, so only the declared type differs. one = dim == 'SQ_RSRC_IMG_1D' - three = dim in ('SQ_RSRC_IMG_3D', 'SQ_RSRC_IMG_2D_ARRAY') + three = dim in ('SQ_RSRC_IMG_3D', 'SQ_RSRC_IMG_2D_ARRAY', 'SQ_RSRC_IMG_CUBE') coords = ops[1] if coords.startswith('['): cs = [c.strip() for c in coords[1:-1].split(',')] @@ -7868,6 +8236,11 @@ def image(self, ops, mods, how): heap = self.heap_sampler(ops[3]) words = None if heap else self.const_words(ops[3]) name = 'image_sample' + ('' if how == 'sample' else '_' + how) + if cube and words and (words[0] >> 28) & 1: + # SQ_IMG_SAMP_WORD0 bit 28 DISABLE_CUBE_WRAP (Mesa src/amd/registers/gfx10-rsrc.json): filtering then + # stops at a face edge, while a D3D12 TextureCube always filters across faces. With the bit clear both + # wrap across faces. A heap or register sampler is not read here, so its bit is not validated. + raise Unsupported('%s on SQ_RSRC_IMG_CUBE with DISABLE_CUBE_WRAP' % name) sjoin = None if dim == 'SQ_RSRC_IMG_2D' and how in ('l', 'lz') and not packed_2d and not heap and words is None: r = reg_range(ops[3]) @@ -7905,6 +8278,9 @@ def image(self, ops, mods, how): uv = 'float2(f16tof32(%s), f16tof32(%s >> 16))' % (packed, packed) elif one: uv = self.f(cs[0]) + elif cube: + self.pipe.uses_cube_dir = True + uv = 'x2w_cube_dir(%s, %s, %s)' % (self.f(cs[0]), self.f(cs[1]), self.f(cs[2])) elif three and how != 'get_lod': uv = 'float3(%s, %s, %s)' % (self.f(cs[0]), self.f(cs[1]), self.f(cs[2])) else: @@ -8943,6 +9319,12 @@ def op_v_readfirstlane_b32(self, ops, mods): if reason: raise Unsupported('compute readfirstlane waterfall: ' + reason) self.set_s(dst[1], self.u(ops[1]), uniform=False) # the selected key varies between lanes + bound = getattr(self, 'waterfall_heap_bounds', {}).get(self.pc) + if bound: + if bound[0] == 'idx': + self.per_lane_index[dst[1]] = ('s%d' % dst[1], bound[1]) + elif bound[0] == 'off5': + self.heap_index[dst[1]] = ('per_lane', '(s%d >> 5)' % dst[1], bound[1]) return if (mods or not dst or dst[0] != 's' or dst[1] != dst[2] or not src or src[0] != 'v' or src[1] != src[2] or not self.proven_uniform_v(src[1])): @@ -9878,6 +10260,37 @@ def op_v_dot8_i32_i4(self, ops, mods): def op_v_dot8_u32_u4(self, ops, mods): return self.dot8_int('v_dot8_u32_u4', False, ops, mods) + def dot2_int(self, name, signed, ops, mods): + """VOP3P 2-halfword integer dot product with 32-bit accumulate and optional saturating clamp.""" + if len(ops) != 4: + raise Unsupported('%s with %d operands, expected 4' % (name, len(ops))) + if any(m != 'clamp' for m in mods): + raise Unsupported('%s with unsupported modifiers %s' % (name, mods)) + dst = reg_range(ops[0]) + if not dst or dst[0] != 'v' or dst[1] != dst[2] or dst[1] > 255: + raise Unsupported('%s destination %s' % (name, ops[0])) + args = [] + for tok in ops[1:4]: + if (tok.startswith('|') or tok.endswith('|') or tok.startswith(('abs(', 'neg(')) + or (tok.startswith('-') and not re.fullmatch(r'-\d+', tok))): + raise Unsupported('%s source modifier %s' % (name, tok)) + sr = reg_range(tok) + if sr and (sr[1] != sr[2] or (sr[0] == 'v' and sr[1] > 255) or (sr[0] == 's' and sr[1] > 105)): + raise Unsupported('%s source %s' % (name, tok)) + args.append(self.u(tok)) + pipe = getattr(self, 'pipe', None) + if pipe is not None and isinstance(getattr(pipe, 'uses_dot2', None), set): + pipe.uses_dot2.add(name) + helper = 'dot2_i32_i16' if signed else 'dot2_u32_u16' + sat = 'true' if 'clamp' in mods else 'false' + self.set_v(dst[1], '%s(%s, %s, %s, %s)' % (helper, args[0], args[1], args[2], sat)) + + def op_v_dot2_i32_i16(self, ops, mods): + return self.dot2_int('v_dot2_i32_i16', True, ops, mods) + + def op_v_dot2_u32_u16(self, ops, mods): + return self.dot2_int('v_dot2_u32_u16', False, ops, mods) + def i64_words(self, tok, signed=False, literal=False): """(low, high) uint expressions of a 64-bit integer source: a VGPR/SGPR pair, an inline int or a 32-bit hex literal when `literal` is set (zero-extended, sign-extended when the operation is signed).""" @@ -10478,6 +10891,8 @@ def declarations(self): lines.append(' uint %s;' % ', '.join('sp%d_%d = 0' % k for k in sorted(self.spill_slots))) if getattr(self, 'uniform_load_temps', None): lines.append(' uint %s;' % ', '.join('%s = 0' % n for n in sorted(self.uniform_load_temps))) + if getattr(self, 'resheap_index_temps', None): + lines.append(' uint %s;' % ', '.join('%s = 0' % n for n in self.resheap_index_temps)) lines.append(' uint vcc = 0, exec = 1, m0 = 0, a = 0, w = 0; bool scc = false; float4 t = 0;') if getattr(self, 'mesh_wave_loads', {}): lines.append(' bool wave_any = false;') @@ -11465,8 +11880,10 @@ class Pipeline: vertex_kind = 'vs' uses_pack16_rne = False uses_bvh = False + uses_cube_dir = False uses_gather_2d_lod = False uses_store_d16_x = False + uses_dot2 = () uses_sad = () uses_dot8 = () uses_lerp_u8 = False @@ -11507,10 +11924,13 @@ def _init_pixel_context(self, root_blob, sampler_heap=None, rtv_formats=(), ps_h self.srv_formats = dict(srv_formats) if isinstance(srv_formats, dict) else dict(enumerate(srv_formats)) self.sampler_heap = os.environ.get('X2W_SAMPLER_HEAP') == '1' if sampler_heap is None else sampler_heap self.uses_sampler_heap = False + self.resheap_count = 0 self.uses_pack16_rne = False self.uses_bvh = False + self.uses_cube_dir = False self.uses_gather_2d_lod = False self.uses_store_d16_x = False + self.uses_dot2 = set() self.uses_sad = set() self.uses_dot8 = set() self.uses_lerp_u8 = False @@ -11583,6 +12003,13 @@ def ud(self, source): return self.uds.index(source) def resource(self, key, kind): + if isinstance(key[0], tuple) and key[0][:2] == ('resheap', 'per_lane'): + if kind != 'buf': + raise Unsupported('per-lane resource heap descriptor used as %s' % kind) + _tag, _sub, expr, bound = key[0] + if self.resheap_count <= bound: + self.resheap_count = bound + 1 + return 'rh[NonUniformResourceIndex(%s)]' % expr if key in self.stored_images(): raise Unsupported('resource %s is both read and stored to' % (key,)) r = self.resources.setdefault(key, dict(index=len(self.resources), kind=kind)) @@ -11594,6 +12021,8 @@ def stored_images(self): return self.uavs or {} def uav(self, key, kind): + if isinstance(key[0], tuple) and key[0][:2] == ('resheap', 'per_lane'): + raise Unsupported('store through %s' % (key[0],)) if key in self.resources: raise Unsupported('resource %s is both read and stored to' % (key,)) if self.uavs is None: @@ -11775,7 +12204,9 @@ def common(self): if self.uses_bvh: out.extend(BVH_HELPERS) for key, r in sorted(self.resources.items(), key=lambda kv: kv[1]['index']): - out.append('%s r%d : register(t%d);' % ({'buf': 'ByteAddressBuffer', 'bvh': 'ByteAddressBuffer', 'tex1d': 'Texture1D<float4>', 'tex2d': 'Texture2D<float4>', 'tex2da': 'Texture2DArray<float4>', 'tex3d': 'Texture3D<float4>'}[r['kind']], r['index'], r['index'])) + out.append('%s r%d : register(t%d);' % ({'buf': 'ByteAddressBuffer', 'bvh': 'ByteAddressBuffer', 'tex1d': 'Texture1D<float4>', 'tex2d': 'Texture2D<float4>', 'tex2da': 'Texture2DArray<float4>', 'tex3d': 'Texture3D<float4>', 'texcube': 'TextureCube<float4>'}[r['kind']], r['index'], r['index'])) + if getattr(self, 'resheap_count', 0): + out.append('ByteAddressBuffer rh[%d] : register(t0, space%d);' % (self.resheap_count, RESHEAP_RANGE_SPACE)) for key, r in sorted(self.stored_images().items(), key=lambda kv: kv[1]['index']): out.append('%s %s%d : register(u%d);' % ({'tex1d': 'RWTexture1D<float4>', 'tex2d': 'RWTexture2D<float4>', 'tex2da': 'RWTexture2DArray<float4>', 'tex3d': 'RWTexture3D<float4>', 'raw': 'RWByteAddressBuffer'}[r['kind']], 'u' if r['kind'] == 'raw' else 'w', r['index'], r['index'])) for key, i in self.samplers.items(): @@ -11784,6 +12215,27 @@ def common(self): out.append('SamplerState qh[%d] : register(s0, space%d);' % (SAMPLER_HEAP_SIZE, SAMPLER_HEAP_SPACE)) out.append('uint x2w_sampler_entry(uint offset) { return (offset & 15u) != 0 || offset >= %du ? %du : offset >> 4; }' % (16 * SAMPLER_HEAP_FALLBACK, SAMPLER_HEAP_FALLBACK)) + if self.uses_cube_dir: + # A direction for TextureCube from a gfx10 cube address (#2943): s and t are the face coordinates + # sc/|ma| + 1.5 and tc/|ma| + 1.5 and f the face id, with the per-face sc and tc of v_cubesc and + # v_cubetc (cube() above). A major component of +-1 reproduces u = sc/|major| and v = tc/|major|. + # A cube-array id (8 * layer + face) keeps only its face, so layer 0 is sampled; faces 6 and 7, a + # negative or NaN id become faces 5 and 0. Coordinates outside [1, 2] are assumed to clamp to face edges + # (untested outside [1, 2]). + out.extend(( + 'float3 x2w_cube_dir(float s, float t, float f) {', + ' float u = clamp(2.0 * (s - 1.5), -1.0, 1.0);', + ' float v = clamp(2.0 * (t - 1.5), -1.0, 1.0);', + ' int k = (f >= 0.0 && f < 2147483648.0) ? ((int)f & 7) : 0;', + ' k = min(k, 5);', + ' if (k == 0) return float3(1.0, -v, -u);', + ' if (k == 1) return float3(-1.0, -v, u);', + ' if (k == 2) return float3(u, 1.0, v);', + ' if (k == 3) return float3(u, -1.0, -v);', + ' if (k == 4) return float3(u, -v, 1.0);', + ' return float3(-u, -v, -1.0);', + '}', + )) if self.uses_pack16_rne: # IEEE binary32 to binary16 round-to-nearest-even (quieting NaN while preserving its sign, # matching RDNA 2 hardware on binary32 inputs), plus exact UNORM16 ratio-to-half conversion @@ -11920,6 +12372,28 @@ def common(self): ' }', '}', )) + if 'v_dot2_u32_u16' in self.uses_dot2: + # RDNA 2 ISA V_DOT2_U32_U16: two unsigned 16-bit products + S2, exact uint32 clamp. + out.append( + 'uint dot2_u32_u16(uint a, uint b, uint c, bool sat) {' + ' uint p0 = (a & 0xffffu) * (b & 0xffffu);' + ' uint p1 = (a >> 16u) * (b >> 16u);' + ' uint r0 = c + p0; uint carry = (r0 < c) ? 1u : 0u;' + ' uint r1 = r0 + p1; carry += (r1 < r0) ? 1u : 0u;' + ' return (sat && carry != 0u) ? 0xffffffffu : r1; }') + if 'v_dot2_i32_i16' in self.uses_dot2: + # RDNA 2 ISA V_DOT2_I32_I16: two signed 16-bit products + int(S2), exact int32 clamp via 64-bit acc. + out.append( + 'uint dot2_i32_i16(uint a, uint b, uint c, bool sat) {' + ' int p0 = (asint((a & 0xffffu) << 16u) >> 16) * (asint((b & 0xffffu) << 16u) >> 16);' + ' int p1 = (asint(a) >> 16) * (asint(b) >> 16);' + ' uint lo = c; int hi = (asint(c) < 0) ? -1 : 0;' + ' uint t0 = lo + asuint(p0); hi += ((p0 < 0) ? -1 : 0) + ((t0 < lo) ? 1 : 0); lo = t0;' + ' uint t1 = lo + asuint(p1); hi += ((p1 < 0) ? -1 : 0) + ((t1 < lo) ? 1 : 0); lo = t1;' + ' if (sat) {' + ' if (hi > 0 || (hi == 0 && (lo & 0x80000000u) != 0u)) return 0x7fffffffu;' + ' if (hi < -1 || (hi == -1 && (lo & 0x80000000u) == 0u)) return 0x80000000u; }' + ' return lo; }') if self.uses_bitreplicate: # RDNA 2 ISA S_BITREPLICATE_B64_B32: replicate each of the low 16 bits twice into 32 bits. out.append( @@ -12180,6 +12654,8 @@ def manifest(self): raise Unsupported('stored image through %s' % (source,)) lines.append('uav %d %s table %d %d' % (r['index'], r['kind'], source[1] if len(source) > 1 else 0, off or 0)) lines += self.sampler_lines() + if self.resheap_count: + lines.append('resheap %d %d' % (self.resheap_count, RESHEAP_RANGE_SPACE)) if self.uses_sampler_heap: lines.append('smpheap %d %d fallback %d' % (SAMPLER_HEAP_SIZE, SAMPLER_HEAP_SPACE, SAMPLER_HEAP_FALLBACK)) lines.append('params %d' % (max(self.params) + 1 if self.params else 0)) @@ -12219,8 +12695,10 @@ def __init__(self, cs_code, root_blob, rsrc2, group, sampler_heap=None, refusals self.vs_fetch, self.packed_position_vgpr, self.rtv_formats = None, None, () self.sampler_heap = os.environ.get('X2W_SAMPLER_HEAP') == '1' if sampler_heap is None else sampler_heap self.uses_sampler_heap = False + self.resheap_count = 0 self.uses_gather_2d_lod = False self.uses_store_d16_x = False + self.uses_dot2 = set() self.uses_bvh = False self.uses_sad = set() self.uses_dot8 = set() @@ -12295,6 +12773,8 @@ def manifest(self): else: lines.append('uav %d %s float %s channels 4' % (r['index'], r['kind'], where)) lines += self.sampler_lines() + if self.resheap_count: + lines.append('resheap %d %d' % (self.resheap_count, RESHEAP_RANGE_SPACE)) if self.uses_sampler_heap: lines.append('smpheap %d %d fallback %d' % (SAMPLER_HEAP_SIZE, SAMPLER_HEAP_SPACE, SAMPLER_HEAP_FALLBACK)) return '\n'.join(lines) + '\n' diff --git a/tools/startup/run.ps1 b/tools/startup/run.ps1 index 5018d4fbf2..153eec009c 100644 --- a/tools/startup/run.ps1 +++ b/tools/startup/run.ps1 @@ -19,7 +19,9 @@ param( [string]$BuildDir = "out/build/release", [int]$MemoryGiB = 14, [int]$ContinueAsserts = 0, # main-image int3s to log and step over (title soft asserts) + [int]$AssertSites = 0, # distinct main-image int3 sites whose every hit is stepped over [string]$InputScript = "", # X2W_INPUT_SCRIPT, e.g. "4@70" = A at 70 s + [string]$MapDrive = "", # e.g. "G=D:\package": rewrite opens on a console letter [string]$StoragePath = "", # X2W_STORAGE_PATH: root of the console drive the title sees (it appends x2w-gamesave) [string]$ShaderCache = "out/startup/shader_cache", [switch]$Render, # draw through translated pipelines @@ -102,12 +104,19 @@ if ($watchShaders) { } $traceArgs = @() if ($TraceCalls) { $traceArgs = @("--trace-calls", "1") } +$mapArgs = @() +if ($MapDrive) { $mapArgs = @("--map-drive", $MapDrive) } $captureArgs = @() if ($CaptureEvery -ne 0) { $captureArgs = @("--capture-every", "$CaptureEvery") } try { - & $python -B (Join-Path $PSScriptRoot "debug_launch.py") $Exe $DataDir $LogDir --timeout $Seconds --memory-gib $MemoryGiB ` - --trace-files 1 --continue-asserts $ContinueAsserts @traceArgs @captureArgs *> "$LogDir.out" - $debuggerExit = $LASTEXITCODE + # Windows PowerShell 5.1 wraps redirected native stderr as an error record. Keep that + # from aborting the launcher before it can report the debugger's exit code. + & { + $ErrorActionPreference = "Continue" + & $python -B (Join-Path $PSScriptRoot "debug_launch.py") $Exe $DataDir $LogDir --timeout $Seconds --memory-gib $MemoryGiB ` + --trace-files 1 --continue-asserts $ContinueAsserts --assert-sites $AssertSites @mapArgs @traceArgs @captureArgs + $script:debuggerExit = $LASTEXITCODE + } *> "$LogDir.out" } finally { # taskkill /T needs a live parent PID to reach the watcher's workers. if ($translator -and -not $translator.HasExited) { diff --git a/tools/startup/run.sh b/tools/startup/run.sh index c3b7b9a1d9..14f174c949 100755 --- a/tools/startup/run.sh +++ b/tools/startup/run.sh @@ -27,7 +27,7 @@ set -uo pipefail usage() { echo "usage: run.sh --exe EXE --data DIR --log DIR [--seconds 120] [--build-dir out/build/release]" >&2 - echo " [--memory-gib 14] [--continue-asserts 0] [--input-script S] [--storage DIR]" >&2 + echo " [--memory-gib 14] [--continue-asserts 0] [--assert-sites 0] [--input-script S] [--storage DIR]" >&2 echo " [--shader-cache out/startup/shader_cache] [--console 0|1] [--render] [--fake-user]" >&2 echo " [--gpu-mirror] [--host-cpu] [--translate] [--startup-below-40] [--trace-calls]" >&2 echo " [--hide-title-window] [--capture-every S] [--fresh-shader-cache]" >&2 @@ -36,18 +36,19 @@ usage() { repo=$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd) here="$repo/tools/startup" -exe="" data="" log="" seconds=120 build_dir=out/build/release memory_gib=14 continue_asserts=0 +exe="" data="" log="" seconds=120 build_dir=out/build/release memory_gib=14 continue_asserts=0 assert_sites=0 input_script="" storage="" shader_cache=out/startup/shader_cache console=1 capture_every=0 render="" fake_user="" gpu_mirror="" host_cpu="" translate="" below_40="" trace_calls="" hide_title="" fresh_cache="" while [ $# -gt 0 ]; do case $1 in - --exe|--data|--log|--seconds|--build-dir|--memory-gib|--continue-asserts|--input-script|--storage|\ + --exe|--data|--log|--seconds|--build-dir|--memory-gib|--continue-asserts|--assert-sites|--input-script|--storage|\ --shader-cache|--console|--capture-every) [ $# -ge 2 ] || usage case $1 in --exe) exe=$2 ;; --data) data=$2 ;; --log) log=$2 ;; --seconds) seconds=$2 ;; --build-dir) build_dir=$2 ;; --memory-gib) memory_gib=$2 ;; --continue-asserts) continue_asserts=$2 ;; # main-image int3s to log and step over + --assert-sites) assert_sites=$2 ;; # distinct int3 sites whose every hit is stepped over --input-script) input_script=$2 ;; # X2W_INPUT_SCRIPT, e.g. "4@70" = A at 70 s --storage) storage=$2 ;; # X2W_STORAGE_PATH: persistent local storage root --shader-cache) shader_cache=$2 ;; --console) console=$2 ;; @@ -229,7 +230,7 @@ capture_args=() [ "$capture_every" = 0 ] || capture_args=(--capture-every "$capture_every") "$wine" "$X2W_WIN_PYTHON" -B "$(win_path "$here/debug_launch.py")" "$(win_path "$exe")" "$(win_path "$data")" \ "$(win_path "$log")" --timeout "$seconds" --memory-gib "$memory_gib" --trace-files 1 \ - --continue-asserts "$continue_asserts" "${trace_args[@]}" "${console_args[@]}" "${capture_args[@]}" > "$log_host.out" 2>&1 + --continue-asserts "$continue_asserts" --assert-sites "$assert_sites" "${trace_args[@]}" "${console_args[@]}" "${capture_args[@]}" > "$log_host.out" 2>&1 debugger_exit=$? if [ -n "$translate" ] && [ -n "$render" ] && [ -z "$revision_warned" ]; then check_cache_revision; fi head -n 5 "$log_host.out" diff --git a/tools/startup/stage_package.ps1 b/tools/startup/stage_package.ps1 index 422b6e7db5..e9105bea6c 100644 --- a/tools/startup/stage_package.ps1 +++ b/tools/startup/stage_package.ps1 @@ -13,7 +13,7 @@ param( ) $ErrorActionPreference = "Stop" -$package = (Resolve-Path -LiteralPath $PackageDir).Path.TrimEnd('\') +$package = (Resolve-Path -LiteralPath $PackageDir).Path $source = if ([IO.Path]::IsPathRooted($Exe)) { (Resolve-Path -LiteralPath $Exe).Path } else { @@ -23,7 +23,7 @@ $sourceDir = Split-Path -Parent $source $provider = $null $drive = $null $run = $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath( - $RunDir, [ref]$provider, [ref]$drive).TrimEnd('\') + $RunDir, [ref]$provider, [ref]$drive) if ($provider.Name -ne 'FileSystem') { throw "RunDir must be a filesystem path." } if (-not (Test-Path -LiteralPath $source -PathType Leaf) -or [IO.Path]::GetExtension($source) -ine '.exe') { throw "Exe must name an executable file." @@ -34,6 +34,52 @@ function Test-PathInside([string]$Path, [string]$Parent) { return $Path.StartsWith($prefix, [StringComparison]::OrdinalIgnoreCase) } +# Resolve drive aliases and junctions before comparing package and staging paths. +# A destination may not exist yet, so resolve its nearest existing ancestor and +# append the remaining names without creating anything. +if (-not ("X2wStagingFinalPath" -as [type])) { + Add-Type -TypeDefinition @' +using System; +using System.ComponentModel; +using System.Runtime.InteropServices; +using System.Text; +using Microsoft.Win32.SafeHandles; + +public static class X2wStagingFinalPath { + [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)] + private static extern SafeFileHandle CreateFileW(string name, uint access, uint share, IntPtr security, + uint creation, uint flags, IntPtr template); + [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)] + private static extern uint GetFinalPathNameByHandleW(SafeFileHandle handle, StringBuilder path, + uint length, uint flags); + public static string Resolve(string name) { + using (var handle = CreateFileW(name, 0, 7, IntPtr.Zero, 3, 0x02000000, IntPtr.Zero)) { + if (handle.IsInvalid) throw new Win32Exception(Marshal.GetLastWin32Error()); + var path = new StringBuilder(32768); + uint length = GetFinalPathNameByHandleW(handle, path, (uint)path.Capacity, 0); + if (length == 0) throw new Win32Exception(Marshal.GetLastWin32Error()); + if (length >= path.Capacity) throw new InvalidOperationException("Resolved path is too long."); + return path.ToString(); + } + } +} +'@ +} +function Get-FinalStagingPath([string]$Path) { + $missing = [System.Collections.Generic.List[string]]::new() + $existing = $Path + while (-not (Test-Path -LiteralPath $existing)) { + $parent = Split-Path -Parent $existing + if (-not $parent -or $parent -eq $existing) { throw "Cannot resolve staging path." } + $missing.Insert(0, (Split-Path -Leaf $existing)) + $existing = $parent + } + $nativePath = $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($existing) + $final = [X2wStagingFinalPath]::Resolve($nativePath) + foreach ($part in $missing) { $final = [IO.Path]::Combine($final, $part) } + return $final +} + if (-not (Test-PathInside $source $package)) { throw "Exe must be inside PackageDir." } @@ -49,6 +95,14 @@ for ($ancestor = $run; $ancestor; $ancestor = Split-Path -Parent $ancestor) { throw "RunDir must not pass through a reparse point." } } +$packageFinal = Get-FinalStagingPath $package +$runFinal = Get-FinalStagingPath $run +$sourceFinal = Get-FinalStagingPath $source +if (-not (Test-PathInside $sourceFinal $packageFinal)) { throw "Exe must be inside PackageDir." } +if ($runFinal.Equals($packageFinal, [StringComparison]::OrdinalIgnoreCase) -or + (Test-PathInside $runFinal $packageFinal) -or (Test-PathInside $packageFinal $runFinal)) { + throw "RunDir must be separate from PackageDir and its parent directories." +} if ((Test-Path -LiteralPath $run) -and (-not (Test-Path -LiteralPath $run -PathType Container) -or @(Get-ChildItem -LiteralPath $run -Force).Count)) { diff --git a/tools/startup/triage_run.py b/tools/startup/triage_run.py index 5342725a7e..d516728e8d 100644 --- a/tools/startup/triage_run.py +++ b/tools/startup/triage_run.py @@ -113,6 +113,14 @@ (re.compile(r"native compute \+0x[0-9a-fA-F]+: unbound numeric SGPR\b"), "unbound numeric SGPR"), (re.compile(r"(?:unknown gfx1013 instruction format|truncated or misaligned gfx1013 instruction|" r"reserved FLAT segment) at byte \d+\Z"), "undecodable word"), + # The fixed reasons of format_compute_runtime_manifest (src/direct_compute_cache.cpp); kind names are enum names. + (re.compile(r"unsupported startup runtime manifest bindings: (" + r"(?:SRV|UAV) kind [a-z0-9_]{1,32}(?: [a-z0-9-]{1,20})?(?: array)?|" + r"(?:SRV|UAV) registers not contiguous|group size has a zero dimension|" + r"root constants above root parameter 15|view above root parameter 15|" + r"more than (?:8 root constants in one root parameter|32 user data words|32 SRVs|8 UAVs)|" + r"resource heap view|sampler heap|comparison sampler|" + r"stride words from a view that is not one raw vector SRV)\Z"), r"runtime manifest: \1"), (re.compile(r"graphics request key mismatch\b"), "graphics request key mismatch"), (re.compile(r"compute request key mismatch\b"), "compute request key mismatch"), (re.compile(r"stale pixel input description\b"), "stale pixel input description"), diff --git a/tools/texture_blocks.py b/tools/texture_blocks.py index 1d6a851409..c23890badf 100644 --- a/tools/texture_blocks.py +++ b/tools/texture_blocks.py @@ -33,7 +33,7 @@ def block_extent(self) -> tuple[int, int, int]: "BC1_UNORM": Format("BC1_UNORM", 71, 4, 4, 1, 8, 2), "BC2_UNORM": Format("BC2_UNORM", 74, 4, 4, 1, 16, 2), "BC3_UNORM": Format("BC3_UNORM", 77, 4, 4, 1, 16, 2), - "BC4_UNORM": Format("BC4_UNORM", 79, 4, 4, 1, 8, 2), + "BC4_UNORM": Format("BC4_UNORM", 80, 4, 4, 1, 8, 2), "BC5_UNORM": Format("BC5_UNORM", 83, 4, 4, 1, 16, 2), "BC6H_UF16": Format("BC6H_UF16", 95, 4, 4, 1, 16, 2), "BC7_UNORM": Format("BC7_UNORM", 98, 4, 4, 1, 16, 2), diff --git a/tools/ttpf_batch_export.py b/tools/ttpf_batch_export.py index 77b565ddbe..ef6226d69c 100644 --- a/tools/ttpf_batch_export.py +++ b/tools/ttpf_batch_export.py @@ -285,6 +285,9 @@ def batch_export(pool_path: Path, out_dir: Path, raise ValueError(f"--manifest path collides with --out: {resolved_manifest}") if resolved_manifest.resolve() in out_dir.resolve().parents: raise ValueError(f"--manifest path cannot be an ancestor of --out: {resolved_manifest}") + for option, source_path in (("history", history_path), ("calibration", calibration_path)): + if source_path is not None and _same_path(resolved_manifest, source_path): + raise ValueError(f"--manifest path collides with --{option}: {resolved_manifest}") if calibration_path is not None and (allow_provisional or history_path is not None): raise ValueError("--calibration cannot be combined with --allow-provisional or --history") @@ -349,7 +352,6 @@ def fitted_decoder(pool): finally: pool.close() - out_dir.mkdir(parents=True, exist_ok=True) manifest_path = resolved_manifest if indices is None: @@ -359,6 +361,13 @@ def fitted_decoder(pool): else: target_indices = [i for i in indices if 0 <= i < total_textures] + # The manifest is published after the workers finish. Its path must not name + # a requested DDS, including one preserved after a failed or skipped export. + for index in target_indices: + if _same_path(manifest_path, out_dir / f"tex_{index:05d}.dds"): + raise ValueError(f"--manifest path collides with DDS output: {manifest_path}") + out_dir.mkdir(parents=True, exist_ok=True) + manifest_entries: list[dict] = [] stats = {"strict": 0, "provisional": 0, "failed": 0, "skipped": 0} if fitted_decoder is not None: