From ec7318d80e2397ac50573b3a03c786860bf435b8 Mon Sep 17 00:00:00 2001 From: JB2WIN Date: Mon, 30 Nov 2026 03:47:29 +0100 Subject: [PATCH 1/8] 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 f58b05fede7649063e3f7448f86c5568d3eef234 Mon Sep 17 00:00:00 2001 From: JB2WIN Date: Mon, 30 Nov 2026 09:49:56 +0100 Subject: [PATCH 2/8] native: translate GPU-selected heap raw buffers through view tokens in compute Refs #3023 #3224. Builds on the heap token textures of #3544. A raw buffer V# loaded with s_load_dwordx4 from the directly indexed resource heap at a GPU-selected byte offset (an SGPR offset, or an address formed by s_add_u32) is read through the view token the title keeps at that address, like the token textures. Reads of that V# in the byte-window form (buffer_load_dword{,x2,x3,x4} with OFFEN, the s_bfe/s_max/s_mul/s_and/s_or rewrite) and scalar buffer loads from it are translated; every other use keeps today's path and refusal text. - Each s_load_dwordx4 candidate is judged on its own; a candidate that fails is dropped and does not take the texture route off the program. An s_add_u32 heap address that is not an eligible candidate keeps the old rejection. - The shader checks magic, id range and the dimension table entry 0x20 (raw buffer view) on every execution and reads ResourceDescriptorHeap[baseraw + id], or the null raw view with one counted miss per wave. - A program with an eligible buffer load publishes seven token words (baseraw and nullraw after the five of the textures): NativeComputeShader:: heap_token_word_count replaces heap_token_words. Texture-only programs keep five words and byte-identical modules and manifests (revision line aside). - native_compute_output_revision 2 -> 3. - The dispatch reader names baseraw and nullraw and still refuses every heaptok line: programs of this change stay refused at dispatch until the runtime binds the views (PR 2). Tests: native_heap_token_texture_controls (eligible forms, controls with today's text, address shapes, loop, mixed texture and buffer), native_heap_token_texture_{warp,hardware} (rawbuf, rawbuf_waterfall, sbuf), native_compute_manifest_reasons, startup_compute_dispatch_texture. The design was frozen by the owner without independent approval (see the PR). Co-Authored-By: Claude Opus 5.5 --- docs/experiments.md | 2 +- .../experiments/native-heap-token-textures.md | 71 +++++- src/direct_compute_cache.cpp | 19 +- src/gfx1013_compute_native.cpp | 231 +++++++++++++----- src/gfx1013_compute_native.h | 8 +- src/gfx1013_direct_compute.inl | 126 ++++++++-- src/native_compute_output.h | 2 +- src/native_compute_pipeline.cpp | 2 +- src/native_compute_pipeline.h | 2 +- src/startup_stubs/d3d12_compute_dispatch.inl | 11 +- tests/native_compute_manifest_reasons.cpp | 39 ++- tests/native_heap_token_texture.cpp | 103 ++++++-- tests/native_heap_token_texture_check.py | 214 +++++++++++++++- .../startup_compute_dispatch_texture_check.py | 7 +- 14 files changed, 721 insertions(+), 116 deletions(-) diff --git a/docs/experiments.md b/docs/experiments.md index de7bdfc6dc..8cf0c8371c 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -18032,4 +18032,4 @@ 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. +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. The same page covers GPU-selected raw buffers read through view tokens (`baseraw` and `nullraw` words). diff --git a/docs/experiments/native-heap-token-textures.md b/docs/experiments/native-heap-token-textures.md index e554728108..e0c6ddee5e 100644 --- a/docs/experiments/native-heap-token-textures.md +++ b/docs/experiments/native-heap-token-textures.md @@ -33,7 +33,7 @@ those two words at the guest byte address and maps the id to a host descriptor. (`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 3 (see Revision below). The root signature of the pipeline sets `CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED` for them. ## Tests @@ -51,3 +51,72 @@ those two words at the guest byte address and maps the id to a host descriptor. 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). + +# GPU-selected raw buffers through view tokens (PR 1c) + +The same token route also reads a raw buffer that the program loads as a V# with `s_load_dwordx4` from the resource heap at +a GPU-selected byte offset, or through an address formed by `s_add_u32` (a waterfall loop over a lane-selected slot, #3224). +Only reads of that V# in the byte-window form and scalar buffer loads from it are translated; everything else keeps today's +path and refusal text. Like the texture route, this translates only where no heap view contract applies +(`HeapViewContract::none`); under a contract the existing `heap_buffer_srv` path is unchanged. + +## What the translator does + +- Candidates are the reached `s_load_dwordx4` from the resource heap with an SGPR offset, and the same load through an + address formed by `s_add_u32` whose high word is the carry of that add (the emitter writes it as 0). Each candidate is + judged on its own (`heap_token_buffer_eligible`). It is eligible when its four words are read only as (a) the V# of a raw + `buffer_load_dword`, `x2`, `x3` or `x4` with OFFEN and without IDXEN, with words 1 to 3 the rewritten fields of the same + load (the byte window: stride cleared, byte count, raw out-of-bounds mode), (b) the base of an `s_buffer_load_dword{,x2,x4,x8,x16}` + of the four unrewritten words, (c) the `s_bfe_u32`, `s_max_u32`, `s_mul_i32`, `s_and_b32` and `s_or_b32` of the rewrite + itself. A copy or numeric read of a word or of a rewritten field, a store, IDXEN, a typed, format or `tbuffer` load, a V# + without the rewrite, a partial V# and a word that a join lost make the candidate not eligible. It is then dropped and keeps + today's path and text; it does not take the texture route off the program. An address formed by `s_add_u32` that is not an + eligible candidate keeps the old rejection of the program for the texture route. +- The analysis of a program with a candidate runs with the byte-window tracking (`heap_window`). If no candidate is + eligible, the program is analysed again exactly as before, so texture-only programs and every other program translate to + the same module and manifest (only the revision line changes). +- The load handler writes the byte address (`so + imm`, or the low word of the added address: the byte offset from heap + slot 0, not a slot index) to the four words. It requires an address that is a multiple of 32: `imm % 32 == 0`, an SGPR + offset that is constant or masked with `(mask & 31) == 0`, no overflow; on an added address `imm == 0` and the same mask. +- The consumer reads the token at that address: `valid = word0 == magic && id < count && dims[min(id, count - 1)] == 0x20`, and + uses `ResourceDescriptorHeap[valid ? baseraw + id : nullraw]` as a raw buffer. A miss is counted as for textures. No + `heap_buffer_srv` binding is created. +- Two more `b0` words follow the five texture words, only in a program with an eligible buffer load: `baseraw`, `nullraw` + (`NativeComputeShader::heap_token_word_count` is 0, 5 or 7). The manifest names them `udsrc K heaptok baseraw|nullraw`. +- The dimension table gains the code `0x20`: a raw buffer view (next to 0 none, else 1 + the image dimension). + The production writer of that table is the runtime change (PR 2); the fixture writes it for its two raw ids. + +## Revision + +`native_compute_output_revision` is 3. `X2W_NATIVE_SHADER_REVISION` hashes the translator sources but not +`native_compute_pipeline.cpp` or `native_compute_output.h`, and the manifest of a program with a token buffer has a new +shape, so the marker is bumped by hand. A request the previous translator refused published nothing, so it is translated +again by the next run (checked: the previous `compile_dxil` refuses the fixture request and leaves its cache empty, the +new one compiles it from the same cache folder). + +## Runtime assumptions and failure modes + +- A1: a token in the bound view heap's memory names the view the title created for that slot. The runtime (PR 2) builds the + raw view per id from the view record, so its byte range is that view's range. +- Failure modes, all read the null raw view (zeros) and count a miss, never a wrong-kind view: no token (the title wrote a raw + V# itself, or the slot was never written because the token write is gated on a title-backed writable view), a wrong magic, + `id >= count`, a content token (word 1 carries flags), a texture id (dimension code not 0x20). +- Not caught: a stale token whose id was released and re-used for another buffer view; the shader then reads the new buffer. + PR 2 must not re-use ids while a stale token can exist (no id reuse, or a generation in word 2 or 3 that this route checks + once PR 2 defines it). +- A2: an out-of-bounds raw buffer read returns 0 (the D3D12 raw buffer bounds rule, an external specification not verified in + this repository; the fixture checks it for lanes past the end of the first raw view on one adapter). +- The runtime reader still refuses every `heaptok` line ("heap token textures are not bound yet"), including `baseraw` and + `nullraw`; programs of this change stay refused at dispatch until PR 2. + +## Tests + +- `native_heap_token_texture_controls`: eligible programs (SGPR offset, added address, scalar buffer load, other widths, an + immediate offset, a texture next to a buffer) and the published manifest; controls that keep today's text (plain V# without + the rewrite, IDXEN, format, `tbuffer`, store, a numeric read of word 2, a copy of a rewritten word, a partial V#, a join, an + immediate offset that breaks the descriptor layout), the new address texts, a window load in a loop + (`heap byte window loaded inside a loop`), and the mixed cases (a texture on the token route next to a buffer load that + keeps today's refusal). +- `native_heap_token_texture_warp` and `_hardware`: modes `rawbuf`, `rawbuf_waterfall` and `sbuf` with two raw views (64 and + 128 dwords) and a texture id in the dimension table: valid tokens read the view (lanes past the first view get 0), every + other case gives zeros and one miss per wave. Results are compared as dwords. diff --git a/src/direct_compute_cache.cpp b/src/direct_compute_cache.cpp index b7f97527e5..b8de014ef8 100644 --- a/src/direct_compute_cache.cpp +++ b/src/direct_compute_cache.cpp @@ -101,7 +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, program.heap_token_word_count); word(out, static_cast(program.stride_srvs.size())); for (unsigned srv : program.stride_srvs) word(out, srv); @@ -158,7 +158,9 @@ 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; + shader.heap_token_word_count = in.count(7); + if (shader.heap_token_word_count != 0 && shader.heap_token_word_count != 5 && shader.heap_token_word_count != 7) + throw std::runtime_error("invalid cached heap token word count"); n = in.count(32); for (unsigned j = 0; j < n; ++j) shader.stride_srvs.push_back(in.count(31)); @@ -942,7 +944,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()) + (program.heap_token_words ? 5u : 0u); + ud_count += static_cast(program.stride_srvs.size()) + program.heap_token_word_count; if (ud_count > 32) return refuse("more than 32 user data words"); @@ -965,7 +967,7 @@ std::optional format_compute_runtime_manifest(const NativeComputeSh 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) + if (!program.heap_token_word_count || 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++)) @@ -1093,11 +1095,14 @@ 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 (program.heap_token_word_count) { + if (program.heap_token_word_count != 5 && program.heap_token_word_count != 7) + return refuse("heap token words are five, or seven with a token buffer"); 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'; + const char *const names[]{"base1d", "base2d", "base2da", "count", "null", "baseraw", "nullraw"}; + for (unsigned k = 0; k < program.heap_token_word_count; ++k) + out << "udsrc " << ud_index++ << " heaptok " << names[k] << '\n'; } out << srv_lines.str() << uav_lines.str() << sampler_lines.str() << "native " << native_compute_output_revision << '\n'; diff --git a/src/gfx1013_compute_native.cpp b/src/gfx1013_compute_native.cpp index a3732e5b14..ddbf00d6c0 100644 --- a/src/gfx1013_compute_native.cpp +++ b/src/gfx1013_compute_native.cpp @@ -1742,6 +1742,11 @@ void lower_blocks(Emit &e) { struct HeapTokenLoad { unsigned pc, dim; }; +// GPU-selected heap raw buffers (view tokens). A consumer of an eligible s_load_dwordx4 from the resource heap: the raw +// MUBUF load or scalar buffer load at `pc` that reads the V# of the heap load at `load`. +struct HeapTokenBufferLoad { + unsigned pc, load; +}; // 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) { @@ -1776,57 +1781,44 @@ static std::vector> conservative_sgpr_reads(const 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) { +// The instructions that can run after p.code[l] (its transitive successors; the load itself only through a loop). +static std::vector instructions_after(const Program &p, size_t l) { + 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 (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; + 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); } + return after; +} +// The texture rules of the heap token route. `loads` are the reached s_load_dwordx8 from the resource heap with an SGPR +// offset (token loads). 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. +static bool heap_token_texture_eligible(const Program &p, const std::vector &loads, + std::vector &consumers) { 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); - } - } + const auto after = instructions_after(p, l); for (size_t n = 0; n < p.code.size(); ++n) { if (n == l || !p.reached[n]) continue; const auto &state = p.before[n]; @@ -1875,6 +1867,108 @@ static bool heap_token_eligible(const Program &p, std::vector &co } return true; } +// The buffer rules of the heap token route for one candidate: p.code[l] is an s_load_dwordx4 from the resource heap (an +// SGPR offset, or an address formed by s_add_u32), the V# of a GPU-selected raw buffer. It is eligible when its four words +// are read only as (a) the V# of a raw MUBUF dword-family load with OFFEN and without IDXEN, in the byte-window form +// (word 0 the token, words 1 to 3 the rewritten fields of this load), (b) the base of a scalar buffer load, or (c) by the +// SALU instructions of the byte-window rewrite (byte_descriptor_field). Every other read of a word or of a field derived +// from it, a copy included, makes the candidate not eligible, as does a word that a join lost before such a read. The +// consumers of an eligible candidate are appended to `consumers`; a candidate without a consumer is not eligible. +static bool heap_token_buffer_eligible(const Program &p, size_t l, std::vector &consumers) { + using T = Symbol::Type; + const auto &load = p.code[l]; + if (load.dst + 4 > 106) return false; + const unsigned immediate = load.b & 0xfffff; + const auto is_token = [&](const Symbol &s, unsigned word) { + return s.type == T::indexed_descriptor && s.value == compute_resource_heap && s.definition == load.pc && + s.offset == immediate + 4 * word; + }; + const auto is_field = [&](const Symbol &s, T type) { + return s.type == type && s.value == compute_resource_heap && s.definition == load.pc; + }; + // A word of this load or a field derived from it. + const auto of_load = [&](const Symbol &s) { + return (s.type == T::indexed_descriptor && s.value == compute_resource_heap && s.definition == load.pc) || + is_field(s, T::stride) || is_field(s, T::byte_stride) || is_field(s, T::zero_stride_word) || + is_field(s, T::byte_count) || is_field(s, T::clear_oob) || is_field(s, T::byte_oob); + }; + const auto after = instructions_after(p, l); + std::vector found; + for (size_t n = 0; n < p.code.size(); ++n) { + if (n == l || !p.reached[n]) continue; + const auto &i = p.code[n]; + const auto &state = p.before[n]; + auto reads = conservative_sgpr_reads(i); + if (i.enc == Encoding::Image) reads.emplace_back(((i.b >> 16) & 31) * 4, 8); + bool reads_load = false; + for (const auto &[first, count] : reads) + for (unsigned r = first; r < first + count && r < 106; ++r) { + // A word of the load that reaches a read through a join with a path that skipped the load: the second + // analysis could not place it. + if (after[n] && r >= load.dst && r < load.dst + 4 && state[r].type == T::unbound) return false; + reads_load |= of_load(state[r]); + } + if (!reads_load) continue; + if (i.enc == Encoding::Mubuf && i.name == "buffer_load_dword" && (i.a & 0x1000) && !(i.a & 0x2000)) { + const unsigned base = ((i.b >> 16) & 31) * 4, soffset = i.b >> 24; + if (base + 4 > 106 || !is_token(state[base], 0) || !is_field(state[base + 1], T::zero_stride_word) || + !is_field(state[base + 2], T::byte_count) || !is_field(state[base + 3], T::byte_oob) || + (soffset < 106 && of_load(state[soffset]))) + return false; + found.push_back({i.pc, load.pc}); + } else if (i.enc == Encoding::Smem && i.op >= 8 && i.op <= 12) { + const unsigned base = i.src[0], soffset = i.b >> 25; + if (base + 4 > 106 || (soffset < 106 && of_load(state[soffset]))) + return false; + for (unsigned j = 0; j < 4; ++j) + if (!is_token(state[base + j], j)) return false; + found.push_back({i.pc, load.pc}); + } else if (!(i.enc == Encoding::Sop2 && byte_descriptor_field(i, state, true))) + return false; + } + if (found.empty()) return false; + consumers.insert(consumers.end(), found.begin(), found.end()); + return true; +} +// The pre-pass of the heap token route. `p` is the analysis with heap_tokens set. Texture rules: every reached +// s_load_dwordx8 from the resource heap with an SGPR offset is a token load, and one that fails them makes the PROGRAM not +// eligible (heap_token_texture_eligible). Buffer rules, when `buffers` is set: every reached s_load_dwordx4 from the +// resource heap with an SGPR offset, or through an address formed by s_add_u32, is a candidate judged on its own +// (heap_token_buffer_eligible); a candidate that fails is dropped and keeps the path without tokens, except that an address +// formed by s_add_u32 which is not an eligible candidate makes the program not eligible, as it always did. Without +// `buffers` every such address makes the program not eligible. Returns true when the route is taken: there are token +// textures, all eligible, or at least one eligible buffer load. +static bool heap_token_eligible(const Program &p, bool buffers, std::vector &consumers, + std::vector &buffer_consumers) { + consumers.clear(); + buffer_consumers.clear(); + std::vector textures, candidates; + 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.op != 3)) continue; + const auto &base = p.before[n].at(i.src[0]); + if (i.op == 2 && (i.b >> 25) == 125 && base.type == Symbol::Type::heap_offset) { + // A descriptor address formed by s_add_u32 (heap_offset_add) is another way into the heap, with its own contract. + if (!buffers || !heap_offset_address(p.before[n], i.src[0])) return false; + candidates.push_back(n); + } else if ((i.b >> 25) != 125 && base.type == Symbol::Type::table && base.value == compute_resource_heap) { + if (i.op == 3) textures.push_back(n); + else if (buffers) candidates.push_back(n); + } + } + if (textures.empty() && candidates.empty()) return false; + if (!heap_token_texture_eligible(p, textures, consumers)) { + consumers.clear(); + return false; + } + for (const size_t l : candidates) + if (!heap_token_buffer_eligible(p, l, buffer_consumers) && (p.code[l].b >> 25) == 125) { + consumers.clear(); + buffer_consumers.clear(); + return false; + } + return !textures.empty() || !buffer_consumers.empty(); +} #include "gfx1013_direct_compute.inl" #include "gfx1013_direct_graphics.inl" #include "gfx1013_direct_mesh.inl" @@ -2012,21 +2106,47 @@ static NativeComputeShader translate_program(const ComputeRequest &request, unsi 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. + // A GPU-selected raw buffer (s_load_dwordx4 from the resource heap, with an SGPR offset or through an address formed by + // s_add_u32) takes the same route when no heap view contract covers it: its V# is the byte window of a view token. It is + // judged on an analysis that tracks the byte window rewrite (heap_window); a program with no eligible buffer load is + // analysed again exactly as before. std::vector token_consumers; + std::vector buffer_consumers; bool heap_tokens = false; - bool token_candidate = false; - for (size_t n = 0; direct_dxil && !stage && n < program.code.size() && !token_candidate; ++n) { + bool token_candidate = false, buffer_candidate = false; + for (size_t n = 0; direct_dxil && !stage && n < program.code.size(); ++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 (!program.reached[n] || i.enc != Encoding::Smem || (i.op != 2 && i.op != 3)) continue; + const auto &base = program.before[n].at(i.src[0]); + if (i.op == 3 && (i.b >> 25) != 125) + token_candidate |= base.type == Symbol::Type::table && base.value == compute_resource_heap; + else if (i.op == 2 && heap_view == HeapViewContract::none) + buffer_candidate |= (base.type == Symbol::Type::table && base.value == compute_resource_heap && + (i.b >> 25) != 125) || + ((i.b >> 25) == 125 && base.type == Symbol::Type::heap_offset); } - 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; + bool compiler_window = heap_window; + if (token_candidate || buffer_candidate) { + auto tokens = parse(request.code, entry, initial, direct_dxil, false, wave64, false, heap_window || buffer_candidate, + narrow_wave64, true); + if (heap_token_eligible(tokens, buffer_candidate, token_consumers, buffer_consumers)) { + if (!buffer_consumers.empty()) { + program = std::move(tokens); + heap_tokens = true; + compiler_window = true; + } else if (!buffer_candidate || heap_window) { + program = std::move(tokens); + heap_tokens = true; + } else { + // Token textures only: the analysis of the program as before this route knew buffers. + auto textures = parse(request.code, entry, initial, direct_dxil, false, wave64, false, heap_window, narrow_wave64, + true); + std::vector none; + if (heap_token_eligible(textures, false, token_consumers, none)) { + program = std::move(textures); + heap_tokens = true; + } + } } } Emit emit{{}, program,layout->Desc_1_1}; @@ -2041,9 +2161,10 @@ static NativeComputeShader translate_program(const ComputeRequest &request, unsi compiler.wave64 = wave64; compiler.narrow_wave64 = narrow_wave64; compiler.heap_view = heap_view; - compiler.heap_window = heap_window; + compiler.heap_window = compiler_window; compiler.heap_tokens = heap_tokens; compiler.heap_token_consumers = token_consumers; + compiler.heap_token_buffer_consumers = buffer_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 cfc75d84a0..c86f6ec4bc 100644 --- a/src/gfx1013_compute_native.h +++ b/src/gfx1013_compute_native.h @@ -51,7 +51,8 @@ enum class ComputeViewKind { // A raw buffer bound as a root UAV. The guest address is the root pointer plus a VGPR offset. 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 + // memory (32-byte tokens); heap_token_dims_srv: one uint per view id (0 none, 0x20 a raw buffer view, else 1 + image + // dimension; the runtime that fills the table names the raw buffer views); the miss UAV // is one raw dword counting the waves that read the null slot. heap_token_srv, heap_token_dims_srv, @@ -150,8 +151,9 @@ 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; + // More b0 words after the stride words, 0, 5 or 7: base1d, base2d, base2da, count, null (heap token textures), then + // baseraw, nullraw when a GPU-selected raw buffer is read through its view token. + unsigned heap_token_word_count = 0; 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 c3c31b8935..1385cfe0bd 100644 --- a/src/gfx1013_direct_compute.inl +++ b/src/gfx1013_direct_compute.inl @@ -90,12 +90,27 @@ struct DirectCompute { 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. + // A program with an eligible raw buffer load (heap_token_buffer_consumers) has two more, in this order: baseraw + // (the first raw view id's slot) and nullraw (a raw buffer view of no bytes, read when the token does not hold a + // raw view). bool heap_tokens = false; std::vector heap_token_consumers; - std::array heap_token_values; + std::vector heap_token_buffer_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(); } + // The views and words exist only when a program uses a token texture or buffer (an unused token load needs none). + bool token_bindings() const { + return heap_tokens && (!heap_token_consumers.empty() || !heap_token_buffer_consumers.empty()); + } + // The number of token words: 5, or 7 with a token buffer. + unsigned token_word_count() const { + return !token_bindings() ? 0u : heap_token_buffer_consumers.empty() ? 5u : 7u; + } + // The load at `pc` is an eligible raw buffer load of the token route. + bool heap_token_buffer_load(unsigned pc) const { + return heap_tokens && std::any_of(heap_token_buffer_consumers.begin(), heap_token_buffer_consumers.end(), + [pc](const auto &c) { return c.load == pc; }); + } unsigned label_number = 0; bool pixel_stage = false; bool pixel_heap_enabled = false; @@ -350,7 +365,7 @@ struct DirectCompute { initialize_constants(); } void initialize_constants(const GraphicsConstantLayout *linked = nullptr) { - unsigned words = static_cast(descriptor_strides.size()) + (token_bindings() ? 5u : 0u); + unsigned words = static_cast(descriptor_strides.size()) + token_word_count(); for (const auto &block : analysis.result.constants) words += block.count; if (words) { @@ -374,9 +389,8 @@ 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++); + for (unsigned k = 0; k < token_word_count(); ++k) + heap_token_values[k] = word_at(pos++); } } // Refuses a GPU-selected heap read that the contract does not cover. raw_buffer, typed_dword and raw_and_typed_dword @@ -397,6 +411,11 @@ struct DirectCompute { // picks the path: typed_buffer_srv is typed, every other kind is raw. string heap_resource(const Inst &i, const State &s, unsigned base, ComputeViewKind kind, unsigned bytes) { const auto &symbol = s.at(base); + // A raw buffer that passed the pre-pass of the token route: the contract gate does not apply, the token is checked + // on every execution instead (heap_token_buffer). + if (!pixel_stage && symbol.type == Symbol::Type::indexed_descriptor && symbol.value == compute_resource_heap && + heap_token_buffer_load(symbol.definition)) + return heap_token_buffer(i, s, base, kind); refuse_heap_contract(i.pc); const bool typed = heap_view == HeapViewContract::typed_dword || (heap_view == HeapViewContract::raw_and_typed_dword && @@ -747,6 +766,39 @@ struct DirectCompute { for (unsigned j = 0; j < 8; ++j) write(i.dst + j, address); return; } + if (!pixel_stage && i.op == 2 && heap_token_buffer_load(i.pc)) { + // The V# of a GPU-selected raw buffer: the view token at the guest byte address, kept in all four words (see + // heap_token_buffer). A token is 32 bytes of title heap memory, so the address is a multiple of 32. The + // address is the byte offset from heap slot 0, not the slot index. + const Word offset = i.b & 0xfffff; + if (i.dst + 4 > 106) refuse(i.pc, "invalid heap token buffer descriptor address"); + string address; + if (so != 125) { + // The SGPR-offset form: the resource heap pointer (high word zero) and a byte offset in so. + if (low.type != Symbol::Type::table || low.value != compute_resource_heap || + !(s.at(i.src[0] + 1) == Symbol{Symbol::Type::constant, 0})) + refuse(i.pc, "invalid heap token buffer descriptor address"); + if (offset % 32) refuse(i.pc, "unaligned heap token buffer immediate byte offset"); + if (so >= limit) refuse(i.pc, "heap token byte offset register"); + const auto value = s.at(so); + const bool aligned = (value.type == Symbol::Type::constant && value.value % 32 == 0) || + (value.type == Symbol::Type::masked && (value.value & 31) == 0); + if (!aligned || value.value > UINT_MAX - offset) + refuse(i.pc, "heap token buffer byte offset has no proven 32-byte aligned range"); + address = ir.binary("add", operand32(i, so), to_string(offset)); + } else { + // The address formed by s_add_u32: its high word is the carry of that add, which the emitter writes as 0 + // (the heap base is slot 0), and its low word is the byte offset. + if (!heap_offset_address(s, i.src[0])) + refuse(i.pc, "heap descriptor address high word is not the carry of its offset add"); + if (offset) refuse(i.pc, "heap token buffer load with an immediate offset on an added address"); + if ((low.index_mask & 31) != 0) + refuse(i.pc, "heap token buffer byte offset has no proven 32-byte aligned range"); + address = read(i.src[0]); + } + for (unsigned j = 0; j < 4; ++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"); @@ -1062,6 +1114,16 @@ struct DirectCompute { 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"); + const auto slot = heap_token_slot(base, 1 + dim, heap_token_values[dim == 0 ? 0 : dim == 1 ? 1 : 2], + heap_token_values[4]); + constexpr unsigned dx_kind[]{1, 2, 0, 0, 0, 7}; + return ir.heap_handle(slot, dx_kind[dim], 1033, false, false); + } + // The heap slot a view token names. The token is read at the byte address held by SGPR `base` (every lane loads the + // same words, so the slot is dynamically uniform): the slot is first + id when the magic and the id range hold and the + // dimension table records `recorded` for the id (texture: 1 + the SQ dimension code; raw buffer: 0x20), and `null` + // otherwise, in which case the first lane of the wave counts one miss. + string heap_token_slot(unsigned base, unsigned recorded_code, const string &first, const string &null) { // 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; @@ -1079,9 +1141,8 @@ struct DirectCompute { 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]); + valid = ir.value("and i1 " + valid + ", " + cmp("eq", recorded, to_string(recorded_code))); + const auto slot = select(valid, ir.binary("add", first, id), null); // 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"); @@ -1095,18 +1156,55 @@ struct DirectCompute { {"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); + return slot; + } + // A GPU-selected raw buffer read through its view token: ResourceDescriptorHeap[baseraw + id] when the token names a + // raw buffer view (dimension table entry 0x20), else the null raw view (reads zero) and a miss. `symbol` is a word of + // the heap load (the s_load_dwordx4 left the token's byte address in all four words; the byte-window rewrite only + // changes what the analysis knows about words 1 to 3). + string heap_token_buffer(const Inst &i, const State &s, unsigned base, ComputeViewKind kind) { + const auto &symbol = s.at(base); + const bool window = kind == ComputeViewKind::byte_window_srv; + if (!window && kind != ComputeViewKind::buffer_srv) + refuse(i.pc, "a heap token raw buffer is read as a raw MUBUF dword load or a scalar buffer load only"); + if (std::none_of(heap_token_buffer_consumers.begin(), heap_token_buffer_consumers.end(), + [&](const auto &c) { return c.pc == i.pc && c.load == symbol.definition; })) + refuse(i.pc, "heap token consumer was not listed by the pre-pass"); + const auto defined = analysis.program.at.find(symbol.definition); + if (defined == analysis.program.at.end() || analysis.program.code[defined->second].enc != Encoding::Smem || + analysis.program.code[defined->second].op != 2 || base + 4 > 106) + refuse(i.pc, "heap token raw buffer descriptor is not a four-word heap load"); + if (symbol.offset % 32 || symbol.type != Symbol::Type::indexed_descriptor) + refuse(i.pc, "unaligned heap descriptor"); + // The same precaution as for a heap descriptor without tokens: the words are compared by the pc of their heap load, + // which a loop around that load executes again for another selection. + if (window) + for (const auto &inst : analysis.program.code) + if (inst.branch() && inst.target() <= symbol.definition && symbol.definition <= inst.pc) + refuse(i.pc, "heap byte window loaded inside a loop"); + constexpr Symbol::Type window_words[] = {Symbol::Type::indexed_descriptor, Symbol::Type::zero_stride_word, + Symbol::Type::byte_count, Symbol::Type::byte_oob}; + for (unsigned j = 1; j < 4; ++j) { + Symbol expected = symbol; + if (window) + expected.type = window_words[j]; // field() already cleared the word offset + else + expected.offset += 4 * j; + if (!(s.at(base + j) == expected)) + refuse(i.pc, "non-contiguous resource descriptor"); + } + const auto slot = heap_token_slot(base, 0x20, heap_token_values[5], heap_token_values[6]); + return ir.heap_handle(slot, 11, 0, 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()); + unsigned words = token_word_count() + 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; + r.heap_token_word_count = token_word_count(); token_srv = analysis.srv++; token_dims_srv = analysis.srv++; token_miss_uav = analysis.uav++; diff --git a/src/native_compute_output.h b/src/native_compute_output.h index 186e4261d8..9b4b0825e1 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 = 2; +constexpr unsigned native_compute_output_revision = 3; enum class NativeComputeOutput { unmarked, current, incompatible }; diff --git a/src/native_compute_pipeline.cpp b/src/native_compute_pipeline.cpp index b3201a1dd6..1fabf667f8 100644 --- a/src/native_compute_pipeline.cpp +++ b/src/native_compute_pipeline.cpp @@ -50,7 +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; + pipeline.token_words = program.heap_token_word_count; for (const auto &block : pipeline.constants) pipeline.constant_words += block.count; pipeline.srv_count = counts[0]; diff --git a/src/native_compute_pipeline.h b/src/native_compute_pipeline.h index b95f8756db..1041af8c1e 100644 --- a/src/native_compute_pipeline.h +++ b/src/native_compute_pipeline.h @@ -17,7 +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 token_words = 0; // heap token words after the stride words: base1d, base2d, base2da, count, null (5), plus baseraw, nullraw (7) 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 cfa61a3d5f..5f17e02623 100644 --- a/src/startup_stubs/d3d12_compute_dispatch.inl +++ b/src/startup_stubs/d3d12_compute_dispatch.inl @@ -348,11 +348,18 @@ 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. + // GPU-selected heap textures and raw buffers (view tokens): published by the translator, not bound by this runtime + // yet. The reader knows the seven word names (baseraw and nullraw belong to raw buffers); every such line is + // refused here until a runtime fills the views and words. + const auto token_word = [&] { + for (const char *known : {"base1d", "base2d", "base2da", "count", "null", "baseraw", "nullraw"}) + if (!std::strcmp(name, known)) return true; + return false; + }; 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())) + (std::sscanf(line.c_str(), "udsrc %u heaptok %15s%n", &i, name, &used) == 2 && whole() && token_word())) 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}); diff --git a/tests/native_compute_manifest_reasons.cpp b/tests/native_compute_manifest_reasons.cpp index 6ac83e92d5..7b72462b9f 100644 --- a/tests/native_compute_manifest_reasons.cpp +++ b/tests/native_compute_manifest_reasons.cpp @@ -134,29 +134,35 @@ int main() { p.bindings.push_back(view(K::heap_token_srv, 1, compute_heap_token)); }}, {"heap token view with another root parameter", [](auto &p) { - p.heap_token_words = true; + p.heap_token_word_count = 5; p.bindings.push_back(view(K::heap_token_srv, 1, 1)); }}, {"heap token view with another root parameter", [](auto &p) { p.bindings.push_back(view(K::buffer_srv, 1, compute_heap_token)); }}, {"heap token words without the three heap token views", [](auto &p) { - p.heap_token_words = true; + p.heap_token_word_count = 5; p.bindings.push_back(view(K::heap_token_srv, 1, compute_heap_token)); }}, {"SRV registers not contiguous", [](auto &p) { - p.heap_token_words = true; + p.heap_token_word_count = 5; p.bindings.push_back(view(K::heap_token_srv, 2, compute_heap_token)); }}, {"more than 32 user data words", [](auto &p) { p.constants.assign(3, {0, 0, 8}); p.stride_srvs = {}; - p.heap_token_words = true; + p.heap_token_word_count = 5; p.constants.push_back({0, 0, 4}); p.bindings.push_back(view(K::heap_token_srv, 1, compute_heap_token)); p.bindings.push_back(view(K::heap_token_dims_srv, 2, compute_heap_token)); p.bindings.push_back(view(K::heap_token_miss_uav, 1, compute_heap_token)); }}, + {"heap token words are five, or seven with a token buffer", [](auto &p) { + p.heap_token_word_count = 6; + p.bindings.push_back(view(K::heap_token_srv, 1, compute_heap_token)); + p.bindings.push_back(view(K::heap_token_dims_srv, 2, compute_heap_token)); + p.bindings.push_back(view(K::heap_token_miss_uav, 1, compute_heap_token)); + }}, }; for (const auto &c : cases) { auto program = base(); @@ -242,7 +248,7 @@ int main() { // 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.heap_token_word_count = 5; 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)); @@ -259,6 +265,27 @@ int main() { 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); + // A program with a token buffer has seven words: baseraw and nullraw follow the five of the textures. + { + auto program = base(); + program.heap_token_word_count = 7; + 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 9\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" + "udsrc 7 heaptok baseraw\nudsrc 8 heaptok nullraw\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 seven heap token words of a token buffer\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) + 5); return failures ? 1 : 0; } diff --git a/tests/native_heap_token_texture.cpp b/tests/native_heap_token_texture.cpp index b54bb4089e..807415b629 100644 --- a/tests/native_heap_token_texture.cpp +++ b/tests/native_heap_token_texture.cpp @@ -6,6 +6,11 @@ // 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 +// rawbuf | rawbuf_waterfall | sbuf GPU-selected raw buffers (PR 1c): the program loads a raw buffer V# +// with s_load_dwordx4 from the resource heap at the token's address (rawbuf: an SGPR offset; +// rawbuf_waterfall: an address formed by s_add_u32), rewrites it to the byte window and lane L reads four +// dwords at byte 16 * L with buffer_load_dwordx4 (sbuf: s_buffer_load_dwordx4 of the unrewritten words, the +// same four dwords in every lane). The results are compared as dwords. // 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 @@ -13,6 +18,10 @@ // 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). +// The raw modes bind baseraw and nullraw too. The host heap has raw views at baseraw + id: id 1 over a buffer of 64 +// dwords (value 0xA0000000 + index), id 2 over 128 dwords (0xB0000000 + index); id 0 and id 3 are null raw views, and the +// dimension table names id 3 a 2D texture. Case 8 is a valid token for id 2. Lanes 16 to 31 read past the 64 dwords of +// id 1 and get 0. Every other case gives zeros and one miss per 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" @@ -36,7 +45,7 @@ constexpr unsigned base_1d = 8, base_2d = 16, base_2da = 24, null_slot = 0, tabl constexpr std::uint32_t magic = 0x56573258u, sentinel = 0x69696969u; using Texel = std::array; -enum class Dim { d1, d2, d2a }; +enum class Dim { d1, d2, d2a, raw }; 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}; } @@ -45,14 +54,29 @@ struct Mode { Dim dim; unsigned valid_id, mismatch_id; Texel expected; + bool scalar = false; // raw modes: every lane gets the first four dwords (s_buffer_load) }; 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 if (name == L"rawbuf" || name == L"rawbuf_waterfall") mode = {Dim::raw, 1, 3, {}}; + else if (name == L"sbuf") mode = {Dim::raw, 1, 3, {}, true}; else return false; return true; } +// The raw views of the raw modes: dwords of id 1 and id 2. +constexpr unsigned raw_base = 8, raw_dims_code = 0x20, raw_words_1 = 64, raw_words_2 = 128; +std::uint32_t raw_word(unsigned id, unsigned index) { + return (id == 1 ? 0xA0000000u : 0xB0000000u) + index; +} +// The four dwords lane `lane` gets for a valid token of raw view `id` (zero past the end of the view). +std::array raw_expected(unsigned id, unsigned lane, bool scalar) { + const unsigned words = id == 1 ? raw_words_1 : raw_words_2, first = scalar ? 0 : lane * 4; + std::array out{}; + for (unsigned k = 0; k < 4; ++k) out[k] = first + k < words ? raw_word(id, first + k) : 0; + return out; +} struct Gpu { ComPtr device; @@ -272,7 +296,7 @@ bool parse_manifest(const std::string &text, Layout &layout) { 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; + (layout.words.size() == 5 || layout.words.size() == 7); } bool same_bits(const Texel &a, const Texel &b) { return std::memcmp(a.data(), b.data(), sizeof a) == 0; } @@ -290,7 +314,8 @@ int run_mode(const std::wstring &sdk, const std::wstring &cache, const std::file std::string reason; const auto manifest = x2w::format_compute_runtime_manifest(program, &reason); Layout layout; - if (!manifest || !parse_manifest(*manifest, layout)) { + const bool raw = mode.dim == Dim::raw; + if (!manifest || !parse_manifest(*manifest, layout) || layout.words.size() != (raw ? 7u : 5u)) { 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; @@ -314,23 +339,40 @@ int run_mode(const std::wstring &sdk, const std::wstring &cache, const std::file [](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); + std::vector raw_1(raw_words_1), raw_2(raw_words_2); + for (unsigned k = 0; k < raw_words_1; ++k) raw_1[k] = raw_word(1, k); + for (unsigned k = 0; k < raw_words_2; ++k) raw_2[k] = raw_word(2, k); + ComPtr raw_buffer_1, raw_buffer_2; + if (raw) { + // The raw views: slot raw_base + id; id 0 and 3 and the null slot are raw views without a resource. + raw_buffer_1 = gpu.upload_buffer(raw_1); + raw_buffer_2 = gpu.upload_buffer(raw_2); + gpu.raw_srv(null_slot, nullptr, 1); + for (unsigned id = 0; id < count; ++id) + gpu.raw_srv(raw_base + id, id == 1 ? raw_buffer_1.Get() : id == 2 ? raw_buffer_2.Get() : nullptr, + id == 1 ? raw_words_1 : id == 2 ? raw_words_2 : 1); + } else { + 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}, + const unsigned case_count = raw ? 9 : 8; + std::vector token_words(case_count * 8, 0xdeadbeefu); + const std::uint32_t tokens[9][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) { + {magic, 0x80000000u | mode.valid_id}, {magic, 0}, {0, 0}, {magic, 2}}; + for (unsigned c = 0; c < case_count; ++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 + // 1 + the SQ image dimension: 2D 2, 2D array 6, 1D 1; 0x20 a raw buffer view (ids 1 and 2), id 3 a 2D texture + gpu.dims = gpu.upload_buffer(raw ? std::vector{0, raw_dims_code, raw_dims_code, 2} + : std::vector{0, 2, 6, 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, @@ -341,14 +383,15 @@ int run_mode(const std::wstring &sdk, const std::wstring &cache, const std::file // 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.tokens, gpu.tokens.Get(), static_cast(token_words.size())); 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}}; + {"count", count}, {"null", null_slot}, {"baseraw", raw_base}, + {"nullraw", null_slot}}; auto dispatch = [&](unsigned address, std::vector &out, std::uint32_t &missed) { gpu.rewrite(gpu.selector.Get(), {address, 0, 0, 0}); @@ -391,14 +434,28 @@ int run_mode(const std::wstring &sdk, const std::wstring &cache, const std::file 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) { + const char *const cases[9] = {"valid", "wrong_magic", "id_at_count", "id_max", "dims_mismatch", "content_token", + "id_zero", "no_token", "second_view"}; + for (unsigned c = 0; c < case_count; ++c) { std::vector out; std::uint32_t missed = 0; dispatch(c * 32, out, missed); + const bool valid_case = c == 0 || (raw && c == 8); + for (unsigned lane = 0; raw && lane < lanes; ++lane) { + // Results as dwords: the buffer data are not floats. + const auto expected_words = valid_case ? raw_expected(c == 8 ? 2 : 1, lane, mode.scalar) + : std::array{}; + std::array got_words; + std::memcpy(got_words.data(), &out[lane * 4], sizeof got_words); + if (got_words != expected_words) { + std::printf("FAIL: %s %s: lane %u is (%08x, %08x, %08x, %08x), expected (%08x, %08x, %08x, %08x)\n", + label.c_str(), cases[c], lane, got_words[0], got_words[1], got_words[2], got_words[3], + expected_words[0], expected_words[1], expected_words[2], expected_words[3]); + return 1; + } + } const Texel expected = c == 0 ? mode.expected : Texel{0, 0, 0, 0}; - for (unsigned lane = 0; lane < lanes; ++lane) { + for (unsigned lane = 0; !raw && lane < lanes; ++lane) { Texel got; std::memcpy(got.data(), &out[lane * 4], sizeof got); if (!same_bits(got, expected)) { @@ -408,14 +465,16 @@ 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; + const std::uint32_t expected_misses = valid_case ? 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); + valid_case ? (raw ? "the dwords of the view" : "the texel of the view") + : (raw ? "zeros" : "the null texel"), + lanes, missed, groups); } return 0; } @@ -423,7 +482,7 @@ int run_mode(const std::wstring &sdk, const std::wstring &cache, const std::file 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); + std::fputs("usage: native_heap_token_texture SDK CACHE REQ.c67 ADAPTER MODE\n", stderr); return 2; } Gpu gpu; diff --git a/tests/native_heap_token_texture_check.py b/tests/native_heap_token_texture_check.py index cf2651ec12..8e5f690966 100644 --- a/tests/native_heap_token_texture_check.py +++ b/tests/native_heap_token_texture_check.py @@ -166,6 +166,150 @@ def full(coords, op, load=TOKEN_LOAD, sampler=SAMPLER, store=STORE, selector=SEL "immediate": full(COORDS_2D, SAMPLE_2D, load=[0xf40c0805, 0x22000020]), } +# GPU-selected raw buffers (PR 1c). The V# of the buffer is an s_load_dwordx4 from the resource heap, at a 32-byte aligned +# byte address chosen by GPU data (the same address form as the texture token), or through an address formed by s_add_u32. +MASK32 = [ + 0x8711ff10, 0x0000ffe0, # s_and_b32 s17, s16, 0xffe0 (proves a 32-byte aligned range) +] +SELECTOR32 = [*SELECTOR_HEAD, *MASK32] +BUFFER_LOAD = [0xf4080805, 0x22000000] # s_load_dwordx4 s[32:35], s[10:11], s17 (a raw buffer: a view token in the heap) +BUFFER_LOAD_IMM = [0xf4080805, 0x22000020] # s_load_dwordx4 s[32:35], s[10:11], s17 offset:0x20 +BUFFER_LOAD_IMM4 = [0xf4080805, 0x22000004] # s_load_dwordx4 s[32:35], s[10:11], s17 offset:0x4 +ADD_HEAP = [ + 0x8014110a, # s_add_u32 s20, s10, s17 + 0x82158080, # s_addc_u32 s21, 0, 0 +] +ADD_HEAP_UNMASKED = [ + 0x8014100a, # s_add_u32 s20, s10, s16 (the offset is not masked) + 0x82158080, # s_addc_u32 s21, 0, 0 +] +BUFFER_LOAD_ADDED = [0xf408080a, 0xfa000000] # s_load_dwordx4 s[32:35], s[20:21], 0x0 +BUFFER_LOAD_ADDED_IMM = [0xf408080a, 0xfa000020] # s_load_dwordx4 s[32:35], s[20:21], 0x20 +# The byte-window rewrite of the V# in s[32:35] (word 1 without stride, word 2 the byte count, word 3 the raw out-of-bounds +# mode), the sequence of the direct heap descriptor path. +REWRITE = [ + 0x93a4ff21, 0x000e0010, # s_bfe_u32 s36, s33, 0xe0010 + 0x84a48124, # s_max_u32 s36, s36, 1 + 0x93222422, # s_mul_i32 s34, s34, s36 + 0x8721ff21, 0xc000ffff, # s_and_b32 s33, s33, 0xc000ffff + 0x8723ff23, 0xcfffffff, # s_and_b32 s35, s35, 0xcfffffff + 0x8823ff23, 0x30000000, # s_or_b32 s35, s35, 0x30000000 +] +REWRITE_NO_WORD3 = REWRITE[:-4] # the rewrite without the out-of-bounds mode words +LANE = [0x34100084] # v_lshlrev_b32_e32 v8, 4, v0 +LOAD_X4 = [0xe0381000, 0x80080408] # buffer_load_dwordx4 v[4:7], v8, s[32:35], 0 offen +LOAD_X1 = [0xe0301000, 0x80080408] # buffer_load_dword v4, v8, s[32:35], 0 offen +LOAD_X3 = [0xe03c1000, 0x80080408] # buffer_load_dwordx3 v[4:6], v8, s[32:35], 0 offen +LOAD_X4_IDXEN = [0xe0382000, 0x80080408] # buffer_load_dwordx4 v[4:7], v8, s[32:35], 0 idxen +LOAD_FORMAT = [0xe00c1000, 0x80080408] # buffer_load_format_xyzw v[4:7], v8, s[32:35], 0 offen +LOAD_TBUFFER = [0xea6b1000, 0x80080408] # tbuffer_load_format_xyzw v[4:7], v8, s[32:35], 0 format:[BUF_FMT_32_32_32_32_FLOAT] offen +STORE_V = [0xe0781000, 0x80080408] # buffer_store_dwordx4 v[4:7], v8, s[32:35], 0 offen (a store through the V#) +SBUFFER_X4 = [0xf4280a10, 0xfa000000] # s_buffer_load_dwordx4 s[40:43], s[32:35], 0x0 +SBUFFER_VGPR = [0x7e080228, 0x7e0a0229, 0x7e0c022a, 0x7e0e022b] # v_mov_b32 v4..v7, s40..s43 +COPY_WORD2 = [0xbeac0322] # s_mov_b32 s44, s34 +NUMERIC_WORD2 = [0x872cff22, 0x000000ff] # s_and_b32 s44, s34, 0xff + + +def buffer_full(load, rewrite=REWRITE, consumer=LOAD_X4, selector=SELECTOR32, store=STORE, pre=(), between=()): + return [*BASES, *TABLE_LOADS, *selector, *pre, *load, *WAIT, *between, *rewrite, *LANE, *WAIT, *consumer, *store] + + +def loop_body(words): + """words as a single-block loop: a backward conditional branch to its first instruction.""" + return [*words, JOIN[0], 0xbf840000 | ((-(len(words) + 2)) & 0xffff)] # s_cmp_eq_u32 s16, 0 ; s_cbranch_scc0 top + + +BUFFER_PROGRAMS = { + "rawbuf": buffer_full(BUFFER_LOAD), + "rawbuf_waterfall": buffer_full(BUFFER_LOAD_ADDED, pre=ADD_HEAP), + "sbuf": [*BASES, *TABLE_LOADS, *SELECTOR32, *BUFFER_LOAD, *WAIT, *SBUFFER_X4, *WAIT, *SBUFFER_VGPR, *LANE, *STORE], +} +# Eligible variants that must compile: the other dword widths, an immediate offset, and a texture next to a buffer. +BUFFER_ACCEPTED = { + "x1": buffer_full(BUFFER_LOAD, consumer=LOAD_X1), + "x3": buffer_full(BUFFER_LOAD, consumer=LOAD_X3), + "immediate": buffer_full(BUFFER_LOAD_IMM), + # s_buffer_load_dwordx4 s[40:43], s[32:35], s17: the SGPR offset of a scalar buffer load that is not the token's + "sbuf_offset": [*BASES, *TABLE_LOADS, *SELECTOR32, *BUFFER_LOAD, *WAIT, 0xf4280a10, 0x22000000, *WAIT, *SBUFFER_VGPR, + *LANE, *STORE], +} +# A texture and a buffer in one program: the V# of the buffer is s[48:51], its rewrite temporaries s52. +MIXED_BUFFER_LOAD = [0xf4080c05, 0x22000000] # s_load_dwordx4 s[48:51], s[10:11], s17 +MIXED_REWRITE = [ + 0x93b4ff31, 0x000e0010, # s_bfe_u32 s52, s49, 0xe0010 + 0x84b48134, # s_max_u32 s52, s52, 1 + 0x93323432, # s_mul_i32 s50, s50, s52 + 0x8731ff31, 0xc000ffff, # s_and_b32 s49, s49, 0xc000ffff + 0x8733ff33, 0xcfffffff, # s_and_b32 s51, s51, 0xcfffffff + 0x8833ff33, 0x30000000, # s_or_b32 s51, s51, 0x30000000 +] +MIXED_CONSUME = [ + 0x34180084, # v_lshlrev_b32_e32 v12, 4, v0 + 0xe0381000, 0x800c100c, # buffer_load_dwordx4 v[16:19], v12, s[48:51], 0 offen +] + + +def mixed(buffer_rewrite, texture_load=TOKEN_LOAD, texture_selector=SELECTOR32, consume=MIXED_CONSUME, + buffer_first=False): + textures = [*texture_load, *SAMPLER, *COORDS_2D] + buffers = [*MIXED_BUFFER_LOAD, *WAIT, *buffer_rewrite, *consume] + order = [*buffers, *textures] if buffer_first else [*textures, *buffers] + return [*BASES, *TABLE_LOADS, *texture_selector, *order, *WAIT, *SAMPLE_2D, *STORE] + + +MIXED_PROGRAMS = { + "mixed": mixed(MIXED_REWRITE), +} +# An eligible texture next to a buffer load that is not eligible (its V# is read without the byte-window rewrite): the +# buffer load keeps today's result, and the texture stays on the token route. The refusal text says which load stopped +# the translation first (program order): a texture shape text only the token route has, or the heap contract text. +MIXED_CONTROLS = { + # the texture load is first and its offset register is not masked: the token route's text + "texture_first": (mixed([], texture_selector=SELECTOR_HEAD, texture_load=[0xf40c0805, 0x20000000]), UNPROVEN), + # the buffer load is first: the heap contract text of the load that keeps today's path + "buffer_first": (mixed([], buffer_first=True), HEAP_REFUSAL), +} + +BUFFER_UNMASKED = "heap token buffer byte offset has no proven 32-byte aligned range" +BUFFER_IMMEDIATE = "unaligned heap token buffer immediate byte offset" +BUFFER_ADDED_IMMEDIATE = "heap token buffer load with an immediate offset on an added address" +LOOP = "heap byte window loaded inside a loop" +# V# uses that make the buffer load not eligible: the refusal text is the one these programs get without the buffer route +# (checked against the base of this change). Two of them are refused before the heap load is reached. +IDXEN_REFUSAL = "raw buffer load needs a linear byte offset and no modifiers" +FORMAT_REFUSAL = "formatted load requires zero or a single linear index" +BUFFER_CONTROLS = { + "plain": (buffer_full(BUFFER_LOAD, rewrite=[]), HEAP_REFUSAL), # no byte-window rewrite + "idxen": (buffer_full(BUFFER_LOAD, consumer=LOAD_X4_IDXEN), IDXEN_REFUSAL), + "format": (buffer_full(BUFFER_LOAD, consumer=LOAD_FORMAT), FORMAT_REFUSAL), + "tbuffer": (buffer_full(BUFFER_LOAD, consumer=LOAD_TBUFFER), HEAP_REFUSAL), + "store": (buffer_full(BUFFER_LOAD, consumer=STORE_V, store=END), HEAP_REFUSAL), + # s_and_b32 s44, s34, 0xff before the rewrite + "numeric_word2": (buffer_full(BUFFER_LOAD, between=NUMERIC_WORD2), HEAP_REFUSAL), + # s_mov_b32 s44, s34 after the rewrite + "copy_field": (buffer_full(BUFFER_LOAD, consumer=[*COPY_WORD2, *LOAD_X4]), HEAP_REFUSAL), + "partial": (buffer_full(BUFFER_LOAD, rewrite=REWRITE_NO_WORD3), HEAP_REFUSAL), # word 3 is still the token + # the buffer load runs on one path only: after the join the words are not the token symbol any more + "join": (buffer_full([*JOIN, *BUFFER_LOAD]), HEAP_REFUSAL), + # the immediate offset 4 moves the words off the 32-byte descriptor layout the rewrite recognizes + "immediate4": (buffer_full(BUFFER_LOAD_IMM4), HEAP_REFUSAL), +} +# Address shapes. Each program is eligible, so it reaches the load and is refused there. +BUFFER_ADDRESS_CONTROLS = { + # s_load_dwordx4 s[32:35], s[10:11], s17 where s17 is s16: not masked + "unmasked": (buffer_full(BUFFER_LOAD, selector=SELECTOR_HEAD), BUFFER_UNMASKED), + # s_and_b32 s17, s16, 0xfffc: bit 2 to 4 may be set + "misaligned": (buffer_full(BUFFER_LOAD, selector=[*SELECTOR_HEAD, *MASK]), BUFFER_UNMASKED), + # the scalar buffer load of the unrewritten words with s_load_dwordx4 ... offset:0x4 + "immediate4": ([*BASES, *TABLE_LOADS, *SELECTOR32, *BUFFER_LOAD_IMM4, *WAIT, *SBUFFER_X4, *WAIT, *SBUFFER_VGPR, *LANE, + *STORE], BUFFER_IMMEDIATE), + "added_unmasked": (buffer_full(BUFFER_LOAD_ADDED, pre=ADD_HEAP_UNMASKED), BUFFER_UNMASKED), + "added_immediate": (buffer_full(BUFFER_LOAD_ADDED_IMM, pre=ADD_HEAP), BUFFER_ADDED_IMMEDIATE), + # the load and its rewrite inside a one-block loop (s_cmp_eq_u32 s16, 0 ; s_cbranch_scc0 back to the load) + "loop": ([*BASES, *TABLE_LOADS, *SELECTOR32, *loop_body([*BUFFER_LOAD, *WAIT, *REWRITE, *LANE, *WAIT, *LOAD_X4]), + *STORE], LOOP), +} + EXPECTED_MANIFEST = """x2w-manifest 2 stage cs group 32 1 1 @@ -181,10 +325,29 @@ def full(coords, op, load=TOKEN_LOAD, sampler=SAMPLER, store=STORE, selector=SEL uav 0 heaptokmiss uav 1 table 0 32 smpl 0 00000092 00000000 00000000 00000000 -native 2 +native 3 +""" +EXPECTED_BUFFER_MANIFEST = """x2w-manifest 2 +stage cs +group 32 1 1 +ud 7 +udsrc 0 heaptok base1d +udsrc 1 heaptok base2d +udsrc 2 heaptok base2da +udsrc 3 heaptok count +udsrc 4 heaptok null +udsrc 5 heaptok baseraw +udsrc 6 heaptok nullraw +srv 0 heaptok +srv 1 heaptokdims +srv 2 buf table 0 0 +uav 0 heaptokmiss +uav 1 table 0 32 +native 3 """ FIXTURE_CASES = ("valid", "wrong_magic", "id_at_count", "id_max", "dims_mismatch", "content_token", "id_zero", "no_token") +BUFFER_FIXTURE_CASES = FIXTURE_CASES + ("second_view",) def main(): @@ -254,6 +417,16 @@ def compile_request(marker): 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") + for mode in BUFFER_PROGRAMS: + marker = request(mode, BUFFER_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 BUFFER_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 seven heaptok words") print(f"{ok_lines} assertions held") return @@ -311,6 +484,45 @@ def compile_request(marker): 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") + # 6. GPU-selected raw buffers. The eligible programs compile and publish seven token words; the module reads the + # token, checks it and reads the buffer from the heap. + for name, words in {**BUFFER_PROGRAMS, **BUFFER_ACCEPTED, **MIXED_PROGRAMS}.items(): + marker = request("b_" + name, words) + code, out, err, output = compile_request(marker) + require(code == 0 and output.exists(), f"{name}: compiles") + 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 buffer comes from createHandleFromHeap") + require("@dx.op.waveIsFirstLane(i32 110)" in listing, f"{name}: the miss is counted by the first lane (op 110)") + require(listing.count("@dx.op.rawBufferLoad.i32(") >= 4, + f"{name}: the module loads the token words, the dimension and the data") + require(", 1448555096" in listing, + f"{name}: the module compares the view token magic") + out_dir = base / f"b_{name}_out" + code, out, err = run([compile_dxil, sdk, base / f"cache_b_{name}", "gfx1013-direct-cs@0", "--requests", + marker.parent, out_dir]) + text = (out_dir / (marker.stem[len("req_"):] + ".txt")).read_text() + if name in ("rawbuf", "rawbuf_waterfall", "sbuf", "x1", "x3", "immediate", "sbuf_offset"): + require(code == 0 and text == EXPECTED_BUFFER_MANIFEST, + f"{name}: the manifest names the token views and the seven token words, and no heap buffer view") + else: + require(code == 0 and "udsrc 6 heaptok nullraw\n" in text and "udsrc 4 heaptok null\n" in text and + "ud 7\n" in text, f"{name}: a texture and a buffer publish seven token words") + # Controls: a V# use that is not the byte window of a raw load or a scalar buffer load keeps today's refusal. + for name, (words, text) in BUFFER_CONTROLS.items(): + code, out, err, output = compile_request(request("bc_" + name, words)) + require(code != 0 and text in err and not output.exists(), f"{name}: refused with \"{text}\" and no .cso") + # Mixed: a buffer load that is not eligible does not take the textures off the token route (and the reverse). + for name, (words, text) in MIXED_CONTROLS.items(): + code, out, err, output = compile_request(request("mc_" + name, words)) + require(code != 0 and text in err and not output.exists(), f"mixed {name}: refused with \"{text}\" and no .cso") + for name, (words, text) in BUFFER_ADDRESS_CONTROLS.items(): + code, out, err, output = compile_request(request("ba_" + name, words)) + require(code != 0 and text in err and not output.exists(), f"buffer {name}: refused with \"{text}\" and no .cso") + # Texture-only programs keep their five words (the same program with a buffer has seven). + code, out, err, output = compile_request(request("t_only", PROGRAMS["tex2d"])) + require(code == 0, "control: the texture-only program still compiles") + print(f"{ok_lines} assertions held") diff --git a/tests/startup_compute_dispatch_texture_check.py b/tests/startup_compute_dispatch_texture_check.py index ffb9c940a6..7426b070d1 100644 --- a/tests/startup_compute_dispatch_texture_check.py +++ b/tests/startup_compute_dispatch_texture_check.py @@ -174,8 +174,13 @@ def check_manifest_refusal(case, variant, reason): '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')): + ('heap token miss counter', 'uav 1 heaptokmiss\n'), ('heap token word', 'udsrc 3 heaptok null\n'), + ('heap token raw buffer base', 'udsrc 3 heaptok baseraw\n'), + ('heap token raw buffer null', 'udsrc 3 heaptok nullraw\n')): check_manifest_refusal(case, original + line, 'heap token textures are not bound yet') + # Control: a token word the reader does not know is not taken for one. + check_manifest_refusal('unknown heap token word', original + 'udsrc 3 heaptok bogus\n', + 'an entry value that is not a root constant or a buffer descriptor word') 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') From 32b9f2672c3c36887e6d187b93c3c27dbbb4d175 Mon Sep 17 00:00:00 2001 From: JB2WIN Date: Mon, 30 Nov 2026 10:33:06 +0100 Subject: [PATCH 3/8] native: judge the heap raw buffer address shape in the analysis Review fixes for the heap token buffer route. - heap_token_buffer_eligible now checks the address the lowering needs, on the state at the load: heap pointer high word is the constant 0, imm % 32 == 0, proven 32-byte aligned SGPR offset, no offset + imm overflow; on an added address imm == 0 and a masked offset. It also compares the V# words symbol for symbol as heap_token_buffer does. A candidate that fails is dropped (an added address keeps the old program-wide rejection) and keeps today's text. The lowering refusals stay as a safeguard. - When no buffer load is eligible, the textures are judged again on the analysis without the byte window, as before the route knew buffers. - Document the carry assumption of an added address (heap-relative model of the existing heap_offset path, no runtime carry check). - Tests: address-shape controls expect the heap contract text of the dropped load; new controls for overflow, a non-constant high word, an unread candidate next to a texture, and an accepted wide mask. Co-Authored-By: Claude Opus 5.5 --- .../experiments/native-heap-token-textures.md | 10 ++- src/gfx1013_compute_native.cpp | 74 ++++++++++++++----- src/gfx1013_direct_compute.inl | 8 +- tests/native_heap_token_texture_check.py | 37 +++++++--- 4 files changed, 94 insertions(+), 35 deletions(-) diff --git a/docs/experiments/native-heap-token-textures.md b/docs/experiments/native-heap-token-textures.md index e0c6ddee5e..5ff2669fad 100644 --- a/docs/experiments/native-heap-token-textures.md +++ b/docs/experiments/native-heap-token-textures.md @@ -76,8 +76,11 @@ path and refusal text. Like the texture route, this translates only where no hea eligible, the program is analysed again exactly as before, so texture-only programs and every other program translate to the same module and manifest (only the revision line changes). - The load handler writes the byte address (`so + imm`, or the low word of the added address: the byte offset from heap - slot 0, not a slot index) to the four words. It requires an address that is a multiple of 32: `imm % 32 == 0`, an SGPR - offset that is constant or masked with `(mask & 31) == 0`, no overflow; on an added address `imm == 0` and the same mask. + slot 0, not a slot index) to the four words. The analysis requires an address that is a multiple of 32, judged on the + state at the load: the heap pointer's high word is the constant 0, `imm % 32 == 0`, an SGPR offset that is constant or + masked with `(mask & 31) == 0`, and no overflow of offset plus immediate; on an added address `imm == 0` and the same mask. + A candidate without that shape is not eligible and keeps today's path and text (the lowering repeats the checks as a + safeguard). The words of the V# must also be exactly the symbols the lowering compares. - The consumer reads the token at that address: `valid = word0 == magic && id < count && dims[min(id, count - 1)] == 0x20`, and uses `ResourceDescriptorHeap[valid ? baseraw + id : nullraw]` as a raw buffer. A miss is counted as for textures. No `heap_buffer_srv` binding is created. @@ -96,6 +99,9 @@ new one compiles it from the same cache folder). ## Runtime assumptions and failure modes +- Carry of an added address: the high word of the `s_add_u32` pair is taken as 0. This relies on the same heap-relative + model as the existing heap_offset path (the model is relative to the heap base, so the high word is the carry of the byte + offset alone, which is 0 for offsets below 2^32; the emitter writes it as 0); no runtime carry check. - A1: a token in the bound view heap's memory names the view the title created for that slot. The runtime (PR 2) builds the raw view per id from the view record, so its byte range is that view's range. - Failure modes, all read the null raw view (zeros) and count a miss, never a wrong-kind view: no token (the title wrote a raw diff --git a/src/gfx1013_compute_native.cpp b/src/gfx1013_compute_native.cpp index ddbf00d6c0..910c893b38 100644 --- a/src/gfx1013_compute_native.cpp +++ b/src/gfx1013_compute_native.cpp @@ -1879,6 +1879,25 @@ static bool heap_token_buffer_eligible(const Program &p, size_t l, std::vector 106) return false; const unsigned immediate = load.b & 0xfffff; + // The address shape the lowering of the load (heap_token_buffer_load site) requires, judged on the state at the load: a + // candidate that does not have it is not eligible, so that it keeps today's path and text. + { + const auto &before = p.before[l]; + const unsigned so = load.b >> 25; + if (so != 125) { + const auto &low = before.at(load.src[0]); + if (low.type != Symbol::Type::table || low.value != compute_resource_heap || + !(before.at(load.src[0] + 1) == Symbol{Symbol::Type::constant, 0}) || immediate % 32 || + so >= smem_sgpr_limit(true)) + return false; + const auto &value = before.at(so); + const bool aligned = (value.type == Symbol::Type::constant && value.value % 32 == 0) || + (value.type == Symbol::Type::masked && (value.value & 31) == 0); + if (!aligned || value.value > UINT_MAX - immediate) return false; + } else if (!heap_offset_address(before, load.src[0]) || immediate || + (before.at(load.src[0]).index_mask & 31) != 0) + return false; + } const auto is_token = [&](const Symbol &s, unsigned word) { return s.type == T::indexed_descriptor && s.value == compute_resource_heap && s.definition == load.pc && s.offset == immediate + 4 * word; @@ -1911,17 +1930,25 @@ static bool heap_token_buffer_eligible(const Program &p, size_t l, std::vector> 16) & 31) * 4, soffset = i.b >> 24; - if (base + 4 > 106 || !is_token(state[base], 0) || !is_field(state[base + 1], T::zero_stride_word) || - !is_field(state[base + 2], T::byte_count) || !is_field(state[base + 3], T::byte_oob) || - (soffset < 106 && of_load(state[soffset]))) + if (base + 4 > 106 || !is_token(state[base], 0) || (soffset < 106 && of_load(state[soffset]))) return false; + // The words the lowering compares (heap_token_buffer): word 0 and the three fields, symbol for symbol. + constexpr T window_words[] = {T::indexed_descriptor, T::zero_stride_word, T::byte_count, T::byte_oob}; + for (unsigned j = 1; j < 4; ++j) { + Symbol expected = state[base]; + expected.type = window_words[j]; + if (!(state[base + j] == expected)) return false; + } found.push_back({i.pc, load.pc}); } else if (i.enc == Encoding::Smem && i.op >= 8 && i.op <= 12) { const unsigned base = i.src[0], soffset = i.b >> 25; if (base + 4 > 106 || (soffset < 106 && of_load(state[soffset]))) return false; - for (unsigned j = 0; j < 4; ++j) - if (!is_token(state[base + j], j)) return false; + for (unsigned j = 0; j < 4; ++j) { + Symbol expected = state[base]; + expected.offset += 4 * j; + if (!is_token(state[base + j], j) || !(state[base + j] == expected)) return false; + } found.push_back({i.pc, load.pc}); } else if (!(i.enc == Encoding::Sop2 && byte_descriptor_field(i, state, true))) return false; @@ -2127,26 +2154,35 @@ static NativeComputeShader translate_program(const ComputeRequest &request, unsi } bool compiler_window = heap_window; if (token_candidate || buffer_candidate) { + // Judged on the analysis that tracks the byte window when there is a buffer candidate (buffer_candidate implies + // that no heap contract is set, so heap_window is false here). auto tokens = parse(request.code, entry, initial, direct_dxil, false, wave64, false, heap_window || buffer_candidate, narrow_wave64, true); - if (heap_token_eligible(tokens, buffer_candidate, token_consumers, buffer_consumers)) { - if (!buffer_consumers.empty()) { + const bool routed = heap_token_eligible(tokens, buffer_candidate, token_consumers, buffer_consumers); + if (routed && !buffer_consumers.empty()) { + // At least one eligible buffer load: translate on the window analysis. + program = std::move(tokens); + heap_tokens = true; + compiler_window = true; + } else if (!buffer_candidate) { + // Textures only, as before this route knew buffers. + if (routed) { program = std::move(tokens); heap_tokens = true; - compiler_window = true; - } else if (!buffer_candidate || heap_window) { - program = std::move(tokens); + } + } else if (token_candidate) { + // No buffer load is eligible (dropped candidates keep today's path): judge the textures again on the analysis + // without the byte window, exactly as before this route knew buffers. + auto textures = parse(request.code, entry, initial, direct_dxil, false, wave64, false, heap_window, narrow_wave64, + true); + std::vector none; + if (heap_token_eligible(textures, false, token_consumers, none)) { + program = std::move(textures); heap_tokens = true; - } else { - // Token textures only: the analysis of the program as before this route knew buffers. - auto textures = parse(request.code, entry, initial, direct_dxil, false, wave64, false, heap_window, narrow_wave64, - true); - std::vector none; - if (heap_token_eligible(textures, false, token_consumers, none)) { - program = std::move(textures); - heap_tokens = true; - } } + } else { + // Buffer candidates only and none eligible: no token route, the program stays as parsed first. + token_consumers.clear(); } } Emit emit{{}, program,layout->Desc_1_1}; diff --git a/src/gfx1013_direct_compute.inl b/src/gfx1013_direct_compute.inl index 1385cfe0bd..2b5bd9bdae 100644 --- a/src/gfx1013_direct_compute.inl +++ b/src/gfx1013_direct_compute.inl @@ -787,8 +787,12 @@ struct DirectCompute { refuse(i.pc, "heap token buffer byte offset has no proven 32-byte aligned range"); address = ir.binary("add", operand32(i, so), to_string(offset)); } else { - // The address formed by s_add_u32: its high word is the carry of that add, which the emitter writes as 0 - // (the heap base is slot 0), and its low word is the byte offset. + // The address formed by s_add_u32. Assumption, no runtime carry check: the model of heap_offset and + // heap_carry is relative to the heap base (slot 0), so the high word is the carry of the byte offset + // alone, which is 0 for offsets below 2^32; the emitter writes it as 0 (see arithmetic()) and the + // existing lshr-5 path of the heap_offset address relies on the same model. The low word is the byte + // offset. The pre-pass (heap_token_buffer_eligible) already judged these shapes; these refusals are + // the safeguard. if (!heap_offset_address(s, i.src[0])) refuse(i.pc, "heap descriptor address high word is not the carry of its offset add"); if (offset) refuse(i.pc, "heap token buffer load with an immediate offset on an added address"); diff --git a/tests/native_heap_token_texture_check.py b/tests/native_heap_token_texture_check.py index 8e5f690966..2f70f7ab50 100644 --- a/tests/native_heap_token_texture_check.py +++ b/tests/native_heap_token_texture_check.py @@ -225,7 +225,7 @@ def loop_body(words): "sbuf": [*BASES, *TABLE_LOADS, *SELECTOR32, *BUFFER_LOAD, *WAIT, *SBUFFER_X4, *WAIT, *SBUFFER_VGPR, *LANE, *STORE], } # Eligible variants that must compile: the other dword widths, an immediate offset, and a texture next to a buffer. -BUFFER_ACCEPTED = { +BUFFER_ACCEPTED = { # (mask_wide is added below, after its mask) "x1": buffer_full(BUFFER_LOAD, consumer=LOAD_X1), "x3": buffer_full(BUFFER_LOAD, consumer=LOAD_X3), "immediate": buffer_full(BUFFER_LOAD_IMM), @@ -268,11 +268,12 @@ def mixed(buffer_rewrite, texture_load=TOKEN_LOAD, texture_selector=SELECTOR32, "texture_first": (mixed([], texture_selector=SELECTOR_HEAD, texture_load=[0xf40c0805, 0x20000000]), UNPROVEN), # the buffer load is first: the heap contract text of the load that keeps today's path "buffer_first": (mixed([], buffer_first=True), HEAP_REFUSAL), + # the buffer load is never read: not a consumer, so it is dropped and keeps today's text after the texture + "texture_unread": (mixed([], consume=[]), HEAP_REFUSAL), + "unread_first": (mixed([], consume=[], buffer_first=True), HEAP_REFUSAL), } -BUFFER_UNMASKED = "heap token buffer byte offset has no proven 32-byte aligned range" -BUFFER_IMMEDIATE = "unaligned heap token buffer immediate byte offset" -BUFFER_ADDED_IMMEDIATE = "heap token buffer load with an immediate offset on an added address" +MASK_WIDE = [0x8711ff10, 0xffffffe0] # s_and_b32 s17, s16, 0xffffffe0 (32-byte aligned, but up to 0xffffffe0) LOOP = "heap byte window loaded inside a loop" # V# uses that make the buffer load not eligible: the refusal text is the one these programs get without the buffer route # (checked against the base of this change). Two of them are refused before the heap load is reached. @@ -294,21 +295,33 @@ def mixed(buffer_rewrite, texture_load=TOKEN_LOAD, texture_selector=SELECTOR32, # the immediate offset 4 moves the words off the 32-byte descriptor layout the rewrite recognizes "immediate4": (buffer_full(BUFFER_LOAD_IMM4), HEAP_REFUSAL), } -# Address shapes. Each program is eligible, so it reaches the load and is refused there. +# Address shapes. The analysis judges the address of the load (the state at the load, as the lowering uses it): a load whose +# address has no proven 32-byte aligned range, an immediate that is not a multiple of 32, a high word that is not the +# constant 0, an offset sum that may overflow, or an added address with an immediate or an unmasked offset is not eligible, +# so it keeps today's path and text (the heap contract text). The refusals of the lowering stay as a safeguard and are not +# reachable from a request. BUFFER_ADDRESS_CONTROLS = { # s_load_dwordx4 s[32:35], s[10:11], s17 where s17 is s16: not masked - "unmasked": (buffer_full(BUFFER_LOAD, selector=SELECTOR_HEAD), BUFFER_UNMASKED), + "unmasked": (buffer_full(BUFFER_LOAD, selector=SELECTOR_HEAD), HEAP_REFUSAL), # s_and_b32 s17, s16, 0xfffc: bit 2 to 4 may be set - "misaligned": (buffer_full(BUFFER_LOAD, selector=[*SELECTOR_HEAD, *MASK]), BUFFER_UNMASKED), + "misaligned": (buffer_full(BUFFER_LOAD, selector=[*SELECTOR_HEAD, *MASK]), HEAP_REFUSAL), # the scalar buffer load of the unrewritten words with s_load_dwordx4 ... offset:0x4 "immediate4": ([*BASES, *TABLE_LOADS, *SELECTOR32, *BUFFER_LOAD_IMM4, *WAIT, *SBUFFER_X4, *WAIT, *SBUFFER_VGPR, *LANE, - *STORE], BUFFER_IMMEDIATE), - "added_unmasked": (buffer_full(BUFFER_LOAD_ADDED, pre=ADD_HEAP_UNMASKED), BUFFER_UNMASKED), - "added_immediate": (buffer_full(BUFFER_LOAD_ADDED_IMM, pre=ADD_HEAP), BUFFER_ADDED_IMMEDIATE), - # the load and its rewrite inside a one-block loop (s_cmp_eq_u32 s16, 0 ; s_cbranch_scc0 back to the load) + *STORE], HEAP_REFUSAL), + # offset:0x20 after a mask that allows 0xffffffe0: the sum may overflow + "overflow": (buffer_full(BUFFER_LOAD_IMM, selector=[*SELECTOR_HEAD, *MASK_WIDE]), HEAP_REFUSAL), + # s_mov_b32 s11, s5 instead of s_mov_b32 s11, 0: the high word of the heap pointer is not the constant 0 + "high_word": ([0xbe880304, 0xbe890380, 0xbe8a0305, 0xbe8b0305, *TABLE_LOADS, *SELECTOR32, *BUFFER_LOAD, *WAIT, + *REWRITE, *LANE, *WAIT, *LOAD_X4, *STORE], HEAP_REFUSAL), + "added_unmasked": (buffer_full(BUFFER_LOAD_ADDED, pre=ADD_HEAP_UNMASKED), HEAP_REFUSAL), + "added_immediate": (buffer_full(BUFFER_LOAD_ADDED_IMM, pre=ADD_HEAP), HEAP_REFUSAL), + # the load and its rewrite inside a one-block loop (s_cmp_eq_u32 s16, 0 ; s_cbranch_scc0 back to the load): eligible, + # refused by the lowering with its own text "loop": ([*BASES, *TABLE_LOADS, *SELECTOR32, *loop_body([*BUFFER_LOAD, *WAIT, *REWRITE, *LANE, *WAIT, *LOAD_X4]), *STORE], LOOP), } +# The same address with a proven range compiles (controls for the refusals above). +BUFFER_ACCEPTED["mask_wide"] = buffer_full(BUFFER_LOAD, selector=[*SELECTOR_HEAD, *MASK_WIDE]) EXPECTED_MANIFEST = """x2w-manifest 2 stage cs @@ -502,7 +515,7 @@ def compile_request(marker): code, out, err = run([compile_dxil, sdk, base / f"cache_b_{name}", "gfx1013-direct-cs@0", "--requests", marker.parent, out_dir]) text = (out_dir / (marker.stem[len("req_"):] + ".txt")).read_text() - if name in ("rawbuf", "rawbuf_waterfall", "sbuf", "x1", "x3", "immediate", "sbuf_offset"): + if name in ("rawbuf", "rawbuf_waterfall", "sbuf", "x1", "x3", "immediate", "sbuf_offset", "mask_wide"): require(code == 0 and text == EXPECTED_BUFFER_MANIFEST, f"{name}: the manifest names the token views and the seven token words, and no heap buffer view") else: From 4a03fafdfd8b530752cd94e1751767e03be964f6 Mon Sep 17 00:00:00 2001 From: JB2WIN Date: Mon, 30 Nov 2026 13:41:40 +0100 Subject: [PATCH 4/8] native: drop heap buffer candidates the lowering would refuse (loop, word budget) Review fixes, round 2. - A byte window load inside a loop is dropped by the analysis with the same query the lowering uses, instead of failing the whole program (textures included) at lowering. - When the seven token words do not fit the 32-word entry layout next to the descriptor strides and root constants (the strides are known only while lowering), the program is translated again with the buffer route off, so the buffer loads keep today's path and text. - Document that words 2 and 3 of the title's V# are not read and that PR 2 must make the raw view's range equal it (A1). - Tests: loop and texture + loop controls now expect today's text; 25 strides compile next to seven token words, 26 are refused with today's text. Co-Authored-By: Claude Opus 5.5 --- .../experiments/native-heap-token-textures.md | 16 ++++++-- src/gfx1013_compute_native.cpp | 26 +++++++++--- src/gfx1013_direct_compute.inl | 3 ++ tests/native_heap_token_texture_check.py | 41 +++++++++++++++++-- 4 files changed, 73 insertions(+), 13 deletions(-) diff --git a/docs/experiments/native-heap-token-textures.md b/docs/experiments/native-heap-token-textures.md index 5ff2669fad..7d7e14c50b 100644 --- a/docs/experiments/native-heap-token-textures.md +++ b/docs/experiments/native-heap-token-textures.md @@ -75,6 +75,9 @@ path and refusal text. Like the texture route, this translates only where no hea - The analysis of a program with a candidate runs with the byte-window tracking (`heap_window`). If no candidate is eligible, the program is analysed again exactly as before, so texture-only programs and every other program translate to the same module and manifest (only the revision line changes). +- The seven token words and the descriptor strides of the program must fit the 32-word entry layout. The strides are known + only while lowering, so a program that does not fit is translated again with the buffer route off: its buffer loads keep + today's path and text. - The load handler writes the byte address (`so + imm`, or the low word of the added address: the byte offset from heap slot 0, not a slot index) to the four words. The analysis requires an address that is a multiple of 32, judged on the state at the load: the heap pointer's high word is the constant 0, `imm % 32 == 0`, an SGPR offset that is constant or @@ -103,7 +106,9 @@ new one compiles it from the same cache folder). model as the existing heap_offset path (the model is relative to the heap base, so the high word is the carry of the byte offset alone, which is 0 for offsets below 2^32; the emitter writes it as 0); no runtime carry check. - A1: a token in the bound view heap's memory names the view the title created for that slot. The runtime (PR 2) builds the - raw view per id from the view record, so its byte range is that view's range. + raw view per id from the view record, so its byte range is that view's range. Words 2 (num_records) and 3 of the title's + own V# are not read: the raw view's range applies, and PR 2 must make it equal the range the title's V# describes. + Nothing in the translator or the shader checks that. - Failure modes, all read the null raw view (zeros) and count a miss, never a wrong-kind view: no token (the title wrote a raw V# itself, or the slot was never written because the token write is gated on a title-backed writable view), a wrong magic, `id >= count`, a content token (word 1 carries flags), a texture id (dimension code not 0x20). @@ -120,9 +125,12 @@ new one compiles it from the same cache folder). - `native_heap_token_texture_controls`: eligible programs (SGPR offset, added address, scalar buffer load, other widths, an immediate offset, a texture next to a buffer) and the published manifest; controls that keep today's text (plain V# without the rewrite, IDXEN, format, `tbuffer`, store, a numeric read of word 2, a copy of a rewritten word, a partial V#, a join, an - immediate offset that breaks the descriptor layout), the new address texts, a window load in a loop - (`heap byte window loaded inside a loop`), and the mixed cases (a texture on the token route next to a buffer load that - keeps today's refusal). + immediate offset that breaks the descriptor layout), address shapes without a proven range (overflow, a high word that is + not the constant 0, an unmasked or misaligned offset, an immediate on an added address; all dropped, today's text), a byte + window load in a loop (dropped by the analysis: the lowering would refuse it with `heap byte window loaded inside a loop` + and take the whole program down), the word budget (25 descriptor strides fit next to seven token words, 26 do not and the + buffer route is dropped), and the mixed cases (a texture on the token route next to a buffer load, an unread load or a + loop that keeps today's refusal). - `native_heap_token_texture_warp` and `_hardware`: modes `rawbuf`, `rawbuf_waterfall` and `sbuf` with two raw views (64 and 128 dwords) and a texture id in the dimension table: valid tokens read the view (lanes past the first view get 0), every other case gives zeros and one miss per wave. Results are compared as dwords. diff --git a/src/gfx1013_compute_native.cpp b/src/gfx1013_compute_native.cpp index 910c893b38..8ac4b1b25e 100644 --- a/src/gfx1013_compute_native.cpp +++ b/src/gfx1013_compute_native.cpp @@ -1888,7 +1888,7 @@ static bool heap_token_buffer_eligible(const Program &p, size_t l, std::vector= smem_sgpr_limit(true)) + so >= smem_sgpr_limit(true)) // as the lowering: smem_sgpr_limit(!graphics_input), true for compute return false; const auto &value = before.at(so); const bool aligned = (value.type == Symbol::Type::constant && value.value % 32 == 0) || @@ -1911,6 +1911,12 @@ static bool heap_token_buffer_eligible(const Program &p, size_t l, std::vector found; for (size_t n = 0; n < p.code.size(); ++n) { @@ -1930,7 +1936,7 @@ static bool heap_token_buffer_eligible(const Program &p, size_t l, std::vector> 16) & 31) * 4, soffset = i.b >> 24; - if (base + 4 > 106 || !is_token(state[base], 0) || (soffset < 106 && of_load(state[soffset]))) + if (in_loop || base + 4 > 106 || !is_token(state[base], 0) || (soffset < 106 && of_load(state[soffset]))) return false; // The words the lowering compares (heap_token_buffer): word 0 and the three fields, symbol for symbol. constexpr T window_words[] = {T::indexed_descriptor, T::zero_stride_word, T::byte_count, T::byte_oob}; @@ -2001,7 +2007,7 @@ static bool heap_token_eligible(const Program &p, bool buffers, std::vector> 16) != 0xd580 || (word(request.code, 12) >> 16) != 0xd580 || (word(request.code, 24) >> 16) != 0xd580 || (word(request.code, 36) >> 16) != 0xbfa0)) refuse(entry, "unrecognized compute header"); @@ -2147,7 +2153,7 @@ static NativeComputeShader translate_program(const ComputeRequest &request, unsi const auto &base = program.before[n].at(i.src[0]); if (i.op == 3 && (i.b >> 25) != 125) token_candidate |= base.type == Symbol::Type::table && base.value == compute_resource_heap; - else if (i.op == 2 && heap_view == HeapViewContract::none) + else if (i.op == 2 && heap_view == HeapViewContract::none && buffers_allowed) buffer_candidate |= (base.type == Symbol::Type::table && base.value == compute_resource_heap && (i.b >> 25) != 125) || ((i.b >> 25) == 125 && base.type == Symbol::Type::heap_offset); @@ -2237,7 +2243,17 @@ static NativeComputeShader translate_program(const ComputeRequest &request, unsi compiler.virtual_waves = static_cast(threads / 64); } } - auto translated = compiler.lower(entry,user,rsrc2,x,y,z); + NativeComputeShader translated; + try { + translated = compiler.lower(entry,user,rsrc2,x,y,z); + } catch (const UnsupportedComputeShader &error) { + // The token words of a buffer load do not fit the 32-word entry layout next to the descriptor strides and root + // constants (the strides are known only while lowering): drop the buffer route and translate again, so the + // buffer loads keep today's path and text. + if (!buffer_consumers.empty() && std::string_view(error.what()).find("heap token words exceed") != std::string_view::npos) + return translate_program(request, entry, direct_dxil, stage, heap_view, false); + throw; + } for (auto &binding : translated.bindings) { if (stage) apply_reflected_table_use(binding, *stage); if (!request.root.empty()) { diff --git a/src/gfx1013_direct_compute.inl b/src/gfx1013_direct_compute.inl index 2b5bd9bdae..cbbd31ef95 100644 --- a/src/gfx1013_direct_compute.inl +++ b/src/gfx1013_direct_compute.inl @@ -1162,6 +1162,9 @@ struct DirectCompute { ir.body << " br label %tokenMissEnd" << tag << "\ntokenMissEnd" << tag << ":\n"; return slot; } + // Words 2 (num_records) and 3 of the title's own V# are not read: the view the token names gives the range, and the shader + // reads that raw view as the byte window (assumption A1). The runtime change (PR 2) must make the raw view's byte range equal + // the range the title's V# describes; nothing here checks it. // A GPU-selected raw buffer read through its view token: ResourceDescriptorHeap[baseraw + id] when the token names a // raw buffer view (dimension table entry 0x20), else the null raw view (reads zero) and a miss. `symbol` is a word of // the heap load (the s_load_dwordx4 left the token's byte address in all four words; the byte-window rewrite only diff --git a/tests/native_heap_token_texture_check.py b/tests/native_heap_token_texture_check.py index 2f70f7ab50..1eed573ff1 100644 --- a/tests/native_heap_token_texture_check.py +++ b/tests/native_heap_token_texture_check.py @@ -274,6 +274,29 @@ def mixed(buffer_rewrite, texture_load=TOKEN_LOAD, texture_selector=SELECTOR32, } MASK_WIDE = [0x8711ff10, 0xffffffe0] # s_and_b32 s17, s16, 0xffffffe0 (32-byte aligned, but up to 0xffffffe0) +# More than 32 entry words: the token words (7 with a buffer) and the descriptor strides of table SRVs read as s_bfe_u32 +# stride fields. 25 strides fit next to seven words, 26 do not: the buffer route is dropped and the program keeps today's text. +ROOT_STRIDES = ("RootFlags(CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED), DescriptorTable(SRV(t0, numDescriptors = 32), UAV(u0))") +STRIDE_TABLE_LOADS = [ + 0xf4080304, 0xfa000000, # s_load_dwordx4 s[12:15], s[8:9], 0x0 (t0: the selector) + 0xf4080604, 0xfa000400, # s_load_dwordx4 s[24:27], s[8:9], 0x400 (u0 follows the 32 SRVs) +] + + +def stride_reads(count): + words = [] + for k in range(1, count + 1): + words += [0xf4080c04, 0xfa000000 | (32 * k), # s_load_dwordx4 s[48:51], s[8:9], 32 * k + 0x93b4ff31, 0x000e0010, # s_bfe_u32 s52, s49, 0xe0010 (the stride of table slot k) + 0x85358081] # s_cselect_b32 s53, 1, 0 (reads SCC: the stride is the runtime's) + return words + + +def stride_program(count): + return [*BASES, *STRIDE_TABLE_LOADS, *stride_reads(count), *SELECTOR32, *BUFFER_LOAD, *WAIT, *REWRITE, *LANE, *WAIT, + *LOAD_X4, *STORE] + + LOOP = "heap byte window loaded inside a loop" # V# uses that make the buffer load not eligible: the refusal text is the one these programs get without the buffer route # (checked against the base of this change). Two of them are refused before the heap load is reached. @@ -315,10 +338,14 @@ def mixed(buffer_rewrite, texture_load=TOKEN_LOAD, texture_selector=SELECTOR32, *REWRITE, *LANE, *WAIT, *LOAD_X4, *STORE], HEAP_REFUSAL), "added_unmasked": (buffer_full(BUFFER_LOAD_ADDED, pre=ADD_HEAP_UNMASKED), HEAP_REFUSAL), "added_immediate": (buffer_full(BUFFER_LOAD_ADDED_IMM, pre=ADD_HEAP), HEAP_REFUSAL), - # the load and its rewrite inside a one-block loop (s_cmp_eq_u32 s16, 0 ; s_cbranch_scc0 back to the load): eligible, - # refused by the lowering with its own text + # the load and its rewrite inside a one-block loop (s_cmp_eq_u32 s16, 0 ; s_cbranch_scc0 back to the load): the lowering + # would refuse the byte window ("heap byte window loaded inside a loop"), so the analysis drops the candidate "loop": ([*BASES, *TABLE_LOADS, *SELECTOR32, *loop_body([*BUFFER_LOAD, *WAIT, *REWRITE, *LANE, *WAIT, *LOAD_X4]), - *STORE], LOOP), + *STORE], HEAP_REFUSAL), + # a texture on the token route next to the same loop: the texture is not taken down with the buffer + "mixed_loop": ([*BASES, *TABLE_LOADS, *SELECTOR32, *TOKEN_LOAD, *SAMPLER, *COORDS_2D, + *loop_body([*MIXED_BUFFER_LOAD, *WAIT, *MIXED_REWRITE, *MIXED_CONSUME]), *WAIT, *SAMPLE_2D, *STORE], + HEAP_REFUSAL), } # The same address with a proven range compiles (controls for the refusals above). BUFFER_ACCEPTED["mask_wide"] = buffer_full(BUFFER_LOAD, selector=[*SELECTOR_HEAD, *MASK_WIDE]) @@ -410,7 +437,7 @@ def request(name, words, root_text=ROOT): 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 + user = 6 if "RootFlags" in root_text 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) @@ -532,6 +559,12 @@ def compile_request(marker): for name, (words, text) in BUFFER_ADDRESS_CONTROLS.items(): code, out, err, output = compile_request(request("ba_" + name, words)) require(code != 0 and text in err and not output.exists(), f"buffer {name}: refused with \"{text}\" and no .cso") + # The word budget: 25 strides + 7 token words fit; 26 do not, and the buffer route is dropped (today's text). + code, out, err, output = compile_request(request("strides25", stride_program(25), ROOT_STRIDES)) + require(code == 0 and output.exists(), "25 descriptor strides next to the seven token words compile") + code, out, err, output = compile_request(request("strides26", stride_program(26), ROOT_STRIDES)) + require(code != 0 and HEAP_REFUSAL in err and not output.exists(), + f"26 descriptor strides: the buffer route is dropped, refused with \"{HEAP_REFUSAL}\" and no .cso") # Texture-only programs keep their five words (the same program with a buffer has seven). code, out, err, output = compile_request(request("t_only", PROGRAMS["tex2d"])) require(code == 0, "control: the texture-only program still compiles") From 8353a6fe61e656ba82de51fff05f66d379442ca1 Mon Sep 17 00:00:00 2001 From: JB2WIN Date: Mon, 30 Nov 2026 13:52:49 +0100 Subject: [PATCH 5/8] native: signal the heap token word budget by exception type, tidy comments - The budget retry in translate_program catches HeapTokenWordBudget (thrown by prepare_heap_tokens with the same text) instead of matching the message. - Exact root signature match for the user SGPR count in the test, comments wrapped to 120 columns, doc line for the seven-word form. Co-Authored-By: Claude Opus 5.5 --- .../experiments/native-heap-token-textures.md | 6 +- src/gfx1013_compute_native.cpp | 67 +++++++++++++------ src/gfx1013_compute_native.h | 3 +- src/gfx1013_direct_compute.inl | 38 +++++++---- src/native_compute_pipeline.h | 3 +- src/startup_stubs/d3d12_compute_dispatch.inl | 3 +- tests/native_heap_token_texture.cpp | 3 +- tests/native_heap_token_texture_check.py | 2 +- 8 files changed, 84 insertions(+), 41 deletions(-) diff --git a/docs/experiments/native-heap-token-textures.md b/docs/experiments/native-heap-token-textures.md index 7d7e14c50b..e1631a4754 100644 --- a/docs/experiments/native-heap-token-textures.md +++ b/docs/experiments/native-heap-token-textures.md @@ -27,12 +27,14 @@ those two words at the guest byte address and maps the id to a host descriptor. - 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 +- Five more `b0` words (seven with a raw buffer, see below) 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`. +- Manifest lines: `srv N heaptok`, `srv N heaptokdims`, `uav N heaptokmiss`, + `udsrc K heaptok base1d|base2d|base2da|count|null`, and in the seven-word form (raw buffers, below) also + `udsrc K heaptok baseraw|nullraw`. `native_compute_output_revision` is 3 (see Revision below). 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 8ac4b1b25e..2d5d159799 100644 --- a/src/gfx1013_compute_native.cpp +++ b/src/gfx1013_compute_native.cpp @@ -1747,6 +1747,13 @@ struct HeapTokenLoad { struct HeapTokenBufferLoad { unsigned pc, load; }; +// Thrown when the token words of a buffer load do not fit the 32-word entry layout (the descriptor strides are known +// only +// while lowering); translate_program then translates the program again without the buffer route. +class HeapTokenWordBudget : public UnsupportedComputeShader { + public: + using UnsupportedComputeShader::UnsupportedComputeShader; +}; // 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) { @@ -1805,8 +1812,10 @@ static std::vector instructions_after(const Program &p, size_t l) { return after; } // The texture rules of the heap token route. `loads` are the reached s_load_dwordx8 from the resource heap with an SGPR -// offset (token loads). 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 +// offset (token loads). 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. @@ -1868,10 +1877,13 @@ static bool heap_token_texture_eligible(const Program &p, const std::vector &consumers) { @@ -1879,7 +1891,8 @@ static bool heap_token_buffer_eligible(const Program &p, size_t l, std::vector 106) return false; const unsigned immediate = load.b & 0xfffff; - // The address shape the lowering of the load (heap_token_buffer_load site) requires, judged on the state at the load: a + // The address shape the lowering of the load (heap_token_buffer_load site) requires, judged on the state at the + // load: a // candidate that does not have it is not eligible, so that it keeps today's path and text. { const auto &before = p.before[l]; @@ -1911,8 +1924,10 @@ static bool heap_token_buffer_eligible(const Program &p, size_t l, std::vector> 25) == 125 && base.type == Symbol::Type::heap_offset) { - // A descriptor address formed by s_add_u32 (heap_offset_add) is another way into the heap, with its own contract. + // A descriptor address formed by s_add_u32 (heap_offset_add) is another way into the heap, with its own + // contract. if (!buffers || !heap_offset_address(p.before[n], i.src[0])) return false; candidates.push_back(n); } else if ((i.b >> 25) != 125 && base.type == Symbol::Type::table && base.value == compute_resource_heap) { @@ -2139,9 +2157,12 @@ static NativeComputeShader translate_program(const ComputeRequest &request, unsi 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. - // A GPU-selected raw buffer (s_load_dwordx4 from the resource heap, with an SGPR offset or through an address formed by - // s_add_u32) takes the same route when no heap view contract covers it: its V# is the byte window of a view token. It is - // judged on an analysis that tracks the byte window rewrite (heap_window); a program with no eligible buffer load is + // A GPU-selected raw buffer (s_load_dwordx4 from the resource heap, with an SGPR offset or through an address + // formed by + // s_add_u32) takes the same route when no heap view contract covers it: its V# is the byte window of a view + // token. It is + // judged on an analysis that tracks the byte window rewrite (heap_window); a program with no eligible buffer load + // is // analysed again exactly as before. std::vector token_consumers; std::vector buffer_consumers; @@ -2162,8 +2183,8 @@ static NativeComputeShader translate_program(const ComputeRequest &request, unsi if (token_candidate || buffer_candidate) { // Judged on the analysis that tracks the byte window when there is a buffer candidate (buffer_candidate implies // that no heap contract is set, so heap_window is false here). - auto tokens = parse(request.code, entry, initial, direct_dxil, false, wave64, false, heap_window || buffer_candidate, - narrow_wave64, true); + auto tokens = parse(request.code, entry, initial, direct_dxil, false, wave64, false, + heap_window || buffer_candidate, narrow_wave64, true); const bool routed = heap_token_eligible(tokens, buffer_candidate, token_consumers, buffer_consumers); if (routed && !buffer_consumers.empty()) { // At least one eligible buffer load: translate on the window analysis. @@ -2177,10 +2198,11 @@ static NativeComputeShader translate_program(const ComputeRequest &request, unsi heap_tokens = true; } } else if (token_candidate) { - // No buffer load is eligible (dropped candidates keep today's path): judge the textures again on the analysis + // No buffer load is eligible (dropped candidates keep today's path): judge the textures again on the + // analysis // without the byte window, exactly as before this route knew buffers. - auto textures = parse(request.code, entry, initial, direct_dxil, false, wave64, false, heap_window, narrow_wave64, - true); + auto textures = parse(request.code, entry, initial, direct_dxil, false, wave64, false, heap_window, + narrow_wave64, true); std::vector none; if (heap_token_eligible(textures, false, token_consumers, none)) { program = std::move(textures); @@ -2246,11 +2268,12 @@ static NativeComputeShader translate_program(const ComputeRequest &request, unsi NativeComputeShader translated; try { translated = compiler.lower(entry,user,rsrc2,x,y,z); - } catch (const UnsupportedComputeShader &error) { - // The token words of a buffer load do not fit the 32-word entry layout next to the descriptor strides and root + } catch (const HeapTokenWordBudget &) { + // The token words of a buffer load do not fit the 32-word entry layout next to the descriptor strides and + // root // constants (the strides are known only while lowering): drop the buffer route and translate again, so the // buffer loads keep today's path and text. - if (!buffer_consumers.empty() && std::string_view(error.what()).find("heap token words exceed") != std::string_view::npos) + if (!buffer_consumers.empty()) return translate_program(request, entry, direct_dxil, stage, heap_view, false); throw; } diff --git a/src/gfx1013_compute_native.h b/src/gfx1013_compute_native.h index c86f6ec4bc..5920e7471d 100644 --- a/src/gfx1013_compute_native.h +++ b/src/gfx1013_compute_native.h @@ -51,7 +51,8 @@ enum class ComputeViewKind { // A raw buffer bound as a root UAV. The guest address is the root pointer plus a VGPR offset. 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, 0x20 a raw buffer view, else 1 + image + // memory (32-byte tokens); heap_token_dims_srv: one uint per view id (0 none, 0x20 a raw buffer view, else 1 + + // image // dimension; the runtime that fills the table names the raw buffer views); the miss UAV // is one raw dword counting the waves that read the null slot. heap_token_srv, diff --git a/src/gfx1013_direct_compute.inl b/src/gfx1013_direct_compute.inl index cbbd31ef95..154f0b124e 100644 --- a/src/gfx1013_direct_compute.inl +++ b/src/gfx1013_direct_compute.inl @@ -411,7 +411,8 @@ struct DirectCompute { // picks the path: typed_buffer_srv is typed, every other kind is raw. string heap_resource(const Inst &i, const State &s, unsigned base, ComputeViewKind kind, unsigned bytes) { const auto &symbol = s.at(base); - // A raw buffer that passed the pre-pass of the token route: the contract gate does not apply, the token is checked + // A raw buffer that passed the pre-pass of the token route: the contract gate does not apply, the token is + // checked // on every execution instead (heap_token_buffer). if (!pixel_stage && symbol.type == Symbol::Type::indexed_descriptor && symbol.value == compute_resource_heap && heap_token_buffer_load(symbol.definition)) @@ -767,7 +768,8 @@ struct DirectCompute { return; } if (!pixel_stage && i.op == 2 && heap_token_buffer_load(i.pc)) { - // The V# of a GPU-selected raw buffer: the view token at the guest byte address, kept in all four words (see + // The V# of a GPU-selected raw buffer: the view token at the guest byte address, kept in all four + // words (see // heap_token_buffer). A token is 32 bytes of title heap memory, so the address is a multiple of 32. The // address is the byte offset from heap slot 0, not the slot index. const Word offset = i.b & 0xfffff; @@ -788,9 +790,11 @@ struct DirectCompute { address = ir.binary("add", operand32(i, so), to_string(offset)); } else { // The address formed by s_add_u32. Assumption, no runtime carry check: the model of heap_offset and - // heap_carry is relative to the heap base (slot 0), so the high word is the carry of the byte offset + // heap_carry is relative to the heap base (slot 0), so the high word is the carry of the byte + // offset // alone, which is 0 for offsets below 2^32; the emitter writes it as 0 (see arithmetic()) and the - // existing lshr-5 path of the heap_offset address relies on the same model. The low word is the byte + // existing lshr-5 path of the heap_offset address relies on the same model. The low word is the + // byte // offset. The pre-pass (heap_token_buffer_eligible) already judged these shapes; these refusals are // the safeguard. if (!heap_offset_address(s, i.src[0])) @@ -1124,7 +1128,8 @@ struct DirectCompute { return ir.heap_handle(slot, dx_kind[dim], 1033, false, false); } // The heap slot a view token names. The token is read at the byte address held by SGPR `base` (every lane loads the - // same words, so the slot is dynamically uniform): the slot is first + id when the magic and the id range hold and the + // same words, so the slot is dynamically uniform): the slot is first + id when the magic and the id range hold + // and the // dimension table records `recorded` for the id (texture: 1 + the SQ dimension code; raw buffer: 0x20), and `null` // otherwise, in which case the first lane of the wave counts one miss. string heap_token_slot(unsigned base, unsigned recorded_code, const string &first, const string &null) { @@ -1162,11 +1167,15 @@ struct DirectCompute { ir.body << " br label %tokenMissEnd" << tag << "\ntokenMissEnd" << tag << ":\n"; return slot; } - // Words 2 (num_records) and 3 of the title's own V# are not read: the view the token names gives the range, and the shader - // reads that raw view as the byte window (assumption A1). The runtime change (PR 2) must make the raw view's byte range equal + // Words 2 (num_records) and 3 of the title's own V# are not read: the view the token names gives the range, and + // the shader + // reads that raw view as the byte window (assumption A1). The runtime change (PR 2) must make the raw view's byte + // range equal // the range the title's V# describes; nothing here checks it. - // A GPU-selected raw buffer read through its view token: ResourceDescriptorHeap[baseraw + id] when the token names a - // raw buffer view (dimension table entry 0x20), else the null raw view (reads zero) and a miss. `symbol` is a word of + // A GPU-selected raw buffer read through its view token: ResourceDescriptorHeap[baseraw + id] when the token + // names a + // raw buffer view (dimension table entry 0x20), else the null raw view (reads zero) and a miss. `symbol` is a + // word of // the heap load (the s_load_dwordx4 left the token's byte address in all four words; the byte-window rewrite only // changes what the analysis knows about words 1 to 3). string heap_token_buffer(const Inst &i, const State &s, unsigned base, ComputeViewKind kind) { @@ -1183,7 +1192,8 @@ struct DirectCompute { refuse(i.pc, "heap token raw buffer descriptor is not a four-word heap load"); if (symbol.offset % 32 || symbol.type != Symbol::Type::indexed_descriptor) refuse(i.pc, "unaligned heap descriptor"); - // The same precaution as for a heap descriptor without tokens: the words are compared by the pc of their heap load, + // The same precaution as for a heap descriptor without tokens: the words are compared by the pc of their heap + // load, // which a loop around that load executes again for another selection. if (window) for (const auto &inst : analysis.program.code) @@ -1209,8 +1219,12 @@ struct DirectCompute { auto &r = analysis.result; unsigned words = token_word_count() + 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"); + if (words > 32) { + std::ostringstream text; + text << "native compute +0x" << std::hex << analysis.program.code.front().pc + << ": heap token words exceed the 32-word compute entry layout"; + throw HeapTokenWordBudget(text.str()); + } r.heap_token_word_count = token_word_count(); token_srv = analysis.srv++; token_dims_srv = analysis.srv++; diff --git a/src/native_compute_pipeline.h b/src/native_compute_pipeline.h index 1041af8c1e..a0cdbd8e49 100644 --- a/src/native_compute_pipeline.h +++ b/src/native_compute_pipeline.h @@ -17,7 +17,8 @@ struct NativeComputePipeline { unsigned srv_count = 0; unsigned uav_count = 0; unsigned constant_words = 0, atomic_views = 0; - unsigned token_words = 0; // heap token words after the stride words: base1d, base2d, base2da, count, null (5), plus baseraw, nullraw (7) + // heap token words after the stride words: base1d, base2d, base2da, count, null (5), plus baseraw, nullraw (7) + unsigned token_words = 0; 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 5f17e02623..b23fd8c252 100644 --- a/src/startup_stubs/d3d12_compute_dispatch.inl +++ b/src/startup_stubs/d3d12_compute_dispatch.inl @@ -348,7 +348,8 @@ 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 and raw buffers (view tokens): published by the translator, not bound by this runtime + // GPU-selected heap textures and raw buffers (view tokens): published by the translator, not bound by this + // runtime // yet. The reader knows the seven word names (baseraw and nullraw belong to raw buffers); every such line is // refused here until a runtime fills the views and words. const auto token_word = [&] { diff --git a/tests/native_heap_token_texture.cpp b/tests/native_heap_token_texture.cpp index 807415b629..bfca80bbe6 100644 --- a/tests/native_heap_token_texture.cpp +++ b/tests/native_heap_token_texture.cpp @@ -19,7 +19,8 @@ // 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). // The raw modes bind baseraw and nullraw too. The host heap has raw views at baseraw + id: id 1 over a buffer of 64 -// dwords (value 0xA0000000 + index), id 2 over 128 dwords (0xB0000000 + index); id 0 and id 3 are null raw views, and the +// dwords (value 0xA0000000 + index), id 2 over 128 dwords (0xB0000000 + index); id 0 and id 3 are null raw views, and +// the // dimension table names id 3 a 2D texture. Case 8 is a valid token for id 2. Lanes 16 to 31 read past the 64 dwords of // id 1 and get 0. Every other case gives zeros and one miss per wave. // Exit 0: every assertion held. 1: a result differs. 4: setup error. 77: capability skip. diff --git a/tests/native_heap_token_texture_check.py b/tests/native_heap_token_texture_check.py index 1eed573ff1..911861d7c0 100644 --- a/tests/native_heap_token_texture_check.py +++ b/tests/native_heap_token_texture_check.py @@ -437,7 +437,7 @@ def request(name, words, root_text=ROOT): counter += 1 folder = base / f"req_{counter}_{name}" folder.mkdir() - user = 6 if "RootFlags" in root_text else 5 # four reserved SGPRs, the table, and the resource heap + user = 6 if root_text in (ROOT, ROOT_STRIDES) 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) From a1c1487aee8fe9f7b58b405d825b6bb55677dd27 Mon Sep 17 00:00:00 2001 From: JB2WIN Date: Mon, 30 Nov 2026 13:53:26 +0100 Subject: [PATCH 6/8] native: rejoin a wrapped comment on the heap token budget retry Co-Authored-By: Claude Opus 5.5 --- src/gfx1013_compute_native.cpp | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/src/gfx1013_compute_native.cpp b/src/gfx1013_compute_native.cpp index 2d5d159799..e6e69a81e3 100644 --- a/src/gfx1013_compute_native.cpp +++ b/src/gfx1013_compute_native.cpp @@ -2270,9 +2270,8 @@ static NativeComputeShader translate_program(const ComputeRequest &request, unsi translated = compiler.lower(entry,user,rsrc2,x,y,z); } catch (const HeapTokenWordBudget &) { // The token words of a buffer load do not fit the 32-word entry layout next to the descriptor strides and - // root - // constants (the strides are known only while lowering): drop the buffer route and translate again, so the - // buffer loads keep today's path and text. + // root constants (the strides are known only while lowering): drop the buffer route and translate again, + // so the buffer loads keep today's path and text. if (!buffer_consumers.empty()) return translate_program(request, entry, direct_dxil, stage, heap_view, false); throw; From 9917aa9cf1f671711f3a484e3fa35a91b3c0f9e0 Mon Sep 17 00:00:00 2001 From: JB2WIN Date: Mon, 30 Nov 2026 14:07:33 +0100 Subject: [PATCH 7/8] 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) From f4cc6a0ea6ad0678b5afaabfd38bca1405f2f0a0 Mon Sep 17 00:00:00 2001 From: JB2WIN Date: Mon, 30 Nov 2026 19:17:14 +0100 Subject: [PATCH 8/8] docs: keep the revision 2 note next to revision 3 for heap token loads Co-Authored-By: Claude Opus 5.5 --- docs/experiments/native-heap-token-textures.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/experiments/native-heap-token-textures.md b/docs/experiments/native-heap-token-textures.md index df3e9c526b..a8048727b5 100644 --- a/docs/experiments/native-heap-token-textures.md +++ b/docs/experiments/native-heap-token-textures.md @@ -99,7 +99,7 @@ path and refusal text. Like the texture route, this translates only where no hea ## Revision -`native_compute_output_revision` is 3. `X2W_NATIVE_SHADER_REVISION` hashes the translator sources but not +`native_compute_output_revision` is 3. Revision 2 (#3544) published texture token loads that were refused before; every revision-1 manifest then reads as another compiler revision and is rebuilt once, also those without a token load. Revision 3 does the same for raw buffer token loads. `X2W_NATIVE_SHADER_REVISION` hashes the translator sources but not `native_compute_pipeline.cpp` or `native_compute_output.h`, and the manifest of a program with a token buffer has a new shape, so the marker is bumped by hand. A request the previous translator refused published nothing, so it is translated again by the next run (checked: the previous `compile_dxil` refuses the fixture request and leaves its cache empty, the