From 4b0156064f8625ac33cdaecb770c9fbb34774733 Mon Sep 17 00:00:00 2001 From: JB2WIN Date: Fri, 27 Nov 2026 14:21:21 +0100 Subject: [PATCH 1/3] native: read GPU-selected heap slots raw and typed in one program A program that reads some GPU-selected heap slots raw and others with a one-channel typed load was refused under both heap view contracts: raw_buffer refuses the typed load, typed_dword the raw load. HeapViewContract::raw_and_typed_dword now lets the kind of each heap load pick its path: buffer_load_format_* (typed_buffer_srv) takes the typed_dword rules, every other kind (tbuffer included) the raw_buffer rules, byte windows included. Which heap index feeds which load stays the caller's guarantee; the comment and the doc say so. .views gains zero or more "also " lines: further selections of the same dispatch, selector word k = selection k. The decoder refuses a slot named twice. refuse_global_srv_selections checks every selection; global_srv_contract returns raw_and_typed_dword when raw and typed selections are both present. compile_dxil and the fixture map the contract with a switch, and compile_dxil reports also=:. The fixture's record takes --also SELECTOR TYPE (selector word 1), dispatches every selected slot and compares against the sum of the slot data (N+M in replay). Tests: native_global_srv_heap_replay_check.py section 11 records, compiles (fresh frontend cache, then a cache hit) and replays a mixed program for raw slots 0 and 1 with typed slot 3, checks a cross-slot mismatch, a refused typed selection, three replay refusals, nine compile refusals and four compile-only cases (two also lines, byte window, formatted byte window, plain tbuffer under the mixed contract). Refs #3023 Co-Authored-By: Claude Opus 5.5 --- .../native-global-srv-heap-replay.md | 54 ++++++- src/direct_compute_cache.cpp | 7 +- src/gfx1013_compute_native.cpp | 8 +- src/gfx1013_compute_native.h | 14 +- src/gfx1013_direct_compute.inl | 23 +-- src/startup_stubs/native_global_srv.h | 69 ++++++++- tests/native_global_srv_heap_replay.cpp | 136 +++++++++++------ tests/native_global_srv_heap_replay_check.py | 140 +++++++++++++++++- tools/startup/compile_dxil.cpp | 23 ++- 9 files changed, 389 insertions(+), 85 deletions(-) diff --git a/docs/experiments/native-global-srv-heap-replay.md b/docs/experiments/native-global-srv-heap-replay.md index 3577e05e36..9657f2f90d 100644 --- a/docs/experiments/native-global-srv-heap-replay.md +++ b/docs/experiments/native-global-srv-heap-replay.md @@ -6,8 +6,8 @@ Issue #2908, branch `cpp-migration`. Builds on the heap read in the direct C++ D ## What changed - The direct compute translation takes a view contract for a GPU-selected heap slot (`x2w::HeapViewContract`: - `none`, `raw_buffer`, `other`). An SMEM descriptor load from the resource heap is refused unless the contract is - `raw_buffer`; without a contract the existing text stays: "direct resource-heap load requires the selected GPU slot and + `none`, `raw_buffer`, `typed_dword`, `raw_and_typed_dword`, `other`). An SMEM descriptor load from the resource heap + is refused unless the contract is `raw_buffer`, `typed_dword` or `raw_and_typed_dword`; without a contract the existing text stays: "direct resource-heap load requires the selected GPU slot and its view type". A scalar buffer load from the heap base, a heap descriptor load with an immediate offset or a constant index (both could address another slot than the captured selection), and a numeric use of a GPU-selected slot's stride in the direct path are refused with their own texts. The contract is part of the frontend cache key when it is @@ -30,6 +30,7 @@ Issue #2908, branch `cpp-migration`. Builds on the heap read in the direct C++ D x2w-global-srv-views 2 select need + also (zero or more, further selections of the same dispatch; selector word k = selection k) slot dword (after the slot lines; typed buffers of 32-bit channels only, #3023) ``` @@ -37,7 +38,8 @@ Issue #2908, branch `cpp-migration`. Builds on the heap read in the direct C++ D - `compile_dxil ... gfx1013-container-cs` reads an optional `req_.views` next to the `.cdx` (single file and `--requests`). It decodes the file, refuses a selection whose slot holds another view type than `need`, refuses a `need` other than `raw_buffer` or a one-channel 32-bit `typed_buffer` (#3023), translates with the matching contract and - prints `global_srv select= need=`. Every refusal happens before the `.cso` is published. Without the file a heap-reading shader is refused as before. The + prints `global_srv select= need=` (and ` also=:` for each further selection, which it checks the + same way and which must name distinct slots). Every refusal happens before the `.cso` is published. Without the file a heap-reading shader is refused as before. The `.views` file is not part of the `.cdx`/`.root` content key: it describes one captured dispatch. ## Meaning of "native recording" and "runtime path" here @@ -90,6 +92,17 @@ The check runs, in order: load (the loop does not contain the load) compiles, and the program with the full rewrite is recorded for selections 0 and 1 (output equals the slot's data), compiled by `compile_dxil --requests`, replayed with the same result, and replaying selection 0 against the slot 1 reference reports a mismatch. +10. Typed heap load (`typed_dword`): record, compile, frontend cache hit and replay of a `buffer_load_format_x` heap + load of slot 3, refusals of selections 0 and 2, and the compile refusals listed under the typed bullet below. +11. Mixed reads (`raw_and_typed_dword`, #3023): a program reads selector word 0 as a raw slot and selector word 1 as a + typed slot and stores the sum. The selector buffer has two words (programs that read word 0 only get 0 in word 1). + Record for raw slot 0 or 1 plus typed slot 3 (`--need raw_buffer --also 3 typed_buffer`), compile with a fresh + frontend cache, compile again (cache hit, same bytes), replay against the sum of the two slots' data, a mismatch + control against another sum, three replay refusals (`also` slot of another type, unknown slot, texture), a refused + record, nine compile refusals (the same program under raw-only and typed-only metadata, a texture `also`, a wrong + type, an unknown slot, an unreadable line, a duplicate slot, missing `dword` metadata, a two-channel typed load), + and four compile-only cases under the mixed contract (a second `also`, the byte window by `buffer_load_dword`, by + `tbuffer_load_format_x`, and a `tbuffer_load_format_x` through a plain heap descriptor). ## Result @@ -139,19 +152,38 @@ ctest --preset dev --no-tests=error -R "^native_global_srv_heap_replay(_warp|_ha `/heap-view/typed_dword`). `.views` gains a `dword ` line for each typed buffer slot of 32-bit channels; `compile_dxil` and the fixture derive the contract from `need typed_buffer` when every captured typed buffer slot is a one-channel 32-bit buffer (`x2w_startup::global_srv_contract`). `record` takes - `--need typed_buffer`. `native_global_srv_heap_replay_hardware` passes with 122 assertions: the typed load is + `--need typed_buffer`. `native_global_srv_heap_replay_hardware` passed with 122 assertions at that step: the typed load is recorded for slot 3 (`R32_UINT`), compiled, compiled again from the frontend cache, and replayed (output equals the slot 3 data); replaying it against slot 0 reports a mismatch; selections 0 and 2 are refused before the dispatch; ten compile refusals cover a two-channel load, a raw load and a `tbuffer` load under the typed contract, the typed load under the raw contract, and metadata without the `dword` line, with a channel count of 5, with a `dword` line for a raw slot, a duplicate or an early `dword` line, or with another selection. On the local capture (counts only) all 906 typed heap loads behind the raw contract have this one-channel `idxen` shape; with `typed_dword` forced by an uncommitted switch, 895 of those programs then stop at a - raw heap read of another slot: they read the heap both ways, which one captured selection does not cover. + raw heap read of another slot: they read the heap both ways, which one captured selection does not cover (the next + bullet adds `raw_and_typed_dword` for them). +- Mixed raw and typed heap reads (#3023): `HeapViewContract::raw_and_typed_dword` (cache identity + `/heap-view/raw_and_typed_dword`) lets one program read some heap slots raw and others typed. The kind of each load + picks the path: `buffer_load_format_*` (kind `typed_buffer_srv`) is typed, with the one-channel rule of + `typed_dword`; every other kind, `tbuffer_load_format_*` through a plain or rewritten heap descriptor included, is + raw, with the rules of `raw_buffer` (byte windows included). `.views` gains zero or more `also ` lines + (header unchanged; an older decoder refuses the file with `unknown line 'also'`). Selector word order: selection 0 is + `select`/`need`, selection k is the k-th `also` line, in file order. The decoder refuses a slot named twice among + `select` and `also`, also with the same type: one selection per selector word, a producer deduplicates. + `refuse_global_srv_selections` checks every selection in that order, and `global_srv_contract` returns + `raw_and_typed_dword` when raw and typed selections are both present. `native_global_srv_heap_replay_hardware` + passes with 174 assertions (section 11 above), in 11.5 s against 11.25 s before. On the local capture (counts only), + a prototype of this contract moved the compiled requests from 392 to 397; the others stop at general refusals (717 + `unbound numeric SGPR sN`, 460 `direct indexed descriptor load shape`, 291 `direct descriptor address outside bound + table`). That is an upper bound for what translation allows, not evidence that a runtime can meet the contract. Not + tested on the GPU: a swapped pairing (the typed selection first, the raw one second) makes the program read a typed + view through a raw handle and the reverse, which is undefined on the device and exactly the caller guarantee the + translator cannot check, so the GPU cases always record the raw selection first. ## Limits - Only raw buffer heap reads (`raw_buffer`) and one-channel 32-bit typed buffer heap reads (`typed_dword`) are - translated, one class per program; other view classes are refused with a named diagnostic. + translated, per program raw, typed, or both by load kind (`raw_and_typed_dword`); other view classes are refused with + a named diagnostic. - Under `typed_dword` the translator sees no descriptor values. The caller guarantees that every selectable slot is an `R32_UINT`, `R32_SINT` or `R32_FLOAT` buffer view bound as `R32_UINT` over the same element range, that the guest descriptor has stride 4, a 32-bit data format, identity `dst_sel_x`, swizzle and `add_tid` disabled, and that its @@ -178,7 +210,15 @@ ctest --preset dev --no-tests=error -R "^native_global_srv_heap_replay(_warp|_ha `max(stride, 1) * num_records` bytes (`indirect_table_buffer`, `src/startup_stubs/d3d12_draw.inl`), the guest window's byte count, or of the title's own view size for a view token. No fixture runs this manifest path for a window. -- Multi-channel typed heap loads, typed loads under the raw contract and scalar loads through the rewritten descriptor +- Under `raw_and_typed_dword` the caller guarantees the `raw_buffer` conditions for every slot a raw load or byte + window can select and the `typed_dword` conditions for every slot a typed load can select. The translator cannot tell + which heap index feeds which load, does not limit the number of heap loads and checks none of this; a program whose + heap loads use more selectors than were captured is outside what the capture proves, under every contract. A + `tbuffer_load_format_*` through a heap descriptor counts as raw. No capture-side producer writes `also` lines yet + (the runtime is a later stage); only the fixture's `record` does, with at most one `--also`, and its `replay` takes + at most one `also` selection. +- Multi-channel typed heap loads, typed loads under the raw contract (under `raw_and_typed_dword` they are translated) + and scalar loads through the rewritten descriptor stay refused. The startup runtime does not pass a contract yet, so none of this reaches a title run (#3023). - The captured `select` must be the slot index the dispatch addresses; producing it from a title capture is outside this diff --git a/src/direct_compute_cache.cpp b/src/direct_compute_cache.cpp index 8b8dcf0802..ce50e394ae 100644 --- a/src/direct_compute_cache.cpp +++ b/src/direct_compute_cache.cpp @@ -317,9 +317,10 @@ NativeComputeShader prepare_direct_compute(const std::filesystem::path &input, u identity += container ? "/container/cs_6_6" : "/slot67/cs_6_6"; word(identity, container ? 0 : entry); if (heap_view != HeapViewContract::none) - identity += heap_view == HeapViewContract::raw_buffer ? "/heap-view/raw_buffer" - : heap_view == HeapViewContract::typed_dword ? "/heap-view/typed_dword" - : "/heap-view/other"; + identity += heap_view == HeapViewContract::raw_buffer ? "/heap-view/raw_buffer" + : heap_view == HeapViewContract::typed_dword ? "/heap-view/typed_dword" + : heap_view == HeapViewContract::raw_and_typed_dword ? "/heap-view/raw_and_typed_dword" + : "/heap-view/other"; if (container) { packed = read_compute_container(input); identity += shader_digest(packed.bytes) + shader_digest(packed.root); diff --git a/src/gfx1013_compute_native.cpp b/src/gfx1013_compute_native.cpp index d37bf75178..82c36cbb7b 100644 --- a/src/gfx1013_compute_native.cpp +++ b/src/gfx1013_compute_native.cpp @@ -437,7 +437,7 @@ Symbol source(const Inst &i, unsigned code, const State &s) { unsigned memory_count(const Inst &i) { return 1u << (i.op & 7); } // Derive the rewritten byte-address V# symbolically. Each field carries its // source table/slot identity. Numeric consumption still requires real bits. -// heap_window: the direct path under HeapViewContract::raw_buffer also rewrites a +// heap_window: the direct path under HeapViewContract::raw_buffer or raw_and_typed_dword also rewrites a // descriptor loaded from the GPU-selected heap slot (its words keep the load pc). static std::optional byte_descriptor_field(const Inst &i, const State &s, bool heap_window = false) { using T = Symbol::Type; @@ -1506,8 +1506,10 @@ static NativeComputeShader translate_program(const ComputeRequest &request, unsi if (!stage && (UINT(layout->Desc_1_1.Flags) & 0xc00u) == 0xc00u && next + 2 == user) initial[next] = {Symbol::Type::table, compute_resource_heap}; const bool wave64 = stage && !stage->wave32; - // The byte-address rewrite of a GPU-selected heap descriptor is read only under the raw_buffer contract. - const bool heap_window = direct_dxil && heap_view == HeapViewContract::raw_buffer; + // The byte-address rewrite of a GPU-selected heap descriptor is read only under the raw_buffer or raw_and_typed_dword + // contract. + const bool heap_window = direct_dxil && (heap_view == HeapViewContract::raw_buffer || + heap_view == HeapViewContract::raw_and_typed_dword); auto program = parse(request.code, entry, initial, direct_dxil, false, wave64, false, heap_window); Emit emit{{}, program,layout->Desc_1_1}; emit.result.constants = constants; diff --git a/src/gfx1013_compute_native.h b/src/gfx1013_compute_native.h index 221522290e..fd33c20e56 100644 --- a/src/gfx1013_compute_native.h +++ b/src/gfx1013_compute_native.h @@ -118,15 +118,23 @@ struct NativeComputeShader { // Under raw_buffer the direct path also reads the byte-address rewrite of the selected descriptor (stride read, // max(stride, 1), byte count, stride cleared, raw out-of-bounds mode) as the same raw view. The caller guarantees that // every slot the program can select is a raw view whose size is the guest range num_records * max(stride, 1); the -// translator does not check that, nor the swizzle bits (word 1 bits 31:30) or the other word 3 fields, and a program -// with two heap loads from different selectors is outside what one captured selection covers. +// translator does not check that, nor the swizzle bits (word 1 bits 31:30) or the other word 3 fields. // typed_dword: only typed loads (buffer_load_format_x, an idxen element index or none, no offsets) read the heap; raw // loads and byte windows are refused. The caller guarantees that every slot the program can select is a typed buffer SRV // of R32_UINT, R32_SINT or R32_FLOAT (default mapping, no flags, no structure stride), bound as R32_UINT over the same // resource and element range, and that the guest descriptor it stands for has stride 4, a 32-bit UINT/SINT/FLOAT data // format, identity dst_sel_x, swizzle and add_tid disabled, and the out-of-bounds rule "index >= num_records reads 0", // with num_records equal to the view's element count. The translator checks none of these values. -enum class HeapViewContract : unsigned { none, raw_buffer, typed_dword, other }; +// raw_and_typed_dword: a program reads some heap slots raw (raw loads and byte windows, all raw_buffer rules) and others +// with typed loads (all typed_dword rules). Each heap load is emitted by its own kind: buffer_load_format_* (kind +// typed_buffer_srv, any channel count) takes the typed path, where more than one channel is refused as under +// typed_dword; every other kind, tbuffer_load_format_* through a plain or rewritten heap descriptor included, takes the +// raw path. The caller guarantees the raw_buffer conditions for every slot a raw load or byte window can select and +// the typed_dword conditions for every slot a typed load can select. The +// translator cannot tell which heap index feeds which load, does not limit the number of heap loads, and checks none of +// these conditions. Under every contract, a program whose heap loads use more selectors than were captured is outside +// what the capture proves. +enum class HeapViewContract : unsigned { none, raw_buffer, typed_dword, raw_and_typed_dword, other }; NativeComputeShader translate_compute(const ComputeRequest &request, unsigned entry_byte_offset, bool direct_dxil = false); NativeComputeShader translate_compute_container(ComputeContainer container, diff --git a/src/gfx1013_direct_compute.inl b/src/gfx1013_direct_compute.inl index d823ab0ca3..7738d837ff 100644 --- a/src/gfx1013_direct_compute.inl +++ b/src/gfx1013_direct_compute.inl @@ -26,7 +26,8 @@ struct DirectCompute { bool wave64 = false; // The view class a GPU-selected heap slot is read as; see HeapViewContract. HeapViewContract heap_view = HeapViewContract::none; - // heap_view is raw_buffer and the path is direct: the byte-address rewrite of a heap descriptor is tracked. + // heap_view is raw_buffer or raw_and_typed_dword and the path is direct: the byte-address rewrite of a heap + // descriptor is tracked. bool heap_window = false; // Binary16 add, sub, subrev and mul are lowered only while MODE stays at // the contract this path implements: round-to-nearest-even, f16 denormals @@ -271,7 +272,8 @@ struct DirectCompute { } } } - // Refuses a GPU-selected heap read that the contract does not cover. raw_buffer and typed_dword are translated. + // Refuses a GPU-selected heap read that the contract does not cover. raw_buffer, typed_dword and raw_and_typed_dword + // are translated. void refuse_heap_contract(unsigned pc) const { if (heap_view == HeapViewContract::none) refuse(pc, "direct resource-heap load requires the selected GPU slot and its view type"); @@ -284,11 +286,14 @@ struct DirectCompute { // A byte window is the byte-address rewrite of that descriptor (word 0 copied, word 1 without stride, word 2 the // byte count, word 3 with the raw out-of-bounds mode; see byte_descriptor_field): read as the same raw slot view. // Under typed_dword the slot is a one-channel 32-bit typed buffer instead: a typed load of one channel (an element - // index), read as R32_UINT; raw reads and byte windows are refused. + // index), read as R32_UINT; raw reads and byte windows are refused. Under raw_and_typed_dword the kind of the load + // picks the path: typed_buffer_srv is typed, every other kind is raw. string heap_resource(const Inst &i, const State &s, unsigned base, ComputeViewKind kind, unsigned bytes) { const auto &symbol = s.at(base); refuse_heap_contract(i.pc); - const bool typed = heap_view == HeapViewContract::typed_dword; + const bool typed = heap_view == HeapViewContract::typed_dword || + (heap_view == HeapViewContract::raw_and_typed_dword && + kind == ComputeViewKind::typed_buffer_srv); if (typed && kind != ComputeViewKind::typed_buffer_srv) refuse(i.pc, "a GPU-selected heap slot is read as a typed dword buffer SRV only"); if (typed && (i.op & 3)) @@ -502,7 +507,7 @@ struct DirectCompute { const auto &low = s.at(i.src[0]); const bool root = low.type == Symbol::Type::root_address; if (!root && low.type == Symbol::Type::table && low.value == compute_resource_heap) { - // Reads from the whole descriptor heap: only the indexed descriptor load of a captured raw buffer slot. + // Reads from the whole descriptor heap: only the indexed descriptor load of a slot under a heap contract. if (i.op >= 8) refuse(i.pc, "scalar buffer load from the descriptor heap is not translated"); refuse_heap_contract(i.pc); @@ -1673,10 +1678,10 @@ struct DirectCompute { const auto field = source(i, i.src[1], state); if (descriptor.type == Symbol::Type::indexed_descriptor && descriptor.value == compute_resource_heap && descriptor.offset % 32 == 4 && field.type == Symbol::Type::constant && field.value == 0xe0010) { - // Reachable only through a heap descriptor load, which needs the raw_buffer contract. A raw buffer view - // has no stride to read, so the stride of a GPU-selected slot stays untranslated in the direct path. - // With the raw_buffer contract a stride read into s0-s105 is tracked symbolically - // (byte_descriptor_field) and does not reach here. + // Reachable only through a heap descriptor load, which needs the raw_buffer or raw_and_typed_dword + // contract. A raw buffer view has no stride to read, so the stride of a GPU-selected slot stays + // untranslated in the direct path. With either contract a stride read into s0-s105 is tracked + // symbolically (byte_descriptor_field) and does not reach here. refuse_heap_contract(i.pc); refuse(i.pc, "a GPU-selected heap slot stride read is not translated with a view contract"); } diff --git a/src/startup_stubs/native_global_srv.h b/src/startup_stubs/native_global_srv.h index 10104b1996..73906bd09f 100644 --- a/src/startup_stubs/native_global_srv.h +++ b/src/startup_stubs/native_global_srv.h @@ -11,7 +11,7 @@ // The view type of a global (descriptor heap) SRV slot that a dispatch can select from GPU data. // -// A shader that picks its slot at run time can only be recorded and replayed if the type of every slot it may pick is +// A shader that picks its slots at run time can only be recorded and replayed if the type of every slot it may pick is // known: the capture keeps {slot, type, stride, bytes} for each slot of the heap (and the 32-bit channel count of a // typed buffer slot), and the dispatch is refused, before any shader runs, when the selected slot holds another type // than the one the shader reads. No heap-indexed data read is translated here; this header only classifies, @@ -68,10 +68,19 @@ inline bool classify_global_srv_view(unsigned heap_slot, const void *bytes, std: return true; } +// One selection of a dispatch: the slot a selector word names and the view type the shader reads it as. +struct GlobalSrvSelection { + unsigned slot = 0; + GlobalSrvType needed = GlobalSrvType::none; +}; + // One request's view metadata, the text that travels with a captured request (req_.views). struct GlobalSrvRequest { unsigned selected = 0; GlobalSrvType needed = GlobalSrvType::none; + // Further selections of the same dispatch. Selector word order: selection 0 is select/need, selection k (k >= 1) + // is also[k-1], in file order. + std::vector also; std::vector views; bool has_selected = false; }; @@ -79,6 +88,8 @@ struct GlobalSrvRequest { inline std::string encode_global_srv_request(const GlobalSrvRequest &request) { std::ostringstream out; out << "x2w-global-srv-views 2\nselect " << request.selected << "\nneed " << global_srv_type_name(request.needed) << '\n'; + for (const auto &selection : request.also) + out << "also " << selection.slot << ' ' << global_srv_type_name(selection.needed) << '\n'; for (const auto &view : request.views) out << "slot " << view.slot << ' ' << global_srv_type_name(view.type) << ' ' << view.stride << ' ' << view.bytes << '\n'; // After the slot lines: the 32-bit channel count of each typed buffer slot that has one. @@ -115,6 +126,19 @@ inline bool decode_global_srv_request(const std::string &text, GlobalSrvRequest return false; } has_need = true; + } else if (key == "also") { + GlobalSrvSelection selection; + std::string name; + if (!(fields >> selection.slot >> name)) { + error = "global SRV view metadata: unreadable also line"; + return false; + } + selection.needed = global_srv_type_from_name(name); + if (selection.needed == GlobalSrvType::none) { + error = "global SRV view metadata: unreadable also line"; + return false; + } + request.also.push_back(selection); } else if (key == "slot") { GlobalSrvView view; std::string name; @@ -150,6 +174,16 @@ inline bool decode_global_srv_request(const std::string &text, GlobalSrvRequest error = std::string("global SRV view metadata lacks the ") + (request.has_selected ? "needed view type" : "selected slot"); return false; } + // One selection per selector word: a slot named twice is refused, also with the same type (a producer deduplicates). + for (std::size_t a = 0; a <= request.also.size(); ++a) + for (std::size_t b = a + 1; b <= request.also.size(); ++b) { + const unsigned slot_a = a ? request.also[a - 1].slot : request.selected; + const unsigned slot_b = request.also[b - 1].slot; + if (slot_a == slot_b) { + error = "global SRV view metadata: duplicate selected slot " + std::to_string(slot_a); + return false; + } + } return true; } @@ -166,21 +200,40 @@ inline std::string refuse_global_srv_selection(const std::vector return "global SRV slot " + std::to_string(selected) + " has no captured view type"; } +// refuse_global_srv_selection for the select/need pair and then for each also entry in order; the first non-empty text +// wins. Call this, not the singular function, wherever a request is checked. +inline std::string refuse_global_srv_selections(const GlobalSrvRequest &request) { + auto text = refuse_global_srv_selection(request.views, request.selected, request.needed); + for (const auto &selection : request.also) { + if (!text.empty()) break; + text = refuse_global_srv_selection(request.views, selection.slot, selection.needed); + } + return text; +} + // The class of heap reads a request's metadata lets the translator emit (x2w::HeapViewContract::none, raw_buffer, -// typed_dword). Call after refuse_global_srv_selection accepted the selection. A typed request needs one-channel 32-bit -// typed buffers: the checks are necessary conditions on the captured resources only; the view's element range and the -// guest descriptor fields stay the caller's guarantee. -enum class GlobalSrvContract { none, raw_buffer, typed_dword }; +// typed_dword, raw_and_typed_dword). Call after refuse_global_srv_selections accepted the selections. A request with a +// typed selection needs one-channel 32-bit typed buffers: the checks are necessary conditions on the captured +// resources only; the view's element range and the guest descriptor fields stay the caller's guarantee. +enum class GlobalSrvContract { none, raw_buffer, typed_dword, raw_and_typed_dword }; inline GlobalSrvContract global_srv_contract(const GlobalSrvRequest &request, std::string &error) { const auto refuse = [&error](std::string text) { error = std::move(text) + "; only raw and one-channel 32-bit typed heap reads are translated"; return GlobalSrvContract::none; }; - if (request.needed == GlobalSrvType::raw_buffer) return GlobalSrvContract::raw_buffer; - if (request.needed != GlobalSrvType::typed_buffer) + bool raw = request.needed == GlobalSrvType::raw_buffer; + bool typed = request.needed == GlobalSrvType::typed_buffer; + if (!raw && !typed) return refuse(std::string("GPU-selected heap slot view type ") + global_srv_type_name(request.needed) + " is not raw_buffer or typed_buffer"); + for (const auto &selection : request.also) { + if (selection.needed != GlobalSrvType::raw_buffer && selection.needed != GlobalSrvType::typed_buffer) + return refuse(std::string("GPU-selected heap slot view type ") + global_srv_type_name(selection.needed) + + " is not raw_buffer or typed_buffer"); + (selection.needed == GlobalSrvType::raw_buffer ? raw : typed) = true; + } + if (!typed) return GlobalSrvContract::raw_buffer; // Every captured typed buffer slot, the selected one included, must be a one-channel 32-bit buffer. for (const auto &view : request.views) { if (view.type != GlobalSrvType::typed_buffer) continue; @@ -189,6 +242,6 @@ inline GlobalSrvContract global_srv_contract(const GlobalSrvRequest &request, st " is not a one-channel 32-bit typed buffer" + (view.dword_channels ? "" : " (no 32-bit channel metadata)")); } - return GlobalSrvContract::typed_dword; + return raw ? GlobalSrvContract::raw_and_typed_dword : GlobalSrvContract::typed_dword; } } // namespace x2w_startup diff --git a/tests/native_global_srv_heap_replay.cpp b/tests/native_global_srv_heap_replay.cpp index 72d6ebdd21..82f158750a 100644 --- a/tests/native_global_srv_heap_replay.cpp +++ b/tests/native_global_srv_heap_replay.cpp @@ -1,13 +1,15 @@ // Native compute fixture whose shader picks a global (descriptor heap) SRV slot from a GPU input. // // root OUT.root writes the root signature the request container carries. -// record SDK CACHE REQ.cdx ADAPTER SELECTOR EXPECT [--no-guard] -// Native recording path: reads the GPU selector back before the dispatch, captures {select, view types} -// into REQ.views, refuses a slot of another view type before the shader runs, otherwise records the -// dispatch with x2w_startup::NativeRecording and NativeDispatchStates and compares the fenced output. +// record SDK CACHE REQ.cdx ADAPTER SELECTOR EXPECT [--no-guard] [--need T] [--also SELECTOR T] +// Native recording path: reads the GPU selector words back before the dispatch (word 0 SELECTOR, word 1 the +// --also SELECTOR), captures {select, also, view types} into REQ.views, refuses a slot of another view type +// before the shader runs, otherwise records the dispatch with x2w_startup::NativeRecording and +// NativeDispatchStates and compares the fenced output. // replay SDK CACHE REQ.cdx COMPILED.cso VIEWS ADAPTER EXPECT REFERENCE_SLOT // Offline request replay: decodes VIEWS, refuses before the dispatch or runs the compiled.cso shader on a -// heap rebuilt from the captured slot types and compares with the reference slot data. +// heap rebuilt from the captured slot types and compares with the reference slot data. REFERENCE_SLOT is N, +// or N+M when the program sums two slots. // EXPECT is "ok" or "refused". Exit 0: outcome as expected. 1: output mismatch for an expected-ok case. 3: the // outcome differs from the expectation. 4: setup error. 77: capability skip. #include "desktop_gpu.h" @@ -16,11 +18,14 @@ #include "startup_stubs/native_global_srv.h" #include "startup_stubs/native_recording.h" #include +#include #include #include #include #include +#include #include +#include #include using Microsoft::WRL::ComPtr; @@ -165,14 +170,14 @@ struct Rig { // t0 (the selector, a raw buffer) and u0 (72 words of output) in their page slots. void create_io() { - selector = make_buffer(device.Get(), 4, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_STATE_COMMON); + selector = make_buffer(device.Get(), 8, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_STATE_COMMON); output = make_buffer(device.Get(), output_words * 4, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS); D3D12_SHADER_RESOURCE_VIEW_DESC srv{}; srv.Format = DXGI_FORMAT_R32_TYPELESS; srv.ViewDimension = D3D12_SRV_DIMENSION_BUFFER; srv.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; - srv.Buffer.NumElements = 1; + srv.Buffer.NumElements = 2; srv.Buffer.Flags = D3D12_BUFFER_SRV_FLAG_RAW; device->CreateShaderResourceView(selector.Get(), &srv, cpu(selector_page_slot)); D3D12_UNORDERED_ACCESS_VIEW_DESC uav{}; @@ -233,14 +238,17 @@ struct Rig { return view; } - unsigned read_selector(unsigned value) { - fill(selector.Get(), {value}); - return read(selector.Get(), 1)[0]; + // Both selector words; programs that read word 0 only get 0 in word 1. + std::array read_selector(std::array values) { + fill(selector.Get(), {values[0], values[1]}); + const auto words = read(selector.Get(), 2); + return {words[0], words[1]}; } // Barriers from the views of the dispatch (NativeDispatchStates), the dispatch, the barriers back, the fence. // `state` is the pipeline-state object to run (null: the one bind() set). - void dispatch(const x2w::NativeComputePipeline &pipeline, ID3D12PipelineState *state, ID3D12Resource *selected) { + void dispatch(const x2w::NativeComputePipeline &pipeline, ID3D12PipelineState *state, + const std::vector &selected) { struct View { ComPtr resource; bool write = false; @@ -250,7 +258,7 @@ struct Rig { std::vector views; views.push_back({selector, false, {}, {}}); views.push_back({output, true, {}, {}}); - views.push_back({selected, false, {}, {}}); + for (auto *resource : selected) views.push_back({resource, false, {}, {}}); x2w_startup::NativeDispatchStates states(views); std::vector before, after; states.whole_states([&](ID3D12Resource *resource, D3D12_RESOURCE_STATES target) { @@ -271,23 +279,30 @@ struct Rig { } }; -std::vector reference_output(unsigned slot) { +// Word i of the data part is the sum (mod 2^32) of word i of every slot; the sentinel words follow. +std::vector reference_output(const std::vector &slots) { std::vector words(output_words, sentinel); - for (unsigned i = 0; i < slot_words; ++i) words[i] = slot_word(slot, i); + for (unsigned i = 0; i < slot_words; ++i) { + words[i] = 0; + for (const unsigned slot : slots) words[i] += slot_word(slot, i); + } return words; } // 0: the 72 words equal the reference; 1 prints the first mismatch. -int compare_output(Rig &rig, unsigned reference_slot) { - const auto expected = reference_output(reference_slot); +int compare_output(Rig &rig, const std::vector &reference_slots) { + const auto expected = reference_output(reference_slots); + const std::string label = reference_slots.size() == 2 + ? std::to_string(reference_slots[0]) + "+" + std::to_string(reference_slots[1]) + : std::to_string(reference_slots.at(0)); const auto actual = rig.read(rig.output.Get(), output_words); for (unsigned i = 0; i < output_words; ++i) if (actual[i] != expected[i]) { - std::printf("mismatch word %u: got 0x%08x expected 0x%08x (reference slot %u)\n", i, actual[i], expected[i], - reference_slot); + std::printf("mismatch word %u: got 0x%08x expected 0x%08x (reference slot %s)\n", i, actual[i], expected[i], + label.c_str()); return 1; } - std::printf("output matches slot %u data (%u words) and the %u sentinel words are intact\n", reference_slot, + std::printf("output matches slot %s data (%u words) and the %u sentinel words are intact\n", label.c_str(), slot_words, output_words - slot_words); return 0; } @@ -330,26 +345,42 @@ void check_pipeline_shape(const x2w::NativeComputePipeline &pipeline) { // The pipeline contract a request's metadata allows; empty error when it is translated. x2w::HeapViewContract heap_contract(const x2w_startup::GlobalSrvRequest &request, std::string &error) { - const auto contract = x2w_startup::global_srv_contract(request, error); - return contract == x2w_startup::GlobalSrvContract::typed_dword ? x2w::HeapViewContract::typed_dword - : x2w::HeapViewContract::raw_buffer; + switch (x2w_startup::global_srv_contract(request, error)) { + case x2w_startup::GlobalSrvContract::none: return x2w::HeapViewContract::none; // the error is set + case x2w_startup::GlobalSrvContract::raw_buffer: return x2w::HeapViewContract::raw_buffer; + case x2w_startup::GlobalSrvContract::typed_dword: return x2w::HeapViewContract::typed_dword; + case x2w_startup::GlobalSrvContract::raw_and_typed_dword: return x2w::HeapViewContract::raw_and_typed_dword; + } + throw std::logic_error("unknown global SRV contract"); +} + +// A view type name given as a command-line argument: ASCII, anything else names no type. +GlobalSrvType type_from_argument(const wchar_t *argument) { + std::string name; + for (const wchar_t c : std::wstring_view(argument)) name += c < 0x80 ? static_cast(c) : '?'; + return x2w_startup::global_srv_type_from_name(name); } int record(int argc, wchar_t **argv) { - if (argc < 8 || argc > 11) return 2; + if (argc < 8 || argc > 14) return 2; const std::wstring expect = argv[7]; - bool guard = true, need_given = false; + bool guard = true, need_given = false, also_given = false; GlobalSrvType needed = GlobalSrvType::raw_buffer; + unsigned also_selector = 0; + GlobalSrvType also_needed = GlobalSrvType::none; for (int a = 8; a < argc; ++a) { const std::wstring_view flag = argv[a]; if (flag == L"--no-guard" && guard) { guard = false; } else if (flag == L"--need" && a + 1 < argc && !need_given) { need_given = true; - std::string name; // a view type name: ASCII, anything else names no type - for (const wchar_t c : std::wstring_view(argv[++a])) name += c < 0x80 ? static_cast(c) : '?'; - needed = x2w_startup::global_srv_type_from_name(name); + needed = type_from_argument(argv[++a]); if (needed == GlobalSrvType::none) return 2; + } else if (flag == L"--also" && a + 2 < argc && !also_given) { + also_given = true; + also_selector = static_cast(std::stoul(argv[++a])); + also_needed = type_from_argument(argv[++a]); + if (also_needed == GlobalSrvType::none) return 2; } else { return 2; } @@ -370,13 +401,16 @@ int record(int argc, wchar_t **argv) { request.views.push_back(rig.add_slot(3, GlobalSrvType::typed_buffer, slot_words * 4)); rig.fill_sentinel(); // The selector is GPU data: it is read back (one CPU/GPU sync) before the dispatch is recorded. - request.selected = rig.read_selector(selector); + const auto words = rig.read_selector({selector, also_selector}); + request.selected = words[0]; request.has_selected = true; + if (also_given) request.also.push_back({words[1], also_needed}); auto views_path = cdx; views_path.replace_extension(L".views"); std::ofstream(views_path, std::ios::binary) << x2w_startup::encode_global_srv_request(request); - std::printf("captured select=%u need=%s views=%s\n", request.selected, - x2w_startup::global_srv_type_name(request.needed), views_path.string().c_str()); + std::printf("captured select=%u need=%s also=%zu views=%s\n", request.selected, + x2w_startup::global_srv_type_name(request.needed), request.also.size(), + views_path.string().c_str()); // The contract depends on the captured views, not on the selection: the shader is translated for every record, // a refused selection included. std::string error; @@ -387,14 +421,22 @@ int record(int argc, wchar_t **argv) { } auto pipeline = x2w::create_native_compute_pipeline(rig.device.Get(), compiler, cdx, 0, argv[3], true, contract); check_pipeline_shape(pipeline); - const auto diagnostic = x2w_startup::refuse_global_srv_selection(request.views, request.selected, request.needed); + const auto diagnostic = x2w_startup::refuse_global_srv_selections(request); if (!diagnostic.empty() && guard) { std::printf("refused select=%u: %s\n", request.selected, diagnostic.c_str()); return refused_path(rig, expect == L"ok"); } - if (request.selected >= slot_count || request.views[request.selected].type != request.needed) - throw std::runtime_error("--no-guard only dispatches a slot of the needed view type"); - rig.dispatch(pipeline, nullptr, rig.slots[request.selected].Get()); + std::vector selections{{request.selected, request.needed}}; + selections.insert(selections.end(), request.also.begin(), request.also.end()); + std::vector selected; + std::vector selected_slots; + for (const auto &selection : selections) { + if (selection.slot >= slot_count || request.views[selection.slot].type != selection.needed) + throw std::runtime_error("--no-guard only dispatches a slot of the needed view type"); + selected.push_back(rig.slots[selection.slot].Get()); + selected_slots.push_back(selection.slot); + } + rig.dispatch(pipeline, nullptr, selected); if (expect == L"refused") { // Discrimination control: without the guard the shader ran, so the output must have changed. const bool intact = rig.sentinels_intact(); @@ -402,7 +444,7 @@ int record(int argc, wchar_t **argv) { intact ? "sentinels intact" : "sentinels changed"); return 3; } - return compare_output(rig, request.selected); + return compare_output(rig, selected_slots); } catch (const std::exception &error) { std::printf("setup error: %s\n", error.what()); return 4; @@ -414,7 +456,14 @@ int replay(int argc, wchar_t **argv) { const std::wstring expect = argv[8]; if (expect != L"ok" && expect != L"refused") return 2; const fs::path cdx = argv[4], cso = argv[5], views_path = argv[6]; - const unsigned reference_slot = static_cast(std::stoul(argv[9])); + std::vector reference_slots; + { + const std::wstring reference = argv[9]; + const auto plus = reference.find(L'+'); + reference_slots.push_back(static_cast(std::stoul(reference.substr(0, plus)))); + if (plus != std::wstring::npos) + reference_slots.push_back(static_cast(std::stoul(reference.substr(plus + 1)))); + } Rig rig; if (int skip = rig.open(argv[7])) return skip; try { @@ -429,8 +478,7 @@ int replay(int argc, wchar_t **argv) { text.assign(std::istreambuf_iterator(file), {}); x2w_startup::decode_global_srv_request(text, request, error); } - if (error.empty()) - error = x2w_startup::refuse_global_srv_selection(request.views, request.selected, request.needed); + if (error.empty()) error = x2w_startup::refuse_global_srv_selections(request); auto contract = x2w::HeapViewContract::raw_buffer; if (error.empty()) contract = heap_contract(request, error); if (!error.empty()) { @@ -448,13 +496,17 @@ int replay(int argc, wchar_t **argv) { pso.CS = {dxil.data(), dxil.size()}; ComPtr compiled; check(rig.device->CreateComputePipelineState(&pso, IID_PPV_ARGS(&compiled)), "compiled shader pipeline"); + if (request.also.size() > 1) + throw std::runtime_error("the fixture replays at most one also selection"); for (const auto &view : request.views) { if (view.slot >= slot_count) throw std::runtime_error("captured slot outside the fixture heap page"); rig.add_slot(view.slot, view.type, view.bytes); } - rig.read_selector(request.selected); - rig.dispatch(pipeline, compiled.Get(), rig.slots[request.selected].Get()); - const int result = compare_output(rig, reference_slot); + rig.read_selector({request.selected, request.also.empty() ? 0 : request.also[0].slot}); + std::vector selected{rig.slots[request.selected].Get()}; + for (const auto &selection : request.also) selected.push_back(rig.slots[selection.slot].Get()); + rig.dispatch(pipeline, compiled.Get(), selected); + const int result = compare_output(rig, reference_slots); if (expect == L"refused") return 3; // ran when a refusal was expected return result; } catch (const std::exception &error) { @@ -474,6 +526,6 @@ int wmain(int argc, wchar_t **argv) { return 4; } std::fputs("usage: native_global_srv_heap_replay root OUT.root | record SDK CACHE REQ.cdx ADAPTER SELECTOR ok|refused " - "[--no-guard] [--need raw_buffer|typed_buffer] | replay SDK CACHE REQ.cdx COMPILED.cso VIEWS ADAPTER ok|refused REFERENCE_SLOT\n", stderr); + "[--no-guard] [--need raw_buffer|typed_buffer] [--also SELECTOR raw_buffer|typed_buffer] | replay SDK CACHE REQ.cdx COMPILED.cso VIEWS ADAPTER ok|refused REFERENCE_SLOT|N+M\n", stderr); return 2; } diff --git a/tests/native_global_srv_heap_replay_check.py b/tests/native_global_srv_heap_replay_check.py index 048a12e3bd..e6212150cb 100644 --- a/tests/native_global_srv_heap_replay_check.py +++ b/tests/native_global_srv_heap_replay_check.py @@ -377,9 +377,9 @@ def typed_dir(name, program=TYPED): (directory / (typed_stem + ".root")).write_bytes(root) return directory, typed_stem - def typed_compile(directory, typed_stem, out_name): + def typed_compile(directory, typed_stem, out_name, cache_dir=cache): out_dir = base / out_name - code, out, err = run([compile_dxil, sdk, cache, "gfx1013-container-cs", "--requests", directory, out_dir]) + code, out, err = run([compile_dxil, sdk, cache_dir, "gfx1013-container-cs", "--requests", directory, out_dir]) return code, out, err, out_dir / (typed_stem[len("req_"):] + ".cs.cso") typed_selection = {} @@ -441,4 +441,140 @@ def typed_compile(directory, typed_stem, out_name): require(code == 1 and expected in err, f"compile_dxil '{name}': refused with '{expected}'") require(not any(cso.parent.glob("*.cso")), f"compile_dxil '{name}': no .cso") + # 11. Mixed raw and typed heap reads (HeapViewContract::raw_and_typed_dword): MIXED reads word 0 of the selector + # buffer as a raw slot (buffer_load_dword) and word 1 as a typed slot (buffer_load_format_x) and stores the + # sum, so u0 equals slot a + slot 3. The capture lists selection 0 as select/need and selection 1 as `also`. + # Assembled with LLVM 15 as above; the first selector word feeds the raw load, the second the typed load. + MIXED = [ + 0xbe810380, # s_mov_b32 s1, 0 + 0xbe830380, # s_mov_b32 s3, 0 + 0xf4080200, 0xfa000000, # s_load_dwordx4 s[8:11], s[0:1], 0x0 (t0: the two selector words) + 0xf4080300, 0xfa000020, # s_load_dwordx4 s[12:15], s[0:1], 0x20 (u0) + 0xf4240404, 0xfa000000, # s_buffer_load_dwordx2 s[16:17], s[8:11], 0x0 (word 0 raw slot, word 1 typed slot) + 0xbf8cc07f, # s_waitcnt lgkmcnt(0) + 0x8f128510, # s_lshl_b32 s18, s16, 5 + 0x8f138511, # s_lshl_b32 s19, s17, 5 + 0xf4080501, 0x24000000, # s_load_dwordx4 s[20:23], s[2:3], s18 (heap descriptor, raw slot) + 0xf4080601, 0x26000000, # s_load_dwordx4 s[24:27], s[2:3], s19 (heap descriptor, typed slot) + 0xbf8cc07f, # s_waitcnt lgkmcnt(0) + 0x34020082, # v_lshlrev_b32_e32 v1, 2, v0 + 0xe0301000, 0x80050201, # buffer_load_dword v2, v1, s[20:23], 0 offen + 0xe0002000, 0x80060300, # buffer_load_format_x v3, v0, s[24:27], 0 idxen + 0xbf8c3f70, # s_waitcnt vmcnt(0) + 0x4a040702, # v_add_nc_u32_e32 v2, v2, v3 + 0xe0701000, 0x80030201, # buffer_store_dword v2, v1, s[12:15], 0 offen + 0xbf810000, # s_endpgm + ] + MIXED_OK = "output matches slot {a}+3 data" + # Its own frontend cache, so that the first compile of each program here translates. + cache11 = base / "cache11" + cache11.mkdir() + + mixed = {} + for a in (0, 1): + directory, mixed_stem = typed_dir(f"mixed{a}", MIXED) + code, out, err = run([fixture, "record", sdk, cache, directory / (mixed_stem + ".cdx"), adapter, a, "ok", + "--need", "raw_buffer", "--also", 3, "typed_buffer"]) + require(code == 0 and MIXED_OK.format(a=a) in out, + f"record mixed select {a}+3: u0 equals the sum of the slot {a} and slot 3 data") + text = (directory / (mixed_stem + ".views")).read_text() + require(text.startswith("x2w-global-srv-views 2\nselect %d\nneed raw_buffer\nalso 3 typed_buffer\n" % a) and + "dword 3 1\n" in text, f"record mixed select {a}+3 captured both selections and the slot 3 channel count") + mixed[a] = (directory, mixed_stem) + MV = (mixed[0][0] / (mixed[0][1] + ".views")).read_text() + + mixed_cso = {} + for a in (0, 1): + directory, mixed_stem = mixed[a] + code, out, err, cso = typed_compile(directory, mixed_stem, f"mixed{a}_out", cache_dir=cache11) + require(code == 0 and "requests=1 compiled=1 refused=0" in out and cso.exists(), + f"compile_dxil mixed select {a}+3: compiled and published a .cso") + require(f"global_srv select={a} need=raw_buffer also=3:typed_buffer" in out, + f"compile_dxil mixed select {a}+3: reports both selections") + if a == 0: + require("frontend_cache_hit=0" in out, "compile_dxil mixed select 0+3: translated (fresh frontend cache)") + mixed_cso[a] = cso + directory, mixed_stem = mixed[0] + code, out, err, again = typed_compile(directory, mixed_stem, "mixed0_again", cache_dir=cache11) + require(code == 0 and "frontend_cache_hit=1" in out and again.read_bytes() == mixed_cso[0].read_bytes(), + "compile_dxil mixed select 0+3 again: frontend cache hit, same .cso") + + for a in (0, 1): + directory, mixed_stem = mixed[a] + code, out, err = run([fixture, "replay", sdk, cache, directory / (mixed_stem + ".cdx"), mixed_cso[a], + directory / (mixed_stem + ".views"), adapter, "ok", f"{a}+3"]) + require(code == 0 and MIXED_OK.format(a=a) in out, f"replay mixed select {a}+3: output equals the sum of the slot data") + directory, mixed_stem = mixed[0] + code, out, err = run([fixture, "replay", sdk, cache, directory / (mixed_stem + ".cdx"), mixed_cso[0], + directory / (mixed_stem + ".views"), adapter, "ok", "1+3"]) + require(code == 1 and "mismatch word 0" in out, "replay mixed select 0+3 compared with slots 1+3 reports a mismatch") + + # Replay refusals: edited metadata, same compiled shader, nothing dispatched. + mixed_replay_refusals = { + "also_raw": ("also 3 typed_buffer", "also 3 raw_buffer", RAW.format(n=3, t="typed_buffer")), + "also_unknown": ("also 3 typed_buffer", "also 9 typed_buffer", "global SRV slot 9 has no captured view type"), + "also_texture": ("also 3 typed_buffer", "also 2 texture", + "GPU-selected heap slot view type texture is not raw_buffer or typed_buffer"), + } + for name, (old, new, expected) in mixed_replay_refusals.items(): + require(old in MV, f"mixed replay refusal '{name}' edits an existing line") + edited = base / f"mixed_{name}.views" + edited.write_text(MV.replace(old, new), newline="\n") + code, out, err = run([fixture, "replay", sdk, cache, directory / (mixed_stem + ".cdx"), mixed_cso[0], edited, + adapter, "refused", "0+3"]) + require(code == 0 and expected in out and "no dispatch submitted" in out and "sentinels intact" in out, + f"replay mixed '{name}': refused with '{expected}', nothing dispatched") + + # The second selection names a raw slot that the shader's typed view cannot stand for: refused before the dispatch. + directory, mixed_stem = typed_dir("mixed_refused", MIXED) + code, out, err = run([fixture, "record", sdk, cache, directory / (mixed_stem + ".cdx"), adapter, 0, "refused", + "--need", "raw_buffer", "--also", 1, "typed_buffer"]) + require(code == 0 and TYPED_RAW.format(n=1, t="raw_buffer") in out and "no dispatch submitted" in out and + "sentinels intact" in out, "record mixed select 0+1 as typed: refused before the dispatch") + + # compile_dxil negatives, no .cso. The first two are the translator-level controls: the same program under a + # contract that is not the mixed one. + typed_xy = typed_program((0xe0042000, 0x80050200)) # buffer_load_format_xy v[2:3], v0, s[20:23], 0 idxen + mixed_negatives = { + "mixed_raw_views": (MIXED, good, "a GPU-selected heap slot is read as a raw buffer SRV only"), + "mixed_typed_views": (MIXED, typed_views, TYPED_ONLY), + "mixed_texture": (MIXED, MV.replace("also 3 typed_buffer", "also 2 texture"), + "GPU-selected heap slot view type texture is not raw_buffer or typed_buffer"), + "mixed_wrong_type": (MIXED, MV.replace("also 3 typed_buffer", "also 3 raw_buffer"), RAW.format(n=3, t="typed_buffer")), + "mixed_unknown_slot": (MIXED, MV.replace("also 3 typed_buffer", "also 9 typed_buffer"), + "global SRV slot 9 has no captured view type"), + "mixed_unreadable": (MIXED, MV.replace("also 3 typed_buffer", "also x y"), + "global SRV view metadata: unreadable also line"), + "mixed_duplicate": (MIXED, MV.replace("also 3 typed_buffer", "also 0 typed_buffer"), + "global SRV view metadata: duplicate selected slot 0"), + "mixed_no_dword": (MIXED, MV.replace("dword 3 1\n", ""), + "GPU-selected heap slot 3 is not a one-channel 32-bit typed buffer (no 32-bit channel metadata)"), + "mixed_typed_xy": (typed_xy, MV, "typed heap load reads one channel only"), + } + for name, (program, views_text, expected) in mixed_negatives.items(): + require(views_text != MV or name == "mixed_typed_xy", f"mixed negative '{name}' changes the metadata") + directory, mixed_stem = typed_dir("neg_" + name, program) + (directory / (mixed_stem + ".views")).write_text(views_text, newline="\n") + code, out, err, cso = typed_compile(directory, mixed_stem, "neg_" + name + "_out", cache_dir=cache11) + require(code == 1 and expected in err, f"compile_dxil '{name}': refused with '{expected}'") + require(not any(cso.parent.glob("*.cso")), f"compile_dxil '{name}': no .cso") + + # compile_dxil positives, compile only: a second `also`, and the raw-path programs under the mixed contract (byte + # windows by the rewrite, a formatted tbuffer load through a plain or rewritten heap descriptor). + mixed_positives = { + "mixed_two_also": (MIXED, MV + "also 1 raw_buffer\n"), + "mixed_window": (WINDOW, MV), + "mixed_twindow": (TWINDOW, MV), + # tbuffer_load_format_x v2, v1, s[20:23], 0 format:[BUF_FMT_32_UINT] offen: refused under typed_dword + "mixed_tbuffer": (typed_program((0xe8a01000, 0x80050201)), MV), + } + for name, (program, views_text) in mixed_positives.items(): + directory, mixed_stem = typed_dir("pos_" + name, program) + (directory / (mixed_stem + ".views")).write_text(views_text, newline="\n") + code, out, err, cso = typed_compile(directory, mixed_stem, "pos_" + name + "_out", cache_dir=cache11) + require(code == 0 and "requests=1 compiled=1 refused=0" in out and cso.exists(), + f"compile_dxil '{name}': compiled under the mixed contract") + if name == "mixed_two_also": + require("also=3:typed_buffer also=1:raw_buffer" in out, "compile_dxil 'mixed_two_also': reports both also entries") + print("native_global_srv_heap_replay: all checks passed") diff --git a/tools/startup/compile_dxil.cpp b/tools/startup/compile_dxil.cpp index c607a39183..67de62011e 100644 --- a/tools/startup/compile_dxil.cpp +++ b/tools/startup/compile_dxil.cpp @@ -70,13 +70,17 @@ static CapturedViews read_captured_views(const fs::path& request_path) { if (!x2w_startup::decode_global_srv_request(text, views.request, error)) throw std::runtime_error(error); views.present = true; const auto& request = views.request; - auto refusal = x2w_startup::refuse_global_srv_selection(request.views, request.selected, request.needed); + auto refusal = x2w_startup::refuse_global_srv_selections(request); if (!refusal.empty()) throw std::runtime_error(refusal); - const auto contract = x2w_startup::global_srv_contract(request, error); - if (contract == x2w_startup::GlobalSrvContract::none) throw std::runtime_error(error); - views.contract = contract == x2w_startup::GlobalSrvContract::typed_dword ? x2w::HeapViewContract::typed_dword - : x2w::HeapViewContract::raw_buffer; - return views; + switch (x2w_startup::global_srv_contract(request, error)) { + case x2w_startup::GlobalSrvContract::none: throw std::runtime_error(error); + case x2w_startup::GlobalSrvContract::raw_buffer: views.contract = x2w::HeapViewContract::raw_buffer; return views; + case x2w_startup::GlobalSrvContract::typed_dword: views.contract = x2w::HeapViewContract::typed_dword; return views; + case x2w_startup::GlobalSrvContract::raw_and_typed_dword: + views.contract = x2w::HeapViewContract::raw_and_typed_dword; + return views; + } + throw std::logic_error("unknown global SRV contract"); } static std::vector compile_to_dxil(x2w::ShaderDxilCompiler& compiler, const std::string& source, @@ -134,10 +138,13 @@ static std::optional compile_one(x2w::ShaderDxilCompiler& compiler, const bool heap_read=std::any_of(program.bindings.begin(),program.bindings.end(),[](const auto& b){ return x2w::compute_heap_binding(b.kind) || b.kind==x2w::ComputeViewKind::heap_stride_srv;}); if(heap_read){ - auto refusal=x2w_startup::refuse_global_srv_selection(views.request.views,views.request.selected,views.request.needed); + auto refusal=x2w_startup::refuse_global_srv_selections(views.request); if(!refusal.empty())throw std::runtime_error(refusal); } - report<<"global_srv select="< Date: Fri, 27 Nov 2026 23:53:11 +0100 Subject: [PATCH 2/3] native: accept a repeated heap selection with the same view type The selector word k is selection k, so two words can pick the same slot. The decoder now accepts a slot named again with the same view type and refuses only a slot named with two view types, so a file record writes decodes. An also line with trailing fields is unreadable. A bad --also selector in the fixture returns 2. Section 11 gains the second-also, repeated-slot, two-type and trailing-field cases and a raw+raw record, compile and replay of one slot picked by both words. The stride-read comment now names all three contracts. Co-Authored-By: Claude Opus 5.5 --- .../native-global-srv-heap-replay.md | 26 ++++++---- src/gfx1013_direct_compute.inl | 9 ++-- src/startup_stubs/native_global_srv.h | 14 +++--- tests/native_global_srv_heap_replay.cpp | 6 ++- tests/native_global_srv_heap_replay_check.py | 49 ++++++++++++++++++- 5 files changed, 81 insertions(+), 23 deletions(-) diff --git a/docs/experiments/native-global-srv-heap-replay.md b/docs/experiments/native-global-srv-heap-replay.md index 9657f2f90d..b7e7204610 100644 --- a/docs/experiments/native-global-srv-heap-replay.md +++ b/docs/experiments/native-global-srv-heap-replay.md @@ -39,7 +39,7 @@ Issue #2908, branch `cpp-migration`. Builds on the heap read in the direct C++ D `--requests`). It decodes the file, refuses a selection whose slot holds another view type than `need`, refuses a `need` other than `raw_buffer` or a one-channel 32-bit `typed_buffer` (#3023), translates with the matching contract and prints `global_srv select= need=` (and ` also=:` for each further selection, which it checks the - same way and which must name distinct slots). Every refusal happens before the `.cso` is published. Without the file a heap-reading shader is refused as before. The + same way; a slot may be named again with the same view type, not with two). Every refusal happens before the `.cso` is published. Without the file a heap-reading shader is refused as before. The `.views` file is not part of the `.cdx`/`.root` content key: it describes one captured dispatch. ## Meaning of "native recording" and "runtime path" here @@ -99,10 +99,14 @@ The check runs, in order: Record for raw slot 0 or 1 plus typed slot 3 (`--need raw_buffer --also 3 typed_buffer`), compile with a fresh frontend cache, compile again (cache hit, same bytes), replay against the sum of the two slots' data, a mismatch control against another sum, three replay refusals (`also` slot of another type, unknown slot, texture), a refused - record, nine compile refusals (the same program under raw-only and typed-only metadata, a texture `also`, a wrong - type, an unknown slot, an unreadable line, a duplicate slot, missing `dword` metadata, a two-channel typed load), - and four compile-only cases under the mixed contract (a second `also`, the byte window by `buffer_load_dword`, by - `tbuffer_load_format_x`, and a `tbuffer_load_format_x` through a plain heap descriptor). + record, thirteen compile refusals (the same program under raw-only and typed-only metadata, a texture `also`, a wrong + type, an unknown slot, an unreadable line, an `also` line with a trailing field, a slot named with two types + (the selected slot and an `also` slot), a second `also` of another type than its slot and a texture second `also`, + missing `dword` metadata, a two-channel typed load), and six compile-only cases under the mixed contract (a second `also`, an `also` naming the selected + slot again with the same type, the same `also` twice, the byte window by `buffer_load_dword`, by + `tbuffer_load_format_x`, and a `tbuffer_load_format_x` through a plain heap descriptor). A raw-only program + whose two selector words pick the same raw slot is recorded (`--also` with the selected slot), compiled and replayed + against twice that slot's data (`N+N`). ## Result @@ -167,11 +171,13 @@ ctest --preset dev --no-tests=error -R "^native_global_srv_heap_replay(_warp|_ha `typed_dword`; every other kind, `tbuffer_load_format_*` through a plain or rewritten heap descriptor included, is raw, with the rules of `raw_buffer` (byte windows included). `.views` gains zero or more `also ` lines (header unchanged; an older decoder refuses the file with `unknown line 'also'`). Selector word order: selection 0 is - `select`/`need`, selection k is the k-th `also` line, in file order. The decoder refuses a slot named twice among - `select` and `also`, also with the same type: one selection per selector word, a producer deduplicates. + `select`/`need`, selection k is the k-th `also` line, in file order. The decoder accepts a slot named again among + `select` and `also` with the same view type (two selector words can pick the same slot; the order is kept and `replay` + writes the repeated slot to its word) and refuses a slot named with two view types + (`slot N selected with two view types`). An `also` line with trailing fields is unreadable. `refuse_global_srv_selections` checks every selection in that order, and `global_srv_contract` returns `raw_and_typed_dword` when raw and typed selections are both present. `native_global_srv_heap_replay_hardware` - passes with 174 assertions (section 11 above), in 11.5 s against 11.25 s before. On the local capture (counts only), + passes with 196 assertions (section 11 above), in 12.5 s against 11.25 s before. On the local capture (counts only), a prototype of this contract moved the compiled requests from 392 to 397; the others stop at general refusals (717 `unbound numeric SGPR sN`, 460 `direct indexed descriptor load shape`, 291 `direct descriptor address outside bound table`). That is an upper bound for what translation allows, not evidence that a runtime can meet the contract. Not @@ -215,8 +221,8 @@ ctest --preset dev --no-tests=error -R "^native_global_srv_heap_replay(_warp|_ha which heap index feeds which load, does not limit the number of heap loads and checks none of this; a program whose heap loads use more selectors than were captured is outside what the capture proves, under every contract. A `tbuffer_load_format_*` through a heap descriptor counts as raw. No capture-side producer writes `also` lines yet - (the runtime is a later stage); only the fixture's `record` does, with at most one `--also`, and its `replay` takes - at most one `also` selection. + (the runtime is a later stage); only the fixture's `record` does, with at most one `--also` (a non-numeric selector + exits 2 like the other usage errors), and its `replay` takes at most one `also` selection. - Multi-channel typed heap loads, typed loads under the raw contract (under `raw_and_typed_dword` they are translated) and scalar loads through the rewritten descriptor stay refused. The startup runtime diff --git a/src/gfx1013_direct_compute.inl b/src/gfx1013_direct_compute.inl index 7738d837ff..d7489e8f59 100644 --- a/src/gfx1013_direct_compute.inl +++ b/src/gfx1013_direct_compute.inl @@ -1678,10 +1678,11 @@ struct DirectCompute { const auto field = source(i, i.src[1], state); if (descriptor.type == Symbol::Type::indexed_descriptor && descriptor.value == compute_resource_heap && descriptor.offset % 32 == 4 && field.type == Symbol::Type::constant && field.value == 0xe0010) { - // Reachable only through a heap descriptor load, which needs the raw_buffer or raw_and_typed_dword - // contract. A raw buffer view has no stride to read, so the stride of a GPU-selected slot stays - // untranslated in the direct path. With either contract a stride read into s0-s105 is tracked - // symbolically (byte_descriptor_field) and does not reach here. + // Reachable only through a heap descriptor load, which needs the raw_buffer, typed_dword or + // raw_and_typed_dword contract. A raw buffer view has no stride to read, so the stride of a + // GPU-selected slot stays untranslated in the direct path. Under raw_buffer and raw_and_typed_dword + // a stride read into s0-s105 is tracked symbolically (byte_descriptor_field) and does not reach + // here; typed_dword admits the heap descriptor load but not that tracking, so it reaches this refusal. refuse_heap_contract(i.pc); refuse(i.pc, "a GPU-selected heap slot stride read is not translated with a view contract"); } diff --git a/src/startup_stubs/native_global_srv.h b/src/startup_stubs/native_global_srv.h index 73906bd09f..d778d1e4f9 100644 --- a/src/startup_stubs/native_global_srv.h +++ b/src/startup_stubs/native_global_srv.h @@ -129,7 +129,8 @@ inline bool decode_global_srv_request(const std::string &text, GlobalSrvRequest } else if (key == "also") { GlobalSrvSelection selection; std::string name; - if (!(fields >> selection.slot >> name)) { + std::string extra; + if (!(fields >> selection.slot >> name) || (fields >> extra)) { error = "global SRV view metadata: unreadable also line"; return false; } @@ -174,13 +175,14 @@ inline bool decode_global_srv_request(const std::string &text, GlobalSrvRequest error = std::string("global SRV view metadata lacks the ") + (request.has_selected ? "needed view type" : "selected slot"); return false; } - // One selection per selector word: a slot named twice is refused, also with the same type (a producer deduplicates). + // One selection per selector word, so a slot may be named again (two words can pick the same slot) with the same + // view type. A slot named with two view types cannot be read as both: refused. for (std::size_t a = 0; a <= request.also.size(); ++a) for (std::size_t b = a + 1; b <= request.also.size(); ++b) { - const unsigned slot_a = a ? request.also[a - 1].slot : request.selected; - const unsigned slot_b = request.also[b - 1].slot; - if (slot_a == slot_b) { - error = "global SRV view metadata: duplicate selected slot " + std::to_string(slot_a); + const auto &first = a ? request.also[a - 1] : GlobalSrvSelection{request.selected, request.needed}; + const auto &second = request.also[b - 1]; + if (first.slot == second.slot && first.needed != second.needed) { + error = "global SRV view metadata: slot " + std::to_string(first.slot) + " selected with two view types"; return false; } } diff --git a/tests/native_global_srv_heap_replay.cpp b/tests/native_global_srv_heap_replay.cpp index 82f158750a..82413a0b5a 100644 --- a/tests/native_global_srv_heap_replay.cpp +++ b/tests/native_global_srv_heap_replay.cpp @@ -378,7 +378,11 @@ int record(int argc, wchar_t **argv) { if (needed == GlobalSrvType::none) return 2; } else if (flag == L"--also" && a + 2 < argc && !also_given) { also_given = true; - also_selector = static_cast(std::stoul(argv[++a])); + try { + also_selector = static_cast(std::stoul(argv[++a])); + } catch (const std::exception &) { + return 2; + } also_needed = type_from_argument(argv[++a]); if (also_needed == GlobalSrvType::none) return 2; } else { diff --git a/tests/native_global_srv_heap_replay_check.py b/tests/native_global_srv_heap_replay_check.py index e6212150cb..a6269649a8 100644 --- a/tests/native_global_srv_heap_replay_check.py +++ b/tests/native_global_srv_heap_replay_check.py @@ -545,8 +545,18 @@ def typed_compile(directory, typed_stem, out_name, cache_dir=cache): "global SRV slot 9 has no captured view type"), "mixed_unreadable": (MIXED, MV.replace("also 3 typed_buffer", "also x y"), "global SRV view metadata: unreadable also line"), - "mixed_duplicate": (MIXED, MV.replace("also 3 typed_buffer", "also 0 typed_buffer"), - "global SRV view metadata: duplicate selected slot 0"), + "mixed_trailing_field": (MIXED, MV.replace("also 3 typed_buffer", "also 3 typed_buffer 7"), + "global SRV view metadata: unreadable also line"), + # The selected slot 0 (raw_buffer) named again with another view type; the same slot twice with the same type + # is accepted (positives below). + "mixed_two_types": (MIXED, MV + "also 0 typed_buffer\n", + "global SRV view metadata: slot 0 selected with two view types"), + "mixed_two_types_also": (MIXED, MV + "also 3 raw_buffer\n", + "global SRV view metadata: slot 3 selected with two view types"), + # Only the second `also` is wrong: the first still holds the valid typed slot 3. + "mixed_second_also_wrong_type": (MIXED, MV + "also 2 raw_buffer\n", RAW.format(n=2, t="texture")), + "mixed_second_also_texture": (MIXED, MV + "also 2 texture\n", + "GPU-selected heap slot view type texture is not raw_buffer or typed_buffer"), "mixed_no_dword": (MIXED, MV.replace("dword 3 1\n", ""), "GPU-selected heap slot 3 is not a one-channel 32-bit typed buffer (no 32-bit channel metadata)"), "mixed_typed_xy": (typed_xy, MV, "typed heap load reads one channel only"), @@ -563,6 +573,8 @@ def typed_compile(directory, typed_stem, out_name, cache_dir=cache): # windows by the rewrite, a formatted tbuffer load through a plain or rewritten heap descriptor). mixed_positives = { "mixed_two_also": (MIXED, MV + "also 1 raw_buffer\n"), + "mixed_also_same_slot": (MIXED, MV + "also 0 raw_buffer\n"), # select 0 again, same type + "mixed_also_twice": (MIXED, MV + "also 3 typed_buffer\n"), # a repeated also, same type "mixed_window": (WINDOW, MV), "mixed_twindow": (TWINDOW, MV), # tbuffer_load_format_x v2, v1, s[20:23], 0 format:[BUF_FMT_32_UINT] offen: refused under typed_dword @@ -576,5 +588,38 @@ def typed_compile(directory, typed_stem, out_name, cache_dir=cache): f"compile_dxil '{name}': compiled under the mixed contract") if name == "mixed_two_also": require("also=3:typed_buffer also=1:raw_buffer" in out, "compile_dxil 'mixed_two_also': reports both also entries") + if name == "mixed_also_same_slot": + require("also=3:typed_buffer also=0:raw_buffer" in out, "compile_dxil 'mixed_also_same_slot': reports both also entries") + if name == "mixed_also_twice": + require("also=3:typed_buffer also=3:typed_buffer" in out, "compile_dxil 'mixed_also_twice': reports both also entries") + + # Two selector words that pick the same raw slot: both words are selections of the same view type, so the file + # `record` writes decodes, and `replay` writes the slot to both words. RAWRAW is MIXED with the typed load of word 1 + # replaced by a raw load (buffer_load_dword v3, v1, s[24:27], 0 offen), so u0 is twice the slot's data. + RAWRAW = list(MIXED) + typed_at = RAWRAW.index(0xe0002000) + RAWRAW[typed_at:typed_at + 2] = [0xe0301000, 0x80060301] + directory, rawraw_stem = typed_dir("rawraw", RAWRAW) + code, out, err = run([fixture, "record", sdk, cache, directory / (rawraw_stem + ".cdx"), adapter, 0, "ok", + "--need", "raw_buffer", "--also", 0, "raw_buffer"]) + require(code == 0 and "output matches slot 0+0 data" in out, + "record two raw selections of slot 0: u0 equals twice the slot 0 data") + text = (directory / (rawraw_stem + ".views")).read_text() + require(text.startswith("x2w-global-srv-views 2\nselect 0\nneed raw_buffer\nalso 0 raw_buffer\n"), + "record two raw selections of slot 0 wrote the repeated slot") + code, out, err, rawraw_cso = typed_compile(directory, rawraw_stem, "rawraw_out", cache_dir=cache11) + require(code == 0 and "global_srv select=0 need=raw_buffer also=0:raw_buffer" in out and rawraw_cso.exists(), + "compile_dxil two raw selections of slot 0: the file record wrote decodes and compiles") + code, out, err = run([fixture, "replay", sdk, cache, directory / (rawraw_stem + ".cdx"), rawraw_cso, + directory / (rawraw_stem + ".views"), adapter, "ok", "0+0"]) + require(code == 0 and "output matches slot 0+0 data" in out, "replay two raw selections of slot 0: twice the slot data") + code, out, err = run([fixture, "replay", sdk, cache, directory / (rawraw_stem + ".cdx"), rawraw_cso, + directory / (rawraw_stem + ".views"), adapter, "ok", "0+1"]) + require(code == 1 and "mismatch word 0" in out, "replay two raw selections of slot 0 compared with slots 0+1 reports a mismatch") + + # A non-numeric --also selector is a usage error (exit 2), like the other bad arguments. + code, out, err = run([fixture, "record", sdk, cache, directory / (rawraw_stem + ".cdx"), adapter, 0, "ok", + "--also", "x", "raw_buffer"]) + require(code == 2, "record with a non-numeric --also selector exits 2") print("native_global_srv_heap_replay: all checks passed") From 2534937a4e4a85ded9e2dfa2e9380452bc66880e Mon Sep 17 00:00:00 2001 From: JB2WIN Date: Sat, 28 Nov 2026 15:32:10 +0100 Subject: [PATCH 3/3] native: say the heap slot type check is necessary but not sufficient for mixed reads Review note on #3063: under raw_and_typed_dword the selection types come from the capture, not from the shader, so the header comment now matches HeapViewContract and the doc's Limits. Comment only. Co-Authored-By: Claude Opus 5.5 --- src/startup_stubs/native_global_srv.h | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/startup_stubs/native_global_srv.h b/src/startup_stubs/native_global_srv.h index d778d1e4f9..765f8a90d3 100644 --- a/src/startup_stubs/native_global_srv.h +++ b/src/startup_stubs/native_global_srv.h @@ -14,7 +14,9 @@ // A shader that picks its slots at run time can only be recorded and replayed if the type of every slot it may pick is // known: the capture keeps {slot, type, stride, bytes} for each slot of the heap (and the 32-bit channel count of a // typed buffer slot), and the dispatch is refused, before any shader runs, when the selected slot holds another type -// than the one the shader reads. No heap-indexed data read is translated here; this header only classifies, +// than the one the shader reads. Under raw_and_typed_dword each selection's type comes from the capture +// (`need`/`also`), not from the shader, so this check is necessary but not sufficient: which load reads which slot +// stays a caller guarantee (HeapViewContract). No heap-indexed data read is translated here; this header only classifies, // serializes and checks, and names the heap view contract a request allows (global_srv_contract). // // A .views file describes the one dispatch it was captured from. It is not part of the .cdx/.root content key of the