Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
122 changes: 122 additions & 0 deletions docs/experiments/native-sampler-heap.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,122 @@
# Sampler descriptors read from the directly indexed sampler heap at a fixed index (translator, stage 1)

Issue #3076, part of #2935 (related #1143). The native compute translator now accepts a sampler that the program loads from
the sampler heap with `s_load_dwordx4` / `s_load_dwordx8` at a constant 16-byte aligned offset and uses with
`image_sample_l` or `image_sample_lz`. It lowers the sampler to `SamplerDescriptorHeap[index]` in the DXIL module. This is
stage 1: the translator, the binding record, the cache, the root signature and `bind()`. Binding a real, mirrored sampler heap
at dispatch time in the runtime is stage 2 and is not part of this change.

## Why

A local start-up capture (counts only; `compile_dxil` at the base commit, 2,689 slot 67 compute requests): 400 compile,
1,830 contain `image_sample*` or `image_gather*`, and in 993 of those at least one sampler is loaded from memory. The
pattern has root flags `0xc00`; the entry SGPR after the resource heap holds the sampler heap base; the program copies it
into an even SGPR pair, sets the high word to 0 and loads one sampler with `s_load_dwordx4` (or two with `s_load_dwordx8`) at
a 16-byte aligned immediate offset; `image_sample_lz` or `image_sample_l` then uses it (95,839 and 20,556 of 127,822
sample and gather instructions). Before this change the native translator left that SGPR `unbound`, so the load was refused
("direct descriptor address outside bound table") and `sampler_index` refused non-literal words ("nonconstant sampler").
There is no compiled-count gain on its own: with the mixed-contract chain of #3023 applied locally (uncommitted probe), 130
requests stop first at such a load (117 `dwordx4`, 13 `dwordx8`). The change removes the next blocker of that chain.

## What changed

- `compute_sampler_heap` (`~0u - 1`) is a second sentinel next to `compute_resource_heap`. Under the existing condition
(root flags `0xc00`, exactly two user SGPRs left after the root parameters) the SGPR after the resource heap is now the table
`{table, compute_sampler_heap}` instead of `unbound`. Entry `n` of the sampler heap is title byte offset `16 * n`.
- Direct path, load from the sampler heap (`gfx1013_direct_compute.inl`), refused in this order: a scalar buffer load ("scalar
buffer load from the sampler heap is not translated"); an SGPR offset ("sampler heap load with an SGPR offset (a
GPU-selected sampler) is not translated"); any width but `dwordx4` / `dwordx8` ("sampler heap load must read one or two
samplers"); an immediate offset that is not a multiple of 16 ("sampler heap offset is not a multiple of 16"); an entry
index above 2046 ("sampler heap index beyond 2046 (2047 is the runtime fallback entry)"). The existing rule that the table
address has a constant zero high word then applies.
- HLSL path: a load through that base is refused ("sampler heap reads need the direct DXIL path").
- `Emit::binding`: a descriptor from the sampler heap used as an image or buffer is refused ("a sampler heap descriptor is
read as a resource").
- `sampler_index` returns `SamplerRef {heap, index}`. Four words that are all literals take the static-sampler path as before;
four contiguous words of one sampler-heap entry make a heap sampler; anything else is "nonconstant sampler". For a heap
sampler, in this order: gathers ("gather through the sampler heap is not translated"), comparison samplers ("comparison
sampler from the sampler heap is not translated"), gradient samplers ("sampler from the sampler heap needs image_sample_l or
image_sample_lz"). Static and heap samplers may appear in one program (the mixed fixture).
- DXIL: `DxilModule::sampler_heap_handle` emits `createHandleFromHeap(i32 218, i32 <index>, i1 true, i1 false)` and
`annotateHandle` with resource properties `{14, 0}`; the emitter sets module flag `0x80000000` (sampler heap indexing), as DXC
does for `SamplerDescriptorHeap[i]` (DXC reference: flags `0x80000010` with raw buffers).
- Binding record: `ComputeViewKind::heap_sampler`, one per program, `{heap_sampler, compute_sampler_heap, byte_offset 0,
register 0, required_bytes 16 * (highest index + 1)}`. The frontend cache accepts the kind with exactly that root value; an
older decoder rejects it and recomputes. `format_compute_runtime_manifest` returns no manifest for it (root parameter above
15), so `compile_dxil --requests` publishes `<key>.cs.cso` without `<key>.txt`; the in-process dispatch route refuses the
kind. `compile_dxil` reports `sampler_heap span=<bytes>`.
- `create_native_compute_pipeline`: `sampler_heap_indexed` adds root flag `0x800` (`SAMPLER_HEAP_DIRECTLY_INDEXED`) and does not
set `heap_indexed` or `0x400`. `NativeComputePipeline::bind` has a last parameter `ID3D12DescriptorHeap *sampler_heap`: with
`sampler_heap_indexed` a null heap throws ("a sampler heap is needed"); with views too, the heaps are set as views first, then
samplers; without it nothing changes. A root without `0x800` and a shader that reads `SamplerDescriptorHeap` fails
`CreateComputePipelineState` with `E_INVALIDARG` (debug layer: "Shader uses sampler descriptor heap indexing, but root
signature is missing the D3D12_ROOT_SIGNATURE_FLAG_SAMPLER_HEAP_DIRECTLY_INDEXED flag"), measured on the RTX 3080 with a
throw-away probe; a root with static samplers and `0x800` with a shader that reads one static and one heap sampler creates
without a debug-layer message.

## Assumptions for stage 2

The runtime must fill the sampler heap bound for a natively translated compute dispatch so that entry `n` is title byte offset
`16 * n` (index parity), with `dynamic_sampler()` decoding (`src/startup_stubs/translated_sampler_bindings.h`: MIN_LOD and MAX_LOD
applied, which is why only the explicit-LOD forms are translated), and entry 2047 (`translated_sampler_fallback`) holding the
fallback sampler. The translator refuses index 2047, so the fallback is never read. None of this is implemented here; the fixture
builds its heap with `dynamic_sampler()` and the index parity itself.

## Fixture

`tests/native_sampler_heap.cpp`, `tests/native_sampler_heap_check.py`, `tests/cmake/native_sampler_heap.cmake`; tests
`native_sampler_heap_hardware` and `native_sampler_heap_warp` (`SKIP_RETURN_CODE 77`: WARP has no 32-lane waves).

The script writes source-built compute requests (`.c67`, as `tests/native_compute_raw_root_check.py`) with the root
`RootFlags(CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED | SAMPLER_HEAP_DIRECTLY_INDEXED), DescriptorTable(SRV(t0), UAV(u0))`, group 32x1x1 and
seven user SGPRs (s4 table, s5 resource heap, s6 sampler heap). The instruction words were assembled once with LLVM 15
(`clang -cc1as -triple amdgcn-amd-amdhsa -target-cpu gfx1013 -filetype asm -show-encoding`) and are embedded with one source
comment per instruction; the test needs no LLVM. One SRV+UAV table is accepted by the direct path (no split into two tables was
needed). The programs copy s6 into an even SGPR pair with a constant-zero high word and sample a 4x4 two-mip texture at (1.375,
-0.375), outside [0, 1]:

| Program | Shape | Expected |
|---|---|---|
| SAMPLE | `s_load_dwordx4` at 0x430 (entry 67), `image_sample_lz` | wrap texel (1, 2) of mip 0 |
| TWO | `s_load_dwordx8` at 0x430, two samples | entry 67 wrap, entry 68 clamp (a swapped second group fails) |
| LOD | `image_sample_l`, LOD 1 | MaxLOD 1 picks mip 1; decoys with MaxLOD 0 (bilinear and point) pick mip 0 |
| MIXED | one literal static sampler and entry 67 | static clamp texel and heap wrap texel; one static sampler in the program |

The fixture dispatches on the RTX 3080 with a 128-entry sampler heap made with `dynamic_sampler()`. Every entry but the entries
under test is a decoy (clamp, mirror, border, a bilinear border with a white colour). It compares every lane with a CPU model,
then dispatches once per decoy with the decoy in place of the entry under test and requires the result to change. It also calls
`prepare_direct_compute` twice on the same fresh cache directory (a miss, then a hit) and requires exactly one binding
`{heap_sampler, compute_sampler_heap, 0, 0, 16 * (highest index + 1)}` in the computed and in the cached program, and that
`bind()` without a sampler heap throws.

The script also compiles the refusal shapes and requires each exact text and no `.cso`: offset 0x438, entry 2047, `dwordx8`
at entries 2046 and 2047, `dwordx2` and `dwordx16`, an SGPR offset, a scalar buffer load, a sampler heap entry used as an image
descriptor, mixed literal and heap words in one sampler, a join that replaces the copied base on one path, `image_gather4_lz`,
`image_gather4_c_lz`, `image_sample_c_lz` and `image_sample_d` with a heap sampler, the HLSL profile, and a root with only
`0x400` (today's refusal, unchanged). Each has a control that compiles (entry 2046, `dwordx8` at 2045 and 2046, the branch
without the overwrite, the four operations with a literal sampler).

## Result

Environment: NVIDIA GeForce RTX 3080, Windows SDK 10.0.26100.0 DXC, D3D12 debug layer not enabled in the fixture.

```
ctest --preset dev --no-tests=error -R "^native_sampler_heap_(hardware|warp)$" -V
```

`native_sampler_heap_hardware` passes with 69 `ok:` assertions in the check script (the fixture's own per-mode checks print
`pass:` lines and are counted inside them);
`native_sampler_heap_warp` skips (77: no 32-lane waves). The regression set
`ctest --preset dev --no-tests=error -R "native_|startup_compute_dispatch|compute_heap" -j 6` passes (163 tests, 0 failed, 5
skips: the four WARP tests that already skipped and the new one).

## Limits

- Stage 1 only: no runtime binding of a mirrored sampler heap for natively translated compute dispatch.
- GPU-selected sampler indices (SGPR offset), comparison, gather and gradient sampling through the heap, and containers are
refused. Roots with only the `0x800` flag (10 requests in the capture) are not covered.
- The fixture samples with point filters and compares exact texels; decoys are checked to change the result (and to run:
not the output sentinel), bilinear decoys only that.
- Not exercised by a test: the highest accepted entry 2046 in a sample (the edge controls only load it), and `bind()`'s
"a view heap is needed" throw (no test program reads the sampler heap without a view table).
- A passing fixture supports the behaviour under test; it does not establish that any title shader runs.
6 changes: 4 additions & 2 deletions src/direct_compute_cache.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -127,11 +127,13 @@ 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<ComputeViewKind>(in.count(static_cast<unsigned>(ComputeViewKind::heap_buffer_srv)));
auto kind = static_cast<ComputeViewKind>(in.count(static_cast<unsigned>(ComputeViewKind::heap_sampler)));
ComputeViewBinding b{kind, in.word(), in.word(), in.word(), in.word(), in.word(), in.word(), in.count(7)};
b.scalar_table = static_cast<ComputeViewBinding::ScalarTable>(in.count(unsigned(ComputeViewBinding::ScalarTable::srv)));
const bool sampler_heap = kind == ComputeViewKind::heap_sampler;
if (!b.array_count || b.array_position >= b.array_count ||
(b.root_parameter >= 16 && b.root_parameter != compute_resource_heap))
(sampler_heap ? b.root_parameter != compute_sampler_heap
: b.root_parameter >= 16 && b.root_parameter != compute_resource_heap))
throw std::runtime_error("invalid cached binding");
shader.bindings.push_back(b);
}
Expand Down
11 changes: 11 additions & 0 deletions src/dxil_module.h
Original file line number Diff line number Diff line change
Expand Up @@ -154,6 +154,17 @@ class DxilModule {
<< "b, %dx.types.ResourceProperties { i32 " << (kind + (uav ? 4096 : 0)) << ", i32 " << props << " })\n";
return h;
}
// A sampler taken from the directly indexed sampler heap at a constant index (SM 6.6 SamplerDescriptorHeap[index]).
// The handle is annotated as a sampler (resource kind 14). The caller sets the module flag 0x80000000.
Text sampler_heap_handle(const Text &index) {
heap_used = true;
const Text h = "%heap" + std::to_string(sequence++);
body << " " << h << "b = call %dx.types.Handle @dx.op.createHandleFromHeap(i32 218, i32 " << index
<< ", i1 true, i1 false)\n"
<< " " << h << " = call %dx.types.Handle @dx.op.annotateHandle(i32 216, %dx.types.Handle " << h
<< "b, %dx.types.ResourceProperties { i32 14, i32 0 })\n";
return h;
}
Text finish_compute(unsigned x, unsigned y, unsigned z, const Text &stage = "cs") {
std::ostringstream out;
out << "target datalayout = "
Expand Down
54 changes: 46 additions & 8 deletions src/gfx1013_compute_native.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -764,6 +764,8 @@ struct Emit {
const bool indexed = sym.type == Symbol::Type::indexed_descriptor;
if ((!indexed && sym.type != Symbol::Type::descriptor) || base + width > state.size())
refuse(i.pc, "unproven resource descriptor s" + to_string(base));
if (sym.value == compute_sampler_heap)
refuse(i.pc, "a sampler heap descriptor is read as a resource");
const bool byte_window = kind == ComputeViewKind::byte_window_srv ||
(kind == ComputeViewKind::raw_buffer_uav && width == 4 && i.name == "buffer_store_raw" &&
state[base + 1].type == Symbol::Type::zero_stride_word);
Expand Down Expand Up @@ -844,15 +846,44 @@ struct Emit {
it->required_bytes = (std::max)(it->required_bytes, bytes);
return (write ? "w" : "r") + to_string(it->shader_register);
}
unsigned sampler_index(const Inst &i, const State &state, bool lod, bool gather_base_level = false,
bool implicit_sample = false, bool comparison = false) {
// heap: the sampler is entry `index` of the directly indexed sampler heap. Otherwise `index` is the static sampler register.
struct SamplerRef {
bool heap;
unsigned index;
};
SamplerRef sampler_index(const Inst &i, const State &state, bool lod, bool gather_base_level = false,
bool implicit_sample = false, bool comparison = false) {
const unsigned base = ((i.b >> 21) & 31) * 4;
ComputeSampler sampler{{}, lod, comparison};
unsigned literal = 0, heap = 0;
const auto &first = state.at(base);
for (unsigned j = 0; j < 4; ++j) {
const auto &s = state.at(base + j);
if (s.type != Symbol::Type::constant)
refuse(i.pc, "nonconstant sampler");
sampler.words[j] = s.value;
literal += s.type == Symbol::Type::constant;
// The heap content is fixed within a dispatch, so contiguity of the four words of one 16-byte entry is enough.
heap += s.type == Symbol::Type::descriptor && s.value == compute_sampler_heap && !s.definition &&
first.offset % 16 == 0 && s.offset == first.offset + 4 * j;
if (s.type == Symbol::Type::constant)
sampler.words[j] = s.value;
}
if (literal != 4 && heap != 4)
refuse(i.pc, "nonconstant sampler");
if (heap == 4) {
if (gather_base_level)
refuse(i.pc, "gather through the sampler heap is not translated");
if (comparison)
refuse(i.pc, "comparison sampler from the sampler heap is not translated");
if (implicit_sample)
refuse(i.pc, "sampler from the sampler heap needs image_sample_l or image_sample_lz");
const unsigned entry = first.offset / 16, bytes = 16 * (entry + 1);
auto &list = result.bindings;
auto found = std::find_if(list.begin(), list.end(),
[](const auto &b) { return b.kind == ComputeViewKind::heap_sampler; });
if (found == list.end())
list.push_back({ComputeViewKind::heap_sampler, compute_sampler_heap, 0, 0, bytes});
else
found->required_bytes = (std::max)(found->required_bytes, bytes);
return {true, entry};
}
if (comparison) {
// Field constraints from pixel_aot.comparison_sampler_state. The
Expand Down Expand Up @@ -891,7 +922,7 @@ struct Emit {
all.push_back(sampler);
it = std::prev(all.end());
}
return first_sampler+static_cast<unsigned>(it - all.begin());
return {false, first_sampler + static_cast<unsigned>(it - all.begin())};
}
void image(const Inst &i, const State &state) {
unsigned mask = (i.a >> 8) & 15, base = ((i.b >> 16) & 31) * 4, addr = i.b & 255;
Expand Down Expand Up @@ -927,7 +958,10 @@ struct Emit {
if (lod || gather) {
if (gather && mask != 1)
refuse(i.pc, "unsupported gather channel");
body << "t=" << tex << (lod ? ".SampleLevel(" : ".GatherRed(") << "q" << sampler_index(i, state, lod)
const auto sampler = sampler_index(i, state, lod);
if (sampler.heap)
refuse(i.pc, "sampler heap reads need the direct DXIL path");
body << "t=" << tex << (lod ? ".SampleLevel(" : ".GatherRed(") << "q" << sampler.index
<< ",float2(asfloat(" << x << "),asfloat(" << y << "))" << (lod ? ",0);\n" : ");\n");
} else
body << "t=" << tex << ".Load(int3(" << x << "," << y << ",0));\n";
Expand Down Expand Up @@ -1319,6 +1353,8 @@ struct Emit {
if (i.op < 8) {
if (s.at(i.src[0]).type != Symbol::Type::table)
refuse(i.pc, "unknown scalar table base");
if (s.at(i.src[0]).value == compute_sampler_heap)
refuse(i.pc, "sampler heap reads need the direct DXIL path");
if (s.at(i.src[0]).value == compute_resource_heap && i.b >> 25 == 125)
refuse(i.pc, "unsupported immediate whole-heap descriptor");
if (i.b >> 25 != 125) {
Expand Down Expand Up @@ -1525,8 +1561,10 @@ static NativeComputeShader translate_program(const ComputeRequest &request, unsi
}
// In this compute ABI the two directly indexed heaps follow the user root parameters.
// Require both flags and exactly two remaining user SGPRs, as in the matched native layouts.
if (!stage && (UINT(layout->Desc_1_1.Flags) & 0xc00u) == 0xc00u && next + 2 == user)
if (!stage && (UINT(layout->Desc_1_1.Flags) & 0xc00u) == 0xc00u && next + 2 == user) {
initial[next] = {Symbol::Type::table, compute_resource_heap};
initial[next + 1] = {Symbol::Type::table, compute_sampler_heap};
}
const bool wave64 = stage && !stage->wave32;
// The byte-address rewrite of a GPU-selected heap descriptor is read only under the raw_buffer contract.
const bool heap_window = direct_dxil && heap_view == HeapViewContract::raw_buffer;
Expand Down
8 changes: 7 additions & 1 deletion src/gfx1013_compute_native.h
Original file line number Diff line number Diff line change
Expand Up @@ -35,9 +35,15 @@ enum class ComputeViewKind {
indexed_atomic_uav,
d16_sample_srv,
byte_window_srv,
heap_buffer_srv // A raw buffer read through ResourceDescriptorHeap[slot]; the slot is a GPU value.
heap_buffer_srv, // A raw buffer read through ResourceDescriptorHeap[slot]; the slot is a GPU value.
// The directly indexed sampler heap; entry n = title byte offset 16 * n (index parity); the runtime fills entries with
// dynamic_sampler() (LOD clamp applied, valid for the explicit-LOD forms translated here); entry 2047 is the runtime
// fallback and never read.
heap_sampler
};
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;
// 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; }
inline bool compute_buffer_uav(ComputeViewKind kind) {
Expand Down
Loading
Loading