diff --git a/docs/experiments.md b/docs/experiments.md index 9f7676bc80..8ccc6c0e0a 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -15963,7 +15963,7 @@ Past the entry block of a program with branches, the read does not copy the VGPR A lane that was inactive at the definition keeps an older VGPR value; the recomputed expression gives every lane the first active lane's value instead. `exec` need not be known at the definition. A conditional branch between the definition and the read is a fall-through, not a join, and is accepted. The one case where hardware can differ is a read with no active lane: it returns lane 0's VGPR, which the program cannot rely on. `tests/startup_gfx2hlsl_readfirstlane_recompute_check.py` checks the accepted forms (including one-path scalars and uniform loop counters both inside and after loops) and refuses each condition above, including a definition under a narrower `exec` than the read, a rewritten scalar input, a loop back edge, a divergent `else`-arm write before a join, a non-uniform loop back-edge and a join where two definitions reach. -A compute buffer load through a read-only descriptor and uniform address is also accepted past the entry block when the entry EXEC mask is still known. The lowering saves the uniform value in a function-scope temporary so the read uses the value held when the load ran, even if the offset scalar later changes. A narrowed mask may be empty. In that case RDNA 2 reads the previous lane-zero VGPR, which an unguarded reload cannot reproduce. Branch targets, EXEC writes and VGPR overwrites invalidate the proof between the load and read. The source-built controls cover scalar and vector addresses, the second dword, formatted loads, and a lane-zero sentinel followed by empty EXEC. +A compute buffer load through a read-only descriptor and uniform address is also accepted past the entry block when the entry EXEC mask is still known. The lowering saves the uniform value in a function-scope temporary so the read uses the value held when the load ran, even if the offset scalar later changes. A narrowed mask may be empty. In that case RDNA 2 reads the previous lane-zero VGPR, which an unguarded reload cannot reproduce. Branch targets, EXEC writes and VGPR overwrites invalidate the proof between the load and read. A loop may revisit the load after changing EXEC. The lowering follows control-flow edges from EXEC writers to catch this case, including detours outside the loop's instruction range. A loop that changes EXEC only after it exits still qualifies. The source-built controls cover scalar and vector addresses, the second dword, formatted loads, and a lane-zero sentinel followed by empty EXEC. [`tests/startup_compute_readfirstlane_check.py`](../tests/startup_compute_readfirstlane_check.py) pairs that unit coverage with a source-built gfx1013 compute fixture (`(4, 1, 1)` local threads x `(2, 1, 1)` groups) containing both a one-path SGPR across a uniform forward branch join and a four-iteration uniform loop counter read via `v_readfirstlane_b32` inside the loop and after exit, machine-code refusal patches (non-uniform `s_cbranch_vccnz` back-edge, divergent `else`/`then` write before a join, lane-mask loop update) and 320-word GPU readback with pinned `dropped-one-path`, `dropped-loop-read` and `dropped-post-loop` negative controls. Verified with zero mismatches and zero D3D12 debug-layer errors or warnings on Windows 11 25H2 (build 26200.9974) across WARP 10.0.26100.9818 and an AMD Radeon RX 7900 XTX (driver 32.0.32029.2010). diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index ece68590a3..5603900747 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -208,9 +208,12 @@ The translation is refused when: - either header has another size; - the code reads an attribute the table does not list. -The shader cache revision is `x2w-startup-shader-21`. Revision 21 refuses a compute lane-mask form that revision 20 translated (`s_and_b32 M, X, exec_lo` with X data, see docs/experiments.md), so its cached compute shaders are not reused. Revision 20 decodes MTBUF/MUBUF format 50 (`R10G10B10A2_UNORM`) in the run-time FORMAT switch, so cached shaders from revision 19 are not reused. Revision 19 folds `s_mov_b32` from a scalar register that -holds a plain constant, so later reads of the copy use the constant word. The matching compute -(`x2w-startup-shader-21cs`) key advances because that stage uses the shared lowering. The fixed slot 57 mesh +Graphics and compute use cache revisions `x2w-startup-shader-22` and `x2w-startup-shader-22cs`. +Revision 22 invalidates compute shaders that assumed the entry EXEC mask at a load reached on a later +loop iteration after an EXEC write. The two cache keys advance together. +Revision 21 refuses a compute lane-mask form that revision 20 translated (`s_and_b32 M, X, exec_lo` with X data). +Revision 20 decodes MTBUF/MUBUF format 50 (`R10G10B10A2_UNORM`) in the run-time FORMAT switch. +Revision 19 folds `s_mov_b32` from a scalar register that holds a plain constant, so later reads of the copy use the constant word. The fixed slot 57 mesh (`x2w-startup-mesh-57-3`) key stays, because that shader is not translated from guest code. Revisions before 19 read a register copied from a constant as a run-time value. Revision 18 preserves the sign of zero in floating-point min, max, min3, max3 and med3. @@ -2792,24 +2795,20 @@ hardware or driver glitch count. ## APU heap stand-in -With `X2W_AUDIO_PERMISSIVE=1`, `AcpHal.dll` serves `ApuAlloc` from the heap that `ApuCreateHeap` reserves -(`MEM_RESERVE`, 0 bytes committed up front). The heap is a first-fit free list in a static table of 4096 -extents, guarded by one lock. `ApuAlloc` commits the 4 KiB page span covering the allocated block on demand -(`MEM_COMMIT`), rolling back the free-list change and returning `E_OUTOFMEMORY` if commit fails. `ApuFree` -gives a block back, merges it with free neighbours, and decommits strictly interior 4 KiB pages -(`[ceil_page(free_begin), floor_page(free_end))` via `MEM_DECOMMIT`) so partial boundary pages shared with -live neighbours stay committed and streaming code that allocates and frees repeatedly no longer exhausts the -heap or commit charge. While nothing has been freed the offsets are the ones a bump allocator hands out. +With `X2W_AUDIO_PERMISSIVE=1`, `AcpHal.dll` serves `ApuAlloc` from the heap that `ApuCreateHeap` commits. The +heap is a first-fit free list in a static table of 4096 extents, guarded by one lock. `ApuFree` gives a +block back and merges it with free neighbours, so streaming code that allocates and frees repeatedly no +longer exhausts the heap. While nothing has been freed the offsets are the ones a bump allocator hands out. - A block is aligned in address (a power of two, 16 at least; 0, anything below 16 and a value that is not a power of two all mean 16). Size and alignment are 32 bits. `ApuCreateHeap` creates and publishes the heap under one lock, so competing first calls cannot reset a heap that already has live blocks. A heap whose 64 KiB-rounded size - exceeds 4 GiB is refused with `E_INVALIDARG` without reserving or committing memory, so every block fits the APU range. + exceeds 4 GiB is refused with `E_INVALIDARG` without committing memory, so every block fits the APU range. - Null or non-writable output (`virtual_address` or optional `apu_address`) is `E_POINTER` without - allocating; size 0 is `E_INVALIDARG`; no room, an offset past 32 bits, a full extent table, or a failed - page commit is `E_OUTOFMEMORY`. A refused call leaves the heap and the optional APU-address output as they were, + allocating; size 0 is `E_INVALIDARG`; no room, an offset past 32 bits, or a full extent table is + `E_OUTOFMEMORY`. A refused call leaves the heap and the optional APU-address output as they were, and writes null to the virtual-address output when writable. -- A block that is reused is zeroed, as fresh heap memory is (including still-committed shared boundary pages). +- A block that is reused is zeroed, as fresh heap memory is. - `ApuFree(NULL)` is `S_OK`. An address that does not start a live block (never allocated, inside a block, already freed) is `E_INVALIDARG` and changes nothing. - `ApuIsVirtualAddressValid` and the two map calls read the published heap bounds under the heap lock and @@ -2820,9 +2819,7 @@ The shape-context allocation (`AcpHalAllocateShapeContexts`, types other than 4) rolling back any already allocated XMA block and zeroing its output pointer and APU address. The source-built check loads the stub, checks non-permissive traps, cycles 64 MiB through a 2 MiB heap, checks reuse, alignment, coalescing, every refused call, shape-context allocation and partial-failure rollback, `AcpHalCreate`, and the -address validity/mapping exports, runs 4 threads of 1000 rounds against an interval map of live blocks, and -verifies on-demand commit, interior-page decommit, shared-boundary-page preservation, and commit-failure -rollback against `GetProcessMemoryInfo().PagefileUsage` and `VirtualQuery` in a 64 MiB heap: +address validity/mapping exports, then runs 4 threads of 1000 rounds against an interval map of live blocks: ``` ctest --preset dev --no-tests=error -R '^startup_acphal_apu_free$' -V diff --git a/src/startup_stubs/d3d12_draw.inl b/src/startup_stubs/d3d12_draw.inl index a59f9888aa..22a8ca3132 100644 --- a/src/startup_stubs/d3d12_draw.inl +++ b/src/startup_stubs/d3d12_draw.inl @@ -353,7 +353,7 @@ Translation* cached_translation(const void* a, std::size_t a_bytes, const void* { // Keep pre-fix desktop bytecode and manifests out of this ABI's cache. // tools/startup/gfx2hlsl.py hashes the same bytes, without a trailing NUL. - constexpr char revision[] = "x2w-startup-shader-21"; + constexpr char revision[] = "x2w-startup-shader-22"; const u64 seed = fnv_bytes(revision, sizeof(revision) - 1); u64 key = fnv_bytes(root_blob.data(), root_blob.size(), fnv_bytes(b, b_bytes, fnv_bytes(a, a_bytes, seed))); // A stream's input layout (stream_input_layout) feeds the vertex fetch, so it is part of the key. @@ -474,7 +474,7 @@ u64 publish_compute_request(const void* desc) std::vector fields(sizeof(words)); words[0] = words[1] = words[3] = words[5] = words[7] = words[9] = words[10] = 0; std::memcpy(fields.data(), words, sizeof(words)); - constexpr char compute_revision[] = "x2w-startup-shader-21cs"; // tools/startup/gfx2hlsl.py compute_key + constexpr char compute_revision[] = "x2w-startup-shader-22cs"; // tools/startup/gfx2hlsl.py compute_key u64 key = fnv_bytes(compute_revision, sizeof(compute_revision) - 1); const std::vector* order[] = {&code, &data, &root_blob, &fields, &state_a, &state_b}; for (const auto* part : order) key = fnv_part(*part, key); diff --git a/tests/startup_compute_request_offline_check.py b/tests/startup_compute_request_offline_check.py index 46042f18ff..cb5c4c0f58 100644 --- a/tests/startup_compute_request_offline_check.py +++ b/tests/startup_compute_request_offline_check.py @@ -25,12 +25,12 @@ DESC = struct.pack('<12Q', 0, 0, 24, 0, 20, 0, len(CODE), 0, len(DATA), 0, 0, 11) STATE_A = struct.pack('<3Q', 1, 0x2c, 0xfff0000000000003) STATE_B = struct.pack('<5I', 0x1234abcd, 0xffff0000, 0, 0, 0) -KEY = 0x90041d02ef75b4e9 # framed key at revision 21cs +KEY = 0x5159f6a85d77858e # framed key at revision 22cs def framed_key(): h = 1469598103934665603 - for b in b'x2w-startup-shader-21cs': + for b in b'x2w-startup-shader-22cs': h = ((h ^ b) * 1099511628211) & 0xffffffffffffffff for part in (CODE, DATA, ROOT, DESC, STATE_A, STATE_B): for b in struct.pack(' translated_pipeline(ID3D12Device* guest, ID3D12RootSignature* r bool needs_start, bool table_buffer = false, bool indexed = false, bool rect = false) { // The opaque guest programs identify synthetic cache entries. The actual bound shaders are source-built DXBC. - constexpr char revision[] = "x2w-startup-shader-21"; + constexpr char revision[] = "x2w-startup-shader-22"; static std::uint32_t vertex_ids[]{0xe0000101, 0xe0000102, 0xe0000103}; static std::uint32_t pixel_ids[]{0xe0000202, 0xe0000203, 0xe0000204}; auto& vertex_id = vertex_ids[indexed ? 2 : needs_start]; diff --git a/tests/startup_packed_position_provenance_check.py b/tests/startup_packed_position_provenance_check.py index c701eb64ec..03b27c1950 100644 --- a/tests/startup_packed_position_provenance_check.py +++ b/tests/startup_packed_position_provenance_check.py @@ -206,7 +206,7 @@ def refused(label, cache, key, reason): cache = Path(tmp) bare = G.pipeline_key(VS_WORDS, ps_words(4), root_blob()) check('without a description the key is unchanged', - bare == G.fnv(root_blob(), G.fnv(ps_words(4), G.fnv(VS_WORDS, G.fnv(b'x2w-startup-shader-21'))))) + bare == G.fnv(root_blob(), G.fnv(ps_words(4), G.fnv(VS_WORDS, G.fnv(b'x2w-startup-shader-22'))))) keys = [put_request(cache, ps_words(4), masks) for masks in (TARGET, SAME_V4, DECOY)] check('same stages, root and layout with three mask pairs: three request identities', len(set(keys)) == 3 and bare not in keys diff --git a/tests/startup_resource_retire_title.cpp b/tests/startup_resource_retire_title.cpp index f750b74376..526db906e3 100644 --- a/tests/startup_resource_retire_title.cpp +++ b/tests/startup_resource_retire_title.cpp @@ -403,7 +403,7 @@ constexpr UINT draw_side = 4; // 4x4 R8G8B8A8_UNORM target constexpr UINT draw_covered = 3; // scissor leaves the last row and column untouched as the sentinel constexpr int draw_seed = 77; constexpr UINT draw_clear_pixel = 0xffff00ffu; // ClearRenderTargetView({1, 0, 1, 1}) in R8G8B8A8_UNORM -constexpr char draw_revision[] = "x2w-startup-shader-21"; // d3d12_draw.inl cached_translation +constexpr char draw_revision[] = "x2w-startup-shader-22"; // d3d12_draw.inl cached_translation constexpr char draw_vertex_shader[] = R"( struct Varying { float4 position : SV_Position; }; diff --git a/tests/startup_shader_cache_key_check.py b/tests/startup_shader_cache_key_check.py index 8c6fccb3b9..670adeb669 100644 --- a/tests/startup_shader_cache_key_check.py +++ b/tests/startup_shader_cache_key_check.py @@ -49,10 +49,10 @@ def check_request(blobs, key, diagnostic=None, rtv_request=None, layout=None): def main(): # Independently executed C++ runtime fnv_bytes/cached_translation known-answer vector. - # Revision x2w-startup-shader-21 excludes NUL. Stored order is a, b, root, then optional input layout. + # Revision x2w-startup-shader-22 excludes NUL. Stored order is a, b, root, then optional input layout. vector = (b"\x00VS\xff", b"PS\x00\x80", b"RTS0\x00") - assert gfx2hlsl.pipeline_key(*vector) == 0x93a74e652d95daf6 - assert gfx2hlsl.pipeline_key(*vector, b"ia\x00\xfe") == 0x1ff6b039237188d6 + assert gfx2hlsl.pipeline_key(*vector) == 0x30009a5d8295d679 + assert gfx2hlsl.pipeline_key(*vector, b"ia\x00\xfe") == 0xdae7d34c534837e5 blobs = (VERTEX, PIXEL, ROOT) canonical = gfx2hlsl.pipeline_key(*blobs) check_request(blobs, canonical) diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index f317c53dd9..38ea83f121 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -2158,6 +2158,7 @@ class Stage: # per-instance sets, so nothing is shared across Stage instances. needs_sm6 = False # the lowering uses a shader model 6.0 intrinsic, so the stage cannot compile as 5.1 exec_known = False # unit probes without __init__ customize this explicitly when needed + loads_after_exec_write = () # compute loads reached from an EXEC writer through the block graph low16_only_v = () # VGPRs whose upper 16 bits are undefined after odd-dmask d16 image_load pinned_low16_v = () # low16_only_v live across basic-block boundaries whole_read_v = () # VGPRs read outside a proven low-16-bit consumer @@ -3373,6 +3374,24 @@ def translate(self): join_writes = self.join_writes(branches) refused = self.execz_refusals() if getattr(self, 'kind', None) == 'cs' else {} # probes skip __init__ joined, forward_splits, div_targets, self.spill_cfg = self.joined_registers(with_cfg=True) + self.loads_after_exec_write = set() + if (back_targets and getattr(self, 'kind', None) == 'cs' and + any(name in UNIFORM_LOADS for _, _, name, _ in self.ins)): + # A later block can reach an earlier load through one or more edges. exec_known only sees + # instructions already translated. Follow the CFG, including paths outside a loop's textual range. + bounds, _, succ, _ = self.spill_cfg + pending = [] + for block, (lo, hi) in enumerate(bounds): + if any(writes_exec(name, parse(asm)[1]) for _, _, name, asm in self.ins[lo:hi]): + pending.extend(succ[block]) + visited = set() + while pending: + block = pending.pop() + if block not in visited: + visited.add(block) + lo, hi = bounds[block] + self.loads_after_exec_write.update(pc for pc, _, name, _ in self.ins[lo:hi] if name in UNIFORM_LOADS) + pending.extend(succ[block]) self.spill_reach = self.spill_reaching(self.spill_cfg) init_sym = dict(self.sym) init_exec_known = getattr(self, 'exec_known', True) @@ -3939,7 +3958,7 @@ def one(self, name, asm): vaddr = reg_range(ops[1]) if load_form and ops[1] != 'off' else None exprs = getattr(self, 'uniform_expr', None) recomputed = (load_form and getattr(self, 'past_entry', False) and exprs is not None - and getattr(self, 'exec_known', False)) + and getattr(self, 'exec_known', False) and self.pc not in self.loads_after_exec_write) loaded_regs = () if loaded or recomputed: candidate = reg_range(ops[0]) @@ -10026,7 +10045,7 @@ def pipeline_key(vs_code, ps_code, root_blob, layout=b'', ps_inputs=None): SPI_PS_INPUT_ENA and SPI_PS_INPUT_ADDR as little-endian u32. Two pipelines with the same stages, root signature and input layout but different masks are then two requests with their own results. Without a description the key is unchanged.""" - key = fnv(root_blob, fnv(ps_code, fnv(vs_code, fnv(b'x2w-startup-shader-21')))) + key = fnv(root_blob, fnv(ps_code, fnv(vs_code, fnv(b'x2w-startup-shader-22')))) key = fnv(layout, key) if layout else key return key if ps_inputs is None else fnv(b'psin1' + struct.pack('