From ec7318d80e2397ac50573b3a03c786860bf435b8 Mon Sep 17 00:00:00 2001 From: JB2WIN Date: Mon, 30 Nov 2026 03:47:29 +0100 Subject: [PATCH 1/2] native: translate GPU-selected heap textures through view tokens in compute A compute program that loads a texture with s_load_dwordx8 from the directly indexed resource heap at an SGPR offset chosen by GPU data is now translated when every use of the eight words is the T# of a supported image instruction (1D, 2D or 2D-array load, load_mip, sample_l, sample_lz, 2D gather4_lz, get_resinfo). The shader reads the 32-byte view token at the guest byte address, checks the magic, the view id range and the dimension recorded for the id, and samples ResourceDescriptorHeap[base(dimension) + id] (a null slot otherwise, counting one miss per wave). The manifest names the runtime- provided views and words (heaptok, heaptokdims, heaptokmiss, five heaptok words); the runtime reader still refuses them by name, so dispatch behaviour is unchanged. Not independently design-approved: see the PR description. AI-assisted. Co-Authored-By: Claude Opus 5.5 --- docs/experiments.md | 2 + .../experiments/native-heap-token-textures.md | 53 +++ src/direct_compute_cache.cpp | 40 +- src/gfx1013_compute_native.cpp | 167 ++++++- src/gfx1013_compute_native.h | 13 +- src/gfx1013_direct_compute.inl | 118 ++++- src/native_compute_output.h | 2 +- src/native_compute_pipeline.cpp | 9 +- src/native_compute_pipeline.h | 1 + src/startup_stubs/d3d12_compute_dispatch.inl | 6 + tests/cmake/native_heap_token_texture.cmake | 15 + tests/native_compile_dxil_watch_check.py | 3 +- tests/native_compute_manifest_reasons.cpp | 49 +- tests/native_heap_token_texture.cpp | 437 ++++++++++++++++++ tests/native_heap_token_texture_check.py | 318 +++++++++++++ tests/native_startup_request_cache_check.py | 9 +- tests/startup_compute_dispatch_check.py | 9 +- .../startup_compute_dispatch_texture_check.py | 4 + tools/startup/triage_run.py | 1 + 19 files changed, 1235 insertions(+), 21 deletions(-) create mode 100644 docs/experiments/native-heap-token-textures.md create mode 100644 tests/cmake/native_heap_token_texture.cmake create mode 100644 tests/native_heap_token_texture.cpp create mode 100644 tests/native_heap_token_texture_check.py diff --git a/docs/experiments.md b/docs/experiments.md index 3fff98730d..de7bdfc6dc 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -18031,3 +18031,5 @@ ctest --preset dev --no-tests=error -j1 -R '^native_pixel_atomic_(warp|hardware) ``` Repeat with the release preset. The source-built fixture verifies 13 actual draws and four refusal controls per adapter/configuration, including contention, guard words, active out-of-view, odd raster edges and real WQM quad-neighbor reads with and without GLC. WQM+GLC records returned old values through a second exact atomic in a private lane slot and checks a valid serialization of the varying addends. Local RX 7900 XT/WARP Debug/Release integration over main 4b0350e passed 52 draws, 3328 DWORD and 1664 pixel comparisons, and 16 refusal controls. The debug layer was unavailable; actual title rendering is not established. + +See [GPU-selected heap textures through view tokens in native compute](experiments/native-heap-token-textures.md) (#3023 stage 3, translator only) for the `heaptok` manifest lines the runtime still refuses. diff --git a/docs/experiments/native-heap-token-textures.md b/docs/experiments/native-heap-token-textures.md new file mode 100644 index 0000000000..e554728108 --- /dev/null +++ b/docs/experiments/native-heap-token-textures.md @@ -0,0 +1,53 @@ +# GPU-selected heap textures through view tokens in native compute (translator, #3023 stage 3, PR 1) + +Issue #3023. The native compute translator accepts a texture that the program loads with `s_load_dwordx8` from the directly +indexed resource heap at a byte offset chosen by GPU data (a "heap token texture"). This change is the translator, the +manifest writer, the reader refusal and the fixtures. The runtime still refuses the new manifest lines by name ("heap token +textures are not bound yet"), so no dispatch behaviour changes. The runtime side (binding the token memory, the dimension +table and the host descriptor ranges) is a later change. + +## Why a token + +The guest computes the descriptor address itself and the title copies descriptors with its own memory copies, so the +translator cannot mirror heap slots. What the title keeps at the descriptor address of a registered view is a 32-byte view +token: word 0 the magic `0x56573258`, word 1 the view id (a content token has bit 31 set and is not an id). The shader reads +those two words at the guest byte address and maps the id to a host descriptor. + +## What the translator does + +- A program is eligible when every reached `s_load_dwordx8` from the resource heap with an SGPR offset (a token load) is + used only as the T# of `image_load`, `image_load_mip`, `image_sample_l`, `image_sample_lz`, `image_gather4_lz` (2D) or + `image_get_resinfo` of a 1D, 2D or 2D-array view, without D16. A copy, a numeric read, an image field read, a store, a + comparison, cube or 3D use or a partial use makes the program not eligible; it then keeps today's analysis and its + refusal text. An eligible program is analysed a second time with the byte address kept in the destination SGPRs + (`heap_tokens` in `transfer()` and `parse()`). +- The load handler requires an immediate offset and a proven SGPR offset (`constant` or `masked`) that are multiples of 4, + writes `so + imm` to the eight words, and bypasses the heap view contract: the contract exists because the runtime cannot + vouch for the view kind of a GPU-selected slot, and this route checks it on every execution. +- Per image instruction of dimension `d`: `valid = word0 == magic && id < count && dims[min(id, count - 1)] == 1 + d`; + the handle is `ResourceDescriptorHeap[valid ? base(d) + id : null]` (kind 1, 2 or 7, `nonuniform` false: every lane loads + the same address). When `!valid`, the first lane of the wave adds one to a miss counter (`waveIsFirstLane`, `atomicBinOp`). +- Five more `b0` words follow the stride words: `base1d`, `base2d`, `base2da`, `count`, `null`. Three runtime-provided views + (root parameter `compute_heap_token`): the token memory (`heap_token_srv`, a raw SRV), the dimension table + (`heap_token_dims_srv`, a raw SRV with one uint per view id: 0 none, else 1 + the image dimension) and the miss counter + (`heap_token_miss_uav`, a raw UAV). They take the first SRV and UAV registers after the stride views, because the module + names the registers while it is lowered. +- Manifest lines: `srv N heaptok`, `srv N heaptokdims`, `uav N heaptokmiss`, `udsrc K heaptok base1d|base2d|base2da|count|null`. + `native_compute_output_revision` is 2. The root signature of the pipeline sets `CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED` for them. + +## Tests + +- `native_heap_token_texture_controls`: compiles source-written requests; checks the published manifest, the module's heap + handle, wave-first-lane and atomic add, and each consumer or address shape that keeps today's refusal text or gets a new one + (`heap token byte offset has no proven 4-byte aligned range`, `unaligned heap token immediate byte offset`). +- `native_heap_token_texture_warp` and `_hardware`: the rig runs 1D, 2D and 2D-array programs on a host heap with one range + per dimension; a valid token gives the texel of its view and no miss; a wrong magic, an id equal to the count, the largest + id, an id of another dimension, a content token, id 0 and an empty token give the null texel and one miss per wave. WARP has + no 32-lane waves and reports 77. +- `native_compute_manifest_reasons` covers the writer; `startup_compute_dispatch_texture` the reader refusal. + +## Open + +The null slot has one word; a null view of another dimension than the instruction's is not defined by D3D12 for dynamic +indexing, so the runtime change has to provide a null slot that every dimension may read (the fixture uses a null view of the +dimension under test). diff --git a/src/direct_compute_cache.cpp b/src/direct_compute_cache.cpp index ab7ff78833..b7f97527e5 100644 --- a/src/direct_compute_cache.cpp +++ b/src/direct_compute_cache.cpp @@ -101,6 +101,7 @@ Bytes encode(const NativeComputeShader &program) { for (unsigned n : {c.root_parameter, c.first_sgpr, c.count}) word(out, n); word(out, program.sampler_heap); + word(out, program.heap_token_words); word(out, static_cast(program.stride_srvs.size())); for (unsigned srv : program.stride_srvs) word(out, srv); @@ -135,14 +136,17 @@ NativeComputeShader decode(std::string_view bytes) { unsigned n = in.count(1000000); shader.bindings.reserve(n); for (unsigned j = 0; j < n; ++j) { - auto kind = static_cast(in.count(static_cast(ComputeViewKind::root_buffer_uav))); + auto kind = static_cast(in.count(static_cast(ComputeViewKind::heap_token_miss_uav))); ComputeViewBinding b{kind, in.word(), in.word(), in.word(), in.word(), in.word(), in.word(), in.count(7)}; b.scalar_table = static_cast(in.count(unsigned(ComputeViewBinding::ScalarTable::srv))); b.requires_identity_dst_sel = in.count(1) != 0; const bool sampler_heap = kind == ComputeViewKind::heap_sampler; + const bool token = kind == ComputeViewKind::heap_token_srv || kind == ComputeViewKind::heap_token_dims_srv || + kind == ComputeViewKind::heap_token_miss_uav; if (!b.array_count || b.array_position >= b.array_count || (sampler_heap ? b.root_parameter != compute_sampler_heap - : b.root_parameter >= 16 && b.root_parameter != compute_resource_heap)) + : token ? b.root_parameter != compute_heap_token + : b.root_parameter >= 16 && b.root_parameter != compute_resource_heap)) throw std::runtime_error("invalid cached binding"); shader.bindings.push_back(b); } @@ -154,6 +158,7 @@ NativeComputeShader decode(std::string_view bytes) { shader.constants.push_back(c); } shader.sampler_heap = in.count(1) != 0; + shader.heap_token_words = in.count(1) != 0; n = in.count(32); for (unsigned j = 0; j < n; ++j) shader.stride_srvs.push_back(in.count(31)); @@ -898,9 +903,10 @@ static const char *view_kind_name(ComputeViewKind kind) { "comparison_texture_srv", "half2_texture_uav", "half4_texture_uav", "cube_sample_srv", "cube_comparison_srv", "indexed_atomic_uav", "d16_sample_srv", "byte_window_srv", "heap_buffer_srv", "heap_sampler", "uint_texture_uav", "float_texture_uav", "float2_texture_uav", "float3_texture_uav", "packed_d16_x_uav", - "indexed_raw_srv", "heap_typed_srv", "root_buffer_uav"}; + "indexed_raw_srv", "heap_typed_srv", "root_buffer_uav", "heap_token_srv", "heap_token_dims_srv", + "heap_token_miss_uav"}; // ponytail: catches a renamed last kind, not one appended after it; extend both together. - static_assert(std::size(names) == static_cast(ComputeViewKind::root_buffer_uav) + 1); + static_assert(std::size(names) == static_cast(ComputeViewKind::heap_token_miss_uav) + 1); const auto index = static_cast(kind); return index < std::size(names) ? names[index] : "unknown"; } @@ -936,7 +942,7 @@ std::optional format_compute_runtime_manifest(const NativeComputeSh return refuse("more than 8 root constants in one root parameter"); ud_count += block.count; } - ud_count += static_cast(program.stride_srvs.size()); + ud_count += static_cast(program.stride_srvs.size()) + (program.heap_token_words ? 5u : 0u); if (ud_count > 32) return refuse("more than 32 user data words"); @@ -950,7 +956,25 @@ std::optional format_compute_runtime_manifest(const NativeComputeSh unsigned srv_count = 0, uav_count = 0; std::ostringstream srv_lines, uav_lines, sampler_lines; + unsigned token_views[3]{}; for (const auto &b : sorted) { + // The runtime-provided views of GPU-selected heap textures: the view token memory, the dimension table and the + // miss counter. They take table registers like any view; the runtime reader does not bind them yet. + const bool token_view = b.kind == ComputeViewKind::heap_token_srv || b.kind == ComputeViewKind::heap_token_dims_srv || + b.kind == ComputeViewKind::heap_token_miss_uav; + if (token_view != (b.root_parameter == compute_heap_token)) + return refuse("heap token view with another root parameter"); + if (token_view) { + if (!program.heap_token_words || b.array_count != 1) + return refuse("heap token view without heap token words"); + const bool miss = b.kind == ComputeViewKind::heap_token_miss_uav; + if (b.shader_register != (miss ? uav_count++ : srv_count++)) + return refuse(miss ? "UAV registers not contiguous" : "SRV registers not contiguous"); + ++token_views[b.kind == ComputeViewKind::heap_token_srv ? 0 : b.kind == ComputeViewKind::heap_token_dims_srv ? 1 : 2]; + (miss ? uav_lines : srv_lines) << (miss ? "uav " : "srv ") << b.shader_register + << (miss ? " heaptokmiss" : b.kind == ComputeViewKind::heap_token_srv ? " heaptok" : " heaptokdims") << '\n'; + continue; + } if (b.root_parameter == compute_resource_heap) return refuse("resource heap view"); if (b.root_parameter == compute_sampler_heap) @@ -1069,6 +1093,12 @@ std::optional format_compute_runtime_manifest(const NativeComputeSh return refuse("stride words from a view that is not one raw vector SRV"); out << "udsrc " << ud_index++ << " stride " << srv << '\n'; } + if (program.heap_token_words) { + if (token_views[0] != 1 || token_views[1] != 1 || token_views[2] != 1) + return refuse("heap token words without the three heap token views"); + for (const char *word : {"base1d", "base2d", "base2da", "count", "null"}) + out << "udsrc " << ud_index++ << " heaptok " << word << '\n'; + } out << srv_lines.str() << uav_lines.str() << sampler_lines.str() << "native " << native_compute_output_revision << '\n'; return out.str(); diff --git a/src/gfx1013_compute_native.cpp b/src/gfx1013_compute_native.cpp index 65ff47aece..a3732e5b14 100644 --- a/src/gfx1013_compute_native.cpp +++ b/src/gfx1013_compute_native.cpp @@ -685,7 +685,7 @@ static std::optional byte_descriptor_field(const Inst &i, const State &s return {}; } State transfer(const Inst &i, State s, bool wave64, bool graphics, bool heap_window, bool direct, - bool narrow_wave64 = false) { + bool narrow_wave64 = false, bool heap_tokens = false) { auto set = [&](unsigned n, Symbol v) { if (n >= s.size()) refuse(i.pc, "invalid SGPR"); @@ -752,7 +752,8 @@ State transfer(const Inst &i, State s, bool wave64, bool graphics, bool heap_win Symbol v{}; if (heap_address) { v = {Symbol::Type::indexed_descriptor, compute_resource_heap, (i.b & 0xfffff) + 4 * j, base.index_mask, i.pc}; - } else if (graphics && i.op == 3 && base.type == Symbol::Type::table && base.value == compute_resource_heap) { + } else if ((graphics || (heap_tokens && offset_reg != 125)) && i.op == 3 && + base.type == Symbol::Type::table && base.value == compute_resource_heap) { const bool fixed = offset_reg == 125 || index.type == Symbol::Type::constant; const Word offset = (i.b & 0xfffff) + (offset_reg != 125 && fixed ? index.value : 0); v = {Symbol::Type::indexed_descriptor, base.value, offset + 4*j, @@ -916,7 +917,7 @@ std::map fixed_vertex_loads(const string &code) { return found ? result : std::map{}; } Program parse(const string &code, unsigned entry, const State &initial, bool graph, bool graphics=false, bool wave64=false, bool fixed_vertex=false, - bool heap_window=false, bool narrow_wave64=false) { + bool heap_window=false, bool narrow_wave64=false, bool heap_tokens=false) { Program p; p.graphics_wave64 = graphics && wave64; if ((entry & 3) || entry >= code.size() || code.size() > 1u << 20) @@ -965,7 +966,7 @@ Program parse(const string &code, unsigned entry, const State &initial, bool gra auto k = work.front(); work.pop_front(); auto &i = p.code[k]; - auto after = transfer(i, p.before[k], wave64, graphics, heap_window, graph, narrow_wave64); + auto after = transfer(i, p.before[k], wave64, graphics, heap_window, graph, narrow_wave64, heap_tokens); auto merge = [&](size_t t) { bool changed = !p.reached[t]; auto &in = p.before[t]; @@ -1737,6 +1738,143 @@ void lower_blocks(Emit &e) { out << "}\n"; } } +// GPU-selected heap textures (view tokens). A consumer of a token load: the image instruction and its dimension. +struct HeapTokenLoad { + unsigned pc, dim; +}; +// SGPR ranges {first, count} an instruction may read, widened where the operand width is not known exactly. Anything +// that cannot be listed (indexed SGPR moves) reads everything. +static std::vector> conservative_sgpr_reads(const Inst &i) { + std::vector> out; + auto add = [&](unsigned first, unsigned count) { + if (first < 106) out.emplace_back(first, count); + }; + const bool wide = i.name.find("64") != Name::npos; + switch (i.enc) { + case Encoding::Sop1: case Encoding::Sop2: case Encoding::Sopc: case Encoding::Sopk: case Encoding::Vop1: + case Encoding::Vop2: case Encoding::Vopc: case Encoding::Vop3: case Encoding::Mix: case Encoding::QuadCompare: + for (unsigned k = 0; k < 3; ++k) + add(i.src[k], wide ? 2 : 1); + if (i.enc == Encoding::Sopk) add(i.dst, 1); + break; + case Encoding::Smem: + add(i.src[0], i.op >= 8 ? 4 : 2); + add(i.b >> 25, 1); + break; + case Encoding::Mubuf: + if (i.name.substr(0, 7) == "global_") add((i.b >> 16) & 127, 2); + else add(((i.b >> 16) & 31) * 4, 4); + add(i.b >> 24, 1); + break; + case Encoding::Image: + add(((i.b >> 21) & 31) * 4, 4); + break; + default: + break; + } + if (i.name.find("movrel") != Name::npos) + out.emplace_back(0, 106); + return out; +} +// The pre-pass of the heap token route. Every reached s_load_dwordx8 from the resource heap with an SGPR offset is a +// token load. The program is eligible when every later read of the eight words (until they are overwritten) is the +// T# of an image_load, image_load_mip, image_sample_l, image_sample_lz, image_gather4_lz (2D) or image_get_resinfo of +// dimension 1D, 2D or 2D array, without D16; a copy, a numeric read, a store, a comparison, cube or 3D use, a +// partial use or a read of the words by an instruction this function cannot place makes it not eligible. `p` is +// the analysis with heap_tokens set. Returns false when there is no token load. +static bool heap_token_eligible(const Program &p, std::vector &consumers) { + consumers.clear(); + std::vector loads; + for (size_t n = 0; n < p.code.size(); ++n) { + const auto &i = p.code[n]; + if (!p.reached[n] || i.enc != Encoding::Smem || i.op != 3 || (i.b >> 25) == 125) continue; + const auto &base = p.before[n].at(i.src[0]); + if (base.type == Symbol::Type::table && base.value == compute_resource_heap) + loads.push_back(n); + } + if (loads.empty()) return false; + // A descriptor address formed by s_add_u32 (heap_offset_add) is another way into the heap, with its own contract. + for (size_t n = 0; n < p.code.size(); ++n) { + const auto &i = p.code[n]; + if (p.reached[n] && i.enc == Encoding::Smem && i.op == 2 && (i.b >> 25) == 125 && + p.before[n].at(i.src[0]).type == Symbol::Type::heap_offset) + return false; + } + for (const size_t l : loads) { + const auto &load = p.code[l]; + if (load.dst + 8 > 106) return false; + // The instructions that can run after this load. A word of the load that reaches one of them without being + // overwritten, but not as the exact token symbol (a join with a path that skipped the load loses it), is a read + // the second analysis could not place: the load is not eligible. + std::vector after(p.code.size()); + { + std::vector pending; + const auto visit = [&](size_t n) { + if (!after[n]) { after[n] = true; pending.push_back(n); } + }; + const auto successors = [&](size_t n) { + const auto &i = p.code[n]; + if (i.branch()) { + const auto t = p.at.find(i.target()); + if (t != p.at.end()) visit(t->second); + } + if (i.name != "s_endpgm" && !(i.branch() && i.op == 2) && n + 1 < p.code.size()) visit(n + 1); + }; + successors(l); + while (!pending.empty()) { + const size_t n = pending.back(); + pending.pop_back(); + successors(n); + } + } + for (size_t n = 0; n < p.code.size(); ++n) { + if (n == l || !p.reached[n]) continue; + const auto &state = p.before[n]; + std::array token{}; + bool any = false; + for (unsigned r = 0; r < 106; ++r) { + const auto &s = state[r]; + token[r] = s.type == Symbol::Type::indexed_descriptor && s.value == compute_resource_heap && + s.definition == load.pc; + any |= token[r]; + } + const auto &i = p.code[n]; + if (after[n]) { + auto reads = conservative_sgpr_reads(i); + if (i.enc == Encoding::Image) reads.emplace_back(((i.b >> 16) & 31) * 4, 8); + for (const auto &[first, count] : reads) + for (unsigned r = first; r < first + count && r < 106; ++r) + if (r >= load.dst && r < load.dst + 8 && !token[r] && !state[r].numeric() && + !(state[r].type == Symbol::Type::indexed_descriptor && state[r].value == compute_resource_heap)) + return false; + } + if (!any) continue; + if (i.enc == Encoding::Image) { + const unsigned base = ((i.b >> 16) & 31) * 4; + unsigned held = 0; + for (unsigned j = 0; j < 8; ++j) held += base + j < 106 && token[base + j]; + if (held) { + const unsigned dim = (i.a >> 3) & 7; + const bool op_ok = i.op == 0 || i.op == 1 || i.op == 14 || i.op == 36 || i.op == 39 || + (i.op == 71 && dim == 1); + if (held != 8 || !op_ok || (dim != 0 && dim != 1 && dim != 5) || (i.b >> 31)) return false; + for (unsigned j = 1; j < 8; ++j) { + auto expected = state[base]; + expected.offset += 4 * j; + if (!(state[base + j] == expected)) return false; + } + if (std::none_of(consumers.begin(), consumers.end(), + [&](const auto &c) { return c.pc == i.pc && c.dim == dim; })) + consumers.push_back({i.pc, dim}); + } + } + for (const auto &[first, count] : conservative_sgpr_reads(i)) + for (unsigned r = first; r < first + count && r < 106; ++r) + if (token[r]) return false; + } + } + return true; +} #include "gfx1013_direct_compute.inl" #include "gfx1013_direct_graphics.inl" #include "gfx1013_direct_mesh.inl" @@ -1872,6 +2010,25 @@ static NativeComputeShader translate_program(const ComputeRequest &request, unsi 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, narrow_wave64); + // A GPU-selected texture loaded with s_load_dwordx8 from the resource heap: when every such load is only used as the + // T# of a supported image instruction, translate the program on the analysis that keeps the byte address. + std::vector token_consumers; + bool heap_tokens = false; + bool token_candidate = false; + for (size_t n = 0; direct_dxil && !stage && n < program.code.size() && !token_candidate; ++n) { + const auto &i = program.code[n]; + if (program.reached[n] && i.enc == Encoding::Smem && i.op == 3 && (i.b >> 25) != 125) { + const auto &base = program.before[n].at(i.src[0]); + token_candidate = base.type == Symbol::Type::table && base.value == compute_resource_heap; + } + } + if (token_candidate) { + auto tokens = parse(request.code, entry, initial, direct_dxil, false, wave64, false, heap_window, narrow_wave64, true); + if (heap_token_eligible(tokens, token_consumers)) { + program = std::move(tokens); + heap_tokens = true; + } + } Emit emit{{}, program,layout->Desc_1_1}; emit.result.constants = constants; if (!lds) @@ -1885,6 +2042,8 @@ static NativeComputeShader translate_program(const ComputeRequest &request, unsi compiler.narrow_wave64 = narrow_wave64; compiler.heap_view = heap_view; compiler.heap_window = heap_window; + compiler.heap_tokens = heap_tokens; + compiler.heap_token_consumers = token_consumers; for (size_t i = 0; i < program.code.size(); ++i) { const auto& inst = program.code[i]; if (!program.reached[i]) continue; diff --git a/src/gfx1013_compute_native.h b/src/gfx1013_compute_native.h index 23855e0e1c..cfc75d84a0 100644 --- a/src/gfx1013_compute_native.h +++ b/src/gfx1013_compute_native.h @@ -49,7 +49,13 @@ enum class ComputeViewKind { indexed_raw_srv, // Fixed-stride record read. required_bytes is one complete record and its checked stride. heap_typed_srv, // A one-channel 32-bit typed buffer read the same way (HeapViewContract::typed_dword). // A raw buffer bound as a root UAV. The guest address is the root pointer plus a VGPR offset. - root_buffer_uav + root_buffer_uav, + // Runtime-provided bindings of GPU-selected heap textures (view tokens). heap_token_srv: raw view over the title view-heap + // memory (32-byte tokens); heap_token_dims_srv: one uint per view id (0 none, else 1 + image dimension); the miss UAV + // is one raw dword counting the waves that read the null slot. + heap_token_srv, + heap_token_dims_srv, + heap_token_miss_uav }; inline unsigned exact_texture_uav_channels(ComputeViewKind kind) { switch (kind) { @@ -65,6 +71,8 @@ inline bool accepts_cbv_window(ComputeViewKind kind) { inline constexpr unsigned compute_resource_heap = ~0u; // the directly indexed sampler heap; entry n is title byte offset 16 * n inline constexpr unsigned compute_sampler_heap = ~0u - 1; +// The root parameter of the runtime-provided heap token bindings (not title tables). +inline constexpr unsigned compute_heap_token = ~0u - 2; // A binding of the whole descriptor heap: it has no table register and no root parameter. inline bool compute_heap_binding(ComputeViewKind kind) { return kind == ComputeViewKind::heap_buffer_srv || kind == ComputeViewKind::heap_typed_srv; @@ -81,6 +89,7 @@ inline bool compute_uav(ComputeViewKind kind) { return kind == ComputeViewKind::texture_uav || kind == ComputeViewKind::half_scalar_uav || kind == ComputeViewKind::half2_texture_uav || kind == ComputeViewKind::half4_texture_uav || kind == ComputeViewKind::uint_texture_uav || kind == ComputeViewKind::root_buffer_uav || + kind == ComputeViewKind::heap_token_miss_uav || exact_texture_uav_channels(kind) || compute_buffer_uav(kind); } struct ComputeViewBinding { @@ -141,6 +150,8 @@ struct NativeComputeShader { std::vector constants; // Additional b0 words, after root constants, read from these bound SRVs. std::vector stride_srvs; + // Five more b0 words after the stride words: base1d, base2d, base2da, count, null (heap token textures). + bool heap_token_words = false; std::string hlsl, dxil_ir; std::vector bindings; std::vector samplers; diff --git a/src/gfx1013_direct_compute.inl b/src/gfx1013_direct_compute.inl index 5c95a73e10..c3c31b8935 100644 --- a/src/gfx1013_direct_compute.inl +++ b/src/gfx1013_direct_compute.inl @@ -88,6 +88,14 @@ struct DirectCompute { unsigned mode_bits = 0xf0; std::vector scc_live; std::map,string> descriptor_strides; + // GPU-selected heap textures through view tokens (the program passed heap_token_eligible). The registers are taken + // before the program is lowered, because the DXIL names them; the five words are base1d, base2d, base2da, count, null. + bool heap_tokens = false; + std::vector heap_token_consumers; + std::array heap_token_values; + unsigned token_srv = 0, token_dims_srv = 0, token_miss_uav = 0; + // The views and words exist only when a program uses a token texture (an unused token load needs none). + bool token_bindings() const { return heap_tokens && !heap_token_consumers.empty(); } unsigned label_number = 0; bool pixel_stage = false; bool pixel_heap_enabled = false; @@ -342,7 +350,7 @@ struct DirectCompute { initialize_constants(); } void initialize_constants(const GraphicsConstantLayout *linked = nullptr) { - unsigned words = static_cast(descriptor_strides.size()); + unsigned words = static_cast(descriptor_strides.size()) + (token_bindings() ? 5u : 0u); for (const auto &block : analysis.result.constants) words += block.count; if (words) { @@ -366,6 +374,9 @@ struct DirectCompute { } for (auto &entry : descriptor_strides) entry.second = ir.binary("and",word_at(pos++),"16383"); + for (auto &value : heap_token_values) + if (token_bindings()) + value = word_at(pos++); } } // Refuses a GPU-selected heap read that the contract does not cover. raw_buffer, typed_dword and raw_and_typed_dword @@ -718,6 +729,24 @@ struct DirectCompute { write(i.dst + j, index); return; } + if (heap_tokens && !pixel_stage && low.type == Symbol::Type::table && low.value == compute_resource_heap && + i.op == 3 && so != 125) { + // A view token read from the title's heap memory at the guest byte address so + imm (see + // heap_token_texture). The contract gate (refuse_heap_contract) does not apply: this route checks the + // magic, the view id and the dimension on every execution instead of trusting a captured view type. + if (i.dst + 8 > 106 || !(s.at(i.src[0] + 1) == Symbol{Symbol::Type::constant,0})) + refuse(i.pc, "invalid heap token texture descriptor address"); + const Word offset = i.b & 0xfffff; + if (offset & 3) refuse(i.pc, "unaligned heap token immediate byte offset"); + if (so >= limit) refuse(i.pc, "heap token byte offset register"); + const auto value = s.at(so); + if ((value.type != Symbol::Type::masked && value.type != Symbol::Type::constant) || + (value.value & 3) || value.value > UINT_MAX - offset) + refuse(i.pc, "heap token byte offset has no proven 4-byte aligned range"); + const auto address = ir.binary("add", operand32(i, so), to_string(offset)); + for (unsigned j = 0; j < 8; ++j) write(i.dst + j, address); + return; + } if (pixel_heap_enabled && low.type == Symbol::Type::table && low.value == compute_resource_heap && i.op == 3) { if (i.dst + 8 > 106 || !(s.at(i.src[0] + 1) == Symbol{Symbol::Type::constant,0})) refuse(i.pc, "invalid pixel heap texture descriptor address"); @@ -1007,6 +1036,84 @@ struct DirectCompute { ir.features |= 0x40000000; return ir.heap_handle(physical,dim==1?2u:7u,1033,false,key.nonuniform); } + // A texture chosen by GPU data from the resource heap, read through its view token. The title's own descriptor words + // are not read: the s_load_dwordx8 left the byte address so + imm of the token in all eight words. The token is 32 + // bytes of title heap memory: word 0 the magic, word 1 the view id (a content token has bit 31 set and is not an id). + // The texture is ResourceDescriptorHeap[base(dimension) + id] when the magic and the id range hold and the dimension + // table says the id names a view of this instruction's dimension (1 + SQ dim code); otherwise the null slot is read + // and the first lane of the wave counts one miss. The index comes from words every lane loads from the same address, + // so it is dynamically uniform. + string heap_token_texture(const Inst &i, const State &s, unsigned base, unsigned dim) { + const auto sym = s.at(base); + if (!heap_tokens || sym.type != Symbol::Type::indexed_descriptor || sym.value != compute_resource_heap || + base + 8 > 106 || (sym.offset & 3) || (dim != 0 && dim != 1 && dim != 5)) + refuse(i.pc, "unproven heap token texture descriptor"); + for (unsigned j = 1; j < 8; ++j) { + auto expected = sym; + expected.offset += 4 * j; + if (!(s.at(base + j) == expected)) refuse(i.pc, "mixed heap token texture descriptor words"); + } + // Only a token load (s_load_dwordx8 from the resource heap) defines such a symbol here; a descriptor address built + // by s_add_u32 (heap_offset_address) does too, and is refused. + const auto defined = analysis.program.at.find(sym.definition); + if (defined == analysis.program.at.end() || analysis.program.code[defined->second].enc != Encoding::Smem || + analysis.program.code[defined->second].op != 3) + refuse(i.pc, "heap token texture descriptor is not a token load"); + if (std::none_of(heap_token_consumers.begin(), heap_token_consumers.end(), + [&](const auto &c) { return c.pc == i.pc && c.dim == dim; })) + refuse(i.pc, "heap token consumer was not listed by the pre-pass"); + // 16: the module reads raw buffers (the token memory and the dimension table), as for every raw view above; + // 0x40000000: it reads ResourceDescriptorHeap. Same flags as heap_resource, see tests/native_heap_handle_probe_check.py. + ir.features |= 16 | 0x40000000; + const auto tokens = ir.handle({0, token_srv, 11}); + const auto dims = ir.handle({0, token_dims_srv, 11}); + const auto address = read(base); + const auto load_word = [&](const string &handle, const string &at) { + const auto ret = load_buffer(handle, at, true, 1); + return ir.value("extractvalue %dx.types.ResRet.i32 " + ret + ", 0"); + }; + const auto magic = load_word(tokens, address); + const auto id = load_word(tokens, ir.binary("add", address, "4")); + const auto &count = heap_token_values[3]; + const auto in_range = cmp("ult", id, count); + const auto clamped = select(in_range, id, ir.binary("sub", count, "1")); + const auto recorded = load_word(dims, ir.binary("shl", clamped, "2")); + auto valid = ir.value("and i1 " + cmp("eq", magic, to_string(0x56573258u)) + ", " + in_range); + valid = ir.value("and i1 " + valid + ", " + cmp("eq", recorded, to_string(1 + dim))); + const auto &first = heap_token_values[dim == 0 ? 0 : dim == 1 ? 1 : 2]; + const auto slot = select(valid, ir.binary("add", first, id), heap_token_values[4]); + // One count per wave and execution that reads the null slot. + ir.uses_wave = true; + const auto first_lane = ir.invoke("i1", "waveIsFirstLane", 110, {}, "nounwind"); + const auto missed = ir.value("and i1 " + ir.value("xor i1 " + valid + ", true") + ", " + first_lane); + const auto tag = to_string(label_number++); + ir.body << " br i1 " << missed << ", label %tokenMiss" << tag << ", label %tokenMissEnd" << tag << "\ntokenMiss" + << tag << ":\n"; + const auto counter = ir.handle({1, token_miss_uav, 11}); + ir.invoke("i32", "atomicBinOp.i32", 78, + {{"%dx.types.Handle", counter}, {"i32", "0"}, {"i32", "0"}, {"i32", "undef"}, {"i32", "undef"}, + {"i32", "1"}}, + "nounwind"); + ir.body << " br label %tokenMissEnd" << tag << "\ntokenMissEnd" << tag << ":\n"; + constexpr unsigned dx_kind[]{1, 2, 0, 0, 0, 7}; + return ir.heap_handle(slot, dx_kind[dim], 1033, false, false); + } + // The runtime-provided bindings and words of the token route. Taken before lowering because the DXIL names them. + void prepare_heap_tokens() { + if (!token_bindings()) return; + auto &r = analysis.result; + unsigned words = 5 + static_cast(descriptor_strides.size()); + for (const auto &block : r.constants) words += block.count; + if (words > 32) + refuse(analysis.program.code.front().pc, "heap token words exceed the 32-word compute entry layout"); + r.heap_token_words = true; + token_srv = analysis.srv++; + token_dims_srv = analysis.srv++; + token_miss_uav = analysis.uav++; + r.bindings.push_back({ComputeViewKind::heap_token_srv, compute_heap_token, 0, token_srv, 0}); + r.bindings.push_back({ComputeViewKind::heap_token_dims_srv, compute_heap_token, 0, token_dims_srv, 0}); + r.bindings.push_back({ComputeViewKind::heap_token_miss_uav, compute_heap_token, 0, token_miss_uav, 4}); + } string texture_dimensions(const string &handle, const string &mip) { return ir.invoke("%dx.types.Dimensions", "getDimensions", 72, {{"%dx.types.Handle", handle}, {"i32", mip}}, "nounwind readonly"); @@ -1182,7 +1289,8 @@ struct DirectCompute { constexpr unsigned dx_kind[]{1, 2, 4, 5, 6, 7, 3, 8}; constexpr unsigned coord_count[]{1, 2, 3, 3, 2, 3, 2, 3}; const unsigned coords = coord_count[dim]; - const bool indexed = pixel_stage && !store && s.at(base).type == Symbol::Type::indexed_descriptor; + const bool indexed = (pixel_stage || (heap_tokens && s.at(base).value == compute_resource_heap)) && !store && + s.at(base).type == Symbol::Type::indexed_descriptor; const bool exact_store = store && !half && !graphics_input && (dim == 1 || dim == 2 || dim == 5) && (mask == 1 || mask == 3 || mask == 7); // Read-only image ops ignore GLC (bit 13, 0x2000) and DLC (bit 7, 0x0080) cache hints; @@ -1219,7 +1327,10 @@ struct DirectCompute { : compare ? ComputeViewKind::comparison_texture_srv : ComputeViewKind::texture_srv; string h; - if (selected || (indexed && s[base].value==compute_resource_heap)) { + if (heap_tokens && !pixel_stage && indexed) { + if (kind != ComputeViewKind::texture_srv) refuse(i.pc,"unsupported heap token texture view class"); + h=heap_token_texture(i,s,base,dim); + } else if (selected || (indexed && s[base].value==compute_resource_heap)) { if (kind != ComputeViewKind::texture_srv) refuse(i.pc,"unsupported pixel heap texture view class"); h=pixel_heap_texture(i,s,base,dim,selected); } else { @@ -5152,6 +5263,7 @@ struct DirectCompute { if (uses_lds) ir.globals << "@lds = internal addrspace(3) global [" << lds_words << " x i32] undef, align 4\n"; prepare_descriptor_strides(); + prepare_heap_tokens(); const auto &p = analysis.program; mode_bits = 0xf0; bool mode_write = false, conditional = false; diff --git a/src/native_compute_output.h b/src/native_compute_output.h index 24b8ccd3ba..186e4261d8 100644 --- a/src/native_compute_output.h +++ b/src/native_compute_output.h @@ -5,7 +5,7 @@ namespace x2w { // Bump whenever a native translation of an unchanged request can change meaning. -constexpr unsigned native_compute_output_revision = 1; +constexpr unsigned native_compute_output_revision = 2; enum class NativeComputeOutput { unmarked, current, incompatible }; diff --git a/src/native_compute_pipeline.cpp b/src/native_compute_pipeline.cpp index f0f51b1299..b3201a1dd6 100644 --- a/src/native_compute_pipeline.cpp +++ b/src/native_compute_pipeline.cpp @@ -50,6 +50,7 @@ NativeComputePipeline create_native_compute_pipeline(ID3D12Device *device, Shade pipeline.uav_count = counts[1]; pipeline.constants = std::move(program.constants); pipeline.stride_srvs = std::move(program.stride_srvs); + pipeline.token_words = program.heap_token_words ? 5u : 0u; for (const auto &block : pipeline.constants) pipeline.constant_words += block.count; pipeline.srv_count = counts[0]; @@ -69,7 +70,7 @@ NativeComputePipeline create_native_compute_pipeline(ID3D12Device *device, Shade D3D12_DESCRIPTOR_RANGE ranges[2]{}; for (const auto &b : pipeline.bindings) pipeline.atomic_views += b.kind == ComputeViewKind::indexed_atomic_uav; - const auto b0_words = pipeline.constant_words + static_cast(pipeline.stride_srvs.size()); + const auto b0_words = pipeline.constant_words + static_cast(pipeline.stride_srvs.size()) + pipeline.token_words; if (unsigned(bool(counts[0])) + unsigned(bool(counts[1])) + b0_words + 2 * pipeline.atomic_views > D3D12_MAX_ROOT_COST) throw UnsupportedComputeShader("indexed atomic view metadata exceeds root parameter budget"); @@ -95,7 +96,7 @@ NativeComputePipeline create_native_compute_pipeline(ID3D12Device *device, Shade param.ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS; param.Constants = {b.shader_register + 1, 0, 2}; } - const UINT root_flags = (pipeline.heap_indexed ? 0x400u : 0u) // CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED + const UINT root_flags = (pipeline.heap_indexed || pipeline.token_words ? 0x400u : 0u) // CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED | (pipeline.sampler_heap_indexed ? 0x800u : 0u); // SAMPLER_HEAP_DIRECTLY_INDEXED D3D12_ROOT_SIGNATURE_DESC desc{param_count, params.data(), static_cast(samplers.size()), samplers.data(), static_cast(root_flags)}; @@ -121,6 +122,8 @@ void NativeComputePipeline::bind(ID3D12GraphicsCommandList *list, ID3D12Descript throw std::runtime_error("compute root constants missing"); if (atomic.size() != atomic_views) throw std::runtime_error("indexed atomic view metadata missing"); + // The heap token words (token_words) are not bound here: no runtime reads them yet (the manifest reader refuses the + // lines), and a caller that needs them, as the fixture does, sets them after bind(). if (strides.size() != stride_srvs.size()) throw std::runtime_error("compute descriptor stride metadata missing"); const bool views = srv_count || uav_count || heap_indexed; @@ -149,7 +152,7 @@ void NativeComputePipeline::bind(ID3D12GraphicsCommandList *list, ID3D12Descript list->SetComputeRoot32BitConstants(parameter, constant_words, words, 0); if (!strides.empty()) list->SetComputeRoot32BitConstants(parameter, static_cast(strides.size()), strides.data(), constant_words); - if (constant_words || !strides.empty()) ++parameter; + if (constant_words || !strides.empty() || token_words) ++parameter; for (const auto &shape : atomic) { const unsigned pair[]{shape.stride, shape.count}; list->SetComputeRoot32BitConstants(parameter++, 2, pair, 0); diff --git a/src/native_compute_pipeline.h b/src/native_compute_pipeline.h index 6dc3d8044e..b95f8756db 100644 --- a/src/native_compute_pipeline.h +++ b/src/native_compute_pipeline.h @@ -17,6 +17,7 @@ struct NativeComputePipeline { unsigned srv_count = 0; unsigned uav_count = 0; unsigned constant_words = 0, atomic_views = 0; + unsigned token_words = 0; // heap token texture words (base1d, base2d, base2da, count, null) after the stride words unsigned instructions = 0; bool cache_hit = false, frontend_cache_hit = false; bool heap_indexed = false; // reads ResourceDescriptorHeap: the root signature indexes the heap directly, which must be set diff --git a/src/startup_stubs/d3d12_compute_dispatch.inl b/src/startup_stubs/d3d12_compute_dispatch.inl index 9356b70f3f..cfa61a3d5f 100644 --- a/src/startup_stubs/d3d12_compute_dispatch.inl +++ b/src/startup_stubs/d3d12_compute_dispatch.inl @@ -348,6 +348,12 @@ const char* load_compute_translation(ComputeTranslation& tr) }; if (line.empty() || (std::sscanf(line.c_str(), "group %u %u %u%n", &x, &y, &z, &used) == 3 && whole())) continue; if (std::sscanf(line.c_str(), "ud %u%n", &declared_uds, &used) == 1 && whole()) continue; + // GPU-selected heap textures (view tokens): published by the translator, not bound by this runtime yet. + if ((std::sscanf(line.c_str(), "srv %u heaptok%n", &i, &used) == 1 && whole()) || + (std::sscanf(line.c_str(), "srv %u heaptokdims%n", &i, &used) == 1 && whole()) || + (std::sscanf(line.c_str(), "uav %u heaptokmiss%n", &i, &used) == 1 && whole()) || + (std::sscanf(line.c_str(), "udsrc %u heaptok %15s%n", &i, name, &used) == 2 && whole())) + return "heap token textures are not bound yet"; if (std::sscanf(line.c_str(), "udsrc %u rootconst %d %d%n", &i, &a, &b, &used) == 3 && whole() && i == tr.uds.size()) tr.uds.push_back({a, b}); else if (std::sscanf(line.c_str(), "udsrc %u %15s %d%n", &i, name, &a, &used) == 3 && whole() && i == tr.uds.size() && diff --git a/tests/cmake/native_heap_token_texture.cmake b/tests/cmake/native_heap_token_texture.cmake new file mode 100644 index 0000000000..495ce5eed9 --- /dev/null +++ b/tests/cmake/native_heap_token_texture.cmake @@ -0,0 +1,15 @@ +# GPU-selected heap textures in compute through view tokens, translated natively (#3023 stage 3, PR 1). +# _controls compiles source-written requests (manifest lines, refusals); the fixture runs the translated programs on a host +# heap with one range per dimension. _warp skips (77): WARP has no 32-lane waves. +if(TARGET compile_dxil AND EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${DXC_BIN_DIR}/dxil.dll" AND EXISTS "${INTAKE_PYTHON}") + add_executable(native_heap_token_texture tests/native_heap_token_texture.cpp tests/desktop_gpu.cpp) + target_include_directories(native_heap_token_texture PRIVATE src tests) + target_link_libraries(native_heap_token_texture PRIVATE x2w_shader_compiler d3d12 dxgi d3dcompiler) + set_property(TARGET native_heap_token_texture PROPERTY MSVC_RUNTIME_LIBRARY "MultiThreaded$<$:Debug>") + foreach(adapter IN ITEMS controls warp hardware) + add_test(NAME native_heap_token_texture_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/native_heap_token_texture_check.py" + "$" "$" "${DXC_BIN_DIR}" ${adapter}) + set_tests_properties(native_heap_token_texture_${adapter} PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 300) + endforeach() +endif() diff --git a/tests/native_compile_dxil_watch_check.py b/tests/native_compile_dxil_watch_check.py index 67b1ab2c9a..bb8f0b93f8 100644 --- a/tests/native_compile_dxil_watch_check.py +++ b/tests/native_compile_dxil_watch_check.py @@ -25,6 +25,7 @@ TARGET_MASKS, VS_WORDS, compile_compute_root, + native_revision, compile_graphics_table_root, compute_program_words, describe_psin, @@ -115,7 +116,7 @@ def main(argv: list[str]) -> int: current_manifest = cs_manifest.read_bytes() old_manifest = b"".join(line for line in current_manifest.splitlines(keepends=True) if not line.startswith(b"native ")) - assert current_manifest.splitlines().count(b"native 1") == 1 + assert current_manifest.splitlines().count(b"native %d" % native_revision()) == 1 assert not cs_hlsl.exists() dummy_cso = b"DXBC" + b"\0" * 20 + struct.pack("c_str() : reason.c_str()); failures += !ok; } - std::printf("%d of %zu manifest reasons wrong\n", failures, std::size(cases) + std::size(published) + 3); + // The views and words of GPU-selected heap textures are published by name, in register order with the other views. + { + auto program = base(); + program.heap_token_words = true; + program.bindings.push_back(view(K::heap_token_srv, 1, compute_heap_token)); + program.bindings.push_back(view(K::heap_token_dims_srv, 2, compute_heap_token)); + program.bindings.push_back(view(K::heap_token_miss_uav, 1, compute_heap_token)); + reason = "unset"; + const auto manifest = format_compute_runtime_manifest(program, &reason); + const std::string wanted = "x2w-manifest 2\nstage cs\ngroup 8 4 1\nud 7\nudsrc 0 rootconst 0 0\n" + "udsrc 1 rootconst 0 1\nudsrc 2 heaptok base1d\nudsrc 3 heaptok base2d\n" + "udsrc 4 heaptok base2da\nudsrc 5 heaptok count\nudsrc 6 heaptok null\n" + "srv 0 buf table 1 64\nsrv 1 heaptok\nsrv 2 heaptokdims\nuav 0 table 1 32\n" + "uav 1 heaptokmiss\nnative " + std::to_string(native_compute_output_revision) + "\n"; + const bool ok = manifest && *manifest == wanted && reason == "unset"; + std::printf("%s publishes the heap token views and words\n", ok ? "ok " : "FAIL"); + if (!ok) + std::printf(" | got: %s\n", manifest ? manifest->c_str() : reason.c_str()); + failures += !ok; + } + std::printf("%d of %zu manifest reasons wrong\n", failures, std::size(cases) + std::size(published) + 4); return failures ? 1 : 0; } diff --git a/tests/native_heap_token_texture.cpp b/tests/native_heap_token_texture.cpp new file mode 100644 index 0000000000..b54bb4089e --- /dev/null +++ b/tests/native_heap_token_texture.cpp @@ -0,0 +1,437 @@ +// Native compute fixture: GPU-selected heap textures read through view tokens (#3023 stage 3, PR 1). +// +// usage: native_heap_token_texture SDK CACHE REQ.c67 ADAPTER MODE +// REQ.c67 a source-built compute request (tests/native_heap_token_texture_check.py) whose root has +// CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED and one SRV+UAV table. The program reads the byte address of a token +// from t0 (a raw buffer), loads the texture with s_load_dwordx8 from the resource heap at that address and +// samples (2D) or loads (1D, 2D array) it at a fixed coordinate; lane L writes its texel to u0 at 16 * L. +// MODE tex2d | tex1d | tex2da the dimension of the instruction under test +// The rig binds what the manifest names for the runtime-provided views: the token memory (a raw SRV over a buffer of +// eight 32-byte tokens), the dimension table (one uint per view id), the miss counter (a raw UAV) and the five words +// base1d, base2d, base2da, count, null. The shader indexes a host heap with one range per dimension, one slot per view id +// (ids 1 2D, 2 2D array, 3 1D; id 0 and every other slot are null views of the range's dimension). +// Cases (token at byte address 32 * case): a valid id, a wrong magic, an id equal to the count, the largest id, an id of +// another dimension, a content token (bit 31), id 0, an empty token. A valid token gives the texel of its view and no +// miss; every other case gives the null texel and one miss per wave (the dispatch is three groups of one wave). +// Exit 0: every assertion held. 1: a result differs. 4: setup error. 77: capability skip. +#include "desktop_gpu.h" +#include "direct_compute_cache.h" +#include "native_compute_pipeline.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using Microsoft::WRL::ComPtr; + +namespace { +constexpr unsigned lanes = 32, groups = 3, count = 4; +constexpr unsigned base_1d = 8, base_2d = 16, base_2da = 24, null_slot = 0, table_start = 32; +constexpr std::uint32_t magic = 0x56573258u, sentinel = 0x69696969u; +using Texel = std::array; + +enum class Dim { d1, d2, d2a }; +Texel texel_1d(int x) { return {1000.f + x, 2000.f + x, 3000.f + x, 4000.f}; } +Texel texel_2d(int x, int y) { return {10.f * x + 1, 10.f * y + 2, 100.f + x + 4 * y, 1000.f}; } +Texel texel_2da(int x, int y, int slice) { return {10.f * x + y + 100.f * slice, 500.f + slice, 600.f + x, 700.f + y}; } + +struct Mode { + Dim dim; + unsigned valid_id, mismatch_id; + Texel expected; +}; +bool make_mode(const std::wstring &name, Mode &mode) { + if (name == L"tex2d") mode = {Dim::d2, 1, 2, texel_2d(1, 2)}; + else if (name == L"tex1d") mode = {Dim::d1, 3, 1, texel_1d(1)}; + else if (name == L"tex2da") mode = {Dim::d2a, 2, 1, texel_2da(1, 2, 1)}; + else return false; + return true; +} + +struct Gpu { + ComPtr device; + ComPtr queue; + ComPtr allocator; + ComPtr list; + ComPtr fence; + HANDLE event = nullptr; + UINT64 fence_value = 0; + UINT increment = 0; + ComPtr views; + ComPtr selector, tokens, dims, output, misses, readback, clear_output, clear_misses; + ComPtr tex1d, tex2d, tex2da; + + ~Gpu() { + if (event) CloseHandle(event); + } + int open(const std::wstring &adapter) { + ComPtr factory; + ComPtr chosen; + if (FAILED(CreateDXGIFactory1(IID_PPV_ARGS(&factory)))) return 77; + if (adapter == L"warp") { + if (FAILED(factory->EnumWarpAdapter(IID_PPV_ARGS(&chosen)))) return 77; + } else { + for (UINT i = 0; i < 8; ++i) { + ComPtr candidate; + if (factory->EnumAdapters1(i, &candidate) == DXGI_ERROR_NOT_FOUND) break; + DXGI_ADAPTER_DESC1 desc{}; + candidate->GetDesc1(&desc); + if (!(desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE)) { + chosen = candidate; + std::printf("adapter=%ls\n", desc.Description); + break; + } + } + if (!chosen) { std::puts("no hardware adapter"); return 77; } + } + if (FAILED(D3D12CreateDevice(chosen.Get(), D3D_FEATURE_LEVEL_11_0, IID_PPV_ARGS(&device)))) { + std::puts("no device"); + return 77; + } + D3D12_FEATURE_DATA_SHADER_MODEL model{D3D_SHADER_MODEL_6_6}; + D3D12_FEATURE_DATA_D3D12_OPTIONS options{}; + if (FAILED(check_feature(device.Get(), D3D12_FEATURE_SHADER_MODEL, &model, sizeof model)) || + model.HighestShaderModel < D3D_SHADER_MODEL_6_6 || + FAILED(check_feature(device.Get(), D3D12_FEATURE_D3D12_OPTIONS, &options, sizeof options)) || + options.ResourceBindingTier < D3D12_RESOURCE_BINDING_TIER_3) { + std::printf("adapter lacks shader model 6.6 or resource binding tier 3 (tier %d)\n", + int(options.ResourceBindingTier)); + return 77; + } + // The native module declares WaveSize=32 (the guest wave), so an adapter without 32-lane waves cannot run it. + D3D12_FEATURE_DATA_D3D12_OPTIONS1 waves{}; + if (FAILED(check_feature(device.Get(), D3D12_FEATURE_D3D12_OPTIONS1, &waves, sizeof waves)) || !waves.WaveOps || + waves.WaveLaneCountMin > 32 || waves.WaveLaneCountMax < 32) { + std::printf("adapter has no 32-lane waves (%u..%u)\n", waves.WaveLaneCountMin, waves.WaveLaneCountMax); + return 77; + } + { + D3D12_ROOT_SIGNATURE_DESC probe{0, nullptr, 0, nullptr, static_cast(0x400)}; + ComPtr blob; + ComPtr root; + if (FAILED(D3D12SerializeRootSignature(&probe, D3D_ROOT_SIGNATURE_VERSION_1, &blob, nullptr)) || + FAILED(device->CreateRootSignature(0, blob->GetBufferPointer(), blob->GetBufferSize(), + IID_PPV_ARGS(&root)))) { + std::puts("adapter refuses a root with the heap-indexing flag 0x400"); + return 77; + } + } + D3D12_COMMAND_QUEUE_DESC queue_desc{D3D12_COMMAND_LIST_TYPE_DIRECT}; + check(device->CreateCommandQueue(&queue_desc, IID_PPV_ARGS(&queue)), "queue"); + check(device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator)), "allocator"); + check(device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocator.Get(), nullptr, IID_PPV_ARGS(&list)), + "list"); + check(list->Close(), "close"); + check(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence)), "fence"); + event = CreateEventW(nullptr, FALSE, FALSE, nullptr); + if (!event) throw std::runtime_error("event"); + increment = device->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); + return 0; + } + void wait() { + check(queue->Signal(fence.Get(), ++fence_value), "signal"); + check(fence->SetEventOnCompletion(fence_value, event), "fence event"); + if (WaitForSingleObject(event, 30000) != WAIT_OBJECT_0) throw std::runtime_error("fence wait timed out"); + } + template void run(Body body) { + check(allocator->Reset(), "allocator reset"); + check(list->Reset(allocator.Get(), nullptr), "list reset"); + body(list.Get()); + check(list->Close(), "list close"); + ID3D12CommandList *lists[]{list.Get()}; + queue->ExecuteCommandLists(1, lists); + wait(); + check(device->GetDeviceRemovedReason(), "device removed"); + } + static D3D12_RESOURCE_BARRIER barrier(ID3D12Resource *resource, D3D12_RESOURCE_STATES before, + D3D12_RESOURCE_STATES after) { + D3D12_RESOURCE_BARRIER b{}; + b.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; + b.Transition = {resource, D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, before, after}; + return b; + } + D3D12_CPU_DESCRIPTOR_HANDLE cpu(unsigned slot) const { + auto handle = views->GetCPUDescriptorHandleForHeapStart(); + handle.ptr += SIZE_T(slot) * increment; + return handle; + } + ComPtr upload_buffer(const std::vector &words) { + auto buffer = make_buffer(device.Get(), words.size() * 4, D3D12_HEAP_TYPE_UPLOAD, D3D12_RESOURCE_STATE_GENERIC_READ); + void *mapped = nullptr; + check(buffer->Map(0, nullptr, &mapped), "upload map"); + std::memcpy(mapped, words.data(), words.size() * 4); + buffer->Unmap(0, nullptr); + return buffer; + } + void rewrite(ID3D12Resource *buffer, const std::vector &words) { + void *mapped = nullptr; + check(buffer->Map(0, nullptr, &mapped), "rewrite map"); + std::memcpy(mapped, words.data(), words.size() * 4); + buffer->Unmap(0, nullptr); + } + // A texture whose texel (x, y, slice) is f(x, y, slice), one mip. + ComPtr texture(D3D12_RESOURCE_DIMENSION dimension, UINT width, UINT height, UINT slices, + const std::function &f) { + D3D12_RESOURCE_DESC td{}; + td.Dimension = dimension; + td.Width = width; + td.Height = height; + td.DepthOrArraySize = static_cast(slices); + td.MipLevels = 1; + td.Format = DXGI_FORMAT_R32G32B32A32_FLOAT; + td.SampleDesc.Count = 1; + auto result = resource(device.Get(), td, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_STATE_COPY_DEST); + std::vector footprints(slices); + UINT64 total = 0; + device->GetCopyableFootprints(&td, 0, slices, 0, footprints.data(), nullptr, nullptr, &total); + auto upload = make_buffer(device.Get(), total, D3D12_HEAP_TYPE_UPLOAD, D3D12_RESOURCE_STATE_GENERIC_READ); + void *mapped = nullptr; + check(upload->Map(0, nullptr, &mapped), "texture upload map"); + for (UINT s = 0; s < slices; ++s) + for (UINT y = 0; y < height; ++y) + for (UINT x = 0; x < width; ++x) + std::memcpy(static_cast(mapped) + footprints[s].Offset + + y * footprints[s].Footprint.RowPitch + x * sizeof(Texel), + f(int(x), int(y), int(s)).data(), sizeof(Texel)); + upload->Unmap(0, nullptr); + run([&](ID3D12GraphicsCommandList *l) { + for (UINT s = 0; s < slices; ++s) { + D3D12_TEXTURE_COPY_LOCATION src{upload.Get(), D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT}, + dst{result.Get(), D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX}; + src.PlacedFootprint = footprints[s]; + dst.SubresourceIndex = s; + l->CopyTextureRegion(&dst, 0, 0, 0, &src, nullptr); + } + auto to_read = barrier(result.Get(), D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE); + l->ResourceBarrier(1, &to_read); + }); + return result; + } + void srv(unsigned slot, ID3D12Resource *resource_or_null, D3D12_SRV_DIMENSION dimension) { + D3D12_SHADER_RESOURCE_VIEW_DESC desc{}; + desc.Format = DXGI_FORMAT_R32G32B32A32_FLOAT; + desc.ViewDimension = dimension; + desc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + if (dimension == D3D12_SRV_DIMENSION_TEXTURE1D) desc.Texture1D.MipLevels = 1; + else if (dimension == D3D12_SRV_DIMENSION_TEXTURE2D) desc.Texture2D.MipLevels = 1; + else { + desc.Texture2DArray.MipLevels = 1; + desc.Texture2DArray.ArraySize = resource_or_null ? 2 : 1; + } + device->CreateShaderResourceView(resource_or_null, &desc, cpu(slot)); + } + void raw_srv(unsigned slot, ID3D12Resource *buffer, UINT words) { + D3D12_SHADER_RESOURCE_VIEW_DESC desc{}; + desc.Format = DXGI_FORMAT_R32_TYPELESS; + desc.ViewDimension = D3D12_SRV_DIMENSION_BUFFER; + desc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + desc.Buffer.NumElements = words; + desc.Buffer.Flags = D3D12_BUFFER_SRV_FLAG_RAW; + device->CreateShaderResourceView(buffer, &desc, cpu(slot)); + } + void raw_uav(unsigned slot, ID3D12Resource *buffer, UINT words) { + D3D12_UNORDERED_ACCESS_VIEW_DESC desc{}; + desc.Format = DXGI_FORMAT_R32_TYPELESS; + desc.ViewDimension = D3D12_UAV_DIMENSION_BUFFER; + desc.Buffer.NumElements = words; + desc.Buffer.Flags = D3D12_BUFFER_UAV_FLAG_RAW; + device->CreateUnorderedAccessView(buffer, nullptr, &desc, cpu(slot)); + } +}; + +// What the manifest says about the runtime-provided views and words. +struct Layout { + int selector = -1, out = -1, tokens = -1, dims = -1, miss = -1; + std::map words; // base1d ... null -> user data index + unsigned srv_count = 0; +}; +bool parse_manifest(const std::string &text, Layout &layout) { + std::istringstream in(text); + std::string line; + while (std::getline(in, line)) { + std::istringstream words(line); + std::vector w; + for (std::string token; words >> token;) w.push_back(token); + if (w.size() >= 3 && w[0] == "srv") { + ++layout.srv_count; + const int n = std::stoi(w[1]); + if (w[2] == "buf" && line == "srv " + w[1] + " buf table 0 0") layout.selector = n; + if (w[2] == "heaptok" && w.size() == 3) layout.tokens = n; + if (w[2] == "heaptokdims" && w.size() == 3) layout.dims = n; + } else if (w.size() >= 3 && w[0] == "uav") { + const int n = std::stoi(w[1]); + if (w[2] == "heaptokmiss" && w.size() == 3) layout.miss = n; + if (line == "uav " + w[1] + " table 0 32") layout.out = n; + } else if (w.size() == 4 && w[0] == "udsrc" && w[2] == "heaptok") + layout.words[w[3]] = static_cast(std::stoul(w[1])); + } + return layout.selector >= 0 && layout.out >= 0 && layout.tokens >= 0 && layout.dims >= 0 && layout.miss >= 0 && + layout.words.size() == 5; +} + +bool same_bits(const Texel &a, const Texel &b) { return std::memcmp(a.data(), b.data(), sizeof a) == 0; } + +int run_mode(const std::wstring &sdk, const std::wstring &cache, const std::filesystem::path &marker, Gpu &gpu, + const std::wstring &name, const std::wstring &) { + Mode mode{}; + if (!make_mode(name, mode)) { + std::puts("unknown mode"); + return 2; + } + const std::string label = std::string(name.begin(), name.end()); + bool hit = false; + const auto program = x2w::prepare_direct_compute(marker, 0, false, cache, hit); + std::string reason; + const auto manifest = x2w::format_compute_runtime_manifest(program, &reason); + Layout layout; + if (!manifest || !parse_manifest(*manifest, layout)) { + std::printf("FAIL: the manifest does not name the token views and words (%s)\n%s\n", reason.c_str(), + manifest ? manifest->c_str() : "(none)"); + return 1; + } + std::printf("pass: %s the manifest names the token views and words\n", label.c_str()); + + x2w::ShaderDxilCompiler compiler(sdk); + auto pipeline = x2w::create_native_compute_pipeline(gpu.device.Get(), compiler, marker, 0, cache, true); + if (pipeline.srv_count != layout.srv_count || pipeline.uav_count != 2) { + std::printf("FAIL: pipeline srv=%u uav=%u, manifest srv=%u\n", pipeline.srv_count, pipeline.uav_count, + layout.srv_count); + return 1; + } + + // Resources. Descriptors below table_start are the host heap the shader indexes; the table follows. + D3D12_DESCRIPTOR_HEAP_DESC hd{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 128, D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE}; + check(gpu.device->CreateDescriptorHeap(&hd, IID_PPV_ARGS(&gpu.views)), "view heap"); + gpu.tex1d = gpu.texture(D3D12_RESOURCE_DIMENSION_TEXTURE1D, 4, 1, 1, [](int x, int, int) { return texel_1d(x); }); + gpu.tex2d = gpu.texture(D3D12_RESOURCE_DIMENSION_TEXTURE2D, 4, 4, 1, [](int x, int y, int) { return texel_2d(x, y); }); + gpu.tex2da = gpu.texture(D3D12_RESOURCE_DIMENSION_TEXTURE2D, 4, 4, 2, + [](int x, int y, int s) { return texel_2da(x, y, s); }); + const auto dimension = mode.dim == Dim::d1 ? D3D12_SRV_DIMENSION_TEXTURE1D + : mode.dim == Dim::d2 ? D3D12_SRV_DIMENSION_TEXTURE2D : D3D12_SRV_DIMENSION_TEXTURE2DARRAY; + gpu.srv(null_slot, nullptr, dimension); // the null slot has the dimension of the instruction under test + for (unsigned id = 0; id < count; ++id) { + gpu.srv(base_1d + id, id == 3 ? gpu.tex1d.Get() : nullptr, D3D12_SRV_DIMENSION_TEXTURE1D); + gpu.srv(base_2d + id, id == 1 ? gpu.tex2d.Get() : nullptr, D3D12_SRV_DIMENSION_TEXTURE2D); + gpu.srv(base_2da + id, id == 2 ? gpu.tex2da.Get() : nullptr, D3D12_SRV_DIMENSION_TEXTURE2DARRAY); + } + gpu.selector = make_buffer(gpu.device.Get(), 16, D3D12_HEAP_TYPE_UPLOAD, D3D12_RESOURCE_STATE_GENERIC_READ); + std::vector token_words(8 * 8, 0xdeadbeefu); + const std::uint32_t tokens[8][2] = {{magic, mode.valid_id}, {magic + 1, mode.valid_id}, {magic, count}, + {magic, 0xffffffffu}, {magic, mode.mismatch_id}, + {magic, 0x80000000u | mode.valid_id}, {magic, 0}, {0, 0}}; + for (unsigned c = 0; c < 8; ++c) { + token_words[c * 8] = tokens[c][0]; + token_words[c * 8 + 1] = tokens[c][1]; + } + gpu.tokens = gpu.upload_buffer(token_words); + gpu.dims = gpu.upload_buffer({0, 2, 6, 1}); // 1 + the SQ image dimension: 2D 2, 2D array 6, 1D 1 + gpu.output = make_buffer(gpu.device.Get(), lanes * sizeof(Texel), D3D12_HEAP_TYPE_DEFAULT, + D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS); + gpu.misses = make_buffer(gpu.device.Get(), 4, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, + D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS); + gpu.readback = make_buffer(gpu.device.Get(), 1024, D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_STATE_COPY_DEST); + gpu.clear_output = gpu.upload_buffer(std::vector(lanes * 4, sentinel)); + gpu.clear_misses = gpu.upload_buffer({0}); + // The table: t-registers first, then u-registers, as bind() lays it out. + const unsigned uav_start = table_start + pipeline.srv_count; + gpu.raw_srv(table_start + layout.selector, gpu.selector.Get(), 4); + gpu.raw_srv(table_start + layout.tokens, gpu.tokens.Get(), 64); + gpu.raw_srv(table_start + layout.dims, gpu.dims.Get(), 4); + gpu.raw_uav(uav_start + layout.out, gpu.output.Get(), lanes * 4); + gpu.raw_uav(uav_start + layout.miss, gpu.misses.Get(), 1); + auto first = gpu.views->GetGPUDescriptorHandleForHeapStart(); + first.ptr += UINT64(table_start) * gpu.increment; + const std::map values{{"base1d", base_1d}, {"base2d", base_2d}, {"base2da", base_2da}, + {"count", count}, {"null", null_slot}}; + + auto dispatch = [&](unsigned address, std::vector &out, std::uint32_t &missed) { + gpu.rewrite(gpu.selector.Get(), {address, 0, 0, 0}); + gpu.run([&](ID3D12GraphicsCommandList *l) { + D3D12_RESOURCE_BARRIER to_copy[2]{ + Gpu::barrier(gpu.output.Get(), D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_DEST), + Gpu::barrier(gpu.misses.Get(), D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_DEST)}; + l->ResourceBarrier(2, to_copy); + l->CopyBufferRegion(gpu.output.Get(), 0, gpu.clear_output.Get(), 0, lanes * sizeof(Texel)); + l->CopyBufferRegion(gpu.misses.Get(), 0, gpu.clear_misses.Get(), 0, 4); + D3D12_RESOURCE_BARRIER to_uav[2]{ + Gpu::barrier(gpu.output.Get(), D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_UNORDERED_ACCESS), + Gpu::barrier(gpu.misses.Get(), D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_UNORDERED_ACCESS)}; + l->ResourceBarrier(2, to_uav); + pipeline.bind(l, gpu.views.Get(), first, gpu.increment); + // The b0 parameter follows the SRV and UAV tables; the token words are user data entries. + for (const auto &[word, k] : layout.words) { + const std::uint32_t value = values.at(word); + l->SetComputeRoot32BitConstants(2, 1, &value, k); + } + l->Dispatch(groups, 1, 1); + D3D12_RESOURCE_BARRIER to_source[2]{ + Gpu::barrier(gpu.output.Get(), D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE), + Gpu::barrier(gpu.misses.Get(), D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE)}; + l->ResourceBarrier(2, to_source); + l->CopyBufferRegion(gpu.readback.Get(), 0, gpu.output.Get(), 0, lanes * sizeof(Texel)); + l->CopyBufferRegion(gpu.readback.Get(), 512, gpu.misses.Get(), 0, 4); + D3D12_RESOURCE_BARRIER back[2]{ + Gpu::barrier(gpu.output.Get(), D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_UNORDERED_ACCESS), + Gpu::barrier(gpu.misses.Get(), D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_UNORDERED_ACCESS)}; + l->ResourceBarrier(2, back); + }); + void *mapped = nullptr; + D3D12_RANGE range{0, 1024}; + check(gpu.readback->Map(0, &range, &mapped), "readback map"); + out.resize(lanes * 4); + std::memcpy(out.data(), mapped, lanes * sizeof(Texel)); + std::memcpy(&missed, static_cast(mapped) + 512, 4); + D3D12_RANGE written{}; + gpu.readback->Unmap(0, &written); + }; + + const char *const cases[8] = {"valid", "wrong_magic", "id_at_count", "id_max", "dims_mismatch", "content_token", + "id_zero", "no_token"}; + for (unsigned c = 0; c < 8; ++c) { + std::vector out; + std::uint32_t missed = 0; + dispatch(c * 32, out, missed); + const Texel expected = c == 0 ? mode.expected : Texel{0, 0, 0, 0}; + for (unsigned lane = 0; lane < lanes; ++lane) { + Texel got; + std::memcpy(got.data(), &out[lane * 4], sizeof got); + if (!same_bits(got, expected)) { + std::printf("FAIL: %s %s: lane %u is (%g, %g, %g, %g), expected (%g, %g, %g, %g)\n", label.c_str(), + cases[c], lane, got[0], got[1], got[2], got[3], expected[0], expected[1], expected[2], + expected[3]); + return 1; + } + } + const std::uint32_t expected_misses = c == 0 ? 0 : groups; + if (missed != expected_misses) { + std::printf("FAIL: %s %s: %u misses, expected %u (one per wave)\n", label.c_str(), cases[c], missed, + expected_misses); + return 1; + } + std::printf("pass: %s %s: %s in all %u lanes, %u misses (%u waves)\n", label.c_str(), cases[c], + c == 0 ? "the texel of the view" : "the null texel", lanes, missed, groups); + } + return 0; +} +} // namespace + +int wmain(int argc, wchar_t **argv) { + if (argc != 6) { + std::fputs("usage: native_heap_token_texture SDK CACHE REQ.c67 ADAPTER tex2d|tex1d|tex2da\n", stderr); + return 2; + } + Gpu gpu; + try { + if (int skip = gpu.open(argv[4])) return skip; + return run_mode(argv[1], argv[2], argv[3], gpu, argv[5], argv[4]); + } catch (const std::exception &error) { + std::printf("setup error: %s\n", error.what()); + return 4; + } +} diff --git a/tests/native_heap_token_texture_check.py b/tests/native_heap_token_texture_check.py new file mode 100644 index 0000000000..cf2651ec12 --- /dev/null +++ b/tests/native_heap_token_texture_check.py @@ -0,0 +1,318 @@ +"""GPU-selected heap textures in compute through view tokens, translated natively (#3023 stage 3, PR 1). + +usage: native_heap_token_texture_check.py FIXTURE COMPILE_DXIL SDK ADAPTER (ADAPTER: controls | warp | hardware) + +A guest program loads a 32-byte texture descriptor with s_load_dwordx8 from the directly indexed resource heap at a byte +offset chosen by GPU data (a raw SRV, t0), and samples or loads it. The translator does not read descriptor words: it +reads the view token that the title keeps at that heap address (word 0 the magic, word 1 the view id), checks the magic, +the id range and the dimension recorded for the id, and uses ResourceDescriptorHeap[base(dimension) + id] (the null slot +otherwise, counting one miss per wave). The published manifest names the runtime-provided views and words; the runtime +reader still refuses them by name. + + controls compiles source-written requests: the published manifest, the module's handles, and every consumer or address + shape that must keep today's refusal text (or get the new text), each with a control that compiles. + warp/ runs the fixture `native_heap_token_texture` (valid 1D, 2D and 2D-array views; wrong magic, id out of range, + hardware a view of another dimension, a content token and an empty token read the null slot and count one miss per + wave). Exit 77 when the fixture reports a capability skip (WARP has no 32-lane waves). + +Instruction words were assembled once with LLVM 15 (clang -cc1as -triple amdgcn -target-cpu gfx1013 -filetype asm +-show-encoding); the comment on each line is the assembler source. The test needs no LLVM. +""" +import pathlib +import struct +import subprocess +import sys +import tempfile + +# Same helper as native_sampler_heap_check.py: writes req_.c67 and its parts. +from native_compute_clear_check import write_request + +ROOT = "RootFlags(CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED), DescriptorTable(SRV(t0), UAV(u0))" +ROOT_NO_HEAP = "DescriptorTable(SRV(t0), UAV(u0))" +HEAP_REFUSAL = "direct resource-heap load requires the selected GPU slot and its view type" +UNPROVEN = "heap token byte offset has no proven 4-byte aligned range" +UNALIGNED_IMMEDIATE = "unaligned heap token immediate byte offset" + +BASES = [ + 0xbe880304, # s_mov_b32 s8, s4 (s[8:9]: the table pointer, high word constant 0) + 0xbe890380, # s_mov_b32 s9, 0 + 0xbe8a0305, # s_mov_b32 s10, s5 (s[10:11]: the resource heap base, high word constant 0) + 0xbe8b0380, # s_mov_b32 s11, 0 +] +TABLE_LOADS = [ + 0xf4080304, 0xfa000000, # s_load_dwordx4 s[12:15], s[8:9], 0x0 (t0: the selector, a raw buffer) + 0xf4080604, 0xfa000020, # s_load_dwordx4 s[24:27], s[8:9], 0x20 (u0: the output) +] +SELECTOR_HEAD = [ + 0xbf8cc07f, # s_waitcnt lgkmcnt(0) + 0xf4200406, 0xfa000000, # s_buffer_load_dword s16, s[12:15], 0x0 (the byte address of the token) + 0xbf8cc07f, # s_waitcnt lgkmcnt(0) +] +MASK = [ + 0x8711ff10, 0x0000fffc, # s_and_b32 s17, s16, 0xfffc (proves a 4-byte aligned range) +] +SELECTOR = [*SELECTOR_HEAD, *MASK] +TOKEN_LOAD = [ + 0xf40c0805, 0x22000000, # s_load_dwordx8 s[32:39], s[10:11], s17 (the texture: a view token in the title heap) +] +SAMPLER = [ + 0xbea803ff, 0x00000092, # s_mov_b32 s40, 0x92 (static sampler: clamp x, y and z, point) + 0xbea90380, # s_mov_b32 s41, 0 + 0xbeaa0380, # s_mov_b32 s42, 0 + 0xbeab0380, # s_mov_b32 s43, 0 + 0x34100084, # v_lshlrev_b32_e32 v8, 4, v0 +] +COMPARISON_SAMPLER = [ + 0xbea803ff, 0x08001012, # s_mov_b32 s40, 0x8001012 + 0xbea903ff, 0x00fff000, # s_mov_b32 s41, 0xfff000 + 0xbeaa03ff, 0x04000000, # s_mov_b32 s42, 0x4000000 + 0xbeab0380, # s_mov_b32 s43, 0 + 0x34100084, # v_lshlrev_b32_e32 v8, 4, v0 +] +COORDS_2D = [ + 0x7e0202ff, 0x3ec00000, # v_mov_b32_e32 v1, 0x3ec00000 (u = 0.375: texel 1 of 4) + 0x7e0402ff, 0x3f200000, # v_mov_b32_e32 v2, 0x3f200000 (v = 0.625: texel 2 of 4) +] +COORDS_1D = [ + 0x7e020281, # v_mov_b32_e32 v1, 1 +] +COORDS_2DA = [ + 0x7e020281, # v_mov_b32_e32 v1, 1 + 0x7e040282, # v_mov_b32_e32 v2, 2 + 0x7e060281, # v_mov_b32_e32 v3, 1 +] +FILL_V3 = [ + 0x7e0602f2, # v_mov_b32_e32 v3, 1.0 +] +WAIT = [0xbf8cc07f] # s_waitcnt lgkmcnt(0) +STORE = [ + 0xbf8c3f70, # s_waitcnt vmcnt(0) + 0xe0781000, 0x80060408, # buffer_store_dwordx4 v[4:7], v8, s[24:27], 0 offen + 0xbf810000, # s_endpgm +] +END = [0xbf810000] # s_endpgm + +SAMPLE_2D = [0xf09c0f08, 0x01480401] # image_sample_lz v[4:7], v[1:2], s[32:39], s[40:43] dmask:0xf dim:SQ_RSRC_IMG_2D +LOAD_1D = [0xf0000f00, 0x00080401] # image_load v[4:7], v1, s[32:39] dmask:0xf dim:SQ_RSRC_IMG_1D +LOAD_2DA = [0xf0000f28, 0x00080401] # image_load v[4:7], v[1:3], s[32:39] dmask:0xf dim:SQ_RSRC_IMG_2D_ARRAY +JOIN = [ + 0xbf068010, # s_cmp_eq_u32 s16, 0 + 0xbf850002, # s_cbranch_scc1 2 (skips the token load) +] +HEAP_ADDRESS = [ + 0x8014110a, # s_add_u32 s20, s10, s17 + 0x82158080, # s_addc_u32 s21, 0, 0 + 0xf4080b0a, 0xfa000000, # s_load_dwordx4 s[44:47], s[20:21], 0x0 (a heap descriptor address built by an add) +] +SAMPLE_2D_PARTIAL = [0xf09c0f08, 0x01470401] # image_sample_lz v[4:7], v[1:2], s[28:35], s[40:43] dmask:0xf dim:SQ_RSRC_IMG_2D +ALL_OPS = [ + 0xf0900f08, 0x01480401, # image_sample_l v[4:7], v[1:3], s[32:39], s[40:43] dmask:0xf dim:SQ_RSRC_IMG_2D + 0xf0040f08, 0x00080c01, # image_load_mip v[12:15], v[1:3], s[32:39] dmask:0xf dim:SQ_RSRC_IMG_2D + 0xf11c0108, 0x01481001, # image_gather4_lz v[16:19], v[1:2], s[32:39], s[40:43] dmask:0x1 dim:SQ_RSRC_IMG_2D + 0xf0380f08, 0x00081401, # image_get_resinfo v[20:23], v1, s[32:39] dmask:0xf dim:SQ_RSRC_IMG_2D + 0xf09c0f08, 0x01480401, # image_sample_lz v[4:7], v[1:2], s[32:39], s[40:43] dmask:0xf dim:SQ_RSRC_IMG_2D +] + + +def full(coords, op, load=TOKEN_LOAD, sampler=SAMPLER, store=STORE, selector=SELECTOR): + return [*BASES, *TABLE_LOADS, *selector, *load, *sampler, *coords, *WAIT, *op, *store] + + +PROGRAMS = { + "tex2d": full(COORDS_2D, SAMPLE_2D), + "tex1d": full(COORDS_1D, LOAD_1D), + "tex2da": full(COORDS_2DA, LOAD_2DA), + "all_ops": full([*COORDS_2D, *FILL_V3], ALL_OPS), + # A token load that is never used. + "unused": [*BASES, *TABLE_LOADS, *SELECTOR, *TOKEN_LOAD, *END], +} +# Uses that keep today's refusal: the token words are not only the T# of a supported image instruction. +CONSUMER_CONTROLS = { + "copy": full(COORDS_2D, [0xbeac0320, *SAMPLE_2D]), # s_mov_b32 s44, s32 + # image_store v[4:7], v[1:2], s[32:39] dmask:0xf dim:SQ_RSRC_IMG_2D + "store": full(COORDS_2D, [0xf0200f08, 0x00080401], store=END), + # image_sample_c_lz v8, v[1:3], s[32:39], s[40:43] dmask:0x1 dim:SQ_RSRC_IMG_2D + "comparison": full([*COORDS_2D, *FILL_V3], [0xf0bc0108, 0x01480801], sampler=COMPARISON_SAMPLER, store=END), + # image_sample_lz v[4:7], v[1:3], s[32:39], s[40:43] dmask:0xf dim:SQ_RSRC_IMG_CUBE + "cube": full([*COORDS_2D, *FILL_V3], [0xf09c0f18, 0x01480401], store=END), + # the same with dim:SQ_RSRC_IMG_3D + "volume": full([*COORDS_2D, *FILL_V3], [0xf09c0f10, 0x01480401], store=END), + "numeric": full(COORDS_2D, [0x872cff20, 0x000000ff, *SAMPLE_2D]), # s_and_b32 s44, s32, 0xff + # the token load runs on one path only: after the join the words are not the token symbol any more + "join": full(COORDS_2D, SAMPLE_2D, load=[*JOIN, *TOKEN_LOAD]), + # the T# holds four words of the token load and four others + "partial": full(COORDS_2D, SAMPLE_2D_PARTIAL), + # a descriptor address formed by s_add_u32 next to a token load + "heap_address": full(COORDS_2D, SAMPLE_2D, load=[*HEAP_ADDRESS, *TOKEN_LOAD]), + "join_copy": full(COORDS_2D, [0xbeac0320, *SAMPLE_2D], load=[*JOIN, *TOKEN_LOAD]), # s_mov_b32 s44, s32 after the join + "numeric_join": full(COORDS_2D, [0x872cff20, 0x000000ff, *SAMPLE_2D], load=[*JOIN, *TOKEN_LOAD]), # s_and_b32 s44, s32, 0xff + "field": full(COORDS_2D, [0x93acff21, 0x000e0010, *SAMPLE_2D]), # s_bfe_u32 s44, s33, 0xe0010 (an image field read) +} +# Address shapes. Each program is eligible, so it reaches the load and is refused there. +ADDRESS_CONTROLS = { + # s_load_dwordx8 s[32:39], s[10:11], s16: the offset register is not masked + "unmasked": (full(COORDS_2D, SAMPLE_2D, load=[0xf40c0805, 0x20000000], selector=SELECTOR_HEAD), UNPROVEN), + # s_and_b32 s17, s16, 0xfffe: bit 1 may be set + "misaligned": (full(COORDS_2D, SAMPLE_2D, selector=[*SELECTOR_HEAD, 0x8711ff10, 0x0000fffe]), UNPROVEN), + # s_load_dwordx8 s[32:39], s[10:11], s17 offset:0x2 + "immediate2": (full(COORDS_2D, SAMPLE_2D, load=[0xf40c0805, 0x22000002]), UNALIGNED_IMMEDIATE), + # s_load_dwordx8 s[32:39], s[10:11], 0x20: no SGPR offset keeps the contract refusal + "immediate_only": (full(COORDS_2D, SAMPLE_2D, load=[0xf40c0805, 0xfa000020]), HEAP_REFUSAL), + # s_load_dwordx4 s[32:35], s[10:11], s17: a four-word heap load keeps the contract refusal + "x4": (full(COORDS_2D, SAMPLE_2D, load=[0xf4080805, 0x22000000]), HEAP_REFUSAL), +} +ACCEPTED_ADDRESS = { + # s_load_dwordx8 s[32:39], s[10:11], s17 offset:0x20 + "immediate": full(COORDS_2D, SAMPLE_2D, load=[0xf40c0805, 0x22000020]), +} + +EXPECTED_MANIFEST = """x2w-manifest 2 +stage cs +group 32 1 1 +ud 5 +udsrc 0 heaptok base1d +udsrc 1 heaptok base2d +udsrc 2 heaptok base2da +udsrc 3 heaptok count +udsrc 4 heaptok null +srv 0 heaptok +srv 1 heaptokdims +srv 2 buf table 0 0 +uav 0 heaptokmiss +uav 1 table 0 32 +smpl 0 00000092 00000000 00000000 00000000 +native 2 +""" + +FIXTURE_CASES = ("valid", "wrong_magic", "id_at_count", "id_max", "dims_mismatch", "content_token", "id_zero", "no_token") + + +def main(): + fixture, compile_dxil, sdk, adapter = sys.argv[1:5] + ok_lines = 0 + + def require(condition, message): + nonlocal ok_lines + if not condition: + print("FAIL: " + message) + sys.exit(1) + ok_lines += 1 + print("ok: " + message) + + def run(command, expect_skip=False): + result = subprocess.run([str(part) for part in command], capture_output=True, timeout=300) + out = result.stdout.decode("utf-8", "replace") + err = result.stderr.decode("utf-8", "replace") + print("$ " + " ".join(pathlib.Path(str(c)).name if i == 0 else str(c) for i, c in enumerate(command))) + for text in (out, err): + for line in text.strip().splitlines()[-60:]: + print(" " + line) + print(f" -> exit {result.returncode}") + if result.returncode == 77 and expect_skip: + print("fixture capability skip (77)") + sys.exit(77) + return result.returncode, out, err + + with tempfile.TemporaryDirectory(prefix="x2w_heap_token_") as scratch: + base = pathlib.Path(scratch) + roots = {} + + def root(text): + if text not in roots: + source = base / f"root{len(roots)}.hlsl" + source.write_text(f'#define RS "{text}"') + binary = base / f"root{len(roots)}.bin" + subprocess.run([pathlib.Path(sdk) / "dxc.exe", "-T", "rootsig_1_1", "-E", "RS", "-Fo", binary, source], + check=True, capture_output=True) + roots[text] = binary.read_bytes() + return roots[text] + + counter = 0 + + def request(name, words, root_text=ROOT): + nonlocal counter + counter += 1 + folder = base / f"req_{counter}_{name}" + folder.mkdir() + user = 6 if root_text == ROOT else 5 # four reserved SGPRs, the table, and the resource heap + sa = struct.pack("<7I", 0, 0, 0, 32 | (1 << 16), 1, 0, user << 1) + return write_request(folder, words, root(root_text), sa) + + def compile_request(marker): + output = marker.with_suffix(".cso") + code, out, err = run([compile_dxil, sdk, marker.parent / "cache", "gfx1013-direct-cs@0", marker, output]) + return code, out, err, output + + if adapter != "controls": + for mode in ("tex2d", "tex1d", "tex2da"): + marker = request(mode, PROGRAMS[mode]) + cache = base / f"cache_{mode}" + cache.mkdir() + code, out, err = run([fixture, sdk, cache, marker, adapter, mode], expect_skip=True) + require(code == 0, f"fixture mode {mode} exits 0") + for case in FIXTURE_CASES: + require(f"pass: {mode} {case}:" in out, f"{mode}: case {case} held") + require(f"pass: {mode} the manifest names the token views and words" in out, + f"{mode}: the manifest names heaptok, heaptokdims, heaptokmiss and five heaptok words") + print(f"{ok_lines} assertions held") + return + + # 1. The accepted programs compile, and the module reads the token and the heap. + for name in ("tex2d", "tex1d", "tex2da", "all_ops", "unused"): + marker = request(name, PROGRAMS[name]) + code, out, err, output = compile_request(marker) + require(code == 0 and output.exists(), f"{name}: compiles") + if name == "unused": + # An eligible load without a consumer needs no token view or word. + out_dir = base / "unused_out" + code, out, err = run([compile_dxil, sdk, base / "cache_unused", "gfx1013-direct-cs@0", "--requests", + marker.parent, out_dir]) + text = (out_dir / (marker.stem[len("req_"):] + ".txt")).read_text() + require(code == 0 and "heaptok" not in text, "unused: a token load without a consumer publishes no token line") + continue + listing = subprocess.run([pathlib.Path(sdk) / "dxc.exe", "-dumpbin", output], capture_output=True, + text=True).stdout + require("@dx.op.createHandleFromHeap(i32 218" in listing, f"{name}: the texture comes from createHandleFromHeap") + require("@dx.op.waveIsFirstLane(i32 110)" in listing, f"{name}: the miss is counted by the first lane (op 110)") + require("@dx.op.atomicBinOp.i32(i32 78" in listing, f"{name}: the miss counter is an atomic add (op 78)") + require(listing.count("@dx.op.rawBufferLoad.i32(") >= 3, + f"{name}: the module loads the token words and the dimension") + require(", 1448555096" in listing, f"{name}: the module compares the view token magic") + marker = request("tex2d", PROGRAMS["tex2d"]) + + # 2. The published manifest. + out_dir = base / "requests_out" + code, out, err = run([compile_dxil, sdk, base / "cache_requests", "gfx1013-direct-cs@0", "--requests", + marker.parent, out_dir]) + manifest = out_dir / (marker.stem[len("req_"):] + ".txt") + require(code == 0 and manifest.exists(), "--requests publishes a manifest for a heap token program") + require(manifest.read_text() == EXPECTED_MANIFEST, "the manifest names the token views and the five token words") + # Control: a program without a token load publishes no token line. + plain = request("plain", [*BASES, *TABLE_LOADS, 0xbf810000]) + plain_out = base / "plain_out" + code, out, err = run([compile_dxil, sdk, base / "cache_plain", "gfx1013-direct-cs@0", "--requests", + plain.parent, plain_out]) + text = (plain_out / (plain.stem[len("req_"):] + ".txt")).read_text() + require(code == 0 and "heaptok" not in text, "control: a program without a token load has no token line") + + # 3. Consumers that make the load not eligible keep today's refusal text. + for name, words in CONSUMER_CONTROLS.items(): + code, out, err, output = compile_request(request("c_" + name, words)) + require(code != 0 and HEAP_REFUSAL in err and not output.exists(), + f"{name}: refused with \"{HEAP_REFUSAL}\" and no .cso") + # 4. Address shapes. + for name, (words, text) in ADDRESS_CONTROLS.items(): + code, out, err, output = compile_request(request("a_" + name, words)) + require(code != 0 and text in err and not output.exists(), f"{name}: refused with \"{text}\" and no .cso") + for name, words in ACCEPTED_ADDRESS.items(): + code, out, err, output = compile_request(request("a_" + name, words)) + require(code == 0 and output.exists(), f"control: {name} compiles") + # 5. Without the heap flag there is no heap base to load from. + code, out, err, output = compile_request(request("noheap", PROGRAMS["tex2d"], ROOT_NO_HEAP)) + require(code != 0 and not output.exists(), "a root without the heap flag does not compile the token program") + + print(f"{ok_lines} assertions held") + + +if __name__ == "__main__": + main() diff --git a/tests/native_startup_request_cache_check.py b/tests/native_startup_request_cache_check.py index ad2c8b0d43..dfc2be935a 100644 --- a/tests/native_startup_request_cache_check.py +++ b/tests/native_startup_request_cache_check.py @@ -30,6 +30,13 @@ COMPUTE_RSRC2 = C.USER7 | C.TGID_X | C.TGID_Y | C.TGID_Z | C.tidig(3) + + +def native_revision(): + """native_compute_output_revision of src/native_compute_output.h: the marker a current native manifest ends with.""" + import re + header = Path(__file__).resolve().parent.parent / "src" / "native_compute_output.h" + return int(re.search(r"native_compute_output_revision\s*=\s*(\d+)", header.read_text()).group(1)) def fullscreen_vs_words() -> bytes: vop1 = lambda op, dst, src: 0x7E000000 | dst << 17 | op << 9 | src vop2 = lambda op, dst, src0, vsrc1: op << 25 | dst << 17 | vsrc1 << 9 | src0 @@ -191,7 +198,7 @@ def check_controls(cli: Path, sdk: Path) -> int: "udsrc 1 rootconst 0 1\n" "srv 0 buf table 1 64\n" "uav 0 table 1 32\n" - "native 1\n" + f"native {native_revision()}\n" ) assert G.pending_keys(str(cache), skip_failed=False) == [], "published entries not recognised as complete" diff --git a/tests/startup_compute_dispatch_check.py b/tests/startup_compute_dispatch_check.py index 5d81322f4d..b7eb8d25a9 100644 --- a/tests/startup_compute_dispatch_check.py +++ b/tests/startup_compute_dispatch_check.py @@ -40,6 +40,13 @@ from startup_stream_check import gfx2hlsl as G + + +def native_revision(): + """native_compute_output_revision of src/native_compute_output.h: the marker a current native manifest ends with.""" + import re + header = Path(__file__).resolve().parent.parent / "src" / "native_compute_output.h" + return int(re.search(r"native_compute_output_revision\s*=\s*(\d+)", header.read_text()).group(1)) def dispatch(directory, consumer, env, mode, *, probe=False): out = directory / 'out.bin' out.unlink(missing_ok=True) @@ -118,7 +125,7 @@ def main(consumer, dxc, adapter): assert len(lines(result, 'Dispatch(3, 2, 2) refused: ' + reason)) == 1, result.stderr[-3000:] # Reuse working bytecode to isolate the manifest gate from native adapter requirements. - manifest.write_bytes(python_manifest + b'native 1\n') + manifest.write_bytes(python_manifest + b'native %d\n' % native_revision()) got, result = dispatch(directory, consumer, env, 'dispatch') assert got == expected and not lines(result, 'refused:'), result.stderr[-3000:] hlsl.write_bytes(python_hlsl) diff --git a/tests/startup_compute_dispatch_texture_check.py b/tests/startup_compute_dispatch_texture_check.py index 19d435a25b..ffb9c940a6 100644 --- a/tests/startup_compute_dispatch_texture_check.py +++ b/tests/startup_compute_dispatch_texture_check.py @@ -172,6 +172,10 @@ def check_manifest_refusal(case, variant, reason): 'out-of-order static sampler', original) check_manifest_refusal('out-of-order static sampler', original + 'smp 1 0 0 0 0\n', 'a sampler that is not a plain static one') + # The translator's heap token texture lines (GPU-selected textures read through view tokens) are named, not bound. + for case, line in (('heap token view', 'srv 1 heaptok\n'), ('heap token dimension table', 'srv 1 heaptokdims\n'), + ('heap token miss counter', 'uav 1 heaptokmiss\n'), ('heap token word', 'udsrc 3 heaptok null\n')): + check_manifest_refusal(case, original + line, 'heap token textures are not bound yet') assert original.count('\nud 3\n') == 1, ('entry count mismatch', original) check_manifest_refusal('entry count mismatch', original.replace('\nud 3\n', '\nud 4\n'), 'entry value, input or output count') diff --git a/tools/startup/triage_run.py b/tools/startup/triage_run.py index db6557928e..03bcb1a896 100644 --- a/tools/startup/triage_run.py +++ b/tools/startup/triage_run.py @@ -217,6 +217,7 @@ 'entry value, input or output count', 'formatted D16 write has an incompatible typed buffer UAV', 'formatted D16 write needs the original typed buffer view', + 'heap token textures are not bound yet', 'manifest version', 'native translation from another compiler revision; rebuild it', 'native translation without a revision; rebuild it', From 9917aa9cf1f671711f3a484e3fa35a91b3c0f9e0 Mon Sep 17 00:00:00 2001 From: JB2WIN Date: Mon, 30 Nov 2026 14:07:33 +0100 Subject: [PATCH 2/2] native: address review of heap token textures (EXEC miss count, native-only refusal, SGPR reads) - Count a token miss only when the wave has an active guest lane (ballot of EXEC), not for a wave that reaches the instruction with EXEC = 0. The hardware fixture gains two modes: EXEC limited to the upper 16 lanes (lane 0 inactive) and EXEC = 0. - The native-only route refuses a program with token words with the manifest reader's text ("heap token textures are not bound yet") instead of "view kind N is not bound". Covered by startup_compute_dispatch_native. - conservative_sgpr_reads: encodings without a case now read every SGPR (control flow, LDS, export and interpolation are listed as reading none), and the v_cndmask_b32 lane mask counts as a pair. Control in native_heap_token_texture_controls (mask_pair vs. a mask clear of the T#). - Say why native_compute_output_revision is 2 (header and doc). AI-assisted. Co-Authored-By: Claude Opus 5.5 --- .../experiments/native-heap-token-textures.md | 9 +++-- src/gfx1013_compute_native.cpp | 12 ++++++- src/gfx1013_direct_compute.inl | 7 ++-- src/native_compute_output.h | 4 +++ src/startup_stubs/d3d12_compute_dispatch.inl | 3 ++ tests/native_heap_token_texture.cpp | 20 ++++++++--- tests/native_heap_token_texture_check.py | 19 ++++++++-- .../startup_compute_dispatch_native_check.py | 36 +++++++++++++++++++ 8 files changed, 97 insertions(+), 13 deletions(-) diff --git a/docs/experiments/native-heap-token-textures.md b/docs/experiments/native-heap-token-textures.md index e554728108..eb9e89c713 100644 --- a/docs/experiments/native-heap-token-textures.md +++ b/docs/experiments/native-heap-token-textures.md @@ -26,14 +26,19 @@ those two words at the guest byte address and maps the id to a host descriptor. vouch for the view kind of a GPU-selected slot, and this route checks it on every execution. - Per image instruction of dimension `d`: `valid = word0 == magic && id < count && dims[min(id, count - 1)] == 1 + d`; the handle is `ResourceDescriptorHeap[valid ? base(d) + id : null]` (kind 1, 2 or 7, `nonuniform` false: every lane loads - the same address). When `!valid`, the first lane of the wave adds one to a miss counter (`waveIsFirstLane`, `atomicBinOp`). + the same address). When `!valid`, the first lane of the wave adds one to a miss counter (`waveIsFirstLane`, `atomicBinOp`), but only when the wave has an + active guest lane (`waveActiveBallot` of EXEC is not zero); a wave that reaches the instruction with EXEC = 0 counts nothing. - Five more `b0` words follow the stride words: `base1d`, `base2d`, `base2da`, `count`, `null`. Three runtime-provided views (root parameter `compute_heap_token`): the token memory (`heap_token_srv`, a raw SRV), the dimension table (`heap_token_dims_srv`, a raw SRV with one uint per view id: 0 none, else 1 + the image dimension) and the miss counter (`heap_token_miss_uav`, a raw UAV). They take the first SRV and UAV registers after the stride views, because the module names the registers while it is lowered. - Manifest lines: `srv N heaptok`, `srv N heaptokdims`, `uav N heaptokmiss`, `udsrc K heaptok base1d|base2d|base2da|count|null`. - `native_compute_output_revision` is 2. The root signature of the pipeline sets `CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED` for them. + `native_compute_output_revision` is 2: a request with such a load was refused before and is published now, so the + same request changed meaning. Every published manifest of revision 1 then reads as "another compiler revision; rebuild + it", also those without a token load, which differ only in the `native` marker line; they are rebuilt once. The native-only + route (no manifest reader) refuses a program with token words with the same text as the manifest reader, + `heap token textures are not bound yet`. The root signature of the pipeline sets `CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED` for them. ## Tests diff --git a/src/gfx1013_compute_native.cpp b/src/gfx1013_compute_native.cpp index a3732e5b14..ac8d936073 100644 --- a/src/gfx1013_compute_native.cpp +++ b/src/gfx1013_compute_native.cpp @@ -1743,7 +1743,7 @@ struct HeapTokenLoad { unsigned pc, dim; }; // SGPR ranges {first, count} an instruction may read, widened where the operand width is not known exactly. Anything -// that cannot be listed (indexed SGPR moves) reads everything. +// that cannot be listed (an encoding without a case here, indexed SGPR moves) reads everything. static std::vector> conservative_sgpr_reads(const Inst &i) { std::vector> out; auto add = [&](unsigned first, unsigned count) { @@ -1769,9 +1769,19 @@ static std::vector> conservative_sgpr_reads(const case Encoding::Image: add(((i.b >> 21) & 31) * 4, 4); break; + case Encoding::Sopp: case Encoding::Lds: case Encoding::Export: case Encoding::Interp: + // Control flow, local data share, export and interpolation read no SGPR below 106 (M0 and EXEC are above it). + break; default: + // An encoding this function does not list (the graphics fetch and fixed-function pseudo encodings) may read + // any SGPR: the program is then not eligible when a token word is live. + out.emplace_back(0, 106); break; } + // The lane mask of v_cndmask_b32 (VOP3 src2) is one SGPR in wave32 and a pair in wave64, and the width is not known + // here: count the pair. + if (i.name == "v_cndmask_b32" && (i.enc == Encoding::Vop2 || i.enc == Encoding::Vop3 || i.enc == Encoding::Mix)) + add(i.src[2], 2); if (i.name.find("movrel") != Name::npos) out.emplace_back(0, 106); return out; diff --git a/src/gfx1013_direct_compute.inl b/src/gfx1013_direct_compute.inl index c3c31b8935..f8bd66f01c 100644 --- a/src/gfx1013_direct_compute.inl +++ b/src/gfx1013_direct_compute.inl @@ -1082,10 +1082,13 @@ struct DirectCompute { valid = ir.value("and i1 " + valid + ", " + cmp("eq", recorded, to_string(1 + dim))); const auto &first = heap_token_values[dim == 0 ? 0 : dim == 1 ? 1 : 2]; const auto slot = select(valid, ir.binary("add", first, id), heap_token_values[4]); - // One count per wave and execution that reads the null slot. + // One count per wave and execution that reads the null slot, and only when a guest lane is active (EXEC): a + // wave that reaches the instruction with no active lane reads nothing. The first hardware lane counts, active or not. ir.uses_wave = true; const auto first_lane = ir.invoke("i1", "waveIsFirstLane", 110, {}, "nounwind"); - const auto missed = ir.value("and i1 " + ir.value("xor i1 " + valid + ", true") + ", " + first_lane); + const auto any_active = cmp("ne", ballot(active()), "0"); + const auto missed = ir.value("and i1 " + ir.value("and i1 " + ir.value("xor i1 " + valid + ", true") + ", " + + first_lane) + ", " + any_active); const auto tag = to_string(label_number++); ir.body << " br i1 " << missed << ", label %tokenMiss" << tag << ", label %tokenMissEnd" << tag << "\ntokenMiss" << tag << ":\n"; diff --git a/src/native_compute_output.h b/src/native_compute_output.h index 186e4261d8..bcc69392ee 100644 --- a/src/native_compute_output.h +++ b/src/native_compute_output.h @@ -5,6 +5,10 @@ namespace x2w { // Bump whenever a native translation of an unchanged request can change meaning. +// 2: a request that loads a texture from the directly indexed resource heap at a GPU-selected offset was refused before +// and is published now (heap token lines), so the same request changed meaning. The cost is that every manifest of +// revision 1 reads as "another compiler revision; rebuild it" although the ones without such a load differ only in +// this marker line; they are rebuilt once. constexpr unsigned native_compute_output_revision = 2; enum class NativeComputeOutput { unmarked, current, incompatible }; diff --git a/src/startup_stubs/d3d12_compute_dispatch.inl b/src/startup_stubs/d3d12_compute_dispatch.inl index cfa61a3d5f..b5ba2c1ae8 100644 --- a/src/startup_stubs/d3d12_compute_dispatch.inl +++ b/src/startup_stubs/d3d12_compute_dispatch.inl @@ -513,6 +513,9 @@ bool translate_compute_natively(ComputeTranslation& tr) } if (result == x2w::ComputePackResult::miss) program = x2w::translate_compute(*frozen, 0, true); + // The same refusal text as the manifest reader gives for the token lines, so triage reads one reason on both routes. + if (program.heap_token_words) + throw std::runtime_error("heap token textures are not bound yet"); for (const auto& block : program.constants) for (unsigned word = 0; word < block.count; ++word) tr.uds.push_back({static_cast(block.root_parameter), static_cast(word)}); diff --git a/tests/native_heap_token_texture.cpp b/tests/native_heap_token_texture.cpp index b54bb4089e..46c36aebba 100644 --- a/tests/native_heap_token_texture.cpp +++ b/tests/native_heap_token_texture.cpp @@ -45,9 +45,14 @@ struct Mode { Dim dim; unsigned valid_id, mismatch_id; Texel expected; + unsigned first_active = 0; // lanes below this are inactive in EXEC; `lanes` means no lane is active }; bool make_mode(const std::wstring &name, Mode &mode) { - if (name == L"tex2d") mode = {Dim::d2, 1, 2, texel_2d(1, 2)}; + // tex2d_exechalf: the guest program sets EXEC to the upper 16 lanes (the first lane is inactive). + // tex2d_execnone: it sets EXEC to 0 and still runs the token load and the sample. + if (name == L"tex2d_exechalf") mode = {Dim::d2, 1, 2, texel_2d(1, 2), 16}; + else if (name == L"tex2d_execnone") mode = {Dim::d2, 1, 2, texel_2d(1, 2), lanes}; + else if (name == L"tex2d") mode = {Dim::d2, 1, 2, texel_2d(1, 2)}; else if (name == L"tex1d") mode = {Dim::d1, 3, 1, texel_1d(1)}; else if (name == L"tex2da") mode = {Dim::d2a, 2, 1, texel_2da(1, 2, 1)}; else return false; @@ -397,8 +402,12 @@ int run_mode(const std::wstring &sdk, const std::wstring &cache, const std::file std::vector out; std::uint32_t missed = 0; dispatch(c * 32, out, missed); - const Texel expected = c == 0 ? mode.expected : Texel{0, 0, 0, 0}; + Texel sentinel_texel; + std::memcpy(sentinel_texel.data(), std::vector(4, sentinel).data(), sizeof sentinel_texel); for (unsigned lane = 0; lane < lanes; ++lane) { + // An inactive lane does not store: its output keeps the sentinel the dispatch started with. + const Texel expected = lane < mode.first_active ? sentinel_texel + : c == 0 ? mode.expected : Texel{0, 0, 0, 0}; Texel got; std::memcpy(got.data(), &out[lane * 4], sizeof got); if (!same_bits(got, expected)) { @@ -408,10 +417,11 @@ int run_mode(const std::wstring &sdk, const std::wstring &cache, const std::file return 1; } } - const std::uint32_t expected_misses = c == 0 ? 0 : groups; + // One per wave with an active lane; a wave with EXEC = 0 counts nothing. + const std::uint32_t expected_misses = c == 0 || mode.first_active >= lanes ? 0 : groups; if (missed != expected_misses) { - std::printf("FAIL: %s %s: %u misses, expected %u (one per wave)\n", label.c_str(), cases[c], missed, - expected_misses); + std::printf("FAIL: %s %s: %u misses, expected %u (one per wave with an active lane)\n", label.c_str(), + cases[c], missed, expected_misses); return 1; } std::printf("pass: %s %s: %s in all %u lanes, %u misses (%u waves)\n", label.c_str(), cases[c], diff --git a/tests/native_heap_token_texture_check.py b/tests/native_heap_token_texture_check.py index cf2651ec12..d906f23b1d 100644 --- a/tests/native_heap_token_texture_check.py +++ b/tests/native_heap_token_texture_check.py @@ -114,14 +114,21 @@ ] -def full(coords, op, load=TOKEN_LOAD, sampler=SAMPLER, store=STORE, selector=SELECTOR): - return [*BASES, *TABLE_LOADS, *selector, *load, *sampler, *coords, *WAIT, *op, *store] +EXEC_UPPER_HALF = [0xbefe03ff, 0xffff0000] # s_mov_b32 exec_lo, 0xffff0000 (lane 0 is inactive) +EXEC_NONE = [0xbefe0380] # s_mov_b32 exec_lo, 0 (the load and the sample still execute) + + +def full(coords, op, load=TOKEN_LOAD, sampler=SAMPLER, store=STORE, selector=SELECTOR, exec_mask=()): + return [*BASES, *TABLE_LOADS, *selector, *load, *sampler, *exec_mask, *coords, *WAIT, *op, *store] PROGRAMS = { "tex2d": full(COORDS_2D, SAMPLE_2D), "tex1d": full(COORDS_1D, LOAD_1D), "tex2da": full(COORDS_2DA, LOAD_2DA), + # The same sample with EXEC cut after the token load: a miss counts only in a wave with an active lane. + "tex2d_exechalf": full(COORDS_2D, SAMPLE_2D, exec_mask=EXEC_UPPER_HALF), + "tex2d_execnone": full(COORDS_2D, SAMPLE_2D, exec_mask=EXEC_NONE), "all_ops": full([*COORDS_2D, *FILL_V3], ALL_OPS), # A token load that is never used. "unused": [*BASES, *TABLE_LOADS, *SELECTOR, *TOKEN_LOAD, *END], @@ -147,7 +154,11 @@ def full(coords, op, load=TOKEN_LOAD, sampler=SAMPLER, store=STORE, selector=SEL "join_copy": full(COORDS_2D, [0xbeac0320, *SAMPLE_2D], load=[*JOIN, *TOKEN_LOAD]), # s_mov_b32 s44, s32 after the join "numeric_join": full(COORDS_2D, [0x872cff20, 0x000000ff, *SAMPLE_2D], load=[*JOIN, *TOKEN_LOAD]), # s_and_b32 s44, s32, 0xff "field": full(COORDS_2D, [0x93acff21, 0x000e0010, *SAMPLE_2D]), # s_bfe_u32 s44, s33, 0xe0010 (an image field read) + # v_cndmask_b32 v9, v1, v2, s[31:32]: the lane mask is a pair in wave64 and reaches into the T# at s32 + "mask_pair": full(COORDS_2D, [0xd5010009, 0x007e0501, *SAMPLE_2D]), } +# Control for mask_pair: the same instruction with the mask clear of the T# (s[40:41]) keeps the program eligible. +MASK_CLEAR = full(COORDS_2D, [0xd5010009, 0x00a20501, *SAMPLE_2D]) # v_cndmask_b32 v9, v1, v2, s[40:41] # Address shapes. Each program is eligible, so it reaches the load and is refused there. ADDRESS_CONTROLS = { # s_load_dwordx8 s[32:39], s[10:11], s16: the offset register is not masked @@ -244,7 +255,7 @@ def compile_request(marker): return code, out, err, output if adapter != "controls": - for mode in ("tex2d", "tex1d", "tex2da"): + for mode in ("tex2d", "tex1d", "tex2da", "tex2d_exechalf", "tex2d_execnone"): marker = request(mode, PROGRAMS[mode]) cache = base / f"cache_{mode}" cache.mkdir() @@ -300,6 +311,8 @@ def compile_request(marker): code, out, err, output = compile_request(request("c_" + name, words)) require(code != 0 and HEAP_REFUSAL in err and not output.exists(), f"{name}: refused with \"{HEAP_REFUSAL}\" and no .cso") + code, out, err, output = compile_request(request("c_mask_clear", MASK_CLEAR)) + require(code == 0 and output.exists(), "control: a lane mask clear of the token words keeps the program eligible") # 4. Address shapes. for name, (words, text) in ADDRESS_CONTROLS.items(): code, out, err, output = compile_request(request("a_" + name, words)) diff --git a/tests/startup_compute_dispatch_native_check.py b/tests/startup_compute_dispatch_native_check.py index 5bd50f3539..308f53dbe3 100644 --- a/tests/startup_compute_dispatch_native_check.py +++ b/tests/startup_compute_dispatch_native_check.py @@ -45,6 +45,7 @@ import startup_compute_image_store_check as A import startup_compute_image_store_d16_check as D import startup_gfx2hlsl_image_store_3d1d_check as V +import native_heap_token_texture_check as K from startup_compute_dispatch_check import dispatch, lines, prepare_case from startup_compute_translate_check import state_a from startup_stream_check import gfx2hlsl as G @@ -341,8 +342,43 @@ def texture_outputs(directory, consumer, dxc_dir, adapter, capability_refusal): assert not published, published +HEAP_TOKEN_REFUSAL = 'heap token textures are not bound yet' + + +def heap_token_refusal(directory, consumer, dxc_dir, adapter): + """A program that loads a GPU-selected heap texture is refused in process with the manifest reader's text. + + The native-only route has no manifest reader, so without a check of its own the program would translate and then + fail at the first view the runtime cannot bind ("view kind N is not bound for a natively translated program"). + Control: the same program without the token load is not refused for token words.""" + cache, env = prepare_case(directory, adapter) + env.update(X2W_NATIVE_SHADERS=dxc_dir, X2W_NATIVE_SHADERS_ONLY='1') + source, binary = directory / 'root.hlsl', directory / 'root.bin' + source.write_text(f'#define RS "{K.ROOT}"') + subprocess.run([Path(dxc_dir) / 'dxc.exe', '-T', 'rootsig_1_1', '-E', 'RS', '-Fo', binary, source], + check=True, capture_output=True) + Path(env['X2W_TEST_COMPUTE_ROOT']).write_bytes(binary.read_bytes()) + # Same state words as the token fixture: a 32 x 1 x 1 group, four reserved SGPRs, the table and the heap pointer. + (directory / 'state').write_bytes(struct.pack('<7I', 0, 0, 0, 32 | (1 << 16), 1, 0, 6 << 1)) + untouched = [C.SENTINEL] * C.WORDS + for name, words, token in (('token', K.PROGRAMS['tex2d'], True), + ('plain', [*K.BASES, *K.TABLE_LOADS, *K.END], False)): + (directory / 'program').write_bytes(struct.pack(f'<{len(words)}I', *words)) + got, result = dispatch(directory, consumer, env, 'dispatch') + assert got == untouched, f'{name}: a refused Dispatch wrote the output' + assert not lines(result, 'is not bound for a natively translated program'), result.stderr[-3000:] + if token: + reason = lines(result, 'not translated natively: ') + assert len(reason) == 1 and reason[0].endswith(HEAP_TOKEN_REFUSAL), result.stderr[-3000:] + assert len(lines(result, 'Dispatch(3, 2, 2) refused: no translation')) == 1, result.stderr[-3000:] + else: + assert not lines(result, HEAP_TOKEN_REFUSAL), result.stderr[-3000:] + + def main(consumer, dxc_dir, adapter): scalar_window_case(consumer, dxc_dir, adapter) + with tempfile.TemporaryDirectory() as temporary: + heap_token_refusal(Path(temporary), consumer, dxc_dir, adapter) with tempfile.TemporaryDirectory() as temporary: directory = Path(temporary) cache, env = prepare_case(directory, adapter)