diff --git a/docs/d3d12_vulkan.md b/docs/d3d12_vulkan.md index aa7913060a..bcd92779ec 100644 --- a/docs/d3d12_vulkan.md +++ b/docs/d3d12_vulkan.md @@ -484,6 +484,13 @@ What is implemented (all of it testable without the game): `E_INVALIDARG` for such a render target, since no other format can view its image. Without that format, render targets are refused as before; depth-stencil and UAV creation are unsupported for this format. + - A `CopyTextureRegion` of the depth plane between two depth formats with the same depth encoding but not the + same `VkFormat` (`D32_SFLOAT_S8_UINT` and `D32_SFLOAT`, `D16_UNORM_S8_UINT` and `D16_UNORM`, + `D24_UNORM_S8_UINT` and `X8_D24_UNORM_PACK32`) goes image → transfer scratch → image too, depth aspect on both + sides (`vulkan_replay.h`, `depth_format_pair`; `replay_copy_offset_test`). `vkCmdCopyImage` requires + depth/stencil formats to match exactly (`VUID-vkCmdCopyImage-srcImage-01548`), and an NVIDIA driver (RTX 4070 + Laptop, 621.40) handed the `D32_SFLOAT_S8_UINT` → `D32_SFLOAT` pair wrote past the end of the `D32_SFLOAT` + image: the world-start `WRITE_INVALID` device loss, with the fault at the first byte after the image. - reserved resources and `GetResourceTiling` (section 4.2); - query heaps for occlusion, timestamps and pipeline statistics, and `GetTimestampFrequency` on the queue (section 4.6); @@ -2878,7 +2885,8 @@ The console has two list topologies Vulkan lacks: rectangle list (`IASetPrimitiv the driver's), as on D3D12. - GPU-writable slot-133 images on a default heap bind memory when replay, presentation or creation of a shader view first needs their Vulkan image. D3D12 placement and logical attachment views can precede that bind. - A CPU-fillable, typed BC texture can initially sample an immutable zero image of the same format, extent, + A CPU-fillable, typed BC texture (filled by host copies or the staged upload) can initially sample + an immutable zero image of the same format, extent, layer count and mip count. A CPU upload or explicit GPU command gives the placement private backing and republishes its existing descriptor keys. The cache holds at most 256 MiB. `LEONIDA_PLACED_IMAGE_DEFER=0` restores eager binding. @@ -2901,11 +2909,15 @@ The console has two list topologies Vulkan lacks: rectangle list (`IASetPrimitiv - Sampled title images can use device-local memory even when Vulkan host image copies require a host-visible memory type. The runtime queries the same image with and without host-transfer usage. When only the latter permits plain device-local backing, it detiles the complete image into a reusable - staging buffer and transfers all its mips and layers together. Linear slot-133 placements retain host - copies. On a device without `VK_EXT_host_image_copy` every colour title image, linear placements too, takes the - staged upload: the refresh before a submission has no other way to fill one, and without it the title's textures - stayed zero (a flat green intro movie). An allocation failure retries the original host-copyable image. - `LEONIDA_TITLE_IMAGE_STAGING=0` + staging buffer and transfers all its mips and layers together. Linear slot-133 placements use host + copies when the image supports them. + A CPU-visible, single-sampled colour title image that needs no format conversion uses the staged upload + if the device, format or image usage lacks host-transfer support, or if the host-transfer image has no + compatible memory type. The runtime logs that last case once per Vulkan format. A GTX 1050 Ti on + NVIDIA 582.66 reported it for R8_UNORM, R8G8B8A8_UNORM and BC1_RGBA_UNORM_BLOCK. + [GTX 1050 Ti test results](https://github.com/ubiquitarianism/leonida/pull/1894#issuecomment-7174515492) + When both placements are available, an allocation failure on the staged path retries the original + host-copyable image. `LEONIDA_TITLE_IMAGE_STAGING=0` restores the original placement policy. With `LEONIDA_MEM_PROBE`, each title image class logs its Vulkan memory type mask, mask without host transfer, and selected type. - `WriteToSubresource`/`ReadFromSubresource` (implemented in `d3d12_vulkan_device.cpp`) complete before they diff --git a/docs/design.md b/docs/design.md index 7888e24f72..1889e30860 100644 --- a/docs/design.md +++ b/docs/design.md @@ -291,7 +291,7 @@ How the generated SPIR-V expects the runtime to work: | DPP on a VOPC compare | A VOPC compare whose src0 field is a DPP marker (250 for DPP16, 233/234 for DPP8) takes src0 through the DPP lane selection of the row above and writes VCC: a lane's bit is `compare(src0 of the selected lane, its own src1)`, with 0 for src0 when the selected lane is out of its row or inactive (`bound_ctrl` 1, or DPP8 with `fi` 0). The second word has the layout of a VOP2's DPP word. `llvm-mc` has no decoding for it on gfx10 (LLVM 21.1.8 rejects the first word for `gfx1013`; LLVM defines the form from GFX11 on), so `tools/shader_disasm.py` prints it: it decodes the pair with the first word turned into `v_max_f32` into `v0`, which takes the same second word, and gives the line the compare's name, a `vcc_lo` destination and the real encoding back (`with_vopc_dpp`); `tools/rdna2_decode.py` decodes it directly. **Only the forms where every lane writes its bit are translated**: `row_mask` and `bank_mask` 0xF and either `bound_ctrl` 1 or DPP8. Any other form, and `v_cmpx`, is refused (`DPP compare with lanes that keep their mask bit`), because what a lane DPP leaves unwritten does to its VCC bit is not measured. Found in 3 of the 2,684 pipeline-library compute programs of 1.0.2.1: 4 `v_cmp_gt_f32` each, with `quad_perm:[1,0,3,2]`, `quad_perm:[2,3,0,1]`, `row_ror:8` (all `bound_ctrl:1`, masks 0xF) and `dpp8:[4,5,6,7,0,1,2,3]`, beside `v_min/max_f32_dpp` and `v_mov_b32_dpp` on the same lanes. **Not measured on hardware**: the rule follows from the encoding, from LLVM's GFX11 definition of the same form and from the VOP2 DPP rules measured in the row above; the sweep that measured those (`tools/crosslane_fuzz.py --dpp-sweep --oracle hw`) does not cover compares. Lane values are checked in `tests/semantic/test_dpp_compare.py` (the SPIR-V interpreter) and on a GPU with `runtime/test/shaders/cs_dpp_cmp.asm`. | | EXEC | A per-invocation `active` flag. VALU writes and exports are masked by it, scalar ops aren't, and `v_cmpx`, saveexec and EXEC writes update it. Measured on native gfx1100 (8 threads): a `v_mov_b32` under `EXEC=0x0F` leaves the other lanes untouched, `EXEC=0` writes nothing, a store writes only active lanes and `v_cmpx_gt_u32` narrows EXEC (4 of 4 cases); note that AMD clang 20 rejects `v_add_co_u32`, `v_sub_co_u32`, `v_add_co_ci_u32` and `v_mad_u64_u32` for `gfx1100`, `gfx1101` and `gfx1102`, so this toolchain could not reproduce the RX 7600 result below, which leaves open whether those parts support the opcodes and says only that they could not be assembled here. **A pixel is written when its lane was on in EXEC at the last `exp ... vm` the path executed (if it executed one) and at the last export to the color target; a path with no export at all goes by EXEC at the end.** The `vm` half is the RDNA2 ISA reference guide's rule (30-November-2020, §11.1 and §11.2.1: EXEC at the export is the valid mask and the final one sent is used; an `exp null ... vm` carries only the mask). The color half is measured: an export sends data only for the lanes that are on, a later export to the same target replaces the earlier one for the whole wave, and a lane with no data from the last one is not written even when a later `exp null done vm` marks it valid. So `exp mrt0 done` (no `vm`) with every lane on, followed by an EXEC write, still writes every pixel, and EXEC off at that export and back on afterwards writes none. **Measured on RDNA2** (AMD Radeon iGPU, gfx1036, driver 26.10.1) with the pixel-shader oracle of #3061 (`ps_oracle.py`), hand-written ISA as the pixel shader of a real draw (wave64 stage): 18 programs that cut EXEC to half of the target before, between or after `exp mrt0` (with and without `vm` and `done`) and `exp null done vm`; all 18 fit the rule, 6 of them differed from the translator, which until 2026-11-23 discarded by EXEC at the end on a path without `vm` and kept the older export's value (or the output's initial value) for a lane that was off at the last color export. The latches (`%vm_mask`, `%col_mask_mrtN`) are only emitted where a path can write EXEC after a `vm` or color export; everywhere else EXEC at the end is the same mask and the SPIR-V is unchanged. With several color targets a pixel stays when any target got an export from its lane (Vulkan cannot skip one attachment per pixel; not measured, the oracle's pipeline has one target); `mrtz` is not part of the color mask (not measured). **Measuring exports needs `s_waitcnt expcnt(0)` after each one**: an export is asynchronous, and without the wait the hardware takes the data and the EXEC of a later moment (`v_mov v9, A; exp mrt0 v9 done vm; v_mov v9, B` shows B, and an EXEC write right after the export decides which pixels are written, which looks like "EXEC at the end decides"); 64 `s_nop 15` have the same effect as the wait. Checked on the CPU by `tests/semantic/test_export_valid_mask.py` and on the GPU by `runtime/test/shaders/ps_exp_color_mask.asm` (RTX 5080 and the Radeon). VALU scalar lane-mask destinations (`v_cmp_*`, `v_add_co_u32`, `v_add_co_ci_u32`, `v_sub_co_u32`, `v_sub_co_ci_u32`, `v_subrev_co_u32`, `v_subrev_co_ci_u32`, `v_mad_u64_u32`, `v_mad_i64_i32`) write 0 for lanes off in EXEC (`SDST[lane] = EXEC[lane] ? bit : 0`, AMD RDNA2 ISA). Until 2026-11-22 the six `*_co_*` ops and `v_mad_u64_u32`/`v_mad_i64_i32` did not AND the carry/sign bit with `active`, so inactive lanes leaked 1 bits into `VCC`/SGPR masks (`s_bcnt1`, `s_cbranch_vccz`, `v_cndmask_b32`). Checked on the CPU by `tests/semantic/test_carry_exec_mask.py` (wave32, wave64, and `--wave64-emulate` structure), and **hardware-verified on an AMD RX 7600 (gfx1102)** with `v_add_co_u32` and `v_add_co_ci_u32` carrying on every active lane: VCC reads `0xffffffff` with full EXEC, `0x0000ffff` for the mask `0x0000ffff` and `0xaaaaaaaa` for `0xaaaaaaaa` in wave32, `vcc_lo = 0x0000ffff` with `vcc_hi = 0x0000000f` for the same partial mask in wave64, and `0` when EXEC is 0 even with VCC preloaded to all ones; with one carrying lane under mask `0x0000ffff` VCC is `0x00000001`, and `v_sub_co_u32`/`v_subrev_co_u32` with a borrow under that mask give `0x0000ffff` too. The `*_co_ci_` forms, `v_mad_u64_u32` and `v_mad_i64_i32` share the same path but were not measured separately; it is also GPU-verified on native RDNA2 (gfx1036, AMD Radeon Graphics) with partial EXEC masks (inactive lanes write 0 in sdst for `v_add_co_u32` and `v_mad_u64_u32`). In a shader that writes EXEC, a run of two or more lane-local VALU instructions (no cross-lane read, no lane-mask, SCC, carry or EXEC write) sits inside one `if (active)` and writes its VGPRs directly, instead of an `OpSelect(active, new, old)` per write: the same result, but the driver predicates the run with its own EXEC instead of keeping both values live. On an RX 5700 XT (RADV) a pixel shader with 8 divergent if/else regions of `v_fma`/`v_mul`/`v_add`/`v_min`/`v_max` went from 0.85 ms to 0.69 ms (the same program as native SPIR-V: 0.65 ms). Not under `--wave64-emulate`. Checked by `tests/semantic/test_active_runs.py`. | | `s_*_saveexec_b32/b64`, `s_andn1/andn2_wrexec_b32/b64` | RDNA2 ISA SOP1. saveexec: `D = EXEC; EXEC = f(S0, EXEC); SCC = (EXEC != 0)`. wrexec: `EXEC = f(S0, EXEC); D = EXEC`. `f` is one of `and`, `or`, `xor`, `andn1` (`~S0 & EXEC`), `andn2` (`S0 & ~EXEC`), `orn1` (`~S0 \| EXEC`), `orn2` (`S0 \| ~EXEC`), `nand`, `nor`, `xnor`, the table in `Gen.EXEC_LOGIC`. The definitions match `tools/cf_ref.py` `_SAVEEXEC`, the FUZZ-8 model. Each invocation holds its own lane's bit (0 or ~0), so `f` is the bitwise op on that bit. A lane EXEC had off becomes active when `f` gives 1 for it (`nand`, `nor`, `orn1`, `orn2`, `xnor`, ...), as on hardware, and SCC is the wave vote. Until 2026-11-22 only `and`/`or`/`andn2_saveexec` and `andn2_wrexec` were translated. CPU-checked by `tests/semantic/test_saveexec_variants.py` (all ten saveexec kinds in wave32 and wave64, both wrexec kinds, partial EXEC and S0, an empty result, every lane against `cf_ref._SAVEEXEC`) and by `tools/cf_diff.py` (300 programs × wave32/64 still pass). Hardware-verified on native RDNA2 (`gfx1036`, Windows 11, driver `32.0.21045.29003`, wave32 & wave64, 0 mismatches): all 10 `saveexec` kinds and both `wrexec` kinds (`andn1`/`andn2`) match bit-for-bit on non-symmetric masks (`src0 = 0x0F0F0F0F`, `exec = 0x33333333` in wave32; `0x0F0F0F0F_00FF00FF` / `0x33333333_55555555` in wave64), zero-result `SCC = 0`, wave64 upper-32-bit-only `new_exec = 0x00000001_00000000` setting `SCC = 1`, and `sdst == src0` register aliasing (`s4, s4` and `s[4:5], s[4:5]`) reading original `src0` before writing old `EXEC` to `sdst`. **Not GPU-verified** for the seven new kinds. Measured on native gfx1100 (single 8-lane workgroup, 36 programs): all ten `saveexec` kinds and both `wrexec` forms follow `f` for three `S0`/`EXEC` pairs, including lanes `EXEC` had off being switched back on (`nand` with `S0=0x03`, `EXEC=0x0F` leaves `0xFFFFFFFC`, activating lanes 4-7), `D` holding the old `EXEC` for `saveexec` and the new one for `wrexec`, and `SCC` the `EXEC != 0` vote. | -| Control flow | Reducible graphs use structured branches and natural loops. Irreducible graphs use the dispatch-loop form, which can also be forced with `--dispatch-loop` for comparisons. The control-flow unit test checks 18,228 generated graphs. Irreducible graphs use node splitting (`cfg_structure.split_irreducible`, up to `min(2*N, N+64)` blocks) and fall back to the dispatch-loop form when capped; it can also be forced with `--dispatch-loop` for comparisons. `cfg_structure.structure`, `cfg_structure.run`, and `rdna2spirv.assemble`'s structured emitter are iterative and hoist each guarded member's dominated tail continuation out of its enclosing guard (exact by strict dominance: no block outside the guard's subtree can target the continuation), keeping `OpSelectionMerge` nesting O(1) on sequential diamond/loop chains instead of nesting O(N) deep and hitting Python's recursion limit on multi-thousand-block shaders (e.g. 2,000 sequential diamonds nest to depth 2 instead of 2,000). The control-flow unit test (`tests/test_cfg_structure.py`) checks 20,000 generated graphs plus 2,000-diamond, 1,200-loop, and 1,500-early-exit chains. AMD A/B checks compare the two forms for selected pixel shaders with defined test inputs. For shaders that never export colour, the comparison checks pixel coverage. **Nesting is bounded (SHADER-299):** a tree deeper than `MAX_STRUCTURED_DEPTH` (16) is emitted in the dispatch-loop form instead, since `spirv-val` time grows roughly with the cube of the measured nesting depth. **Nesting is bounded (SHADER-299, SHADER-427):** a tree deeper than `MAX_STRUCTURED_DEPTH` (64; `--max-structured-depth N`, 0 = no bound) is emitted in the dispatch-loop form instead, since `spirv-val` time grows roughly with the cube of the measured nesting depth. Before #1904, over the 1.0.2.1 corpus (26,503 modules, `spirv-val` 2026.4): the deepest block of a module is nested 118 constructs deep, 12,963 modules are structured (median 15) and 6,000 of those are deeper than 16; an estimated 85% of the corpus's `spirv-val` time is in modules nested 20 or deeper. Median `spirv-val` time for the same module in each form: depth 20 181 -> 129 ms (1.4x), 30 507 -> 371 (1.4x), 50 1,712 -> 738 (2.3x), 64 2,692 -> 1,163 (2.3x), 77 5,122 -> 1,130 (4.5x), and the deepest (118) 13,683 -> 1,352 ms (10.1x). Depth 5-12 shows no gain (at depth 6 the flat form is slightly slower), which is why the bound first sat at 16. Since #1904 (`cfg_structure` hoists tails) the deepest tree in the corpus is 29: of 12,944 structured modules, 1,031 are deeper than 16 (747 CS, 284 PS), 57 deeper than 20, 24 deeper than 24. For those 1,031 the flat form saves only 12% of `spirv-val` time (1,235 -> 1,091 s summed, slowest module 8.3 -> 5.9 s), while on an RTX 5070 Ti (NVIDIA 621.24) it compiles slower: the 284 pixel shaders 1.67x (827 -> 1,382 s summed, two rounds), four compute modules at depth 19-24 2.0x (297 -> 591 s, 1.6-2.7x each), so the bound now sits above the corpus (SHADER-427). Both forms pass `spirv-val` on a 200-shader slice (200/200 each), and `gen.nesting` records the tree depth. AMD's Windows driver adds a reason to keep the structured form (SHADER-995): on a Radeon gfx1036 iGPU (32.0.21042.62) the dispatch-loop module of `XboxBvhBuilder.dll`'s `LeafRehydration` (tree depth 18, a 581-case switch) takes 34 minutes to create (XXDESIGN), where its structured module is created in 2.9 s; ten other programs of that DLL compile in the dispatch-loop form there in 0.4-40 s, 2.5-5x their structured time ([embedded_shaders.md](embedded_shaders.md), section 7). | +| Control flow | Reducible graphs use structured branches and natural loops. Irreducible graphs use the dispatch-loop form, which can also be forced with `--dispatch-loop` for comparisons. The control-flow unit test checks 18,228 generated graphs. Irreducible graphs use node splitting (`cfg_structure.split_irreducible`, up to `min(2*N, N+64)` blocks) and fall back to the dispatch-loop form when capped; it can also be forced with `--dispatch-loop` for comparisons. `cfg_structure.structure`, `cfg_structure.run`, and `rdna2spirv.assemble`'s structured emitter are iterative and hoist each guarded member's dominated tail continuation out of its enclosing guard (exact by strict dominance: no block outside the guard's subtree can target the continuation), keeping `OpSelectionMerge` nesting O(1) on sequential diamond/loop chains instead of nesting O(N) deep and hitting Python's recursion limit on multi-thousand-block shaders (e.g. 2,000 sequential diamonds nest to depth 2 instead of 2,000). The control-flow unit test (`tests/test_cfg_structure.py`) checks 20,000 generated graphs plus 2,000-diamond, 1,200-loop, and 1,500-early-exit chains. `capped_tree()` also runs `cfg_structure.unwrap_known_pc_guards` (shared with `wave64_emulate_opt`) to unwrap tautological `("guard", g, ...)` nodes whenever abstract interpretation proves `%pc == g` on all incoming paths (e.g. post-dominating merge blocks after diamonds and loops); this keeps `ms_wave_info_s3`'s `s_barrier` in uniform top-level control flow (fixing an AMD Windows LLPC `0xC0000005` pipeline-creation crash on AMD Ryzen 5 7600 RDNA2 iGPU driver `24.10.24`, `4096/4096` exact on AMD RDNA2 and RTX 4070 SUPER) and avoids false `needs_barrier_rounds` triggers (`SHADER-STRUCTURED-PC-UNWRAP`). AMD A/B checks compare the two forms for selected pixel shaders with defined test inputs. For shaders that never export colour, the comparison checks pixel coverage. **Nesting is bounded (SHADER-299):** a tree deeper than `MAX_STRUCTURED_DEPTH` (16) is emitted in the dispatch-loop form instead, since `spirv-val` time grows roughly with the cube of the measured nesting depth. **Nesting is bounded (SHADER-299, SHADER-427):** a tree deeper than `MAX_STRUCTURED_DEPTH` (64; `--max-structured-depth N`, 0 = no bound) is emitted in the dispatch-loop form instead, since `spirv-val` time grows roughly with the cube of the measured nesting depth. Before #1904, over the 1.0.2.1 corpus (26,503 modules, `spirv-val` 2026.4): the deepest block of a module is nested 118 constructs deep, 12,963 modules are structured (median 15) and 6,000 of those are deeper than 16; an estimated 85% of the corpus's `spirv-val` time is in modules nested 20 or deeper. Median `spirv-val` time for the same module in each form: depth 20 181 -> 129 ms (1.4x), 30 507 -> 371 (1.4x), 50 1,712 -> 738 (2.3x), 64 2,692 -> 1,163 (2.3x), 77 5,122 -> 1,130 (4.5x), and the deepest (118) 13,683 -> 1,352 ms (10.1x). Depth 5-12 shows no gain (at depth 6 the flat form is slightly slower), which is why the bound first sat at 16. Since #1904 (`cfg_structure` hoists tails) the deepest tree in the corpus is 29: of 12,944 structured modules, 1,031 are deeper than 16 (747 CS, 284 PS), 57 deeper than 20, 24 deeper than 24. For those 1,031 the flat form saves only 12% of `spirv-val` time (1,235 -> 1,091 s summed, slowest module 8.3 -> 5.9 s), while on an RTX 5070 Ti (NVIDIA 621.24) it compiles slower: the 284 pixel shaders 1.67x (827 -> 1,382 s summed, two rounds), four compute modules at depth 19-24 2.0x (297 -> 591 s, 1.6-2.7x each), so the bound now sits above the corpus (SHADER-427). Both forms pass `spirv-val` on a 200-shader slice (200/200 each), and `gen.nesting` records the tree depth. AMD's Windows driver adds a reason to keep the structured form (SHADER-995): on a Radeon gfx1036 iGPU (32.0.21042.62) the dispatch-loop module of `XboxBvhBuilder.dll`'s `LeafRehydration` (tree depth 18, a 581-case switch) takes 34 minutes to create (XXDESIGN), where its structured module is created in 2.9 s; ten other programs of that DLL compile in the dispatch-loop form there in 0.4-40 s, 2.5-5x their structured time ([embedded_shaders.md](embedded_shaders.md), section 7). | | Loop guard | Each loop counts header visits per invocation and exits through its structured merge at `--loop-limit N` (default 65536, zero disables). Counters reset on entry, including nested EXEC retries and atomic loops. A PC-dispatch visit counts a dispatch iteration. Natural exits within the budget preserve their outputs. Five-star-recomp (b12a952) reported a story-load timeout when the shader input made its exit condition unreachable. | | User data | **Push constants, 144 bytes:** dwords 0–31 = initial s0–s31 (the user SGPRs the console driver loads from the root signature: descriptor-table pointers, constants and so on), dwords 32–33 = the 64-bit **heap base**, dwords 34–35 = the **code base**: the Xbox VA where the runtime uploaded this shader's whole FSSM blob. `--mesh-compute` modules add dwords 36–37, the output buffer address (152 bytes; see "Mesh shaders as compute"). `--pc-tail-ubo` keeps only dwords 0–31 here (128 bytes) and moves the rest to a uniform block (see "Push-constant tail as a uniform block"). The runtime has to reproduce the console driver's root-signature-to-user-SGPR mapping; that comes from the exe or driver behaviour. **Mesh shaders** read their root SGPRs through the graphics root window: s16..s31 come from dwords 8..23 (where a VS, PS or GS reads s8..s23), s8..s15 are 0, s0..s7 dwords 0..7; the index records `"root_window": {"sgpr": 16, "dword": 8}` (D3D-448-GRAPHICS, `docs/d3d12_vulkan.md` 3.5). Checked by `tests/semantic/test_ms_root_window.py` (MeshEXT and `--mesh-compute`, CPU interpreter) and `d3d12_mesh_test` (RX 9070 XT). | | Direct resource heap | In the matched Prop/Tree BatchCull compute signature the two explicit tables and scalar constant occupy s4–s6. Bind the resource heap's uint32 arena-relative byte address at s7 (push-constant byte 28). The program supplies a zero high word and scales the resource index by 32 bytes. Other stages and signatures consume different SGPRs. See [descriptor heaps and the bindless model](d3d12_vulkan.md#34-descriptor-heaps-and-the-bindless-model) for the evidence and graphics examples. | diff --git a/docs/gamedata.md b/docs/gamedata.md index a05fd1ea56..bcaa55f4d3 100644 --- a/docs/gamedata.md +++ b/docs/gamedata.md @@ -1416,7 +1416,8 @@ bounded by the largest field. The generic conversion follows the parser's own co - `x/y/z/w` is a vector tuple. - `content=` is the array body. `short_array`, `float_array` and `float16_array` give number lists; `vector2_array`, `vec3v_array`, `matrix33` and `matrix34` give tuples. -- `type="Class"` is a polymorphic object `{"$type": ...}`, and `type="NULL"` is `None`. +- `type="Class"` is a polymorphic object `{"$type": ...}`, including an empty object with no fields or text. + Explicit scalar/vector/array/reference conventions and nonempty text keep their values; `type="NULL"` is `None`. - `ref=` is `{"$ref": ...}`. - All-`Item` children are a list, or a dict when every one carries `key=`. A repeated tag is a list. A text-only element is its text. Any other attribute is kept as `"@name"`. @@ -1440,11 +1441,13 @@ On the 1.0.2.1 carve of `common.rpf` the run takes about 5 s, with 0 conversion | arrays | 13,449 | | lists | 13,465 | | keyed maps | 526 | -| polymorphic objects | 6,490 (317 `type` classes over 6,903 typed elements) | +| polymorphic objects | 6,663 (317 `type` classes over 6,903 typed elements) | | `NULL` pointers | 278 | | references | 924 | | elements with extra attributes | 5,262 | +The object count includes 173 empty instances across 13 documents (54 types). + The 7 roots missing from the 118 occur only in documents that are not well-formed. Counts only: the JSON that `--out` writes is the game's data and stays local. `tests/test_gamedata_reader.py` checks every convention, both dispatch tables, that streaming equals a whole-tree conversion, and the CLI, on synthetic XML. diff --git a/make_game.py b/make_game.py index 3eb0899458..b8c90a11f9 100644 --- a/make_game.py +++ b/make_game.py @@ -61,6 +61,7 @@ import tempfile import threading import time +import traceback from concurrent.futures import ThreadPoolExecutor if __name__ == "__main__" and sys.version_info < (3, 12): # before code an older Python can't run @@ -2912,6 +2913,20 @@ def fn_pipelines(): "pipelines": fn_pipelines, } + reported: set[str] = set() + + def report_unexpected(name: str, exc: BaseException) -> None: + """A stage that fails through fail() already printed a diagnostic; one that raises outright did + not. Report the stage and the exception once per stage, so a failure is never silent.""" + if isinstance(exc, RuntimeError) and str(exc).startswith("stage exited with "): + return # fail() called sys.exit; its diagnostic already went out + key = f"{name}: {exc!r}" + if key in reported: + return + reported.add(key) + print(f"\nERROR: stage '{name}' failed with an unexpected exception: {exc!r}", file=sys.stderr) + traceback.print_exc(file=sys.stderr) + if not overlap: order = [s for s in ("shaders", "assets", "runtime", "pipelines") if s in stages] if not order: @@ -2921,7 +2936,8 @@ def fn_pipelines(): try: _invoke_stage(name, builders[name]) progress.complete(name) - except Exception: + except Exception as exc: + report_unexpected(name, exc) sys.exit(1) return @@ -2950,7 +2966,8 @@ def wait(name: str) -> bool: futures[name].result() progress.complete(name) return True - except Exception: + except Exception as exc: + report_unexpected(name, exc) failed = True return False @@ -2968,7 +2985,8 @@ def wait(name: str) -> bool: try: fut.result() progress.complete(name) - except Exception: + except Exception as exc: + report_unexpected(name, exc) failed = True ex.shutdown(wait=True) except KeyboardInterrupt: diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt index c1d0e7cb53..66af48c7da 100644 --- a/runtime/CMakeLists.txt +++ b/runtime/CMakeLists.txt @@ -3478,7 +3478,7 @@ if(TARGET Vulkan::Headers) target_compile_definitions(d3d12_unmapped_vsharp_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX LEONIDA_VULKAN_DEVICE) target_compile_options(d3d12_unmapped_vsharp_test PRIVATE /W4 /permissive- /utf-8) add_test(NAME d3d12_unmapped_vsharp COMMAND d3d12_unmapped_vsharp_test) - set_tests_properties(d3d12_unmapped_vsharp PROPERTIES SKIP_RETURN_CODE 77 ENVIRONMENT "LEONIDA_CONSOLE_FIX_US=0") + set_tests_properties(d3d12_unmapped_vsharp PROPERTIES SKIP_RETURN_CODE 77) add_executable(d3d12_indirect_zero_test test/d3d12_indirect_zero_test.cpp) target_link_libraries(d3d12_indirect_zero_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) target_compile_definitions(d3d12_indirect_zero_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) diff --git a/runtime/README.md b/runtime/README.md index 070fa28add..b89a82a711 100644 --- a/runtime/README.md +++ b/runtime/README.md @@ -365,7 +365,7 @@ ones marked *diagnostic* only add log lines or exist to compare a run with and w | `LEONIDA_WINDOW` | unset | `WxH` resizes the title's window when the presenter attaches to it. | | `LEONIDA_PRESENT_DUMP` | unset | *Diagnostic.* `DIR` or `DIR,N` writes every Nth presented frame (60 by default) as a PNG into `DIR` (`src/present_dump.h`). The files are pictures of the title: keep them out of commits, issues and pull requests. | | `LEONIDA_LOCAL_SPEECH` | unset | `1` forwards the title's speech-synthesis calls to the host's installed `xgameruntime.dll` where there is one. Unset, and wherever that library is missing, the silent voice answers. No profile sets it. | -| `LEONIDA_CONSOLE_FIX_US` | `4000` | Microseconds one submission may spend fixing the changed slots of a console descriptor heap's copy. Past it, each further changed slot is written as a null descriptor and queued for `LEONIDA_CONSOLE_RETRY_US`, so a shader reads it as empty until its turn comes. `0` removes the limit. | +| `LEONIDA_CONSOLE_FIX_US` | `0` | Microseconds one submission may spend fixing the changed slots of a console descriptor heap's copy; `0` sets no limit. Past it, each further changed slot is written as a null descriptor and queued for `LEONIDA_CONSOLE_RETRY_US`, so a shader reads it as empty until its turn comes: a limit changes results, and can hang the GPU. | | `LEONIDA_CONSOLE_RETRY_US` | `500` | Microseconds one submission may spend retrying, round robin, the console heap slots not settled yet (a T# whose texture does not exist yet, or one deferred by `LEONIDA_CONSOLE_FIX_US`). `0` retries all of them at every submission. | | `LEONIDA_SHADOW_ALIAS_MS` | `0` | The shortest time, in milliseconds, between two copies of the title-memory pages that XMem maps at two addresses (no write guard can watch them) into the slot-133 shadows and title windows. `0` copies them at every submission; a larger value lets a GPU read of them be up to that many milliseconds behind the title's writes. | | `LEONIDA_REFRESH_PER_FRAME` | `0` | Trades correctness for speed. `1`: the slot-133 shadows, title windows and geometry copies are brought up to date only by the first submission after each present, not by every submission; `2`: the console descriptor heaps too. A GPU read of them can then be a frame behind the title's writes (wrong pixels). `0` refreshes all of them at every submission. | diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp index 45f899b2f3..ba794ff5f4 100644 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ b/runtime/shims/d3d12_vulkan_device.cpp @@ -3291,15 +3291,16 @@ struct DeviceState { // The slots on [offset, offset + bytes) of a heap copy's mirror, just brought up to date: each that differs from // what its arena slot was made from is written there and fixed up. - // Past LEONIDA_CONSOLE_FIX_US of fixing in one submission (4000 by default, 0: no limit), a changed slot is written - // as a null descriptor and left to retry_console_slots: after the story load the title rewrote up to 3.7 MiB of - // its heap at once and one submission spent 28 s fixing it (speed-8). A shader reads such a slot as empty until - // its turn comes. + // LEONIDA_CONSOLE_FIX_US limits the fixing in one submission (0, the default: no limit). Past it a changed slot is + // written as a null descriptor and left to retry_console_slots: after the story load the title rewrote up to + // 3.7 MiB of its heap at once and one submission spent 28 s fixing it (speed-8). A shader reads such a slot as + // empty until its turn comes, so a limit changes results: at the first world frame lib_cs_01144 read the size it + // divides by from a nulled buffer slot and its loops never ended, which lost the device. void fix_console_slots(ConsoleHeap& heap, std::size_t offset, std::size_t bytes) { static const std::uint64_t budget_us = [] { char text[16] = {}; const DWORD n = GetEnvironmentVariableA("LEONIDA_CONSOLE_FIX_US", text, sizeof(text)); - return n > 0 && n < sizeof(text) ? std::strtoull(text, nullptr, 10) : 4000ull; + return n > 0 && n < sizeof(text) ? std::strtoull(text, nullptr, 10) : 0ull; }(); const std::size_t end = std::min(offset + bytes, std::size_t(heap.bytes)); if (!heap.resource_heap) { @@ -6189,8 +6190,8 @@ class Resource final // Textures the CPU reads and writes (WriteToSubresource/ReadFromSubresource) copy on the host when they can. // (A D24 texture stored as D32 goes through the staged copy: the host copy would not convert. Nor would it // repack a 96-bit texture's 12-byte texels.) - host_transfer_ = cpu_visible() && samples == 1 && !format.d24_as_float && !format.rgb96 && - device_.host_transfer_format(format.format); + const bool cpu_copyable = cpu_visible() && samples == 1 && !format.d24_as_float && !format.rgb96; + host_transfer_ = cpu_copyable && device_.host_transfer_format(format.format); rgb96_ = format.rgb96; if (host_transfer_) info.usage |= VK_IMAGE_USAGE_HOST_TRANSFER_BIT_EXT; HRESULT support = device_.check_image_support(info); @@ -6217,6 +6218,17 @@ class Resource final const char* value = std::getenv("LEONIDA_TITLE_IMAGE_STAGING"); return !value || std::strcmp(value, "0"); }(); + const bool can_stage_title = stage_title && allow_staged_title && cpu_copyable && + origin != TitleImageOrigin::ordinary && format.aspects == VK_IMAGE_ASPECT_COLOR_BIT; + VkMemoryRequirements with_host{}; + const bool have_host_requirements = can_stage_title && host_transfer_ && device_.memory_requirements(info, with_host); + // A driver can accept HOST_TRANSFER for the image yet give it no bindable memory type. + if (have_host_requirements && !with_host.memoryTypeBits) { + info.usage &= ~VK_IMAGE_USAGE_HOST_TRANSFER_BIT_EXT; + host_transfer_ = false; + if (HRESULT hr = device_.check_image_support(info); FAILED(hr)) return hr; + log_once("title image has no host-transfer memory type, using staging for Vulkan format", int(info.format)); + } // Keep placed movie planes with a known linear CPU layout on the host-copy path, where there is one. // Map on a staged placement still returns the title's pages and participates in the refresh. std::uint32_t xg_layout = 0; @@ -6228,47 +6240,53 @@ class Resource final const char* value = std::getenv("LEONIDA_PLACED_IMAGE_DEFER"); return !value || std::strcmp(value, "0"); }(); + // A device without host copies has no other way to fill a title image: a refresh before a submission may not + // use a staged copy through the queue (host_copy_now). Its linear movie planes are staged too. + const bool no_host_copy = !device_.copy_memory_to_image && cpu_copyable; // Private BC copies start with the exact same zero blocks as the shared image. The host // transition and clear complete before a private view is published, including during command prepare. - if (defer_placed && origin == TitleImageOrigin::placed && host_transfer_ && device_.bindless && + // Without host copies the staged upload fills the private image, and the first shader submission clears what + // it has not filled. + const bool can_fill = host_transfer_ || (no_host_copy && stage_title && allow_staged_title && + device_.image_requirements); + if (defer_placed && origin == TitleImageOrigin::placed && can_fill && device_.bindless && desc_.Flags == D3D12_RESOURCE_FLAG_NONE && desc_.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE2D && desc_.SampleDesc.Count == 1 && asked_castable.empty() && !format.typeless && leonida::block_format(format.format, format.aspects).block > 1) { - VkMemoryRequirements footprint{}; - if (device_.memory_requirements(info, footprint)) - shared_zero_ = device_.zero_sampled_image(desc_, format, footprint.size); + if (have_host_requirements || device_.memory_requirements(info, with_host)) + shared_zero_ = device_.zero_sampled_image(desc_, format, with_host.size); } std::uint32_t plain_bits = 0; - // A device without host copies has no other way to fill a title image: a refresh before a submission may not - // use a staged copy through the queue (host_copy_now). Its linear movie planes are staged too. - const bool no_host_copy = !device_.copy_memory_to_image && cpu_visible() && samples == 1 && - !format.d24_as_float && !format.rgb96; - if (stage_title && !shared_zero_ && allow_staged_title && origin != TitleImageOrigin::ordinary && - (no_host_copy || (!linear_placement && host_transfer_)) && format.aspects == VK_IMAGE_ASPECT_COLOR_BIT && - device_.image_requirements) { + const bool can_stage = can_stage_title && (!shared_zero_ || no_host_copy); + // A refresh must queue an upload when this image cannot take host copies, including linear movie planes. + const bool needs_staging = can_stage && !host_transfer_; + if (needs_staging) { + staged_title_ = true; + plain_bits = UINT32_MAX; // the image already lacks HOST_TRANSFER; any compatible memory type will do + } else if (can_stage && !linear_placement && device_.image_requirements) { for (std::uint32_t i = 0; i < device_.memory.memoryTypeCount; ++i) { const auto flags = device_.memory.memoryTypes[i].propertyFlags; if ((flags & (VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT | VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT)) == VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT) plain_bits |= 1u << i; } - if (no_host_copy) plain_bits = UINT32_MAX; // nothing to compare with: any memory type will do - VkMemoryRequirements with{}, without{}; + VkMemoryRequirements without{}; auto staged = info; staged.usage &= ~VK_IMAGE_USAGE_HOST_TRANSFER_BIT_EXT; - if (plain_bits && (no_host_copy || (device_.memory_requirements(info, with) && - !(with.memoryTypeBits & plain_bits))) && + if (plain_bits && have_host_requirements && !(with_host.memoryTypeBits & plain_bits) && device_.memory_requirements(staged, without) && (without.memoryTypeBits & plain_bits)) { staged_title_ = true; host_transfer_ = false; info.usage = staged.usage; } } + const bool can_retry_host = staged_title_ && !needs_staging; auto retry_host = [&] { if (image_) vk.vkDestroyImage(device_.info.device, image_, nullptr); if (memory_) vk.vkFreeMemory(device_.info.device, memory_, nullptr); image_ = VK_NULL_HANDLE; memory_ = VK_NULL_HANDLE; staged_title_ = false; + shared_zero_ = VK_NULL_HANDLE; log_once("no room for a staged title image; retrying host-copyable backing, format", int(info.format)); return create_texture(format, asked_castable, origin, false); }; @@ -6287,7 +6305,7 @@ class Resource final } return E_OUTOFMEMORY; }; - if (HRESULT hr = create_image(); FAILED(hr)) return staged_title_ ? retry_host() : hr; + if (HRESULT hr = create_image(); FAILED(hr)) return can_retry_host ? retry_host() : hr; VkMemoryRequirements requirements{}; std::uint32_t type = UINT32_MAX; const bool stream = origin == TitleImageOrigin::streamed || origin == TitleImageOrigin::pending_stream; @@ -6324,7 +6342,7 @@ class Resource final // A title image (placed or streamed) takes the title image pool or an allocation of its own, of the memory // types its placement allows; the shared texture blocks below are for the layer's ordinary textures. if (!bind_texture_memory(stream, allowed, requirements, type)) { - if (staged_title_) return retry_host(); + if (can_retry_host) return retry_host(); std::fprintf(stderr, "[rt] d3d12: texture memory unavailable: %llu bytes, alignment %llu, type bits 0x%x (vk " "format %d %ux%u)\n", @@ -6494,6 +6512,7 @@ class Resource final } if (shared_zero_) { if (host_transfer_ && !host_initialize()) return false; + if (!host_transfer_) device_.context->note_shader_image(id()); // zeros until something fills it publish_streamed_texture(); } return true; @@ -7213,10 +7232,11 @@ class Resource final std::shared_ptr heap_range_; }; -// One immutable, host-zeroed BC image per exact view shape. It has the right sampled format, extent, +// One immutable, zeroed BC image per exact view shape (zeroed on the host, or by the first shader submission). It has +// the right sampled format, extent, // mip count and zero-block decoding even before the title first supplies data or copies into the placement. VkImage DeviceState::zero_sampled_image(const D3D12_RESOURCE_DESC& d, const Format& format, VkDeviceSize bytes) { - if (!host_transfer_format(format.format)) return VK_NULL_HANDLE; + if (copy_memory_to_image && !host_transfer_format(format.format)) return VK_NULL_HANDLE; const ZeroShape key{d.Format, d.Width, d.Height, d.DepthOrArraySize, d.MipLevels}; std::lock_guard lock(zero_image_mutex); if (auto it = zero_images.find(key); it != zero_images.end()) return it->second ? it->second->image() : VK_NULL_HANDLE; @@ -7225,12 +7245,13 @@ VkImage DeviceState::zero_sampled_image(const D3D12_RESOURCE_DESC& d, const Form if (used >= limit || bytes > limit - used) return VK_NULL_HANDLE; const D3D12_HEAP_PROPERTIES heap{D3D12_HEAP_TYPE_CUSTOM, D3D12_CPU_PAGE_PROPERTY_WRITE_BACK, D3D12_MEMORY_POOL_L0, 1, 1}; auto* zero = new Resource(*this, d, heap, D3D12_HEAP_FLAG_NONE); - if (FAILED(zero->create_texture(format)) || !zero->host_initialized_image() || + if (FAILED(zero->create_texture(format)) || (copy_memory_to_image && !zero->host_initialized_image()) || zero->image_backing_bytes() > limit - used) { zero->Release(); zero_images.emplace(key, nullptr); return VK_NULL_HANDLE; } + if (!zero->host_initialized_image()) context->note_shader_image(zero->id()); // cleared before a shader reads it zero_images.emplace(key, zero); zero_image_bytes.fetch_add(zero->image_backing_bytes(), std::memory_order_relaxed); return zero->image(); diff --git a/runtime/src/vulkan_replay.h b/runtime/src/vulkan_replay.h index 725cd34870..359fabff07 100644 --- a/runtime/src/vulkan_replay.h +++ b/runtime/src/vulkan_replay.h @@ -548,6 +548,27 @@ inline bool a8_mixed_backing(VkFormat a, VkFormat b) { #endif } +// Two depth formats whose depth aspect has the same encoding but which are not the same VkFormat: D32_SFLOAT and +// D32_SFLOAT_S8_UINT, D16_UNORM and D16_UNORM_S8_UINT, X8_D24_UNORM_PACK32 and D24_UNORM_S8_UINT. D3D12 copies the +// depth plane between them; Vulkan's vkCmdCopyImage requires depth/stencil formats to match exactly +// (VUID-vkCmdCopyImage-srcImage-01548), and an NVIDIA driver handed D32_SFLOAT_S8_UINT -> D32_SFLOAT writes past the +// end of the D32 image (the world-start WRITE_INVALID). The replay stages these through a buffer, where the depth +// aspect has the same texel layout on both sides. +inline bool depth_format_pair(VkFormat a, VkFormat b) { + const auto encoding = [](VkFormat format) -> int { + switch (format) { + case VK_FORMAT_D32_SFLOAT: + case VK_FORMAT_D32_SFLOAT_S8_UINT: return 32; + case VK_FORMAT_X8_D24_UNORM_PACK32: + case VK_FORMAT_D24_UNORM_S8_UINT: return 24; + case VK_FORMAT_D16_UNORM: + case VK_FORMAT_D16_UNORM_S8_UINT: return 16; + default: return 0; + } + }; + return a != b && encoding(a) && encoding(a) == encoding(b); +} + inline bool depth_colour_pair(const ResourceBinding& a, const ResourceBinding& b) { const auto family = [](VkFormat format) -> int { switch (format) { @@ -3629,7 +3650,8 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun } if (result == ReplayResult::success && !p.image_copies.empty() && (p.image_copies[0].srcSubresource.aspectMask != p.image_copies[0].dstSubresource.aspectMask || - a8_mixed_backing(p.source.format, p.binding.format))) { + a8_mixed_backing(p.source.format, p.binding.format) || + depth_format_pair(p.source.format, p.binding.format))) { // Depth <-> colour: vkCmdCopyImage cannot mix aspects, so each region goes image -> scratch -> image, // tightly packed. Depth aspects want 4-byte buffer offsets; 16 covers every texel size here. The two // backings of A8_UNORM take the same route: one byte per texel on both sides, but Vulkan does not diff --git a/runtime/test/d3d12_existing_heap_test.cpp b/runtime/test/d3d12_existing_heap_test.cpp index 3d65fc7409..2c567f6a80 100644 --- a/runtime/test/d3d12_existing_heap_test.cpp +++ b/runtime/test/d3d12_existing_heap_test.cpp @@ -1236,7 +1236,7 @@ int check_placed_target_backing(ID3D12Device* device) { // Two sampled BC placements have distinct T#s. A CPU write to the first and a GPU copy into // the second must each promote only their destination and keep previously copied descriptors usable. -int check_shared_bc_placements(ID3D12Device* device) { +int check_shared_bc_placements(ID3D12Device* device, bool must_share = false) { const char* who = "shared slot-133 BC images"; if (!rt::d3d12::bindless_set_layout(device)) return 0; constexpr UINT width = 32, height = 32, pitch = width / 4 * 8; @@ -1259,6 +1259,8 @@ int check_shared_bc_placements(ID3D12Device* device) { const auto second = rt::d3d12::bindless_hash_lookup(device, bv); EXPECT(first && second && first != second); const bool shared = !rt::d3d12::vulkan_memory_flags(a.p); + const char* defer = std::getenv("LEONIDA_PLACED_IMAGE_DEFER"); + EXPECT(shared || !must_share || (defer && !std::strcmp(defer, "0"))); EXPECT(bool(rt::d3d12::vulkan_memory_flags(b.p)) == !shared); std::array pattern{}, result{}; for (std::size_t i = 0; i < pattern.size(); ++i) pattern[i] = std::uint8_t(i * 13 + 71); @@ -1978,6 +1980,79 @@ int check_mapped_bc_array(ID3D12Device* device) { return 0; } +// Model a device that supports host image copies, with two per-image exceptions. +PFN_vkGetInstanceProcAddr original_instance_proc; +PFN_vkGetPhysicalDeviceFormatProperties2 original_format_properties; +PFN_vkGetPhysicalDeviceImageFormatProperties2 original_image_properties; + +VKAPI_ATTR void VKAPI_CALL without_r8_host_transfer(VkPhysicalDevice device, VkFormat format, + VkFormatProperties2* properties) { + original_format_properties(device, format, properties); + if (format != VK_FORMAT_R8_UNORM) return; + for (auto* p = static_cast(properties->pNext); p; p = p->pNext) + if (p->sType == VK_STRUCTURE_TYPE_FORMAT_PROPERTIES_3) + reinterpret_cast(p)->optimalTilingFeatures &= + ~VK_FORMAT_FEATURE_2_HOST_IMAGE_TRANSFER_BIT_EXT; +} + +VKAPI_ATTR VkResult VKAPI_CALL without_bc1_host_usage(VkPhysicalDevice device, + const VkPhysicalDeviceImageFormatInfo2* info, + VkImageFormatProperties2* properties) { + if (info->format == VK_FORMAT_BC1_RGBA_UNORM_BLOCK && (info->usage & VK_IMAGE_USAGE_HOST_TRANSFER_BIT_EXT)) + return VK_ERROR_FORMAT_NOT_SUPPORTED; + return original_image_properties(device, info, properties); +} + +VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL per_format_instance_proc(VkInstance instance, const char* name) { + if (std::strcmp(name, "vkGetPhysicalDeviceFormatProperties2") == 0) + return reinterpret_cast(without_r8_host_transfer); + if (std::strcmp(name, "vkGetPhysicalDeviceImageFormatProperties2") == 0) + return reinterpret_cast(without_bc1_host_usage); + return original_instance_proc(instance, name); +} + +// Pascal can create the mapped R8 movie plane with HOST_TRANSFER yet offer no memory for it. +// Use the bound-image requirements API for both the probe and the eventual allocation. +PFN_vkGetDeviceProcAddr original_device_proc; +std::atomic host_plane{}; + +VKAPI_ATTR VkResult VKAPI_CALL track_plane(VkDevice device, const VkImageCreateInfo* info, + const VkAllocationCallbacks* allocator, VkImage* image) { + auto create = reinterpret_cast(original_device_proc(device, "vkCreateImage")); + const VkResult result = create(device, info, allocator, image); + if (result == VK_SUCCESS && info->format == VK_FORMAT_R8_UNORM && + info->extent.width == 256 && info->extent.height == 8 && (info->usage & VK_IMAGE_USAGE_HOST_TRANSFER_BIT_EXT)) + host_plane = *image; + return result; +} + +VKAPI_ATTR void VKAPI_CALL untrack_plane(VkDevice device, VkImage image, const VkAllocationCallbacks* allocator) { + VkImage expected = image; + host_plane.compare_exchange_strong(expected, VK_NULL_HANDLE); + reinterpret_cast(original_device_proc(device, "vkDestroyImage"))(device, image, allocator); +} + +VKAPI_ATTR void VKAPI_CALL plane_requirements(VkDevice device, VkImage image, VkMemoryRequirements* requirements) { + auto get = reinterpret_cast( + original_device_proc(device, "vkGetImageMemoryRequirements")); + get(device, image, requirements); + if (image == host_plane) requirements->memoryTypeBits = 0; +} + +VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL plane_device_proc(VkDevice device, const char* name) { + if (!std::strcmp(name, "vkGetDeviceImageMemoryRequirements") || + !std::strcmp(name, "vkGetDeviceImageMemoryRequirementsKHR")) return nullptr; + if (!std::strcmp(name, "vkCreateImage")) return reinterpret_cast(track_plane); + if (!std::strcmp(name, "vkDestroyImage")) return reinterpret_cast(untrack_plane); + if (!std::strcmp(name, "vkGetImageMemoryRequirements")) return reinterpret_cast(plane_requirements); + return original_device_proc(device, name); +} + +VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL plane_instance_proc(VkInstance instance, const char* name) { + if (!std::strcmp(name, "vkGetDeviceProcAddr")) return reinterpret_cast(plane_device_proc); + return original_instance_proc(instance, name); +} + void print_cases(const std::vector& cases, const char* who) { for (const Case& c : cases) std::printf("%s: %-44s hr=0x%08lX size=%llu align=%llu type=%d cpu=%d pool=%d flags=0x%x\n", who, c.name, @@ -2029,6 +2104,25 @@ int main(int argc, char** argv) { failures += check_shared_bc_placements(ours.p); failures += check_mapped_plane(ours.p); failures += check_mapped_bc_array(ours.p); + + original_instance_proc = vk.instance_proc; + original_format_properties = + vk.instance_fn("vkGetPhysicalDeviceFormatProperties2"); + original_image_properties = + vk.instance_fn("vkGetPhysicalDeviceImageFormatProperties2"); + auto per_format = info; + per_format.get_instance_proc = per_format_instance_proc; + Ref limited; + if (FAILED(rt::d3d12::create_vulkan_device(per_format, IID_PPV_ARGS(&limited.p)))) return 1; + failures += check_mapped_plane(limited.p); + failures += check_mapped_bc_array(limited.p); + + original_device_proc = vk.device_proc; + auto no_plane_memory = info; + no_plane_memory.get_instance_proc = plane_instance_proc; + Ref restricted; + if (FAILED(rt::d3d12::create_vulkan_device(no_plane_memory, IID_PPV_ARGS(&restricted.p)))) return 1; + failures += check_mapped_plane(restricted.p); } { // Without host image copies a title image is filled through the staged upload, a linear plane too. @@ -2036,6 +2130,7 @@ int main(int argc, char** argv) { no_host_copy.host_image_copy = false; Ref staged; if (FAILED(rt::d3d12::create_vulkan_device(no_host_copy, IID_PPV_ARGS(&staged.p)))) return 1; + failures += check_shared_bc_placements(staged.p, true); failures += check_mapped_plane(staged.p); failures += check_mapped_bc_array(staged.p); } diff --git a/runtime/test/replay_copy_offset_test.cpp b/runtime/test/replay_copy_offset_test.cpp index b67b94678b..d079e65fb0 100644 --- a/runtime/test/replay_copy_offset_test.cpp +++ b/runtime/test/replay_copy_offset_test.cpp @@ -49,8 +49,12 @@ VKAPI_ATTR void VKAPI_CALL rec_copy_i2b(VkCommandBuffer, VkImage, VkImageLayout, for (std::uint32_t i = 0; i < count; ++i) i2b_copies.push_back(regions[i]); } +std::vector image_copies; + VKAPI_ATTR void VKAPI_CALL noop_copy_image(VkCommandBuffer, VkImage, VkImageLayout, VkImage, VkImageLayout, - std::uint32_t, const VkImageCopy*) {} + std::uint32_t count, const VkImageCopy* regions) { + for (std::uint32_t i = 0; i < count; ++i) image_copies.push_back(regions[i]); +} template T handle(std::uintptr_t n) { @@ -138,6 +142,25 @@ int main(int argc, char** argv) { rgb96_img.samples = 1; rgb96_img.rgb96 = true; + // A depth-stencil texture and a depth-only one of the same size, both 32-bit float depth (D32_FLOAT_S8X24 and + // D32_FLOAT in D3D12). + ResourceBinding d32s8_img{}; + d32s8_img.image = handle(6); + d32s8_img.format = VK_FORMAT_D32_SFLOAT_S8_UINT; + d32s8_img.aspects = VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT; + d32s8_img.width = 64; + d32s8_img.height = 32; + d32s8_img.mip_levels = 1; + d32s8_img.array_layers = 1; + d32s8_img.depth = 1; + d32s8_img.samples = 1; + ResourceBinding d32_img = d32s8_img; + d32_img.image = handle(7); + d32_img.format = VK_FORMAT_D32_SFLOAT; + d32_img.aspects = VK_IMAGE_ASPECT_DEPTH_BIT; + ResourceBinding d32_img2 = d32_img; + d32_img2.image = handle(8); + const auto resolve = [&](ResourceId id) -> const ResourceBinding* { switch (id) { case 1: return &src_buf; @@ -145,6 +168,9 @@ int main(int argc, char** argv) { case 3: return &rgba_img; case 4: return &d24_img; case 5: return &rgb96_img; + case 6: return &d32s8_img; + case 7: return &d32_img; + case 8: return &d32_img2; default: return nullptr; } }; @@ -155,6 +181,7 @@ int main(int argc, char** argv) { transfer_writes_ordered = false; b2i_copies.clear(); i2b_copies.clear(); + image_copies.clear(); depth24_jobs.clear(); return replay(list, VK_NULL_HANDLE, resolve, vk); }; @@ -485,6 +512,51 @@ int main(int argc, char** argv) { dst_buf = saved_dst; } + // 7. CopyTextureRegion of the depth plane between two depth formats with the same encoding but not the same + // VkFormat (D32_SFLOAT_S8_UINT and D32_SFLOAT): vkCmdCopyImage requires depth/stencil formats to match exactly + // (VUID-vkCmdCopyImage-srcImage-01548), and an NVIDIA driver handed the D32S8 -> D32 pair wrote past the end of the + // D32 image (the world-start WRITE_INVALID). The copy goes image -> transfer scratch -> image, depth aspect on + // both sides, 4 bytes a texel. The same format on both sides keeps vkCmdCopyImage. + { + VkDeviceSize scratch_bytes = 0; + vk.copy_scratch = [&](VkDeviceSize bytes, VkBuffer& out, VkDeviceSize& base) { + scratch_bytes = bytes; + out = handle(0x9100); + base = 256; + return true; + }; + const auto staged_depth = [&](ResourceId dst, ResourceId src, const char* what) { + const CopyLocation to{dst, false, 0, 0, 0, 0, 0, 0}, from{src, false, 0, 0, 0, 0, 0, 0}; + CommandList list; + expect(list.copy_texture({to, 0, 0, 0, from, false, {}}) && list.close(), what); + expect(run(list) == ReplayResult::success, what); + expect(image_copies.empty(), "a depth copy between different depth formats does not use vkCmdCopyImage"); + expect(i2b_copies.size() == 1 && b2i_copies.size() == 1, "the depth plane is staged through a buffer"); + if (i2b_copies.size() == 1 && b2i_copies.size() == 1) { + const VkBufferImageCopy &read = i2b_copies[0], &write = b2i_copies[0]; + expect(read.imageSubresource.aspectMask == VK_IMAGE_ASPECT_DEPTH_BIT && + write.imageSubresource.aspectMask == VK_IMAGE_ASPECT_DEPTH_BIT, + "both staged halves name the depth aspect"); + expect(read.imageExtent.width == 64 && read.imageExtent.height == 32 && read.imageExtent.depth == 1 && + write.imageExtent.width == 64 && write.imageExtent.height == 32, + "the staged depth copy covers the whole 64x32 plane"); + expect(read.bufferOffset == 256 && write.bufferOffset == 256, + "the read and the write share one scratch range"); + } + expect(scratch_bytes >= VkDeviceSize(64) * 32 * 4, "the scratch holds 4 bytes a depth texel"); + }; + staged_depth(7, 6, "D32_SFLOAT_S8_UINT depth plane into D32_SFLOAT"); + staged_depth(6, 7, "D32_SFLOAT into the depth plane of D32_SFLOAT_S8_UINT"); + + const CopyLocation to{8, false, 0, 0, 0, 0, 0, 0}, from{7, false, 0, 0, 0, 0, 0, 0}; + CommandList same; + expect(same.copy_texture({to, 0, 0, 0, from, false, {}}) && same.close(), "record D32_SFLOAT copy"); + expect(run(same) == ReplayResult::success, "D32_SFLOAT into D32_SFLOAT replays"); + expect(image_copies.size() == 1 && i2b_copies.empty() && b2i_copies.empty(), + "the same depth format on both sides keeps vkCmdCopyImage"); + vk.copy_scratch = {}; + } + if (failures) return 1; std::printf("replay_copy_offset: CopyResource and CopyTexture apply ResourceBinding::buffer_offset\n"); return 0; diff --git a/tests/semantic/test_structured_pc_unwrap.py b/tests/semantic/test_structured_pc_unwrap.py new file mode 100644 index 0000000000..d8e42e6072 --- /dev/null +++ b/tests/semantic/test_structured_pc_unwrap.py @@ -0,0 +1,186 @@ +"""Semantic regression tests for structured %pc guard unwrapping (SHADER-STRUCTURED-PC-UNWRAP). + +Pure Python stdlib only (no llvm-mc, spirv-val, GPU, or game data). Verifies end-to-end translation +and execution of synthetic hand-written RDNA2 compute shaders where the last basic block ends in a +conditional branch with no trailing s_endpgm (fallthrough writes %pc = len(blocks) = END): + + 1. Loop whose back-edge is a conditional branch at the very end of the shader (succ = [[2, 1], [], [0]], + out_pcs[2] = {0, END}): exiting the loop leaves %pc in {1, END}, so guard 1 must stay and a + not-taken back-edge must terminate without executing block 1. + 2. Non-loop conditional branch at the very end of the shader whose single explicit target is + immediately dominated by it (succ = [[2], [], [1]], out_pcs[2] = {1, END}): both native + structured control flow and --wave64-emulate structured control flow must keep guard 1. + 3. Single-arm if-then join (0 -> {2, 1}, 1 -> {2}, 2 -> []) with s_barrier in block 2: block 2 + unwraps to top level so wave32 compute does not falsely fall back to barrier rounds. +""" +import os +import sys +import unittest + +HERE = os.path.dirname(os.path.abspath(__file__)) +ROOT = os.path.dirname(os.path.dirname(HERE)) +TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") + +sys.dont_write_bytecode = True +for _p in (HERE, TOOLS_DIR): + if _p not in sys.path: + sys.path.insert(0, _p) + +import rdna2spirv # noqa: E402 +from test_loop_ballot_barrier import VSHARP, _translate_cs, run_compute_workgroup # noqa: E402 + + +class StructuredPcUnwrapSemanticTest(unittest.TestCase): + def test_loop_last_block_cbranch_falloff_keeps_exit_guard(self): + """Loop back-edge in the last block with no s_endpgm after it: falling off the end must NOT run block 1.""" + prog = [ + "head:", + "s_cmp_eq_u32 s4, 0", + "s_cbranch_scc1 tail", + "v_lshlrev_b32_e32 v2, 2, v0", + "v_mov_b32_e32 v1, 0x1111", + "buffer_store_dword v1, v2, s[0:3], 0 offen", + "s_endpgm", + "tail:", + "s_mov_b32 s4, 1", + "s_cmp_eq_u32 s5, 1", + "s_cbranch_scc1 head", + ] + spv_struct, gen_struct = _translate_cs("cs_cbranch_falloff_loop", prog, threads=32, structured=True) + spv_disp, gen_disp = _translate_cs("cs_cbranch_falloff_loop_disp", prog, threads=32, structured=False) + self.assertEqual(gen_struct.control_flow, "structured") + self.assertEqual(gen_disp.control_flow, "dispatch loop") + self.assertEqual(gen_struct.succ, [[2, 1], [], [0]]) + self.assertEqual(gen_struct.out_pcs[2], frozenset({0, -1})) + tree, _ = rdna2spirv.capped_tree(gen_struct.succ, gen_struct.out_pcs) + self.assertEqual(tree, [ + ("loop", 0, [("block", 0), ("guard", 2, [("block", 2)])]), + ("guard", 1, [("block", 1)]), + ]) + + cases = [ + (1, 0, [0x1111] * 32), # B0 falls into B1 -> stores 0x1111 + (0, 1, [0x1111] * 32), # B0 -> B2 (s4=1, back-edge taken) -> B0 -> B1 -> stores 0x1111 + (0, 0, [0] * 32), # B0 -> B2 (back-edge not taken -> falls off end) -> no store + ] + for s4, s5, want in cases: + with self.subTest(s4=s4, s5=s5): + pc = VSHARP + [s4, s5] + mem_s = run_compute_workgroup(spv_struct, 32, 32, push_constants=pc) + mem_d = run_compute_workgroup(spv_disp, 32, 32, push_constants=pc) + got_s = [mem_s.get(4 * t, 0) for t in range(32)] + got_d = [mem_d.get(4 * t, 0) for t in range(32)] + self.assertEqual(got_d, want) + self.assertEqual(got_s, want) + + def test_nonloop_last_block_cbranch_falloff_keeps_dominated_target_guard(self): + """Last block ending in s_cbranch_scc1 to its single dominated target (no s_endpgm) must keep its guard.""" + prog = [ + "s_branch tail", + "do_store:", + "v_lshlrev_b32_e32 v2, 2, v0", + "v_mov_b32_e32 v1, 0x2222", + "buffer_store_dword v1, v2, s[0:3], 0 offen", + "s_endpgm", + "tail:", + "s_cmp_eq_u32 s4, 1", + "s_cbranch_scc1 do_store", + ] + for mode, threads, sg_sz, emulate in ( + ("w32_structured", 32, 32, False), + ("w64_emulate", 64, 32, True), + ): + # Include a 64-bit exec op in the wave64 case so rdna2spirv classifies the shader as wave64 + # and exercises wave64_emulate_opt.plan_structured_emulation(). + mode_prog = (["s_mov_b64 s[10:11], exec"] + prog) if emulate else prog + spv, gen = _translate_cs(f"cs_cbranch_falloff_{mode}", mode_prog, threads=threads, emulate=emulate) + if emulate: + self.assertEqual(gen.control_flow, "emulated wave64 structured") + else: + self.assertEqual(gen.control_flow, "structured") + tree, _ = rdna2spirv.capped_tree(gen.succ, gen.out_pcs) + self.assertEqual(tree, [("block", 0), ("block", 2), ("guard", 1, [("block", 1)])]) + for s4, want_val in ((1, 0x2222), (0, 0)): + with self.subTest(mode=mode, s4=s4): + mem = run_compute_workgroup(spv, threads, sg_sz, push_constants=VSHARP + [s4]) + self.assertEqual([mem.get(4 * t, 0) for t in range(threads)], [want_val] * threads) + + def test_postdominating_join_barrier_unwraps_to_top_level(self): + """A post-dominating merge block after a single-arm branch unwraps to top level (no false barrier rounds).""" + prog = [ + "v_lshlrev_b32_e32 v2, 2, v0", + "v_mov_b32_e32 v1, 1", + "s_cmp_eq_u32 s4, 0", + "s_cbranch_scc1 join", + "v_mov_b32_e32 v1, 2", + "join:", + "ds_write_b32 v2, v1", + "s_waitcnt lgkmcnt(0)", + "s_barrier", + "ds_read_b32 v3, v2", + "s_waitcnt lgkmcnt(0)", + "buffer_store_dword v3, v2, s[0:3], 0 offen", + "s_endpgm", + ] + spv, gen = _translate_cs("cs_join_barrier_unwrap", prog, threads=64, lds_bytes=256, emulate=False) + self.assertFalse(gen.bar_rounds) + self.assertEqual(gen.control_flow, "structured") + tree, _ = rdna2spirv.capped_tree(gen.succ, gen.out_pcs) + self.assertEqual(tree, [("block", 0), ("guard", 1, [("block", 1)]), ("block", 2)]) + for s4, want_val in ((0, 1), (1, 2)): + with self.subTest(s4=s4): + mem = run_compute_workgroup(spv, 64, 32, push_constants=VSHARP + [s4]) + self.assertEqual([mem.get(4 * t, 0) for t in range(64)], [want_val] * 64) + + def test_wave64_emulate_exec_fold_refuses_last_block_cbranch_falloff(self): + """A wave64 s_cbranch_execz region containing a trailing conditional branch (no s_endpgm) must NOT be + folded into a region that unconditionally continues at `skip`: falling off the end must terminate.""" + prog_to_x = [ + "s_mov_b64 s[10:11], exec", + "s_cbranch_execz skip", + "s_branch last", + "X:", + "v_lshlrev_b32_e32 v2, 2, v0", + "v_mov_b32_e32 v1, 0x3333", + "buffer_store_dword v1, v2, s[0:3], 0 offen", + "s_branch skip", + "skip:", + "v_lshlrev_b32_e32 v2, 2, v0", + "v_mov_b32_e32 v1, 0x4444", + "buffer_store_dword v1, v2, s[0:3], 0 offen offset:256", + "s_endpgm", + "last:", + "s_cmp_eq_u32 s4, 1", + "s_cbranch_scc1 X", + ] + prog_to_skip = [ + "s_mov_b64 s[10:11], exec", + "s_cbranch_execz skip", + "s_branch last", + "skip:", + "v_lshlrev_b32_e32 v2, 2, v0", + "v_mov_b32_e32 v1, 0x4444", + "buffer_store_dword v1, v2, s[0:3], 0 offen offset:256", + "s_endpgm", + "last:", + "s_cmp_eq_u32 s4, 1", + "s_cbranch_scc1 skip", + ] + for name, prog, want_taken_x, want_taken_skip in ( + ("branch_to_x", prog_to_x, 0x3333, 0x4444), + ("branch_to_skip", prog_to_skip, 0, 0x4444), + ): + for structured in (True, False): + spv, _ = _translate_cs( + f"cs_fold_falloff_{name}_{int(structured)}", + prog, threads=64, emulate=True, structured=structured, + ) + for s4, exp_x, exp_skip in ((0, 0, 0), (1, want_taken_x, want_taken_skip)): + with self.subTest(case=name, structured=structured, s4=s4): + mem = run_compute_workgroup(spv, 64, 32, push_constants=VSHARP + [s4]) + self.assertEqual([mem.get(4 * t, 0) for t in range(64)], [exp_x] * 64) + self.assertEqual([mem.get(256 + 4 * t, 0) for t in range(64)], [exp_skip] * 64) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_ab_control_flow.py b/tests/test_ab_control_flow.py index 403d0af1dc..ac12184256 100644 --- a/tests/test_ab_control_flow.py +++ b/tests/test_ab_control_flow.py @@ -1129,5 +1129,95 @@ def side_effect(args, **kwargs): self.assertEqual(content, f"ps_test\t{expected}\n") +class HardeningRegressionTest(unittest.TestCase): + def test_select_candidates_strips_bom_crlf_and_blank_lines(self): + with tempfile.TemporaryDirectory() as tmp: + names = os.path.join(tmp, "names.txt") + with open(names, "wb") as f: + f.write(b"\xef\xbb\xbfps_alpha\r\n\r\n ps_beta \r\n\n") + self.assertEqual( + AB.select_candidates({}, tmp, tmp, names_file=names), + ["ps_alpha", "ps_beta"], + ) + + def test_main_reads_utf8_bom_index_json(self): + import json + + with tempfile.TemporaryDirectory() as tmp: + repo = os.path.join(tmp, "repo") + shaders = os.path.join(tmp, "shaders") + out = os.path.join(tmp, "out") + os.makedirs(os.path.join(repo, "runtime", "build")) + os.makedirs(os.path.join(shaders, "dxbc", "disasm")) + os.makedirs(os.path.join(shaders, "spirv")) + with open(os.path.join(shaders, "spirv", "index.json"), "wb") as f: + f.write(b"\xef\xbb\xbf" + json.dumps({"ps_bom": {"stage": "ps"}}).encode("utf-8")) + with open(os.path.join(shaders, "dxbc", "disasm", "ps_bom.s"), "w", encoding="utf-8", newline="\n") as f: + f.write("\ts_cbranch_scc0 10\n\ts_branch 20\n\ts_endpgm\n") + with open(os.path.join(shaders, "spirv", "ps_bom.spv"), "wb") as f: + f.write(b"stub") + + def side_effect(args, **kwargs): + if "spirv-as" in str(args[0]): + with open(args[-1], "wb") as fh: + fh.write(b"vs") + return SimpleNamespace(returncode=0, stdout="ok") + if "spirv-val" in str(args[0]): + return SimpleNamespace(returncode=0, stdout="ok") + if "rdna2spirv.py" in str(args): + out_dir = args[args.index("--out") + 1] + os.makedirs(out_dir, exist_ok=True) + with open(os.path.join(out_dir, "ps_bom.spvasm"), "w", encoding="utf-8", newline="\n") as fh: + fh.write("%out_mrt0 = OpVariable %po Output\n") + with open(os.path.join(out_dir, "ps_bom.spv"), "wb") as fh: + fh.write(b"spv") + return SimpleNamespace(returncode=0, stdout="1 pass spirv-val\n") + with open(args[3], "wb") as fh: + fh.write(bytes(AB.READBACK_BYTES)) + return SimpleNamespace(returncode=0, stdout="ok") + + with patch("subprocess.run", side_effect=side_effect), contextlib.redirect_stdout(io.StringIO()): + rc = AB.main([repo, shaders, out, "--count", "1", "--harness", "dummy.exe"]) + self.assertEqual(rc, 0) + with open(os.path.join(out, "outcomes.tsv"), encoding="utf-8") as f: + self.assertEqual(f.read(), "ps_bom\tidentical MRT0: non-clear\n") + + def test_write_outcomes_atomic_preserves_existing_on_replace_failure(self): + with tempfile.TemporaryDirectory() as tmp: + target = os.path.join(tmp, "outcomes.tsv") + with open(target, "w", encoding="utf-8", newline="\n") as f: + f.write("prev\tidentical\n") + with patch.object(AB.replace_retry, "replace", side_effect=PermissionError("locked")): + with self.assertRaises(PermissionError): + AB.write_outcomes(tmp, [("new", "DIFFERENT")]) + with open(target, encoding="utf-8") as f: + self.assertEqual(f.read(), "prev\tidentical\n") + self.assertEqual([n for n in os.listdir(tmp) if n.startswith(".outcomes-")], []) + + with patch.object(AB.replace_retry, "replace", wraps=AB.replace_retry.replace) as spy: + out_path = AB.write_outcomes(tmp, [("new", "DIFFERENT")]) + spy.assert_called_once() + with open(out_path, encoding="utf-8") as f: + self.assertEqual(f.read(), "new\tDIFFERENT\n") + + def test_render_targets_passes_utf8_replace_to_subprocess(self): + with tempfile.TemporaryDirectory() as tmp: + dir_a, dir_b, out = os.path.join(tmp, "a"), os.path.join(tmp, "b"), os.path.join(tmp, "out") + for d in (dir_a, dir_b, out): + os.makedirs(d) + seen = [] + + def fake_run(cmd, **kwargs): + seen.append(kwargs) + return SimpleNamespace(returncode=1) + + with patch("subprocess.run", side_effect=fake_run): + AB.render_targets((("old", dir_a), ("new", dir_b)), "ps_x", "harness", "vs", out, 1, 5, [0], [0], False) + self.assertEqual(len(seen), 2) + for kw in seen: + self.assertEqual(kw.get("encoding"), "utf-8") + self.assertEqual(kw.get("errors"), "replace") + + if __name__ == "__main__": unittest.main() diff --git a/tests/test_bcpack_tables_bptc.py b/tests/test_bcpack_tables_bptc.py index a9363cf059..8c6bc8cc7b 100644 --- a/tests/test_bcpack_tables_bptc.py +++ b/tests/test_bcpack_tables_bptc.py @@ -15,6 +15,7 @@ import sys import tempfile import unittest +from unittest import mock ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) TOOLS_DIR = os.path.join(ROOT, "tools") @@ -638,5 +639,89 @@ def test_validation_errors(self) -> None: bptc.load_bc7({"bc7": bad_sec}) +class TestSecurityAndEdgeValidation(unittest.TestCase): + """Regression tests for section validation, recursion bounds, bit-shift bounds, and cache identity.""" + + def test_non_dict_codec_section_raises_value_error(self) -> None: + for bad in ([], 123, "bad"): + with self.subTest(bad=bad): + with self.assertRaisesRegex(ValueError, "JSON object"): + bptc.load_bc6h({"bc6h": bad}) + with self.assertRaisesRegex(ValueError, "JSON object"): + bptc.load_bc7({"bc7": bad}) + + def test_recursion_error_in_json_raises_value_error(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + path = os.path.join(tmp, "deep.json") + with open(path, "w", encoding="utf-8", newline="\n") as fh: + fh.write("{}") + bptc._FILE_CACHE.pop(os.path.realpath(path), None) + bptc._FILE_CACHE.pop(os.path.abspath(path), None) + with mock.patch.object(bptc.json, "load", side_effect=RecursionError("too deep")): + for fn in ( + lambda: bptc.load_bc6h(path), + lambda: bptc.load_bc7(path), + lambda: bptc.load_bc_history(1, path), + ): + with self.assertRaisesRegex(ValueError, "too deep"): + fn() + + def test_bc7_low2_fit_confirmed_bits_above_8_raises_value_error_not_negative_shift(self) -> None: + sec = { + "historyEndpoints": {"0": [0x80] * 24}, + "historyEndpointBits": {"0": [4] * 24}, + "historyEndpointConfirmedBits": {"0": [9] + [0] * 23}, + "historyEndpointLow2Fits": [[0, 0, 1]], + } + with self.assertRaisesRegex(ValueError, "out of bounds"): + bptc.load_bc7({"bc7": sec}) + for bad_fits in (123, [[0, 0]], [[True, 0, 1]], [[0, 0, "1"]]): + with self.subTest(bad_fits=bad_fits): + bad_sec = { + "historyEndpoints": {"0": [0x80] * 24}, + "historyEndpointBits": {"0": [4] * 24}, + "historyEndpointLow2Fits": bad_fits, + } + with self.assertRaises(ValueError): + bptc.load_bc7({"bc7": bad_sec}) + + def test_bc7_last_resort_scalar_or_out_of_bounds_raises_value_error(self) -> None: + for bad_lr in (123, [123], [[256, 0]], [[-1, 0]], [[0, 24]], [[0, 3, 0, 0]], [[0, 0, 2, 0]], [[0, 0, 0, 4]]): + with self.subTest(bad_lr=bad_lr): + with self.assertRaises(ValueError): + bptc.load_bc7({"bc7": {"historyEndpointLastResort": bad_lr}}) + + def test_bc6h_scalar_row_raises_value_error(self) -> None: + for bad_sec in ( + {"endpointHistory": {"0": 123}}, + {"endpointHistory": {"0": [123, [0] * 4, [0] * 4]}}, + {"indexHistory": {"0": 123}}, + {"endpointConfirmedBits": {"0": 123}}, + {"indexConfirmedBits": {"0": 123}}, + ): + with self.subTest(bad_sec=bad_sec): + with self.assertRaises(ValueError): + bptc.load_bc6h({"bc6h": bad_sec}) + + def test_file_cache_invalidates_on_same_size_mtime_inode_replacement(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + hist = os.path.join(tmp, "hist.json") + staged = os.path.join(tmp, "staged.json") + payload_a = json.dumps({"bc6h": {"endpointClass": {"0": 1}}}) + payload_b = json.dumps({"bc6h": {"endpointClass": {"0": 2}}}) + self.assertEqual(len(payload_a), len(payload_b)) + with open(hist, "w", encoding="utf-8", newline="\n") as fh: + fh.write(payload_a) + st = os.stat(hist) + self.assertEqual(bptc.load_bc6h(hist)[2][0], 1) + + with open(staged, "w", encoding="utf-8", newline="\n") as fh: + fh.write(payload_b) + os.utime(staged, ns=(st.st_atime_ns, st.st_mtime_ns)) + os.replace(staged, hist) + os.utime(hist, ns=(st.st_atime_ns, st.st_mtime_ns)) + self.assertEqual(bptc.load_bc6h(hist)[2][0], 2) + + if __name__ == "__main__": unittest.main() diff --git a/tests/test_cfg_structure.py b/tests/test_cfg_structure.py index d4fa490588..761bb21ee6 100644 --- a/tests/test_cfg_structure.py +++ b/tests/test_cfg_structure.py @@ -146,10 +146,17 @@ def split_choose(b, _orig=orig, _ns=new_succ, _seed=seed, _v=visits): loops += '"loop"' in repr(tree).replace("'", '"') placed = blocks_in(tree) assert len(placed) == len(set(placed)), f"a block is placed twice: {succ}" + out_pcs = {b: (set(succ[b]) if succ[b] else {S.END}) for b in range(len(succ))} + utree = S.unwrap_known_pc_guards(tree, out_pcs) + uplaced = blocks_in(utree) + assert len(uplaced) == len(set(uplaced)) and set(uplaced) == set(placed), ( + f"unwrap changed block set for {succ}: {placed} vs {uplaced}") for seed in range(6): want = walk(succ, chooser(succ, seed), 200) got = S.run(tree, chooser(succ, seed), 200) assert got == want, f"graph {succ} seed {seed}: tree ran {got}, graph runs {want}" + ugot = S.run(utree, chooser(succ, seed), 200) + assert ugot == want, f"unwrapped graph {succ} seed {seed}: tree ran {ugot}, graph runs {want}" assert structured > 5000 and refused > 1000 and loops > 2000, (structured, refused, loops) assert split_ok > 1000 and split_ok + split_cap == refused, (split_ok, split_cap, refused) return structured, refused, loops, split_ok, split_cap @@ -247,10 +254,42 @@ def test_deep_sequential_chains_stay_flat_and_iterative(): assert got == want +def test_unwrap_known_pc_guards(): + def unwrap(succ, out_pcs=None): + if out_pcs is None: + out_pcs = {b: (set(succ[b]) if succ[b] else {S.END}) for b in range(len(succ))} + tree = S.structure(succ, out_pcs=out_pcs) + assert tree is not None + return S.unwrap_known_pc_guards(tree, out_pcs) + + # Single-arm if-then (ms_wave_info_s3 shape: 0 -> {2, 1}, 1 -> {2}, 2 -> []): join block 2 unwraps to top level. + assert unwrap([[2, 1], [2], []]) == [("block", 0), ("guard", 1, [("block", 1)]), ("block", 2)] + # Diamond (0 -> {1, 2}, 1 -> {3}, 2 -> {3}, 3 -> []): join block 3 unwraps to top level. + assert unwrap([[1, 2], [3], [3], []]) == [("block", 0), ("guard", 2, [("block", 2)]), + ("guard", 1, [("block", 1)]), ("block", 3)] + # Loop exit (0 -> {0, 1}, 1 -> []): block 1 unwraps to top level because exiting loop 0 proves pc == 1. + assert unwrap([[0, 1], []]) == [("loop", 0, [("block", 0)]), ("block", 1)] + # Early exit in arm 1 (0 -> {1, 2}, 1 -> [], 2 -> []): both arms MUST remain guarded (pc may be END). + assert unwrap([[1, 2], [], []]) == [("block", 0), ("guard", 2, [("block", 2)]), ("guard", 1, [("block", 1)])] + # Conditional branch in the last block with no s_endpgm after it (fallthrough writes END): + # loop body block 2 has succ [0] but out_pcs {0, END}, so exiting loop 0 leaves pc in {1, END}; + # guard 1 MUST stay so falling off the end does not execute block 1. + assert unwrap([[2, 1], [], [0]], out_pcs={0: {2, 1}, 1: {S.END}, 2: {0, S.END}}) == [ + ("loop", 0, [("block", 0), ("guard", 2, [("block", 2)])]), + ("guard", 1, [("block", 1)]), + ] + # Non-loop conditional branch falling off the end whose single explicit target is immediately dominated by it: + # block 2 has succ [1] and out_pcs {1, END}, so structure() and unwrap MUST both keep guard 1. + assert unwrap([[2], [], [1]], out_pcs={0: {2}, 1: {S.END}, 2: {1, S.END}}) == [ + ("block", 0), ("block", 2), ("guard", 1, [("block", 1)]), + ] + + if __name__ == "__main__": test_depth() test_shapes() test_deep_sequential_chains_stay_flat_and_iterative() + test_unwrap_known_pc_guards() structured, refused, loops, split_ok, split_cap = _check_random_graphs() print(f"ok: {structured} graphs structured and run, {refused} irreducible " f"({split_ok} split-structured, {split_cap} capped), {loops} with loops") diff --git a/tests/test_docs_adjacent_fenced_blocks.py b/tests/test_docs_adjacent_fenced_blocks.py new file mode 100644 index 0000000000..0eacf8b050 --- /dev/null +++ b/tests/test_docs_adjacent_fenced_blocks.py @@ -0,0 +1,138 @@ +"""No docs page repeats the same fenced block twice in a row. + +Two copies of one code block, with nothing but blank lines between them, is what a merge of a +rebased copy leaves behind: the page shows the same snippet twice, and an edit to one copy +leaves the other stale next to it. That is how `docs/character_models.md` carried the same +`manifest.json` block twice (lines 312-320 and 322-330) until it was dropped. + +The rule is deliberately narrow: the blocks must be identical, carry the same language tag, and be adjacent, so the +same command quoted again in a later section, two blocks that differ in one line, or one expression shown for two +languages are not reported. + + python -I tests/test_docs_adjacent_fenced_blocks.py + +Synthetic Markdown only; no game data. +""" +import os +import re +import unittest + +HERE = os.path.dirname(os.path.abspath(__file__)) +ROOT = os.path.dirname(HERE) +DOCS = os.path.join(ROOT, "docs") + +FENCE = re.compile(r"^ {0,3}(`{3,}|~{3,})(.*)$") + + +def fenced_blocks(lines): + """[(opening fence index, closing fence index, info string, content lines)] for `lines`.""" + blocks, opened = [], None + for index, line in enumerate(lines): + match = FENCE.match(line) + if opened is None: + if match: + marker = match.group(1) + opened = (index, marker[0], len(marker), match.group(2).strip().lower(), []) + continue + # A closing fence is the same character, at least as long, and nothing after it. + if match and match.group(1)[0] == opened[1] and len(match.group(1)) >= opened[2] \ + and not match.group(2).strip(): + blocks.append((opened[0], index, opened[3], opened[4])) + opened = None + continue + opened[4].append(line) + return blocks + + +def adjacent_repeats(text): + """[(first block's line number, second block's line number)] for identical blocks back to back. + + Line numbers are 1-based and name the opening fence. Blocks with prose between them are not + back to back, blocks with different info strings are different examples even when the text matches + (a Python and a Ruby snippet can read the same), and empty blocks are ignored. + """ + lines = text.splitlines() + found = [] + blocks = fenced_blocks(lines) + for (start_a, end_a, info_a, body_a), (start_b, _end_b, info_b, body_b) in zip(blocks, blocks[1:]): + if body_a != body_b or info_a != info_b or not any(line.strip() for line in body_a): + continue + if all(not line.strip() for line in lines[end_a + 1:start_b]): + found.append((start_a + 1, start_b + 1)) + return found + + +class AdjacentFencedBlocks(unittest.TestCase): + def test_detector_finds_only_identical_adjacent_blocks(self): + src = "\n".join([ + "# page", # 1 + "", # 2 + "```python", # 3 + "print('a')", # 4 + "```", # 5 + "", # 6 + "```python", # 7 + "print('a')", # 8 + "```", # 9 -> 3 and 7 are a repeat + "", # 10 + "Some prose.", # 11 + "", # 12 + "```python", # 13 + "print('a')", # 14 + "```", # 15 same block, but prose above: allowed + "", # 16 + "```python", # 17 + "print('b')", # 18 + "```", # 19 + "", # 20 + "```python", # 21 + "print('b')", # 22 + "```", # 23 -> 17 and 21 repeat + "", # 24 + "````markdown", # 25 + "```", # 26 a shorter fence does not close it + "print('c')", # 27 + "````", # 28 + "", # 29 + "~~~~", # 30 + "print('d')", # 31 + "~~~~", # 32 + "", # 33 + "~~~python", # 34 + "print('e')", # 35 + "~~~", # 36 + "", # 37 + "~~~ruby", # 38 + "print('e')", # 39 + "~~~", # 40 same text, another language: allowed + ]) + self.assertEqual(adjacent_repeats(src), [(3, 7), (17, 21)]) + + def test_detector_ignores_one_line_differences_and_empty_blocks(self): + src = "\n".join([ + "```sh", # 1 + "run --one", # 2 + "```", # 3 + "```sh", # 4 + "run --two", # 5 + "```", # 6 + "```", # 7 empty + "```", # 8 empty + ]) + self.assertEqual(adjacent_repeats(src), []) + + def test_no_page_repeats_a_block_back_to_back(self): + if not os.path.isdir(DOCS): + self.skipTest("no docs directory") + pages = sorted(name for name in os.listdir(DOCS) if name.endswith(".md")) + self.assertGreater(len(pages), 40, "the scan found almost no pages; is the layout different?") + bad = [] + for name in pages: + with open(os.path.join(DOCS, name), encoding="utf-8", errors="replace") as handle: + for first, second in adjacent_repeats(handle.read()): + bad.append(f"docs/{name}: the block at line {first} is repeated at line {second}") + self.assertEqual(bad, []) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_gamedata_reader.py b/tests/test_gamedata_reader.py index 1d8d9e081f..af1717eeb0 100644 --- a/tests/test_gamedata_reader.py +++ b/tests/test_gamedata_reader.py @@ -103,6 +103,42 @@ def test_polymorphic_root_and_list_root(self): self.assertEqual(reader.read(b'')[2], [1, 2]) self.assertEqual(reader.read(b'leaf')[2], "leaf") + def test_empty_typed_objects_keep_class_in_roots_lists_and_maps(self): + cases = ( + (b'', {"$type": "CEmpty"}, 1), + (b' \t\n ', {"$type": "CEmpty"}, 1), + (b'\n', + [{"$type": "CEmpty"}, {"$type": "CEmpty", "@name": "named", "@userFlags": 3}], 2), + (b'', + {"first": {"$type": "CEmpty"}, "second": {"$type": "CEmpty"}}, 2), + ) + for raw, expected, object_count in cases: + with self.subTest(raw=raw): + stream_reader = R.Reader(root_handlers={}, type_handlers={}) + whole_reader = R.Reader(root_handlers={}, type_handlers={}) + self.assertEqual(stream_reader.read(raw)[2], expected) + self.assertEqual(whole_reader.convert(ET.fromstring(raw)), expected) + self.assertEqual(stream_reader.stats, whole_reader.stats) + self.assertEqual(stream_reader.types, {"CEmpty": object_count}) + self.assertEqual(stream_reader.types, whole_reader.types) + self.assertEqual(stream_reader.stats["object"], object_count) + self.assertEqual(stream_reader.stats["text"], 0) + + def test_empty_objects_do_not_change_other_leaf_conventions(self): + raw = (b' leaf ' + b'' + b'') + expected = {"plain": "", "null": None, "text": "leaf", "scalar": 0, "vector": (1.0, 2.0), + "array": [], "ref": {"$ref": "target"}} + stream_reader = R.Reader(root_handlers={}, type_handlers={}) + whole_reader = R.Reader(root_handlers={}, type_handlers={}) + self.assertEqual(stream_reader.read(raw)[2], expected) + self.assertEqual(whole_reader.convert(ET.fromstring(raw)), expected) + self.assertEqual(stream_reader.stats, whole_reader.stats) + self.assertEqual(stream_reader.types, whole_reader.types) + self.assertEqual(stream_reader.stats["object"], 0) + self.assertEqual(stream_reader.stats["text"], 2) + def test_vector_with_extra_attributes_and_non_vector_xyzw(self): reader = R.Reader(root_handlers={}, type_handlers={}) self.assertEqual( @@ -165,6 +201,31 @@ def spy_iterparse(*args, **kwargs): class Dispatch(unittest.TestCase): + def test_empty_type_handler_can_use_generic_class_without_double_counting(self): + def empty(el, reader): + generic = reader.convert(el, use_type_handler=False) + return {**generic, "default": 7} + + raw = b'' + reader = R.Reader(root_handlers={}, type_handlers={"CEmpty": empty}) + self.assertEqual(reader.read(raw)[2], [{"$type": "CEmpty", "@name": "named", "default": 7}]) + self.assertEqual(reader.types, {"CEmpty": 1}) + self.assertEqual(reader.stats["type handler"], 1) + self.assertEqual(reader.stats["object"], 1) + self.assertEqual(reader.stats["extra attributes"], 1) + + calls = [] + + def root(el, reader): + calls.append((el.tag, el.attrib["type"])) + return "root default" + + root_reader = R.Reader(root_handlers={"Root": root}, type_handlers={"CEmpty": empty}) + self.assertEqual(root_reader.read(b'')[2], "root default") + self.assertEqual(calls, [("Root", "CEmpty")]) + self.assertEqual(root_reader.stats["root handler"], 1) + self.assertEqual(root_reader.stats["type handler"], 0) + def test_type_handler(self): calls = [] diff --git a/tests/test_gamedata_sps1_atomic.py b/tests/test_gamedata_sps1_atomic.py new file mode 100644 index 0000000000..d008b71079 --- /dev/null +++ b/tests/test_gamedata_sps1_atomic.py @@ -0,0 +1,131 @@ +"""Atomic --json write, path validation, and index-read tests for tools/gamedata_sps1.py. + + python -I tests/test_gamedata_sps1_atomic.py +""" +import contextlib +import io +import json +import os +import struct +import sys +import tempfile +import unittest +from unittest import mock + +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +TOOLS = os.path.join(ROOT, "tools") +if TOOLS not in sys.path: + sys.path.insert(0, TOOLS) + +import gamedata_sps1 # noqa: E402 + + +def _sps1_blob(entries: list[tuple[str, str, int]]) -> bytes: + buf = bytearray(b"SPS1" + struct.pack("> (8 - max(depth, ep_cb[k][field])): - raise ValueError("BC7 low-bit fit changes a known prefix") - row = list(ep[k]) - row[field] = value - ep[k] = tuple(row) + low2 = sec.get("historyEndpointLow2Fits") + if low2 is not None: + if not isinstance(low2, (list, tuple)): + raise ValueError("historyEndpointLow2Fits must be a list") + for item in low2: + if not isinstance(item, (list, tuple)) or len(item) != 3 or not all(type(x) is int for x in item): + raise ValueError("invalid BC7 low-bit endpoint fit") + k, field, low = item + if not (0 <= k < 256 and field in (0, 4, 8, 12, 16, 20) and 0 <= low < 4): + raise ValueError("invalid BC7 low-bit endpoint fit") + depth = ep_b[k][field] + cb = ep_cb[k][field] + if not 0 <= cb <= 8: + raise ValueError("BC7 confirmed bit depth out of bounds") + old = ep[k][field] + value = (old & ~3) | low + if not 4 <= depth < 8 or (old ^ value) >> (8 - max(depth, cb)): + raise ValueError("BC7 low-bit fit changes a known prefix") + row = list(ep[k]) + row[field] = value + ep[k] = tuple(row) last_resort = set() - for item in sec.get("historyEndpointLastResort") or (): - if len(item) == 4: - k, sub, e, c = (int(x) for x in item) - last_resort.add((k, sub * 8 + e * 4 + c)) - elif len(item) == 2: - last_resort.add((int(item[0]), int(item[1]))) - else: - raise ValueError("historyEndpointLastResort entries must have 2 or 4 integers") + last_resort_raw = sec.get("historyEndpointLastResort") + if last_resort_raw is not None: + if not isinstance(last_resort_raw, (list, tuple)): + raise ValueError("historyEndpointLastResort must be a list") + for item in last_resort_raw: + if not isinstance(item, (list, tuple)): + raise ValueError("historyEndpointLastResort entries must have 2 or 4 integers") + if len(item) == 4: + k, sub, e, c = (int(x) for x in item) + if not (0 <= k < 256 and 0 <= sub < 3 and 0 <= e < 2 and 0 <= c < 4): + raise ValueError("historyEndpointLastResort index out of bounds") + last_resort.add((k, sub * 8 + e * 4 + c)) + elif len(item) == 2: + k, field = int(item[0]), int(item[1]) + if not (0 <= k < 256 and 0 <= field < 24): + raise ValueError("historyEndpointLastResort index out of bounds") + last_resort.add((k, field)) + else: + raise ValueError("historyEndpointLastResort entries must have 2 or 4 integers") return { **static, "history_endpoints": tuple(ep), @@ -387,18 +422,7 @@ def load_bc_history(codec, history=None): if not os.path.isfile(candidate): return None path = candidate - abspath = os.path.abspath(path) - st = os.stat(abspath) - cache_key = (st.st_mtime_ns, st.st_size) - cached = _FILE_CACHE.get(abspath) - if cached is not None and cached[0] == cache_key: - data = cached[1] - else: - with open(abspath, "r", encoding="utf-8-sig") as fh: - data = json.load(fh) - if not isinstance(data, dict): - raise ValueError(f"{path}: expected a JSON object") - _FILE_CACHE[abspath] = (cache_key, data) + data = _load_json_file(path) if codec_key in data: sec = data[codec_key] elif data.get("codec") == codec_key: diff --git a/tools/cfg_structure.py b/tools/cfg_structure.py index 3409d4dbf5..9b7b412127 100644 --- a/tools/cfg_structure.py +++ b/tools/cfg_structure.py @@ -80,7 +80,7 @@ def _dominators(rpo, preds): return idom, pos -def structure(succ): +def structure(succ, out_pcs=None): rpo, back, preds = _order(succ) idom, pos = _dominators(rpo, preds) @@ -158,7 +158,8 @@ def member(x, region): out_list.append(("loop", x, lbody)) else: out_list.append(("block", x)) - if kind == "b" and len(below) == 1 and list(succ[x]) == [below[0][1]]: + if (kind == "b" and len(below) == 1 and list(succ[x]) == [below[0][1]] + and (out_pcs is None or set(out_pcs[x]) == {below[0][1]})): stack.append(("emit", out_list, parent_list, below[0], depth)) else: hoist = (parent_list is not None and below @@ -347,3 +348,66 @@ def run(tree, choose, limit): else: stack.pop() return trace + + +def unwrap_known_pc_guards(tree, out_pcs, entry_pc=0): + """Unwrap `("guard", g, body)` nodes whenever abstract interpretation proves `%pc == g` on all incoming paths. + + `structure()` wraps post-dominating join blocks after a diamond or loop in `("guard", g, ...)`. When every + incoming path guarantees `%pc == g` (e.g. a merge block with `s_barrier` after a wave-divergent branch like + `ms_wave_info_s3`), unwrapping the tautological guard keeps `OpControlBarrier` in uniform top-level control + flow (avoiding an AMD Windows LLPC 0xC0000005 pipeline-creation crash in MeshEXT and preventing false + `needs_barrier_rounds` triggers) and avoids redundant `%pc` merge phis. + + `out_pcs[b]` is the finite set of `%pc` values block `b` may write (`{END}` when `b` terminates). + """ + root_out = [] + stack = [[collections.deque(tree), root_out, {entry_pc}, None]] + while stack: + frame = stack[-1] + q, dst, cur_pc, tag = frame + if not q: + if len(stack) > 1 and tag[0] == "guard" and len(cur_pc) == 1: + nxt_g = next(iter(cur_pc)) + skip_pc = tag[3] + parent_q = stack[-2][0] + if parent_q and parent_q[0][0] == "guard" and parent_q[0][1] == nxt_g and nxt_g not in skip_pc: + for child in reversed(parent_q.popleft()[2]): + q.appendleft(child) + continue + stack.pop() + if not stack: + break + parent = stack[-1] + if tag[0] == "guard": + _, g, child_dst, skip_pc = tag + parent[1].append(("guard", g, child_dst)) + parent[2] = skip_pc | cur_pc + else: + _, h, child_dst = tag + parent[1].append(("loop", h, child_dst)) + parent[2] = cur_pc - {h} + continue + it = q.popleft() + kind = it[0] + if kind == "block": + b = it[1] + dst.append(it) + frame[2] = set(out_pcs[b]) + elif kind == "guard": + g, gbody = it[1], it[2] + if cur_pc == {g}: + for child in reversed(gbody): + q.appendleft(child) + else: + child_dst = [] + skip_pc = set(cur_pc) + skip_pc.discard(g) + stack.append([collections.deque(gbody), child_dst, {g}, ("guard", g, child_dst, skip_pc)]) + else: + h, lbody = it[1], it[2] + child_dst = [] + # In a structure() tree lbody[0] is always ("block", h), which overwrites cur_pc with out_pcs[h]; + # keep cur_pc | {h} defensively so back-edge iterations stay sound even on non-structure() trees. + stack.append([collections.deque(lbody), child_dst, set(cur_pc) | {h}, ("loop", h, child_dst)]) + return root_out diff --git a/tools/gamedata_reader.py b/tools/gamedata_reader.py index c9d4ae40fe..0d8dd7e835 100644 --- a/tools/gamedata_reader.py +++ b/tools/gamedata_reader.py @@ -174,8 +174,11 @@ def _convert(self, el, use_type_handler=True): return {"$ref": a["ref"]} kids = list(el) if not kids: + text = (el.text or "").strip() + if t is not None and not text: + return self._typed_object(t, {}) self.stats["text"] += 1 - return (el.text or "").strip() + return text return self._typed_object(t, self.children(kids)) def _typed_object(self, t, value): diff --git a/tools/gamedata_sps1.py b/tools/gamedata_sps1.py index b8aa701874..08c24f75d3 100644 --- a/tools/gamedata_sps1.py +++ b/tools/gamedata_sps1.py @@ -29,15 +29,18 @@ import re import struct import sys +import tempfile # -I keeps the script directory off sys.path, so add it explicitly before importing sibling helpers. TOOLS = os.path.dirname(os.path.abspath(__file__)) if TOOLS not in sys.path: sys.path.insert(0, TOOLS) +from file_mode import published_mode # noqa: E402 import gamedata_index as gi # noqa: E402 import gamedata_maps as gm # noqa: E402 from hashdict import joaat # noqa: E402 +from replace_retry import replace as replace_retry # noqa: E402 from report_paths import same_report_path # noqa: E402 import sgd5_effects as se # noqa: E402 @@ -208,10 +211,11 @@ def _load_from_source(rows: list[dict], read_row) -> list[dict]: return out -def read_payloads(target: str) -> list[dict]: +def read_payloads(target: str, rows: list[dict] | None = None) -> list[dict]: """Load SPS1 payloads from a carve directory, a raw .bin file, or an .rpf archive.""" if os.path.isdir(target): - rows = gm._read_index_rows(target) + if rows is None: + rows = gm._read_index_rows(target) return _load_from_source(rows, lambda r: gm._read_row(target, r)) if not os.path.isfile(target): raise FileNotFoundError(target) @@ -322,6 +326,36 @@ def _public(payload: dict) -> dict: return {k: v for k, v in payload.items() if not k.startswith("_")} +def _write_json_atomic(path: str, payload: dict) -> None: + dest = os.path.realpath(path) + parent = os.path.dirname(dest) or "." + os.makedirs(parent, exist_ok=True) + fd, tmp = tempfile.mkstemp(dir=parent, prefix=".tmp-", suffix=".json") + try: + try: + f = os.fdopen(fd, "w", encoding="utf-8", newline="\n") + except BaseException: + os.close(fd) + raise + with f: + json.dump(payload, f, indent=1) + f.write("\n") + f.flush() + os.fsync(f.fileno()) + os.chmod(tmp, published_mode(dest)) + replace_retry(tmp, dest) + except BaseException: + try: + os.chmod(tmp, 0o600) + except OSError: + pass + try: + os.unlink(tmp) + except OSError: + pass + raise + + def main(argv=None) -> int: ap = argparse.ArgumentParser(description=__doc__.splitlines()[0]) ap.add_argument("target", help="rpf9_carve.py directory, common.rpf archive, or SPS1 .bin file") @@ -337,6 +371,12 @@ def main(argv=None) -> int: ap.error("--preset-hash expects up to eight hexadecimal digits") target_hash = int(a.preset_hash, 16) + if a.json is not None: + if not a.json.strip(): + ap.error("--json path must not be empty") + if a.json.endswith(("/", "\\")) or (os.sep and a.json.endswith(os.sep)): + ap.error(f"--json is a directory path: {a.json}") + # A missing input path is a usage error (exit 2), not a failed run, as in BUILD-1046. for path in (a.target, a.shaders): if path is not None and not os.path.exists(path): @@ -346,11 +386,12 @@ def main(argv=None) -> int: try: if a.json: check_report_path(a.json, a.target, a.shaders) + rows = None if os.path.isdir(a.target): rows = gm._read_index_rows(a.target) if a.json: check_report_path(a.json, a.target, a.shaders, rows=rows) - payloads = read_payloads(a.target) + payloads = read_payloads(a.target, rows=rows) xref = cross_reference_sgd5(payloads, a.shaders) if a.shaders else None matches = lookup_preset_hash(payloads, target_hash) if target_hash is not None else None except (OSError, ValueError, KeyError, TypeError, struct.error, RuntimeError) as e: @@ -387,9 +428,7 @@ def main(argv=None) -> int: if matches is not None: out["hash_matches"] = matches try: - gm._make_parent(a.json) - with open(a.json, "w", encoding="utf-8", newline="\n") as f: - json.dump(out, f, indent=1) + _write_json_atomic(a.json, out) except OSError as e: print(f"error: cannot write {a.json}: {e.strerror or e}", file=sys.stderr) return 1 diff --git a/tools/int_hw_probe.py b/tools/int_hw_probe.py index c76b659781..467fbfb6d6 100644 --- a/tools/int_hw_probe.py +++ b/tools/int_hw_probe.py @@ -57,7 +57,9 @@ sys.path.insert(0, p) import rdna2spirv # noqa: E402 +import replace_retry # noqa: E402 import spirv_mini_interp # noqa: E402 +from file_mode import published_mode # noqa: E402 STUB_DXBC = b"DXBC" + bytes(24) + struct.pack("> i & 1} # noqa: E731 - entry_ok &= len(set(lanes)) == len(lanes) and bits(e) == set(lanes) - wqm_ok &= len(w) == 1 and bits(w.pop() if len(w) == 1 else 0) == {4 * q + i for q in quads for i in range(4)} - packed &= quads == set(range(len(quads))) - detail.append(f"0x{e:016x}: {len(pix)} covered lanes in {len(quads)} quads") - out.append(("entry EXEC = the covered pixels (helpers off)", entry_ok, f"{len(waves)} waves: " + "; ".join(detail))) + for e, pix in sorted(waves.items()): + lanes = [lane[p] for p in pix] + quads = {ln // 4 for ln in lanes} + w = {wqm[p] for p in pix} + entry_ok &= len(set(lanes)) == len(lanes) and bits(e) == set(lanes) + wqm_ok &= len(w) == 1 and bits(w.pop() if len(w) == 1 else 0) == {4 * q + i for q in quads for i in range(4)} + packed &= quads == set(range(len(quads))) + detail.append(f"0x{e:016x}: {len(pix)} covered lanes in {len(quads)} quads") + waves_detail = f"{len(waves)} waves: " + "; ".join(detail) + else: + entry_ok = wqm_ok = packed = False + waves_detail = "0 waves (no covered pixels)" + out.append(("entry EXEC = the covered pixels (helpers off)", entry_ok, waves_detail)) out.append(("s_wqm turns on exactly the quads with a covered pixel", wqm_ok, "")) out.append(("quads packed from lane 0; none without a covered pixel", packed, "")) - order = {(p[0] & 1) + 2 * (p[1] & 1) == lane[p] % 4 for p in cov} - out.append(("lane % 4 = (x & 1) + 2 (y & 1): 0 top-left, 1 top-right, 2 bottom-left, 3 bottom-right", - order == {True}, "")) - err_c = max(max(abs(f32(res["self"][p][2]) - ndc(p, size)[0]), abs(f32(res["self"][p][3]) - ndc(p, size)[1])) - for p in cov) - err_h = 0.0 - for p, k in helpers: - got = {1: res["nb12"][p][0:2], 2: res["nb12"][p][2:4], 3: res["nb3"][p][0:2]}[k] - ex = ndc(neighbour(p, k), size) - err_h = max(err_h, abs(f32(got[0]) - ex[0]), abs(f32(got[1]) - ex[1])) - out.append(("after s_wqm a helper interpolates its own pixel centre, as precisely as a covered pixel", - err_h <= 1.5 * err_c + 1e-6, f"helper |error| max {err_h:.2e}, covered {err_c:.2e}")) - nm = res["nowqm_masks"] - out.append(("without s_wqm EXEC stays the entry mask", all( - (nm[p][1] | nm[p][2] << 32) == entry[p] and nm[p][3] == entry[p] & 0xFFFFFFFF for p in cov), "")) + if cov: + order = {(p[0] & 1) + 2 * (p[1] & 1) == lane[p] % 4 for p in cov} + out.append(("lane % 4 = (x & 1) + 2 (y & 1): 0 top-left, 1 top-right, 2 bottom-left, 3 bottom-right", + order == {True}, "")) + err_c = max(max(abs(f32(res["self"][p][2]) - ndc(p, size)[0]), abs(f32(res["self"][p][3]) - ndc(p, size)[1])) + for p in cov) + err_h = 0.0 + for p, k in helpers: + got = {1: res["nb12"][p][0:2], 2: res["nb12"][p][2:4], 3: res["nb3"][p][0:2]}[k] + ex = ndc(neighbour(p, k), size) + err_h = max(err_h, abs(f32(got[0]) - ex[0]), abs(f32(got[1]) - ex[1])) + out.append(("after s_wqm a helper interpolates its own pixel centre, as precisely as a covered pixel", + err_h <= 1.5 * err_c + 1e-6, f"helper |error| max {err_h:.2e}, covered {err_c:.2e}")) + nm = res["nowqm_masks"] + out.append(("without s_wqm EXEC stays the entry mask", all( + (nm[p][1] | nm[p][2] << 32) == entry[p] and nm[p][3] == entry[p] & 0xFFFFFFFF for p in cov), "")) + else: + out.append(("lane % 4 = (x & 1) + 2 (y & 1): 0 top-left, 1 top-right, 2 bottom-left, 3 bottom-right", + False, "no covered pixels")) + out.append(("after s_wqm a helper interpolates its own pixel centre, as precisely as a covered pixel", + False, "no covered pixels")) + out.append(("without s_wqm EXEC stays the entry mask", False, "no covered pixels")) h1 = [p for p in cov if neighbour(p, 1) not in cov] ij = {p: (f32(res["nowqm_ij"][p][0]), f32(res["nowqm_ij"][p][1])) for p in h1} err_ij = max([max(abs(g[0] - bary(neighbour(p, 1), size, tri)[0]), abs(g[1] - bary(neighbour(p, 1), size, tri)[1])) @@ -251,11 +266,69 @@ def _run(o): o.close() +def _validate_json_out(raw_path): + """Validate --json output path before running the GPU harness; return (abs_path, err_msg).""" + if not raw_path.strip(): + return None, "--json path must not be empty" + if raw_path.endswith(("/", "\\")) or (os.sep and raw_path.endswith(os.sep)): + return None, f"--json is a directory path: {raw_path}" + out_path = os.path.abspath(raw_path) + if os.path.isdir(out_path): + return None, f"--json is a directory: {out_path}" + cur = os.path.dirname(out_path) + while cur: + if os.path.exists(cur): + if not os.path.isdir(cur): + return None, f"--json parent path is not a directory: {cur}" + break + parent = os.path.dirname(cur) + if parent == cur: + break + cur = parent + return out_path, None + + +def _write_json_atomic(path, payload): + dest = os.path.realpath(path) + parent = os.path.dirname(dest) or "." + os.makedirs(parent, exist_ok=True) + fd, tmp = tempfile.mkstemp(dir=parent, prefix=".tmp-", suffix=".json") + try: + try: + f = os.fdopen(fd, "w", encoding="utf-8", newline="\n") + except BaseException: + os.close(fd) + raise + with f: + json.dump(payload, f, indent=1) + f.write("\n") + f.flush() + os.fsync(f.fileno()) + os.chmod(tmp, published_mode(dest)) + replace_retry(tmp, dest) + except BaseException: + try: + os.chmod(tmp, 0o600) + except OSError: + pass + try: + os.unlink(tmp) + except OSError: + pass + raise + + def main(argv=None): ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) ap.add_argument("--build", required=True, help="runtime build folder with vk_harness") ap.add_argument("--json", help="write {device, checks, words} here") a = ap.parse_args(argv) + out_path = None + if a.json is not None: + out_path, err_msg = _validate_json_out(a.json) + if err_msg: + print(f"ps_helper_probe: {err_msg}", file=sys.stderr) + return 2 try: device, res = measure(a.build) except ps_oracle.Unavailable as e: @@ -273,11 +346,17 @@ def main(argv=None): print(f"{'ok ' if ok else 'FAIL'} {name}" + (f" ({detail})" if detail else "")) good = sum(ok for _n, ok, _d in checks) print(f"{good}/{len(checks)} checks hold") - if a.json: - with open(a.json, "w", encoding="utf-8", newline="\n") as fh: - json.dump({"device": device, "checks": [[n, ok, d] for n, ok, d in checks], - "words": {n: {f"{x},{y}": list(w) for (x, y), w in px.items()} for n, px in res.items()}}, - fh, indent=1) + if out_path is not None: + payload = { + "device": device, + "checks": [[n, ok, d] for n, ok, d in checks], + "words": {n: {f"{x},{y}": list(w) for (x, y), w in px.items()} for n, px in res.items()}, + } + try: + _write_json_atomic(out_path, payload) + except OSError as e: + print(f"ps_helper_probe: cannot write {a.json}: {e.strerror or e}", file=sys.stderr) + return 2 return 0 if good == len(checks) else 1 diff --git a/tools/rdna2spirv.py b/tools/rdna2spirv.py index 95f11d961c..6b32d01024 100644 --- a/tools/rdna2spirv.py +++ b/tools/rdna2spirv.py @@ -420,6 +420,7 @@ def __init__(self, stage, hoist_reg_ptrs=False, cache_active=False): # single defining plain v_mov of it); valid I/J sources (SHADER-177) self.blocks = [] # per basic block: list of SPIR-V lines (dispatch-loop form), empty = straight-line self.succ = [] # per basic block: the blocks it can go to next (none = the program ends there) + self.out_pcs = None # per basic block: exact set of %pc values written (including cfg_structure.END) self.desc_fn = None # lines of the descriptor-lookup function, once an instruction needs it self.tbuffer_norm_fns: dict[int, list[str]] = {} # one exact quotient per used magnitude width self.fmt_fn = None # lines of the typed-buffer format-decode function, once a dynamic-format load needs it @@ -16505,7 +16506,7 @@ def assemble(gen): helpers.extend(function) for function in gen.x_round_fns.values(): helpers.extend(function) - tree, nesting = (capped_tree(gen.succ) if gen.blocks and not gen.emulate and not gen.bar_rounds + tree, nesting = (capped_tree(gen.succ, gen.out_pcs) if gen.blocks and not gen.emulate and not gen.bar_rounds else (None, None)) if nesting is not None: gen.nesting = nesting @@ -18298,6 +18299,7 @@ def target(ins): g.cu(n) raw_edges = split_edges succ = [list(dict.fromkeys(e)) for e in raw_edges] + g.out_pcs = _block_out_pcs(blocks, raw_edges, succ) g.vm_latch = stage == "ps" and exec_changes_after_vm(blocks, succ) g.park_masks((blocks, succ)) halves_analysis(g, blocks, succ) @@ -18577,14 +18579,34 @@ def finish_module(g): return spirv_loop_guard.add_guards(text, LOOP_LIMIT) -def capped_tree(succ): +def _block_out_pcs(blocks, raw_edges, succ): + """Possible `%pc` values each basic block can store (`cfg_structure.END` when the block can end the shader). + A conditional branch with no fallthrough block (`len(raw_edges[b]) == 1`, i.e. the last block or a split clone + of it) emits `OpSelect %uint cond tgt len(blocks)` and therefore writes either `tgt` or `END`.""" + out_pcs = {} + for b, blk in enumerate(blocks): + pcs = set(succ[b]) + if not pcs: + pcs.add(cfg_structure.END) + elif len(raw_edges[b]) == 1: + last = next((i for i in blk if base_op(i["op"]) == "s_endpgm" or base_op(i["op"]) in BRANCHES), None) + if last is not None and base_op(last["op"]) in BRANCHES and base_op(last["op"]) != "s_branch": + pcs.add(cfg_structure.END) + out_pcs[b] = frozenset(pcs) + return out_pcs + + +def capped_tree(succ, out_pcs=None): """(tree, nesting): the structured tree for `succ` and its depth, or (None, None) under --dispatch-loop or when cfg_structure can't structure it; tree is None (nesting still the measured depth) when it nests deeper than MAX_STRUCTURED_DEPTH. assemble() emits exactly this tree, and needs_barrier_rounds() decides from the same one (SHADER-427 review): a barrier in a tree that falls back to the dispatch loop isn't at a structured top level.""" - tree = cfg_structure.structure(succ) if STRUCTURED else None + if out_pcs is None: + out_pcs = {b: (set(succ[b]) if succ[b] else {cfg_structure.END}) for b in range(len(succ))} + tree = cfg_structure.structure(succ, out_pcs=out_pcs) if STRUCTURED else None if tree is None: return None, None + tree = cfg_structure.unwrap_known_pc_guards(tree, out_pcs) nesting = cfg_structure.depth(tree) if MAX_STRUCTURED_DEPTH and nesting > MAX_STRUCTURED_DEPTH: return None, nesting # too deep to validate cheaply: use the flat form @@ -18611,7 +18633,7 @@ def needs_barrier_rounds(g, blocks, succ): break if not with_barrier: return False - tree, _ = capped_tree(succ) # the tree assemble() emits: over MAX_STRUCTURED_DEPTH it's the dispatch loop + tree, _ = capped_tree(succ, g.out_pcs) # the tree assemble() emits: over MAX_STRUCTURED_DEPTH it's the dispatch loop top = {it[1] for it in tree if it[0] == "block"} if tree is not None else set() return not with_barrier <= top diff --git a/tools/script_qtable.py b/tools/script_qtable.py index 6c29a52602..d2e9096cfb 100644 --- a/tools/script_qtable.py +++ b/tools/script_qtable.py @@ -22,14 +22,17 @@ import os import struct import sys +import tempfile # -I keeps the script directory off sys.path, so add it explicitly before importing sibling helpers. TOOLS = os.path.dirname(os.path.abspath(__file__)) if TOOLS not in sys.path: sys.path.insert(0, TOOLS) +from file_mode import published_mode # noqa: E402 import gamedata_index as gi # noqa: E402 import gamedata_maps as gm # noqa: E402 +from replace_retry import replace as replace_retry # noqa: E402 from report_paths import same_report_path # noqa: E402 HEADER_BYTES = 40 @@ -480,12 +483,11 @@ def __init__(self, directory: str): if not os.path.isfile(full): continue sz = os.path.getsize(full) - try: - off = int(os.path.splitext(name)[0], 16) - except ValueError: - other_rows.append((name, sz)) + stem = os.path.splitext(name)[0] + if stem and all(c in "0123456789abcdefABCDEF" for c in stem): + hex_rows.append((int(stem, 16), name, sz)) else: - hex_rows.append((off, name, sz)) + other_rows.append((name, sz)) hex_rows.sort(key=lambda item: (item[0], item[1])) next_off = (hex_rows[-1][0] + 0x10000) if hex_rows else 0 self.rows = [{"off": off, "stored": sz, "size": sz, "_name": name} for off, name, sz in hex_rows] @@ -534,6 +536,10 @@ def load_qtable_payload(target: str) -> tuple[bytes, dict]: def check_report_path(out_path: str, target: str, rows: list[dict] | None = None) -> None: """Refuse a --json destination that is a directory or collides with any input.""" + if not out_path.strip(): + raise UsageError("--json path must not be empty") + if out_path.endswith(("/", "\\")) or (os.sep and out_path.endswith(os.sep)): + raise UsageError(f"--json is a directory path: {out_path}") if os.path.isdir(out_path): raise UsageError(f"--json is a directory: {out_path}") if os.path.isdir(target): @@ -589,6 +595,36 @@ def _print_summary(report: dict) -> None: ) +def _write_json_atomic(path: str, payload: dict) -> None: + dest = os.path.realpath(path) + parent = os.path.dirname(dest) or "." + os.makedirs(parent, exist_ok=True) + fd, tmp = tempfile.mkstemp(dir=parent, prefix=".tmp-", suffix=".json") + try: + try: + f = os.fdopen(fd, "w", encoding="utf-8", newline="\n") + except BaseException: + os.close(fd) + raise + with f: + json.dump(payload, f, indent=1) + f.write("\n") + f.flush() + os.fsync(f.fileno()) + os.chmod(tmp, published_mode(dest)) + replace_retry(tmp, dest) + except BaseException: + try: + os.chmod(tmp, 0o600) + except OSError: + pass + try: + os.unlink(tmp) + except OSError: + pass + raise + + def main(argv=None) -> int: ap = argparse.ArgumentParser(description=__doc__.splitlines()[0]) ap.add_argument("target", help="carved script directory, script.rpf archive, or joined .bin file") @@ -600,7 +636,7 @@ def main(argv=None) -> int: try: root_h = _parse_hex_u32(a.root_hash) if a.root_hash is not None else None type_h = _parse_hex_u32(a.type_hash) if a.type_hash is not None else None - if a.json: + if a.json is not None: rows = gm._read_index_rows(a.target) if os.path.isdir(a.target) and os.path.isfile(os.path.join(a.target, "index.json")) else None check_report_path(a.json, a.target, rows=rows) blob, meta = load_qtable_payload(a.target) @@ -621,11 +657,9 @@ def main(argv=None) -> int: out = {"location": meta, **report} _print_summary(out) - if a.json: + if a.json is not None: try: - gm._make_parent(a.json) - with open(a.json, "w", encoding="utf-8", newline="\n") as f: - json.dump(out, f, indent=1) + _write_json_atomic(a.json, out) except OSError as e: print(f"ERROR: cannot write {a.json}: {e.strerror or e}", file=sys.stderr) return 2 diff --git a/tools/wave64_emulate_opt.py b/tools/wave64_emulate_opt.py index d6e1ad7d5b..1ff464fd15 100644 --- a/tools/wave64_emulate_opt.py +++ b/tools/wave64_emulate_opt.py @@ -1105,70 +1105,8 @@ def _drop_tree_block(tree, b): def _unwrap_known_pc_guards(tree, out_pcs, entry_pc=0): - """Unwrap `("guard", g, body)` nodes whenever abstract interpretation proves `%pc == g` on all incoming paths. - - In `cfg_structure.structure`, every post-dominating join block `g` after a conditional diamond or loop is - still wrapped in `("guard", g, ...)`. Because `%pc` is a Function-scope variable in SPIR-V, LLVM/NVVM's - `SROA`/`Mem2Reg` promotes `%pc` at the same time as `%vgpr[0..255]` and `%sgpr[0..127]`, before `%pc == g` - can be constant-folded, forcing ~384 redundant Phi nodes at every spine guard merge block (and preventing - early block merging across convergent `OpControlBarrier`s). - - Tracks the exact finite set `cur_pc` of values `%pc` can hold before each item in `tree`: - - `("block", b)` overwrites `%pc` with `out_pcs[b]`. - - `("guard", g, gbody)`: if `cur_pc == {g}`, `%pc == g` is tautologically true on every path reaching - this item, so the guard unwraps in place; otherwise `gbody` is processed starting from `{g}` and its - exit `%pc` set merges with the skip path `cur_pc - {g}`. - - `("loop", h, lbody)`: `lbody` is processed starting from `cur_pc | {h}`; exiting the loop proves - `%pc != h`, leaving `pc_after_lbody - {h}`. - """ - root_out = [] - stack = [[collections.deque(tree), root_out, {entry_pc}, None]] - while stack: - frame = stack[-1] - q, dst, cur_pc, tag = frame - if not q: - if len(stack) > 1 and tag[0] == "guard" and len(cur_pc) == 1: - nxt_g = next(iter(cur_pc)) - skip_pc = tag[3] - parent_q = stack[-2][0] - if parent_q and parent_q[0][0] == "guard" and parent_q[0][1] == nxt_g and nxt_g not in skip_pc: - for child in reversed(parent_q.popleft()[2]): - q.appendleft(child) - continue - stack.pop() - if not stack: - break - parent = stack[-1] - if tag[0] == "guard": - _, g, child_dst, skip_pc = tag - parent[1].append(("guard", g, child_dst)) - parent[2] = skip_pc | cur_pc - else: - _, h, child_dst = tag - parent[1].append(("loop", h, child_dst)) - parent[2] = cur_pc - {h} - continue - it = q.popleft() - kind = it[0] - if kind == "block": - b = it[1] - dst.append(it) - frame[2] = set(out_pcs[b]) - elif kind == "guard": - g, gbody = it[1], it[2] - if cur_pc == {g}: - for child in reversed(gbody): - q.appendleft(child) - else: - child_dst = [] - skip_pc = set(cur_pc) - skip_pc.discard(g) - stack.append([collections.deque(gbody), child_dst, {g}, ("guard", g, child_dst, skip_pc)]) - else: - h, lbody = it[1], it[2] - child_dst = [] - stack.append([collections.deque(lbody), child_dst, set(cur_pc) | {h}, ("loop", h, child_dst)]) - return root_out + """Unwrap `("guard", g, body)` nodes whenever abstract interpretation proves `%pc == g` on all incoming paths.""" + return cfg_structure.unwrap_known_pc_guards(tree, out_pcs, entry_pc=entry_pc) def _region_has_cycle(region, succ): @@ -1357,7 +1295,8 @@ def find_local_exec_folds(blocks, raw_edges, succ, lane_masks, scc_live, mask_wr u = work.pop() if u == skip or u in region: continue - if u == b or u == 0 or not succ[u] or not blk_info[u][0]: + if (u == b or u == 0 or not succ[u] or not blk_info[u][0] + or (len(raw_edges[u]) == 1 and terms[u][0] == "br" and terms[u][1] != "s_branch")): ok = False break region.add(u) @@ -1611,23 +1550,26 @@ def plan_structured_emulation(blocks, raw_edges, succ, folds, fold_chain, absorb eff_succ[b] = nxt eff_succ_compact.append([eff_idx[s] for s in nxt]) - compact_tree = cfg_structure.structure(eff_succ_compact) - if compact_tree is None: - return None - tree = _map_tree_ids(compact_tree, eff_blocks) - out_pcs = {} for b in eff_blocks: tail = chain_of[b][-1] s = set(eff_succ[b]) if not s: - s.add(-1) + s.add(cfg_structure.END) elif tail not in folds and len(raw_edges[tail]) == 1: last = active_blocks[tail][-1] if active_blocks[tail] else None op = base_op(last["op"]) if last is not None else None if op in BRANCHES and op != "s_branch": - s.add(-1) + s.add(cfg_structure.END) out_pcs[b] = frozenset(s) + compact_out_pcs = { + eff_idx[b]: frozenset(eff_idx[p] if p != cfg_structure.END else cfg_structure.END for p in pcs) + for b, pcs in out_pcs.items() + } + compact_tree = cfg_structure.structure(eff_succ_compact, out_pcs=compact_out_pcs) + if compact_tree is None: + return None + tree = _map_tree_ids(compact_tree, eff_blocks) tree = _unwrap_known_pc_guards(tree, out_pcs, eff_blocks[0]) # Precompute per-superblock instruction summaries (for dirty transfer, sync-free check, s_barrier, s_endpgm).