diff --git a/.github/workflows/windows.yml b/.github/workflows/windows.yml index 0a36fcd1a0..d6d7515949 100644 --- a/.github/workflows/windows.yml +++ b/.github/workflows/windows.yml @@ -102,6 +102,7 @@ jobs: (["tests/startup_compute_image_store_check.py", "--llvm-mc", "llvm-mc-15"], {}), (["tests/startup_compute_image_store_d16_check.py", "--llvm-mc", "llvm-mc-15"], {}), (["tests/startup_compute_readfirstlane_check.py", "--llvm-mc", "llvm-mc-15"], {}), + (["tests/startup_gfx2hlsl_heap_record_check.py", "--llvm-mc", "llvm-mc-15"], {}), (["tests/startup_compute_gather_l_check.py", "--llvm-mc", "llvm-mc-15"], {}), (["tests/startup_compute_buffer_atomics_check.py", "--llvm-mc", "llvm-mc-15"], {}), (["tests/startup_compute_store_d16_x_check.py", "binary", "llvm-mc-15"], {}), @@ -280,6 +281,7 @@ jobs: tests/startup_joined_table_pointer_check.py \ tests/startup_gfx2hlsl_readfirstlane_recompute_check.py \ tests/startup_compute_readfirstlane_check.py \ + tests/startup_gfx2hlsl_heap_record_check.py \ tests/startup_gfx2hlsl_calculated_target_check.py \ tests/startup_triage_run_check.py \ tests/startup_run_ps1_check.py \ diff --git a/AGENTS.md b/AGENTS.md index b7eb67ad76..780aacd075 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -170,6 +170,7 @@ python3 -m venv out/pe-env ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_compute_check.py ./out/pe-env/bin/python -B tests/startup_compute_image_store_check.py ./out/pe-env/bin/python -B tests/startup_compute_image_store_d16_check.py +./out/pe-env/bin/python -B tests/startup_gfx2hlsl_heap_record_check.py ./out/pe-env/bin/python -B tests/startup_compute_store_format_xyzw_check.py ./out/pe-env/bin/python -B tests/startup_compute_translate_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_swap_check.py diff --git a/CMakeLists.txt b/CMakeLists.txt index c8612e7b39..17d4efe020 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -3220,6 +3220,8 @@ if(EXISTS "${INTAKE_PYTHON}") "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_compute_image_store_check.py") add_test(NAME startup_compute_image_store_d16 COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_compute_image_store_d16_check.py") + add_test(NAME startup_gfx2hlsl_heap_record COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_heap_record_check.py") add_test(NAME startup_compute_readfirstlane COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_compute_readfirstlane_check.py") add_test(NAME startup_compute_gather_l COMMAND "${INTAKE_PYTHON}" -B @@ -4130,6 +4132,17 @@ if(EXISTS "${INTAKE_PYTHON}") PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) set_tests_properties(startup_compute_translate_e2e_wrong_group_${adapter} PROPERTIES PASS_REGULAR_EXPRESSION "control wrong-group: rejected at word=[0-9]+ ") + add_test(NAME startup_compute_dispatch_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_compute_dispatch_check.py" "$" + "${DXC_EXECUTABLE}" ${adapter}) + add_test(NAME startup_compute_dispatch_texture_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_compute_dispatch_texture_check.py" "$" + "${DXC_EXECUTABLE}" ${adapter}) + add_test(NAME startup_compute_dispatch_heap_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_compute_dispatch_heap_check.py" "$" + "${DXC_EXECUTABLE}" ${adapter}) + set_tests_properties(startup_compute_dispatch_${adapter} startup_compute_dispatch_texture_${adapter} + startup_compute_dispatch_heap_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) endforeach() add_test(NAME startup_stream_adapter_filter COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_stream_rasterizer_check.py" diff --git a/docs/experiments.md b/docs/experiments.md index 38fa8d0ffc..0401eaf628 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -15984,6 +15984,17 @@ ctest --preset dev --no-tests=error -R "^startup_image_sample_d_draw_(warp|hardw `tests/startup_gfx2hlsl_mul24_align_check.py` translates each instruction, evaluates the emitted text on the CPU against a reference written with unbounded integers, and checks that `v_mul_hi_u32_u24` is refused. Run with `python3 -B tests/startup_gfx2hlsl_mul24_align_check.py` (`ctest --preset dev --no-tests=error -R '^startup_gfx2hlsl_mul24_align$' -V`). `tests/startup_gfx2hlsl_mul24_align_draw_check.py` draws the six translated instructions through FXC `ps_5_1` and DXC `ps_6_0` and compares the GPU readback with the same reference (`startup_gfx2hlsl_mul24_align_warp` and `_hardware`); both compilers run before the test fails, so one compiler's failure does not hide the other's result. The draw covers the six translated instructions only. +## Startup list Dispatch + +Command-list slot 14 (`Dispatch`) is recorded on the desktop list only when the list is open and direct or compute, a desktop compute pipeline and a desktop compute root signature are bound, the compute root declares no static samplers and only root SRV parameters (slot 43), the compute pipeline was built against that same root signature, every root SRV the root declares was set since the root was bound (a rejected or unaligned replacement clears its binding), and every group count is at most 65535. Zero groups on an axis is forwarded and runs nothing. A root with other parameters is refused with `compute root arguments are not forwarded`, a pipeline from another root with `compute pipeline was built against another root signature`, an unset or rejected root SRV with `a compute root SRV is not bound`, because this path forwards none of the compute root-argument slots (35, 37, 39, 41, 45) to the desktop list and the dispatch would run with them unset. Other refusals are logged as `x2w-render Dispatch(x, y, z) refused: `. + +Only the decision is checked: `tests/startup_list_dispatch_check.cpp` runs without a device and its five mutated runs must fail. Executing a dispatch on a GPU, with real results read back, is not verified yet. + +```powershell +cmake --build --preset dev --target startup_list_dispatch_check +ctest --preset dev --no-tests=error -R "^startup_list_dispatch" -V +``` + ## Non-constant scalar symbols at branch targets in the startup translator Follow-up to #2279, which drops scalar constants at a join that another path writes, over the textual range between @@ -16006,6 +16017,37 @@ is 0, so bit 0 of the result is 0 (1 for `s_orn2_b64`) whatever S holds. This re a lane whose exec bit is 0 takes the branch; it is pure Python only, not run on a GPU, and its words are built from the field layouts rather than assembled. +## Translated compute Dispatch + +With a device slot 67 placeholder bound, command-list slot 14 looks up the translation of the pipeline's published request (`.txt` with `stage cs`, and `.cs.cso`) and records it on the desktop list. It binds, from the compute descriptor tables of slot 35: raw buffers named by 16-byte hardware buffer descriptors, and 2D textures named by the token of a view the caller created (device slot 18 for an input, slot 19 for an output the program stores `float4` to). `smp` manifest lines become static samplers, and entry values come from the compute root constants of slots 37 and 39. A buffer input must resolve to a complete GPU-backed range; a buffer output must be a placed buffer that aliases the caller's memory and allows unordered access; a texture view must be 2D, created on the desktop, and for an output have a float or normalized format that is not packed, on a texture that is not also an input of the call. Any other manifest line (other texture kinds, sampler heaps, comparison samplers, root views, `stride` and `descword3` entry values) leaves the pipeline untranslated, and a Dispatch that cannot be bound completely is refused with one logged reason: no Dispatch is recorded and nothing is bound (the upload of an input texture the caller filled in memory may already be recorded; it only syncs content). No view is ever bound null. The entry values live in the compute root-constant store of #1975: a word no slot 37 or 39 call wrote since the compute root was set (slot 33 with another root, or a list reset) has no value and is refused with `an entry value was not set since the compute root`; setting the same root again keeps the words, and the graphics words of slot 40 are separate. + +`tests/startup_compute_dispatch_check.py` drives a source-built gfx1013 program through the stand-in's list on WARP and on a physical adapter (exit 77 without one) and reads the 320 output words back from the aliased memory. Controls in the same run: before the offline translation, without a Dispatch, and with the two descriptors exchanged, every output word must keep its sentinel. The two entry values arrive through slot 37 and slot 39, with other values written through slot 40 in between; `dispatch-same-root` must still give the expected words, and five refused modes must log their reason and keep the sentinels: a missing word, another compute root set and the first set again, a list reset, a compute root that is not the pipeline's, and one buffer named as input and output. `tests/startup_compute_dispatch_texture_check.py` does the same for a program that stores to a 32x8 RGBA16_FLOAT texture (1024 halves read back through CopyTextureRegion; controls: before translation, without a Dispatch, a texture without unordered access) and for the raw buffer program with a level-zero sample of a 1x1 texture XORed into each stored word (control: no view at the table entry). The texture output program is also bound under a manifest edited to declare no entry values. + +The log line `x2w-render compute dispatches: translated , refused , no translation , not modelled ` follows the render totals; "not modelled" counts calls whose manifest exists but holds a line the runtime does not bind. It is followed by a census: the refused calls per first refusal reason of their key, and every dispatched key by call count, each with its count, the calls recorded and the first refused table descriptor. + +Measured on three fixture programs. The sampling fixture uses a 1x1 texture, so it does not tell sampler filter or address modes apart. Programs with other texture kinds, sampler heaps, the same texture as input and output, or buffer outputs in memory that is not aliased are not dispatched. + +```powershell +cmake --build --preset dev --target startup_stream_consumer +ctest --preset dev --no-tests=error -R "^startup_compute_dispatch_" -V +``` + +### An input named by a resource heap record + +A compute root signature that indexes the resource heap directly (root flag 0x400) passes the heap pointer in one SGPR after the root parameters. `gfx2hlsl.py` lowers one form of a load through that pointer: `s_lshl_b32 R, , 5`, then, with no write of `R` and no branch target in between, `s_load_dwordx4 D, s[H:H+1], R` with a constant zero in `s[H+1]` and no `offset:` modifier. `D` is then a buffer descriptor, and the manifest names it `srv buf heap rootconst `. Slot 32 now records the title memory of the list's view heap on every call; at Dispatch the stand-in reads the 16-byte descriptor at byte `word << 5` (32-bit arithmetic, as the program computes it) of that memory and binds the buffer through the path a `table` record takes. A record outside the heap refuses the dispatch (`a heap record is outside the list's view heap`) and binds nothing. + +Every other form keeps a refusal that names it: another shift or index, an index register written again, a branch target between the shift and the load, a high word that is not a constant zero, an `offset:` modifier, eight dwords (an image record), and an index read from a buffer (`s_load of a resource heap record whose index is read from a buffer`). A formatted load or a store through such a record, and the graphics stages, are refused as before. + +`tests/startup_gfx2hlsl_heap_record_check.py` compares the manifest and the HLSL of a source-built gfx1013 program whole, runs 19 refused controls and one translator mutation (without the write tracking, a refused control translates), and with `--llvm-mc` reassembles every instruction. `tests/startup_compute_dispatch_heap_check.py` dispatches that program through the stand-in's list on WARP and on a physical adapter (exit 77 without one): the input descriptor is only in heap record 2, records 0 and 1 hold the output's descriptor, and all 320 output words must match; before translation and for a record outside the heap every word keeps its sentinel. Changing the runtime's shift to 4, or ignoring the index, makes the dispatch test fail (`an output buffer is also an input`). + +Measured on one synthetic program. The offset is a literal byte offset into the title's heap memory, as a table offset is; a heap whose descriptor increment on the desktop adapter is not 32 bytes (WARP is such an adapter, so its run covers the literal offset only) is not checked against a caller that addresses records by that increment. In a local set of 184 compute programs with a register-offset load through the heap pointer, every such load lowers in 4 programs and none of the 184 translates yet: 151 hold a load whose index is read from a buffer, and the 4 stop at other instructions. + +```powershell +python -B tests/startup_gfx2hlsl_heap_record_check.py --llvm-mc llvm-mc-15 +cmake --build --preset dev --target startup_stream_consumer +ctest --preset dev --no-tests=error -R "^startup_compute_dispatch_heap_" -V +``` + ## Startup compute dual-offset/stride-64 LDS ops and 32-bit LDS atomics [`tools/startup/gfx2hlsl.py`](../tools/startup/gfx2hlsl.py) (`lds_dual`, `lds_atomic`, `_lds_general_barrier_ok`, refs `#1541`, `#2274`) lowers the remaining 32-bit RDNA 2 DS dual-offset/stride-64 and unsigned/bitwise atomic instructions onto `groupshared uint lds[N]` (`COMPUTE_PGM_RSRC2.GRANULATED_LDS_SIZE`, nonzero and `<= 32 KiB` / 8192 dwords): diff --git a/src/startup_stubs/d3d12_compute_dispatch.inl b/src/startup_stubs/d3d12_compute_dispatch.inl new file mode 100644 index 0000000000..dffee39960 --- /dev/null +++ b/src/startup_stubs/d3d12_compute_dispatch.inl @@ -0,0 +1,399 @@ +// Translated compute programs at Dispatch (list slot 14). A device slot 67 pipeline is a placeholder that keeps +// the key of its published request; gfx2hlsl.py --pending answers the request with .txt (`stage cs`) and +// .cs.cso. Bound from the compute tables recorded by slot 35: raw buffers (`srv buf table ` +// inputs, `uav table ` outputs) named by hardware buffer descriptors, and 2D textures +// (`srv tex2d table ` inputs, `uav tex2d float table channels 4` outputs) named +// by the token of a view the title created (device slots 18 and 19). `smp` lines become static samplers. Entry +// values come from the compute root constants of slots 37 and 39. Any other manifest line makes the translation +// unavailable; a dispatch that cannot be bound completely is refused with one reason and records no Dispatch and +// binds nothing (the upload of an input texture the title filled in memory may already be recorded: it only +// syncs content). + +struct ComputeTranslation { + // Root parameter and byte offset (views), or parameter and word (entry values). A heap view names the root + // constant (parameter and word) that indexes its 32-byte record in the list's view heap. + struct Slot { int a, b; bool texture, heap; }; + u64 key = 0; + int state = 0; // 0 not loaded, 1 ready, 2 unavailable + ULONGLONG retry_manifest_at = 0; // only an absent manifest can become ready later + std::vector uds, srvs, uavs; + x2w_startup::TranslatedSamplers samplers; // static ones only + x2w_startup::ComPtr root; + x2w_startup::ComPtr pipeline; + const char* unmodelled = nullptr; // why a manifest that exists cannot be used + u64 dispatches = 0, translated = 0; // census: Dispatch calls with this key bound, and those recorded + const char* first_refusal = nullptr; // reason of the first refused call + std::uint32_t refusal_words[4] = {}; // the table descriptor that reason was about, if any; a view token's + // last word is replaced by its view format | dimension << 16 + ~ComputeTranslation() + { + // The per-process cache is destroyed during DLL detach. A driver may already have shut + // down when the process is terminating. Explicit unload still releases both references. + if (x2w_startup::d3d12_process_terminating) { + pipeline.Detach(); + root.Detach(); + } + } +}; + +// Formats a `float` typed output may be viewed with: the program stores float4. +bool float_output_format(DXGI_FORMAT format) +{ + switch (format) { + case DXGI_FORMAT_R32G32B32A32_FLOAT: case DXGI_FORMAT_R16G16B16A16_FLOAT: case DXGI_FORMAT_R16G16B16A16_UNORM: + case DXGI_FORMAT_R16G16B16A16_SNORM: case DXGI_FORMAT_R32G32_FLOAT: case DXGI_FORMAT_R10G10B10A2_UNORM: + case DXGI_FORMAT_R11G11B10_FLOAT: case DXGI_FORMAT_R8G8B8A8_UNORM: case DXGI_FORMAT_R8G8B8A8_SNORM: + case DXGI_FORMAT_R16G16_FLOAT: case DXGI_FORMAT_R16G16_UNORM: case DXGI_FORMAT_R16G16_SNORM: case DXGI_FORMAT_R32_FLOAT: + case DXGI_FORMAT_R8G8_UNORM: case DXGI_FORMAT_R8G8_SNORM: case DXGI_FORMAT_R16_FLOAT: case DXGI_FORMAT_R16_UNORM: + case DXGI_FORMAT_R16_SNORM: case DXGI_FORMAT_R8_UNORM: case DXGI_FORMAT_R8_SNORM: case DXGI_FORMAT_B8G8R8A8_UNORM: + return true; + default: + return false; + } +} +std::unordered_map& compute_translations() { static std::unordered_map m; return m; } +LONG compute_dispatches_translated, compute_dispatches_refused, compute_dispatches_untranslated, compute_dispatches_unmodelled; + +// draw_lock held. Returns the reason the translation is unavailable, or null when it is ready or still absent. +const char* load_compute_translation(ComputeTranslation& tr) +{ + tr.state = 2; + wchar_t path[MAX_PATH]; + std::string manifest; + if (!cache_path(path, L"", tr.key, L".txt") || !read_text(path, manifest)) { + tr.retry_manifest_at = GetTickCount64() + 1000; + return nullptr; + } + tr.retry_manifest_at = 0; + unsigned declared_uds = 0, line_number = 0; + for (std::size_t at = 0; at < manifest.size(); ++line_number) { + std::size_t end = manifest.find('\n', at); + if (end == std::string::npos) end = manifest.size(); + std::string line = manifest.substr(at, end - at); + at = end + 1; + if (!line.empty() && line.back() == '\r') line.pop_back(); + if (line_number == 0) { + if (line != "x2w-manifest 2") return "manifest version"; + continue; + } + if (line_number == 1) { + if (line != "stage cs") return "not a compute manifest"; + continue; + } + unsigned i = 0, x = 0, y = 0, z = 0, w = 0; + int a = 0, b = 0, used = 0; + const auto whole = [&] { return used == static_cast(line.size()); }; + 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; + 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(), "srv %u buf table %d %d%n", &i, &a, &b, &used) == 3 && whole() && i == tr.srvs.size()) + tr.srvs.push_back({a, b}); + else if (std::sscanf(line.c_str(), "srv %u buf heap rootconst %d %d%n", &i, &a, &b, &used) == 3 && whole() && + i == tr.srvs.size()) + tr.srvs.push_back({a, b, false, true}); + else if (std::sscanf(line.c_str(), "uav %u table %d %d%n", &i, &a, &b, &used) == 3 && whole() && i == tr.uavs.size()) + tr.uavs.push_back({a, b}); + else if (std::sscanf(line.c_str(), "uav %u tex2d float table %d %d channels 4%n", &i, &a, &b, &used) == 3 && whole() && + i == tr.uavs.size()) + tr.uavs.push_back({a, b, true}); + else if (std::sscanf(line.c_str(), "srv %u tex2d table %d %d%n", &i, &a, &b, &used) == 3 && whole() && i == tr.srvs.size()) + tr.srvs.push_back({a, b, true}); + else if (std::sscanf(line.c_str(), "smp %u %x %x %x %x%n", &i, &x, &y, &z, &w, &used) == 5 && whole() && + i == tr.samplers.statics.size()) + tr.samplers.read_manifest_line(line.c_str()); + else return line.rfind("srv", 0) == 0 ? "a resource that is not a raw table buffer or a 2D texture" + : line.rfind("uav", 0) == 0 ? "an output that is not a raw table buffer or a 2D float texture" + : line.rfind("udsrc", 0) == 0 ? "an entry value that is not a root constant" + : line.rfind("smp", 0) == 0 ? "a sampler that is not a plain static one" : "an unknown manifest line"; + } + if (tr.uds.size() != declared_uds || tr.uds.size() > 32 || tr.srvs.size() > 32 || tr.uavs.size() > 8) + return "entry value, input or output count"; + x2w_startup::ComPtr code; + if (!cache_path(path, L"", tr.key, L".cs.cso") || FAILED(D3DReadFileToBlob(path, &code))) return "no compiled program"; + // Parameter 0 keeps one constant for a program without entry values: a constants parameter cannot be empty. + if (FAILED(x2w_startup::create_translated_root(device_of(the_device), static_cast(tr.uds.empty() ? 1 : tr.uds.size()), + static_cast(tr.srvs.size()), tr.samplers, &tr.root, static_cast(tr.uavs.size())))) + return "root signature creation failed"; + D3D12_COMPUTE_PIPELINE_STATE_DESC desc{}; + desc.pRootSignature = tr.root.Get(); + desc.CS = {code->GetBufferPointer(), code->GetBufferSize()}; + if (FAILED(device_of(the_device)->CreateComputePipelineState(&desc, IID_PPV_ARGS(&tr.pipeline)))) + return "pipeline creation failed"; + tr.state = 1; + log("x2w-draw compute pipeline %016llx translated: %zu entry values, %zu inputs, %zu outputs", tr.key, tr.uds.size(), + tr.srvs.size(), tr.uavs.size()); + return nullptr; +} + +// True when the bound pipeline is a slot 67 placeholder with a request key: the call is then settled here +// (dispatched, or refused and logged). False leaves it to the desktop-pipeline decision of list_dispatch. +bool dispatch_translated(Wrapper* self, UINT x, UINT y, UINT z) +{ + auto* list = recording(self); + Pass& pass = pass_of(self); + const u64 key = list && pass.pipeline ? pass.pipeline->own().compute_request_key : 0; + if (!key) return false; + const char* reason = nullptr; + LONG* counter = &compute_dispatches_refused; + struct View { + ID3D12Resource* resource; + u64 offset, bytes; + bool transition, texture, described; + unsigned char desc[40]; // a texture view's description, as the title gave it with a desktop format + Wrapper* wrapper; + } views[40]{}; + static_assert(sizeof(D3D12_SHADER_RESOURCE_VIEW_DESC) == 40 && sizeof(D3D12_UNORDERED_ACCESS_VIEW_DESC) == 40); + const auto type = list->GetType(); + AcquireSRWLockExclusive(&draw_lock); + ComputeTranslation* const tr = &compute_translations()[key]; + tr->key = key; + ++tr->dispatches; + std::uint32_t words[8] = {}; + if (type != D3D12_COMMAND_LIST_TYPE_DIRECT && type != D3D12_COMMAND_LIST_TYPE_COMPUTE) reason = "the list type has no Dispatch"; + else if (x > x2w_startup::max_dispatch_groups || y > x2w_startup::max_dispatch_groups || z > x2w_startup::max_dispatch_groups) + reason = "a group count is over the limit"; + else if (pass.compute_root_wrapper != pass.pipeline->own().compute_request_root) + reason = "the compute root set is not the one the pipeline was created with"; + else if (!ensure_draw_heap(self->own().list_device)) reason = "no descriptor heap on this device"; + else { + if (!tr->state || (tr->retry_manifest_at && GetTickCount64() >= tr->retry_manifest_at)) { + tr->unmodelled = load_compute_translation(*tr); + if (tr->unmodelled) log("x2w-draw compute pipeline %016llx not translated: %s", key, tr->unmodelled); + } + if (tr->state != 1) { + // A manifest the runtime cannot bind is the dispatch side's work; an absent one is the translator's. + reason = tr->unmodelled ? tr->unmodelled : "no translation"; + counter = tr->unmodelled ? &compute_dispatches_unmodelled : &compute_dispatches_untranslated; + } + } + // A word no slot 37 or 39 call wrote since the compute root was set has no value to pass (it is not 0). + for (std::size_t i = 0; !reason && i < tr->uds.size(); ++i) + if (!pass.compute_constants.is_bound(tr->uds[i].a, tr->uds[i].b, 1)) reason = "an entry value was not set since the compute root"; + const std::size_t inputs = reason ? 0 : tr->srvs.size(), count = reason ? 0 : inputs + tr->uavs.size(); + for (std::size_t i = 0; i < count && !reason; ++i) { + const bool output = i >= inputs; + const ComputeTranslation::Slot slot = output ? tr->uavs[i - inputs] : tr->srvs[i]; + // A heap record sits at the 32-bit byte offset the program computes, the root constant word shifted left by + // 5, in the title memory of the list's view heap: a literal byte offset, as a table's is. + const u64 entry = slot.a < 0 || slot.b < 0 ? 0 + : slot.heap ? pass.title_view_heap.record(std::uint32_t{pass.compute_constants.word(slot.a, slot.b)} << 5, 16) + : pass.compute_tables.table(slot.a).record(static_cast(slot.b), slot.texture ? 32 : 16); + std::memset(words, 0, sizeof(words)); + const std::size_t entry_bytes = slot.texture ? 32 : 16; + if (!entry || !x2w_local::readable(reinterpret_cast(entry), entry_bytes)) { + reason = slot.heap ? "a heap record is outside the list's view heap" : "a table descriptor is not bound"; + break; + } + std::memcpy(words, reinterpret_cast(entry), entry_bytes); + if (slot.texture) { + // The title's descriptor memory carries the id of the view it created there. Nothing else is bound: + // a null view would read zeros or drop the program's stores without a trace. + ViewRecord record{}; + bool known = false, created = false; + if (words[0] == view_token_magic) { + AcquireSRWLockShared(¬e_lock); + known = words[1] < view_records().size(); + if (known) { + record = view_records()[words[1]]; + created = view_materialized()[words[1]] != 0; + } + ReleaseSRWLockShared(¬e_lock); + } + Wrapper* const wrapper = known ? as_wrapper(reinterpret_cast(record.resource)) : nullptr; + ID3D12Resource* const texture = !wrapper || wrapper->own().kind != resource_kind ? nullptr + : output ? static_cast(wrapper->own().real) : sampled_address_texture(wrapper); + const D3D12_RESOURCE_DESC resource = texture ? texture->GetDesc() : D3D12_RESOURCE_DESC{}; + if (!output) { + D3D12_SHADER_RESOURCE_VIEW_DESC desc{}; + const bool described = record.desc_bytes >= sizeof(desc); + if (described) std::memcpy(&desc, record.desc, sizeof(desc)); + if (desc.Format) desc.Format = desktop_format(desc.Format); + words[3] = static_cast(desc.Format ? desc.Format : resource.Format) | static_cast(desc.ViewDimension) << 16; + if (!known || record.slot != 18) reason = "an input texture entry is not the token of a shader resource view"; + else if (!texture || (resource.Flags & D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE)) + reason = "an input texture has no desktop texture to sample"; + else if (described ? desc.ViewDimension != D3D12_SRV_DIMENSION_TEXTURE2D + : resource.Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE2D || resource.DepthOrArraySize != 1) + reason = "an input texture view is not 2D"; + // shortcut: a packed format needs the stand-in rules of the draw path; add them with its first user. + else if (x2w_startup::packed_target_format(desc.Format)) reason = "an input texture view has a packed format"; + views[i] = {texture, 0, 0, true, true, described}; + std::memcpy(views[i].desc, &desc, sizeof(desc)); + views[i].wrapper = wrapper; + continue; + } + D3D12_UNORDERED_ACCESS_VIEW_DESC desc{}; + const bool described = record.desc_bytes >= sizeof(desc); + if (described) std::memcpy(&desc, record.desc, sizeof(desc)); + if (desc.Format) desc.Format = desktop_format(desc.Format); + const DXGI_FORMAT format = desc.Format ? desc.Format : resource.Format; + words[3] = static_cast(format) | static_cast(desc.ViewDimension) << 16; + if (!known || record.slot != 19) reason = "an output texture entry is not the token of an unordered access view"; + else if (!created || !texture || !(resource.Flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS)) + reason = "an output texture view was not created on the desktop"; + else if (described ? desc.ViewDimension != D3D12_UAV_DIMENSION_TEXTURE2D || desc.Texture2D.PlaneSlice + : resource.Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE2D || resource.DepthOrArraySize != 1) + reason = "an output texture view is not 2D"; + else if (x2w_startup::packed_target_format(format)) reason = "an output texture view has a packed format"; + else if (!float_output_format(format)) reason = "an output texture format is not a float or normalized one"; + // One state per resource here: a texture read and written by the same call is refused. Two outputs + // of one texture (two mips) share the unordered access state. + for (std::size_t input = 0; input < inputs && !reason; ++input) + if (views[input].wrapper == wrapper) reason = "an output texture is also an input of the dispatch"; + views[i] = {texture, 0, 0, true, true, described}; + std::memcpy(views[i].desc, &desc, sizeof(desc)); + views[i].wrapper = wrapper; + continue; + } + if (!output) { + const IndirectBufferView view = indirect_table_buffer(self, words); + if (!view.resource || view.offset % D3D12_RAW_UAV_SRV_BYTE_ALIGNMENT) reason = "an input is not a complete GPU-backed buffer range"; + views[i] = {view.resource, view.offset, view.bytes, !view.upload}; + continue; + } + // An output is written by the GPU: only a placed buffer that aliases the title's memory shows the result + // to the title. shortcut: view tokens and copied placements are refused, add them with their first user. + const u64 address = words[0] | (u64{words[1] & 0xffff} << 32); + const UINT stride = (words[1] >> 16) & 0x3fff; + const u64 bytes = u64{stride ? stride : 1} * words[2]; + const auto placed = words[0] == view_token_magic || !bytes || bytes % 4 || bytes > (16u << 20) + ? PlacedVertexView{} : placed_buffer_range(self->own().list_device, address, bytes); + const ResourceInfo* info = placed.alias ? resource_info(placed.owner) : nullptr; + const u64 offset = placed.alias ? address - reinterpret_cast(placed.owner->own().title_memory) : 0; + if (!info || info->initial_state != D3D12_RESOURCE_STATE_COMMON || offset % D3D12_RAW_UAV_SRV_BYTE_ALIGNMENT || + !(placed.alias->GetDesc().Flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS)) + reason = "an output is not an aliased placed buffer range with unordered access"; + for (std::size_t input = 0; input < inputs && !reason; ++input) + if (views[input].resource == placed.alias) reason = "an output buffer is also an input"; + views[i] = {placed.alias, offset, bytes, true}; + } + // A texture the title filled in memory is brought up to date first. An upload recorded before a later one + // fails only syncs content, as a draw sampling that texture would. + for (std::size_t i = 0; i < inputs && !reason; ++i) + if (views[i].texture && !upload_texture(self, views[i].wrapper, views[i].resource)) { + reason = "an input texture could not be uploaded"; + std::memset(words, 0, sizeof(words)); + } + if (reason) { + if (!tr->first_refusal) { + tr->first_refusal = reason; + std::memcpy(tr->refusal_words, words, sizeof(tr->refusal_words)); + } + ReleaseSRWLockExclusive(&draw_lock); + InterlockedIncrement(counter); + // Dispatches that arrive before the offline translation must not use up the lines for bind refusals. + static LONG untranslated, refusals; + if (first_calls(counter == &compute_dispatches_refused ? refusals : untranslated, 16)) log("x2w-draw compute %016llx Dispatch(%u, %u, %u) refused: %s", key, x, y, z, reason); + return true; + } + const UINT n = static_cast(count); + UINT first = static_cast(InterlockedExchangeAdd(&draw_heap_cursor, static_cast(n))) % draw_heap_size; + if (first + n > draw_heap_size) { + first = 0; + InterlockedExchange(&draw_heap_cursor, static_cast(n)); + } + D3D12_CPU_DESCRIPTOR_HANDLE dest{draw_heap->GetCPUDescriptorHandleForHeapStart().ptr + std::size_t{first} * draw_heap_increment}; + for (std::size_t i = 0; i < count; ++i, dest.ptr += draw_heap_increment) { + const View& view = views[i]; + if (i < inputs && view.texture) { + // A compute list accepts no pixel-shader or depth state in a transition. + require_state(self, view.resource, type == D3D12_COMMAND_LIST_TYPE_COMPUTE ? D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE + : sampled_state(self, view.resource) | D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE); + device_of(the_device)->CreateShaderResourceView(view.resource, + view.described ? reinterpret_cast(view.desc) : nullptr, dest); + continue; + } + if (i < inputs) { + if (view.transition) require_state(self, view.resource, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE); + buffer_view(dest, view.resource, view.offset, static_cast(view.bytes)); + continue; + } + require_state(self, view.resource, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); + if (view.texture) { + device_of(the_device)->CreateUnorderedAccessView(view.resource, nullptr, + view.described ? reinterpret_cast(view.desc) : nullptr, dest); + continue; + } + D3D12_UNORDERED_ACCESS_VIEW_DESC desc{}; + desc.Format = DXGI_FORMAT_R32_TYPELESS; + desc.ViewDimension = D3D12_UAV_DIMENSION_BUFFER; + desc.Buffer.FirstElement = view.offset / 4; + desc.Buffer.NumElements = static_cast(view.bytes / 4); + desc.Buffer.Flags = D3D12_BUFFER_UAV_FLAG_RAW; + device_of(the_device)->CreateUnorderedAccessView(view.resource, nullptr, &desc, dest); + } + std::uint32_t values[32] = {}; + for (std::size_t i = 0; i < tr->uds.size(); ++i) values[i] = pass.compute_constants.word(tr->uds[i].a, tr->uds[i].b); + if (!pass.heap_set) { + x2w_startup::bind_translated_heaps(list, draw_heap, nullptr); + pass.heap_set = true; + pass.bound_sampler_heap = nullptr; + } + list->SetPipelineState(tr->pipeline.Get()); + list->SetComputeRootSignature(tr->root.Get()); + if (!tr->uds.empty()) list->SetComputeRoot32BitConstants(0, static_cast(tr->uds.size()), values, 0); + if (n) list->SetComputeRootDescriptorTable(1, D3D12_GPU_DESCRIPTOR_HANDLE{draw_heap->GetGPUDescriptorHandleForHeapStart().ptr + u64{first} * draw_heap_increment}); + list->Dispatch(x, y, z); + for (std::size_t i = inputs; i < count; ++i) { // a later dispatch on this list reads what this one wrote + D3D12_RESOURCE_BARRIER barrier{}; + barrier.Type = D3D12_RESOURCE_BARRIER_TYPE_UAV; + barrier.UAV.pResource = views[i].resource; + list->ResourceBarrier(1, &barrier); + } + // The translated root replaced the desktop compute root of the title and its arguments. + if (pass.desktop_compute_root) { + list->SetComputeRootSignature(pass.desktop_compute_root.Get()); + for (UINT parameter = 0; parameter < pass.desktop_compute_upload_srvs.size(); ++parameter) + if (const auto address = pass.desktop_compute_upload_srvs[parameter]) list->SetComputeRootShaderResourceView(parameter, address); + } + ++tr->translated; + ReleaseSRWLockExclusive(&draw_lock); + static LONG checks; // as translated draws do: the queue's execute drains the rest + if ((InterlockedIncrement(&checks) & 63) == 1) check_device("translated dispatch", 14); + InterlockedIncrement(&compute_dispatches_translated); + static LONG logged; + if (first_calls(logged, 8)) + log("x2w-draw compute %016llx Dispatch(%u, %u, %u) translated: entry [%x %x %x %x], %zu inputs, %zu outputs", key, x, y, z, + values[0], values[1], values[2], values[3], inputs, count - inputs); + return true; +} + +// With the periodic totals: refused dispatches by the first refusal reason of their key, then every key by +// dispatch count. The per-call log lines above share one small budget, so they cannot rank keys. +void log_compute_census() +{ + struct Reason { const char* text; u64 keys, dispatches; }; + std::vector reasons; + std::vector keys; + AcquireSRWLockShared(&draw_lock); + for (const auto& item : compute_translations()) { + const ComputeTranslation& tr = item.second; + ComputeTranslation copy; + copy.key = tr.key; + copy.dispatches = tr.dispatches; + copy.translated = tr.translated; + copy.first_refusal = tr.first_refusal; + std::memcpy(copy.refusal_words, tr.refusal_words, sizeof(copy.refusal_words)); + keys.push_back(copy); + if (!tr.first_refusal) continue; + auto found = std::find_if(reasons.begin(), reasons.end(), [&](const Reason& r) { return !std::strcmp(r.text, tr.first_refusal); }); + if (found == reasons.end()) found = reasons.insert(reasons.end(), Reason{tr.first_refusal, 0, 0}); + ++found->keys; + found->dispatches += tr.dispatches - tr.translated; + } + ReleaseSRWLockShared(&draw_lock); + if (keys.empty()) return; + std::sort(reasons.begin(), reasons.end(), [](const Reason& a, const Reason& b) { return a.dispatches > b.dispatches; }); + std::sort(keys.begin(), keys.end(), [](const ComputeTranslation& a, const ComputeTranslation& b) { return a.dispatches > b.dispatches; }); + log("x2w-render compute census: %zu keys dispatched", keys.size()); + for (const Reason& r : reasons) + log("x2w-render compute census reason \"%s\": %llu keys, %llu dispatches", r.text, r.keys, r.dispatches); + for (std::size_t i = 0; i < keys.size(); ++i) + log("x2w-render compute census key %016llx: %llu dispatches, %llu translated, first refusal: %s [%08x %08x %08x %08x]", + keys[i].key, keys[i].dispatches, keys[i].translated, keys[i].first_refusal ? keys[i].first_refusal : "none", + keys[i].refusal_words[0], keys[i].refusal_words[1], keys[i].refusal_words[2], keys[i].refusal_words[3]); +} + +// Fixtures: the census without waiting for the frame that logs it. +extern "C" __declspec(dllexport) void x2w_d3d12_compute_census() { log_compute_census(); } diff --git a/src/startup_stubs/d3d12_draw.inl b/src/startup_stubs/d3d12_draw.inl index 209c82255b..04830e6c10 100644 --- a/src/startup_stubs/d3d12_draw.inl +++ b/src/startup_stubs/d3d12_draw.inl @@ -314,10 +314,11 @@ LONG pointer_like_qwords(const std::vector& blob) SRWLOCK compute_request_lock = SRWLOCK_INIT; std::unordered_set& compute_keys_seen() { static std::unordered_set s; return s; } -void publish_compute_request(const void* desc) +// Returns the request key, or 0 when publishing is disabled or the description is refused. +u64 publish_compute_request(const void* desc) { wchar_t marker[MAX_PATH]; - if (!render_mode() || !cache_path(marker, L"req_", 0, L".c67")) return; // publishing disabled + if (!render_mode() || !cache_path(marker, L"req_", 0, L".c67")) return 0; // publishing disabled static LONG logged; const char* refusal = nullptr; u64 words[12]{}; @@ -356,7 +357,7 @@ void publish_compute_request(const void* desc) if (refusal) { InterlockedIncrement(&compute_requests_failed); if (first_calls(logged, 12)) log("x2w-draw compute request not written: %s", refusal); - return; + return 0; } const auto& [code, data, state_a, state_b] = copies; // Pointer words never reach .desc or the key; 9 and 10 are not followed (shortcut: two descriptions that @@ -392,6 +393,7 @@ void publish_compute_request(const void* desc) log("x2w-draw compute request %016llx %s (code %llu bytes, data %llu bytes, state blocks %llu + %llu bytes, " "pointer-like blob qwords %ld)", key, present ? "already present" : written ? "published" : "not written", words[6], words[8], words[2], words[4], pointers); + return key; } // Slot 57 fixed descriptors consumed by a decoded DispatchMesh signature. @@ -2387,10 +2389,12 @@ const char* draw_translated_indirect(Wrapper* self, ID3D12CommandSignature* sign } // List slot 32, SetDescriptorHeaps. Track the title's shader-visible sampler -// source while translated draws use their own physical descriptor heaps. +// source while translated draws use their own physical descriptor heaps, and the +// title memory of the view heap for a program that indexes the heap itself. void __stdcall list_set_descriptor_heaps(Wrapper* self, UINT count, void* const* heaps) { x2w_startup::SamplerSource source; + x2w_startup::ViewTable heap_records; x2w_startup::ViewHeapSelection view_heaps; if (count && count <= 4 && x2w_local::readable(heaps, std::size_t{count} * sizeof(*heaps))) { AcquireSRWLockShared(¬e_lock); @@ -2399,6 +2403,10 @@ void __stdcall list_set_descriptor_heaps(Wrapper* self, UINT count, void* const* if (heap.wrapper == reinterpret_cast(heaps[i]) && heap.type == D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV) view_heaps.note(heap.wrapper, heap.desktop_gpu != 0, heap.logical_count, heap.count); + if (heap.wrapper == reinterpret_cast(heaps[i]) && + heap.type == D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV) + heap_records = x2w_startup::resolve_view_table(heap.desktop_gpu, heap.title_cpu, heap.logical_count, + heap.increment, heap.desktop_gpu); if (heap.wrapper == reinterpret_cast(heaps[i]) && heap.type == D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER && heap.desktop_gpu) source = {static_cast(heap.title_sampler_cpu), heap.count}; @@ -2413,6 +2421,7 @@ void __stdcall list_set_descriptor_heaps(Wrapper* self, UINT count, void* const* pass.compute_tables.set_view_heap(view_heaps.compute); pass.source_view_heap = view_heaps.graphics; pass.title_samplers = source; + pass.title_view_heap = heap_records; } // The table at a title GPU handle, looked up in the title's view heap (the one set by slot 32 when known). diff --git a/src/startup_stubs/d3d12_xs_device.cpp b/src/startup_stubs/d3d12_xs_device.cpp index 0dcb9e742e..81c9679a31 100644 --- a/src/startup_stubs/d3d12_xs_device.cpp +++ b/src/startup_stubs/d3d12_xs_device.cpp @@ -185,6 +185,8 @@ struct alignas(16) WrapperOwn { LONG compute_trace_dispatches; bool root_without_bindings; // RootSignature: decoded and has no parameters or static samplers ID3D12RootSignature* pipeline_root; // PipelineState: desktop root signature its compute stream declared + u64 compute_request_key; // PipelineState: key of the slot 67 request it published, or 0 + const void* compute_request_root; // PipelineState: root signature wrapper named by that slot 67 description bool root_srv_only; // RootSignature: decoded, no static samplers, every parameter a root SRV (those are forwarded) volatile LONG queue_wait_seen; // CommandQueue: publish later signals only after GPU completion. void* pass; // CommandList (render mode): recording state (Pass) @@ -2451,6 +2453,7 @@ struct Pass { x2w_startup::ViewTable view_tables[16]{}; x2w_startup::ComputeTables compute_tables; // slot 35, read by a Dispatch handler u64 source_view_heap = 0; + x2w_startup::ViewTable title_view_heap; // slot 32: the title memory of the list's view heap (heap records) u64 root_address[16] = {}; // title address of each root descriptor std::uint32_t constants[16][8] = {}; unsigned char constant_words_bound[16] = {}; @@ -2661,6 +2664,9 @@ void __stdcall list_compute_root(Wrapper* self, void* root) pass.compute_root = real ? static_cast(w->own().real) : nullptr; pass.compute_tables.set_signature(w ? root_info(w) : nullptr); // a different signature leaves no table bound pass.compute_params = real ? root_info(w) : nullptr; + pass.compute_srv_bound = 0; + // Root SRV parameters are forwarded by their own slot; anything else the root declares is not. + pass.compute_root_has_arguments = real && !w->own().root_without_bindings && !w->own().root_srv_only; if (compute_binding_trace_enabled() && (!pass.compute_trace || pass.compute_trace->root != w)) { pass.compute_trace = std::make_unique(); pass.compute_trace->root = w; @@ -3648,8 +3654,10 @@ void __stdcall list_root_cbv(Wrapper* self, UINT parameter, u64 address) pass.root_address[parameter] = (address && readable_window(address, 1)) ? address : 0; } // List slot 14, Dispatch. Forwarded only with a desktop compute pipeline and root bound and group counts within the limit. +bool dispatch_translated(Wrapper* self, UINT x, UINT y, UINT z); void __stdcall list_dispatch(Wrapper* self, UINT x, UINT y, UINT z) { + if (dispatch_translated(self, x, y, z)) return; // a slot 67 placeholder never reaches the desktop decision auto* list = recording(self); x2w_startup::ListDispatch request; request.list_open = list != nullptr; @@ -3724,6 +3732,7 @@ std::unordered_map& written_textures(); ID3D12Resource* sampled_address_texture(Wrapper* resource); bool console_layout_srv(const D3D12_RESOURCE_DESC& desc); #include "startup_stubs/d3d12_draw.inl" +#include "startup_stubs/d3d12_compute_dispatch.inl" #include "startup_stubs/mesh86_cache.inl" #include "startup_stubs/d3d12_compute_binding_trace.inl" #include "startup_stubs/list_copy_texture.inl" @@ -5792,9 +5801,15 @@ HRESULT __stdcall device_create_pipeline_placeholder(Wrapper*, const void* desc, hex_text(desc, 96, bytes, sizeof(bytes)); log("x2w-d3d12 Device::slot%d(pipeline?) desc=[%s] riid=%s -> placeholder", N, bytes, text); } - if constexpr (N == 67) publish_compute_request(desc); *out = wrap(nullptr, pipeline_kind); if (!*out) return E_OUTOFMEMORY; + if constexpr (N == 67) { + // A translated Dispatch finds its program by this key (d3d12_compute_dispatch.inl). + if (const u64 key = publish_compute_request(desc)) { + static_cast(*out)->own().compute_request_key = key; + static_cast(*out)->own().compute_request_root = as_wrapper(*static_cast(desc)); + } + } note_pipeline(static_cast(*out), N, nullptr, desc, 0x300); return S_OK; } @@ -6195,6 +6210,11 @@ HRESULT __stdcall queue_present(Wrapper* self, UINT planes, const void* plane_pa heap_root_refusals[static_cast(x2w_startup::RealRootDecision::both_heaps_missing)], heap_root_refusals[static_cast(x2w_startup::RealRootDecision::state_not_restorable)], indirect_first_lookups, compute_requests_published, compute_requests_present, compute_requests_failed, compute_blob_pointer_words); + if (render_mode() && frame % 300 == 0) { + log("x2w-render compute dispatches: translated %ld, refused %ld, no translation %ld, not modelled %ld", + compute_dispatches_translated, compute_dispatches_refused, compute_dispatches_untranslated, compute_dispatches_unmodelled); + log_compute_census(); + } if (render_mode() && frame % 300 == 0) { // Slot-61 calls since the start, by outcome, then by signature kind (zero kinds left out). static const char* const outcomes[] = {"forwarded", "refused graphics-pipeline", "compute-pipeline", diff --git a/src/startup_stubs/translated_sampler_bindings.h b/src/startup_stubs/translated_sampler_bindings.h index a4aca72ddf..8d06fa71a6 100644 --- a/src/startup_stubs/translated_sampler_bindings.h +++ b/src/startup_stubs/translated_sampler_bindings.h @@ -113,17 +113,20 @@ inline std::vector decode_statics(const TranslatedSam inline UINT sampler_root_parameter(UINT srvs) { return srvs ? 2u : 1u; } inline HRESULT create_translated_root(ID3D12Device* device, UINT constants, UINT srvs, - const TranslatedSamplers& samplers, ID3D12RootSignature** out) + const TranslatedSamplers& samplers, ID3D12RootSignature** out, UINT uavs = 0) { D3D12_ROOT_PARAMETER parameters[3]{}; parameters[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS; parameters[0].Constants.Num32BitValues = constants; - const D3D12_DESCRIPTOR_RANGE srv_range{D3D12_DESCRIPTOR_RANGE_TYPE_SRV, srvs, 0, 0, 0}; + // A compute program's outputs (u0..) follow its resources in the same table. + const D3D12_DESCRIPTOR_RANGE view_ranges[2]{{D3D12_DESCRIPTOR_RANGE_TYPE_SRV, srvs, 0, 0, 0}, + {D3D12_DESCRIPTOR_RANGE_TYPE_UAV, uavs, 0, 0, srvs}}; parameters[1].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; - parameters[1].DescriptorTable = {1, &srv_range}; + // A range of no descriptors does not serialize: a program without resources starts the table at its outputs. + parameters[1].DescriptorTable = {(srvs ? 1u : 0u) + (uavs ? 1u : 0u), srvs ? view_ranges : view_ranges + 1}; const D3D12_DESCRIPTOR_RANGE sampler_range{ D3D12_DESCRIPTOR_RANGE_TYPE_SAMPLER, translated_sampler_count, 0, translated_sampler_space, 0}; - UINT count = sampler_root_parameter(srvs); + UINT count = sampler_root_parameter(srvs + uavs); if (samplers.heap) { parameters[count].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; parameters[count].DescriptorTable = {1, &sampler_range}; diff --git a/tests/startup_compute_dispatch_check.py b/tests/startup_compute_dispatch_check.py new file mode 100644 index 0000000000..018d4a4b76 --- /dev/null +++ b/tests/startup_compute_dispatch_check.py @@ -0,0 +1,132 @@ +"""A translated compute program dispatched through the stand-in's command list (list slot 14). + +usage: startup_compute_dispatch_check.py + +The consumer creates case A of startup_gfx2hlsl_compute_check.py as a device slot 67 pipeline and records, on a +stand-in list, the descriptor heap, the pipeline, its root signature, two root constants (word 0 by slot 37, word 1 +by slot 39, with a slot 40 call of other words in between), one table of two +hardware buffer descriptors and Dispatch(3, 2, 2). Input and output are placed buffers that alias the consumer's +memory; the output words are read from that memory after the queue's fence. Four runs share one cache: + +1. before translation: the request is published, the Dispatch is refused with "no translation" and every output + word keeps the sentinel (the check fails when nothing translated is dispatched); +2. after gfx2hlsl.py --pending with DXC: all 320 words equal the case's expectation; +3. dispatch-none (no Dispatch recorded): every word keeps the sentinel; +4. dispatch-swapped (the two descriptors exchanged, so the output names the buffer without unordered access): + refused with one logged reason, every word keeps the sentinel and the input is unchanged; +5. dispatch-same-root (the same compute root set again after the constants): all 320 words still match; +6. five more refusals, each with its one logged reason and an untouched output: dispatch-missing-word (no slot 37 + call), dispatch-root-changed (another compute root and back after the constants), dispatch-reset (list closed + and reset after the constants), dispatch-wrong-root (recorded under a root the pipeline was not created with) + and dispatch-same-buffer (the output buffer is also the input). +Exit 77 when the adapter is not available. +""" +import os +from pathlib import Path +import struct +import subprocess +import sys +import tempfile + +import startup_gfx2hlsl_compute_check as C +from startup_compute_request_check import DATA, prepare +from startup_compute_translate_check import state_a +from startup_stream_check import gfx2hlsl as G + + +def dispatch(directory, consumer, env, mode): + out = directory / 'out.bin' + out.unlink(missing_ok=True) + args = [consumer, directory / 'vertex', directory / 'pixel', directory / 'root', 'slot67', + directory / 'program', directory / 'data', directory / 'state', mode] + result = subprocess.run(args, env=dict(env, X2W_TEST_DISPATCH_OUT=str(out)), capture_output=True, text=True) + if result.returncode == 77: + print(result.stdout, end='') + sys.exit(77) + assert result.returncode == 0, f'{mode}: consumer exit {result.returncode}\n{result.stderr[-3000:]}' + return list(struct.unpack('<%dI' % C.WORDS, out.read_bytes())), result + + +def lines(result, text): + return [line for line in result.stderr.splitlines() if text in line] + + +def main(consumer, dxc, adapter): + with tempfile.TemporaryDirectory() as temporary: + directory = Path(temporary) + cache, env = prepare(directory) + env.update(X2W_D3D12_LIST_NOOP='1', X2W_D3D12_DEBUG='1') # guest lists; debug-layer messages go to the log + if adapter == 'hardware': + env['X2W_TEST_DISPATCH_HARDWARE'] = '1' + (directory / 'compute_root').write_bytes(C.root_blob(table_range=True)) + env['X2W_TEST_COMPUTE_ROOT'] = str(directory / 'compute_root') + _, words, rsrc2, group, groups = C.CASES['A'] + assert groups == (3, 2, 2) and (C.KEY, C.STRIDE) == (0x01234567, 0x9e3779b9), 'the consumer hard-codes case A' + (directory / 'program').write_bytes(words) + (directory / 'data').write_bytes(DATA) + (directory / 'state').write_bytes(state_a(group, rsrc2)) + untouched, expected = [C.SENTINEL] * C.WORDS, C.expected('A') + assert expected != untouched + + got, result = dispatch(directory, consumer, env, 'dispatch') + print(result.stdout, end='') + assert got == untouched, 'a Dispatch without a translation wrote the output' + assert len(lines(result, 'Dispatch(3, 2, 2) refused: no translation')) == 1, result.stderr[-3000:] + published = lines(result, 'x2w-draw compute request') + assert published and ' published ' in published[0], result.stderr[-3000:] + key = int(published[0].split()[3], 16) + census = lines(result, 'x2w-render compute census') + assert census == ['x2w-render compute census: 1 keys dispatched', + 'x2w-render compute census reason "no translation": 1 keys, 1 dispatches', + f'x2w-render compute census key {key:016x}: 1 dispatches, 0 translated, first refusal: ' + 'no translation [00000000 00000000 00000000 00000000]'], census + + out = subprocess.run([sys.executable, '-B', G.__file__, '--pending', cache], check=True, capture_output=True, + text=True, env=dict(os.environ, X2W_DXC=dxc)).stdout + assert f'{key:016x}: ok' in out, out + + got, result = dispatch(directory, consumer, env, 'dispatch') + wrong = [i for i in range(C.WORDS) if got[i] != expected[i]] + assert not wrong, 'word=%d got=%08x expected=%08x (%d words differ)\n%s' % ( + wrong[0], got[wrong[0]], expected[wrong[0]], len(wrong), result.stderr[-3000:]) + assert len(lines(result, 'Dispatch(3, 2, 2) translated')) == 1 and not lines(result, 'refused'), result.stderr[-3000:] + census = lines(result, 'x2w-render compute census') + assert len(census) == 2 and census[1].endswith(': 1 dispatches, 1 translated, first refusal: none ' + '[00000000 00000000 00000000 00000000]'), census + layer = lines(result, 'x2w-d3d12 debug layer: ') + errors = [line for line in lines(result, 'x2w-d3d12-debug ') if ' sev=0 ' in line or ' sev=1 ' in line] + assert not errors, errors[0] + print('debug layer: ' + ('enabled, no error message' if layer and '0x00000000' in layer[0] else 'unavailable')) + + got, result = dispatch(directory, consumer, env, 'dispatch-none') + assert got == untouched and not lines(result, 'Dispatch('), 'the output changed without a Dispatch' + assert not lines(result, 'x2w-render compute census'), 'a census without a Dispatch' + + got, result = dispatch(directory, consumer, env, 'dispatch-swapped') + assert got == untouched, 'a refused Dispatch wrote the output' + refused = lines(result, 'refused: ') + census = lines(result, 'x2w-render compute census') + assert len(census) == 3 and census[1].endswith( + 'reason "an output is not an aliased placed buffer range with unordered access": 1 keys, 1 dispatches') \ + and '[00000000 00000000 ' not in census[2], census + assert len(refused) == 1 and 'an output is not an aliased placed buffer range with unordered access' in refused[0], \ + result.stderr[-3000:] + got, result = dispatch(directory, consumer, env, 'dispatch-same-root') + assert got == expected and not lines(result, 'refused'), 'setting the same compute root again lost the constants' + + unset = 'an entry value was not set since the compute root' + for mode, reason in (('dispatch-missing-word', unset), ('dispatch-root-changed', unset), ('dispatch-reset', unset), + ('dispatch-wrong-root', 'the compute root set is not the one the pipeline was created with'), + ('dispatch-same-buffer', 'an output buffer is also an input')): + got, result = dispatch(directory, consumer, env, mode) + assert got == untouched, f'{mode}: a refused Dispatch wrote the output' + refused = lines(result, 'refused: ') + assert len(refused) == 1 and refused[0].endswith('refused: ' + reason), f'{mode}: {refused}\n{result.stderr[-3000:]}' + print(f'startup_compute_dispatch: PASS on {adapter} (all {C.WORDS} words match after translation and with the ' + 'same root set again; untouched before translation, without a Dispatch and for 6 refusals)') + + +if __name__ == '__main__': + if len(sys.argv) != 4 or sys.argv[3] not in ('warp', 'hardware'): + sys.exit(__doc__) + main(*sys.argv[1:]) diff --git a/tests/startup_compute_dispatch_heap_check.py b/tests/startup_compute_dispatch_heap_check.py new file mode 100644 index 0000000000..c5addfad71 --- /dev/null +++ b/tests/startup_compute_dispatch_heap_check.py @@ -0,0 +1,87 @@ +"""A translated compute program whose input is the resource heap record a root constant indexes (list slot 14). + +usage: startup_compute_dispatch_heap_check.py + +The consumer creates the program of startup_gfx2hlsl_heap_record_check.py as a device slot 67 pipeline, with a +root signature that indexes the resource heap directly, and records the descriptor heap, the pipeline, the root +signature, three root constants, one table and Dispatch(3, 2, 2). The output descriptor is at table byte 16 as in +startup_compute_dispatch_check.py. The input descriptor is only in heap record 2 (heap byte 64), which the third +root constant indexes; heap bytes 0 and 32 hold the output's descriptor, so a dispatch that ignores the index or +scales it by 16 is refused instead of passing. Three runs share one cache: + +1. before translation: the request is published and the Dispatch is refused with "no translation"; +2. after gfx2hlsl.py --pending with DXC: the manifest names the heap record and all 320 words equal the + expectation of case A of startup_gfx2hlsl_compute_check.py (the program computes the same words); +3. dispatch-heap-outside (the constant is 0x07ffffff, a record past the heap): refused with one + logged reason, every word keeps the sentinel and the input is unchanged. +Exit 77 when the adapter is not available. +""" +import os +from pathlib import Path +import subprocess +import sys +import tempfile + +import startup_gfx2hlsl_compute_check as C +import startup_gfx2hlsl_heap_record_check as H +from startup_compute_dispatch_check import dispatch, lines +from startup_compute_request_check import DATA, prepare +from startup_compute_translate_check import state_a +from startup_stream_check import gfx2hlsl as G + +OUTSIDE = "a heap record is outside the list's view heap" + + +def main(consumer, dxc, adapter): + with tempfile.TemporaryDirectory() as temporary: + directory = Path(temporary) + cache, env = prepare(directory) + env.update(X2W_D3D12_LIST_NOOP='1', X2W_D3D12_DEBUG='1') # guest lists; debug-layer messages go to the log + if adapter == 'hardware': + env['X2W_TEST_DISPATCH_HARDWARE'] = '1' + (directory / 'compute_root').write_bytes(H.root_blob(table_range=True)) + env['X2W_TEST_COMPUTE_ROOT'] = str(directory / 'compute_root') + assert H.GROUPS == (3, 2, 2) and H.INDEX_WORD == 2, 'the consumer hard-codes the dispatch and the index word' + (directory / 'program').write_bytes(H.WORDS) + (directory / 'data').write_bytes(DATA) + (directory / 'state').write_bytes(state_a(H.GROUP, H.RSRC2)) + untouched, expected = [C.SENTINEL] * C.WORDS, C.expected('A') + assert expected != untouched + + got, result = dispatch(directory, consumer, env, 'dispatch-heap') + print(result.stdout, end='') + assert got == untouched, 'a Dispatch without a translation wrote the output' + assert len(lines(result, 'Dispatch(3, 2, 2) refused: no translation')) == 1, result.stderr[-3000:] + published = lines(result, 'x2w-draw compute request') + assert published and ' published ' in published[0], result.stderr[-3000:] + key = int(published[0].split()[3], 16) + + out = subprocess.run([sys.executable, '-B', G.__file__, '--pending', cache], check=True, capture_output=True, + text=True, env=dict(os.environ, X2W_DXC=dxc)).stdout + assert f'{key:016x}: ok' in out, out + assert (cache / f'{key:016x}.txt').read_text() == H.MANIFEST + + got, result = dispatch(directory, consumer, env, 'dispatch-heap') + wrong = [i for i in range(C.WORDS) if got[i] != expected[i]] + assert not wrong, 'word=%d got=%08x expected=%08x (%d words differ)\n%s' % ( + wrong[0], got[wrong[0]], expected[wrong[0]], len(wrong), result.stderr[-3000:]) + assert len(lines(result, 'Dispatch(3, 2, 2) translated')) == 1 and not lines(result, 'refused'), result.stderr[-3000:] + layer = lines(result, 'x2w-d3d12 debug layer: ') + errors = [line for line in lines(result, 'x2w-d3d12-debug ') if ' sev=0 ' in line or ' sev=1 ' in line] + assert not errors, errors[0] + print('debug layer: ' + ('enabled, no error message' if layer and '0x00000000' in layer[0] else 'unavailable')) + + got, result = dispatch(directory, consumer, env, 'dispatch-heap-outside') + assert got == untouched, 'a refused Dispatch wrote the output' + refused = lines(result, 'refused: ') + census = lines(result, 'x2w-render compute census') + assert len(refused) == 1 and OUTSIDE in refused[0], result.stderr[-3000:] + assert len(census) == 3 and census[1].endswith(f'reason "{OUTSIDE}": 1 keys, 1 dispatches'), census + print(f'startup_compute_dispatch_heap: PASS on {adapter} (all {C.WORDS} words match through heap record 2; ' + 'untouched before translation and for a record outside the heap)') + + +if __name__ == '__main__': + if len(sys.argv) != 4 or sys.argv[3] not in ('warp', 'hardware'): + sys.exit(__doc__) + main(*sys.argv[1:]) diff --git a/tests/startup_compute_dispatch_texture_check.py b/tests/startup_compute_dispatch_texture_check.py new file mode 100644 index 0000000000..4ec3eb5088 --- /dev/null +++ b/tests/startup_compute_dispatch_texture_check.py @@ -0,0 +1,203 @@ +"""Translated compute programs with 2D texture views, dispatched through the stand-in's command list (slot 14). + +usage: startup_compute_dispatch_texture_check.py + +Texture output: the consumer creates the image store program of startup_compute_image_store_d16_check.py as a +device slot 67 pipeline, fills a 32x8 RGBA16_FLOAT texture with sentinel halves, creates an unordered access view of +it at table byte 64 (device slot 19), records Dispatch(2, 1, 1) and copies the texture to a readback buffer. Four +runs share one cache: + +1. before translation: refused with "no translation", every half keeps its sentinel; +2. after gfx2hlsl.py --pending with DXC: the 1024 halves equal mip 0 of the fixture's CPU reference (64 changed); +3. texture-store-none (no Dispatch recorded): every half keeps its sentinel; +4. texture-store-denied (a texture without unordered access, whose view the stand-in does not create): refused + with one logged reason, every half keeps its sentinel. +A fifth run binds the same program under a manifest edited to declare no entry values. + +Texture input: case A of startup_gfx2hlsl_compute_check.py with a level-zero sample of a 2D texture XORed into the +stored word (a static sampler, a texture view at table byte 64). The consumer adds a 1x1 RGBA8 texture whose red +is 1.0 and a shader resource view of it (device slot 18). After translation all 320 words equal the case's +expectation XOR the bits of 1.0f; dispatch-sampled-unbound (no view created) is refused with one logged reason and +every word keeps the sentinel. +Exit 77 when the adapter is not available. +""" +import os +from pathlib import Path +import struct +import subprocess +import sys +import tempfile + +import startup_compute_image_store_d16_check as S +import startup_gfx2hlsl_compute_check as C +from startup_compute_dispatch_check import lines +from startup_compute_request_check import DATA, prepare +from startup_compute_translate_check import state_a +from startup_stream_check import gfx2hlsl as G + + +def run(directory, consumer, env, mode, layout): + out = directory / 'out.bin' + out.unlink(missing_ok=True) + args = [consumer, directory / 'vertex', directory / 'pixel', directory / 'root', 'slot67', + directory / 'program', directory / 'data', directory / 'state', mode] + result = subprocess.run(args, env=dict(env, X2W_TEST_DISPATCH_OUT=str(out)), capture_output=True, text=True) + if result.returncode == 77: + print(result.stdout, end='') + sys.exit(77) + assert result.returncode == 0, f'{mode}: consumer exit {result.returncode}\n{result.stderr[-3000:]}' + return list(struct.unpack(layout, out.read_bytes())), result + + +def translate(cache, dxc, key): + out = subprocess.run([sys.executable, '-B', G.__file__, '--pending', cache], check=True, capture_output=True, + text=True, env=dict(os.environ, X2W_DXC=dxc)).stdout + assert f'{key:016x}: ok' in out, out + + +def clean(result): + assert not lines(result, 'refused'), result.stderr[-3000:] + errors = [line for line in lines(result, 'x2w-d3d12-debug ') if ' sev=0 ' in line or ' sev=1 ' in line] + assert not errors, errors[0] + layer = lines(result, 'x2w-d3d12 debug layer: ') + return 'enabled, no error message' if layer and '0x00000000' in layer[0] else 'unavailable' + + +def store(directory, consumer, dxc, env): + cache, base = prepare(directory) + env = dict(base, **env) + (directory / 'compute_root').write_bytes(C.root_blob(3, table_range=True)) + env['X2W_TEST_COMPUTE_ROOT'] = str(directory / 'compute_root') + assert S.fixture.GROUP == (4, 2, 1) and S.fixture.GROUPS == 2, 'the consumer hard-codes Dispatch(2, 1, 1)' + (directory / 'program').write_bytes(S.fixture.WORDS) + (directory / 'data').write_bytes(DATA) + (directory / 'state').write_bytes(state_a(S.fixture.GROUP, S.RSRC2)) + reference = S.fixture.reference() + halves = 32 * 8 * 4 # mip 0 comes first in both halves of the reference + untouched, expected = reference[:halves], reference[len(reference) // 2:][:halves] + assert sum(a != b for a, b in zip(untouched, expected)) == 64 + layout = '<%dH' % halves + + got, result = run(directory, consumer, env, 'texture-store', layout) + print(result.stdout, end='') + assert got == untouched, 'a Dispatch without a translation wrote the texture' + assert len(lines(result, 'Dispatch(2, 1, 1) refused: no translation')) == 1, result.stderr[-3000:] + key = int(lines(result, 'x2w-draw compute request')[0].split()[3], 16) + translate(cache, dxc, key) + + got, result = run(directory, consumer, env, 'texture-store', layout) + wrong = [i for i in range(halves) if got[i] != expected[i]] + assert not wrong, 'half=%d got=%04x expected=%04x (%d halves differ)\n%s' % ( + wrong[0], got[wrong[0]], expected[wrong[0]], len(wrong), result.stderr[-3000:]) + assert len(lines(result, 'Dispatch(2, 1, 1) translated')) == 1, result.stderr[-3000:] + layer = clean(result) + + got, result = run(directory, consumer, env, 'texture-store-none', layout) + assert got == untouched and not lines(result, 'Dispatch('), 'the texture changed without a Dispatch' + + got, result = run(directory, consumer, env, 'texture-store-denied', layout) + assert got == untouched, 'a refused Dispatch wrote the texture' + refused = lines(result, 'refused: ') + assert len(refused) == 1 and 'an output texture view was not created on the desktop' in refused[0], result.stderr[-3000:] + + # Refusals the runtime already had, each with its one logged reason and an untouched texture: an integer view + # format, another manifest version, another stage, and (with a manifest line added here for a view the consumer + # creates) the output texture named as an input too. + manifest = cache / f'{key:016x}.txt' + original = manifest.read_text() + for mode, old, new, reason in ( + ('texture-store-uint', '', '', 'an output texture format is not a float or normalized one'), + ('texture-store', 'x2w-manifest 2', 'x2w-manifest 3', 'manifest version'), + ('texture-store', 'stage cs', 'stage ps', 'not a compute manifest'), + ('texture-store-self', 'uav 0 tex2d', 'srv 0 tex2d table 1 0' + chr(10) + 'uav 0 tex2d', + 'an output texture is also an input of the dispatch')): + assert not old or original.count(old) == 1, original + manifest.write_bytes(original.replace(old, new).encode() if old else original.encode()) + got, result = run(directory, consumer, env, mode, layout) + refused = lines(result, 'refused: ') + assert got == untouched and len(refused) == 1 and refused[0].endswith('refused: ' + reason), ( + mode, reason, refused, result.stderr[-3000:]) + manifest.write_bytes(original.encode()) + + # The same compiled program under a manifest without entry values (the program reads none of its three): the + # runtime binds no constants. The manifest is edited here; the translator writes `ud 0` for a root without them. + manifest = cache / f'{key:016x}.txt' + kept = [line for line in manifest.read_text().splitlines() if not line.startswith('udsrc ')] + assert len(kept) == 5 and kept[3] == 'ud 3', kept + manifest.write_bytes(('\n'.join(kept).replace('ud 3', 'ud 0') + '\n').encode()) + got, result = run(directory, consumer, env, 'texture-store', layout) + assert got == expected and lines(result, 'translated: 0 entry values, 0 inputs, 1 outputs'), result.stderr[-3000:] + clean(result) + print(f'texture output: all {halves} halves match after translation (64 changed) and without entry values; ' + f'untouched before translation, without a Dispatch and for a refused view; debug layer: {layer}') + + +# v_xor_b32 v5, v5, v12: the assembled `v_xor_b32 v5, v5, v6` of case A with its second source register changed +# (not assembled by llvm-mc here; the translation below is checked to read it as written). +XOR = 'v_xor_b32 v5, v5, v12' +SAMPLED = ('s_mov_b64 s[20:21], 0', 's_mov_b64 s[22:23], 0', 's_load_dwordx8 s[24:31], s[10:11], 0x40', + 'image_sample_lz v[12:15], v[0:1], s[24:31], s[20:23] dmask:0xf dim:SQ_RSRC_IMG_2D', XOR) + + +def sample(directory, consumer, dxc, env): + cache, base = prepare(directory) + env = dict(base, **env) + (directory / 'compute_root').write_bytes(C.root_blob(table_range=True)) + env['X2W_TEST_COMPUTE_ROOT'] = str(directory / 'compute_root') + _, words, rsrc2, group, groups = C.CASES['A'] + assert groups == (3, 2, 2) and (C.KEY, C.STRIDE) == (0x01234567, 0x9e3779b9), 'the consumer hard-codes case A' + assert words[96:100].hex() == '050d0a3a', 'case A no longer holds v_xor_b32 v5, v5, v6 at byte 96' + C.SPLICE[XOR] = '05190a3a' + code = C.splice(*SAMPLED) + pipeline = C.translate('A', code=code) + assert 'v5 = v5 ^ v12;' in pipeline.hlsl_cs() and pipeline.manifest().endswith( + 'srv 0 buf table 1 0\nsrv 1 tex2d table 1 64\nuav 0 table 1 16\nsmp 0 0x0 0x0 0x0 0x0\n'), pipeline.manifest() + (directory / 'program').write_bytes(code) + (directory / 'data').write_bytes(DATA) + (directory / 'state').write_bytes(state_a(group, rsrc2)) + one = struct.unpack('] + +The root signature has three root constants (s4-s6), one descriptor table (s7) and the directly indexed +resource heap (root flag 0x400, pointer in s8). The program is case A of startup_gfx2hlsl_compute_check.py +with its input descriptor loaded as + + s_lshl_b32 s6, s6, 5 + s_load_dwordx4 s[16:19], s[8:9], s6 + +after s9 is set to zero. gfx2hlsl.py names that input `srv 0 buf heap rootconst 0 2` in the manifest: the +dispatch reads the 32-byte heap record that root constant word 2 indexes. The HLSL and the manifest are +compared whole. Every other form keeps a refusal: another shift, another index, an index register written +again, a branch target between the shift and the load, a high word that is not a constant zero, an offset +modifier, eight dwords, an index read from a buffer (named as such), a formatted load or a store through the +record, and the graphics stages. --llvm-mc reassembles every instruction used here and compares the words. +""" +import argparse +import struct + +from startup_gfx2hlsl_compute_check import G, TGID_X, TGID_Y, TGID_Z, assemble, refused, tidig + +GROUP, GROUPS = (2, 3, 4), (3, 2, 2) +RSRC2 = (9 << 1) | TGID_X | TGID_Y | TGID_Z | tidig(3) # s0-s3, three constants, the table, the heap pointer +INDEX_WORD = 2 # the root constant word the program shifts + +SHIFT, CLEAR, LOAD = 's_lshl_b32 s6, s6, 5', 's_mov_b32 s9, 0', 's_load_dwordx4 s[16:19], s[8:9], s6' +READ = 'buffer_load_dword v5, v4, s[16:19], 0 offen' +WRITE = 'buffer_store_dword v5, v4, s[20:23], 0 offen' +PROGRAM = ( + 's_mov_b32 s12, s7', 's_mov_b32 s13, 0', 's_load_dwordx4 s[20:23], s[12:13], 0x10', + 's_mov_b32 s14, s9', CLEAR, SHIFT, LOAD, 's_waitcnt lgkmcnt(0)', + 'v_mad_u32_u24 v3, v1, 2, v0', 'v_mad_u32_u24 v3, v2, 6, v3', 's_mul_i32 s24, s10, 3', 's_add_u32 s24, s24, s14', + 's_mul_i32 s25, s11, 6', 's_add_u32 s24, s24, s25', 's_mul_i32 s24, s24, 24', 'v_add_nc_u32 v3, s24, v3', + 'v_lshlrev_b32 v4, 2, v3', READ, 'v_mul_lo_u32 v6, v3, s5', 'v_add_nc_u32 v6, s4, v6', 's_waitcnt vmcnt(0)', + 'v_mul_lo_u32 v5, v5, 33', 'v_xor_b32 v5, v5, v6', WRITE, 's_endpgm') +# Every instruction of the program and of the controls, recorded from llvm-mc 15. +ENCODED = { + 's_mov_b32 s12, s7': '07038cbe', 's_mov_b32 s13, 0': '80038dbe', + 's_load_dwordx4 s[20:23], s[12:13], 0x10': '060508f4100000fa', 's_mov_b32 s14, s9': '09038ebe', + CLEAR: '800389be', SHIFT: '0685068f', LOAD: '040408f40000000c', 's_waitcnt lgkmcnt(0)': '7fc08cbf', + 'v_mad_u32_u24 v3, v1, 2, v0': '030043d501050104', 'v_mad_u32_u24 v3, v2, 6, v3': '030043d5020d0d04', + 's_mul_i32 s24, s10, 3': '0a831893', 's_add_u32 s24, s24, s14': '180e1880', 's_mul_i32 s25, s11, 6': '0b861993', + 's_add_u32 s24, s24, s25': '18191880', 's_mul_i32 s24, s24, 24': '18981893', 'v_add_nc_u32 v3, s24, v3': '1806064a', + 'v_lshlrev_b32 v4, 2, v3': '82060834', READ: '001030e004050480', 'v_mul_lo_u32 v6, v3, s5': '060069d5030b0000', + 'v_add_nc_u32 v6, s4, v6': '040c0c4a', 's_waitcnt vmcnt(0)': '703f8cbf', 'v_mul_lo_u32 v5, v5, 33': '050069d505430100', + 'v_xor_b32 v5, v5, v6': '050d0a3a', WRITE: '001070e004050580', 's_endpgm': '000081bf', + 's_lshl_b32 s6, s6, 4': '0684068f', 's_lshl_b32 s6, s6, 6': '0686068f', 's_lshl_b32 s6, s6, s5': '0605068f', + 's_lshl_b32 s6, s14, 5': '0e85068f', 's_mov_b32 s9, 1': '810389be', 's_mov_b32 s9, s5': '050389be', + 's_load_dwordx4 s[16:19], s[8:9], s6 offset:0x20': '040408f42000000c', + 's_load_dwordx8 s[16:23], s[8:9], s6': '04040cf40000000c', 's_load_dwordx4 s[16:19], s[8:9], s5': '040408f40000000a', + 's_load_dwordx4 s[16:19], s[8:9], m0': '040408f4000000f8', 's_add_u32 s6, s6, 0': '06800680', + 's_load_dwordx4 s[28:31], s[12:13], 0x20': '060708f4200000fa', + 's_buffer_load_dword s6, s[28:31], 0x0': '8e0120f4000000fa', 's_buffer_load_dword s26, s[28:31], 0x0': '8e0620f4000000fa', + 's_lshl_b32 s6, s26, 5': '1a85068f', 's_cmp_eq_u32 s4, 0': '048006bf', 's_cbranch_scc0 1': '010084bf', 's_nop 0': '000080bf', + 'buffer_load_format_xyzw v[5:8], v4, s[16:19], 0 offen': '00100ce004050480', + 'buffer_store_dword v5, v4, s[16:19], 0 offen': '001070e004050480', +} +TABLE_LOAD = 's_load_dwordx4 s[28:31], s[12:13], 0x20' +JUMP = ('s_cmp_eq_u32 s4, 0', 's_cbranch_scc0 1', 's_nop 0') # the instruction after the s_nop is a branch target + +MANIFEST = """\ +x2w-manifest 2 +stage cs +group 2 3 4 +ud 3 +udsrc 0 rootconst 0 0 +udsrc 1 rootconst 0 1 +udsrc 2 rootconst 0 2 +srv 0 buf heap rootconst 0 2 +uav 0 table 1 16 +""" +BINDINGS = """\ +cbuffer entry : register(b0) { uint ud0; uint ud1; uint ud2; }; +ByteAddressBuffer r0 : register(t0); +RWByteAddressBuffer u0 : register(u0); +""" +MAIN = """\ +[numthreads(2, 3, 4)] +void main(uint3 gid : SV_GroupID, uint3 tid : SV_GroupThreadID) { + uint s6 = 0, s9 = 0, s10 = 0, s11 = 0, s13 = 0, s14 = 0, s24 = 0, s25 = 0; + uint v0 = 0, v1 = 0, v2 = 0, v3 = 0, v4 = 0, v5 = 0, v6 = 0; + uint vcc = 0, exec = 1, m0 = 0, a = 0, w = 0; bool scc = false; float4 t = 0; + s9 = gid.x; + s10 = gid.y; + s11 = gid.z; + v0 = tid.x; + v1 = tid.y; + v2 = tid.z; + s13 = 0x00000000u; + s14 = s9; + s9 = 0x00000000u; + s6 = ud2 << (0x00000005u & 31); + scc = s6 != 0; + v3 = (v1 & 0xffffffu) * (0x00000002u & 0xffffffu) + v0; + v3 = (v2 & 0xffffffu) * (0x00000006u & 0xffffffu) + v3; + s24 = s10 * 0x00000003u; + s24 = s24 + s14; + s25 = s11 * 0x00000006u; + s24 = s24 + s25; + s24 = s24 * 0x00000018u; + v3 = s24 + v3; + v4 = v3 << (0x00000002u & 31); + a = v4 + 0; + v5 = r0.Load(a + 0); + v6 = v3 * ud1; + v6 = ud0 + v6; + v5 = v5 * 0x00000021u; + v5 = v5 ^ v6; + a = (v4 + 0) & 0xfffffffcu; + u0.Store(a, v5); +} +""" + + +def root_blob(table_range=False, flags=0x400): + """RTS0: param 0 = three root constants (b0), param 1 = a descriptor table, the resource heap directly indexed. + table_range gives the table one SRV range, as startup_gfx2hlsl_compute_check.root_blob does for a device.""" + params_at, constants_at = 24, 24 + 2 * 12 + table_at = constants_at + 12 + ranges = struct.pack('<6I', 0, 1, 0, 0, 0, 0xffffffff) if table_range else b'' + rts0 = (struct.pack('<6I', 2, 2, params_at, 0, table_at + 8 + len(ranges), flags) + + struct.pack('<3I', 1, 0, constants_at) + struct.pack('<3I', 0, 0, table_at) + + struct.pack('<3I', 0, 0, 3) + struct.pack('<2I', len(ranges) // 24, table_at + 8) + ranges) + part = b'RTS0' + struct.pack('((*static_cast(device))[127])( + device, &heap, D3D12_HEAP_FLAG_NONE, &desc, state, nullptr, nullptr, 0, nullptr, &__uuidof(ID3D12Resource), &resource); + return SUCCEEDED(hr) ? resource : nullptr; +} + +// Case A of startup_gfx2hlsl_compute_check.py through the stand-in's own list: two root constants (word 0 by slot +// 37, word 1 by slot 39; a slot 40 call with other words in between must not reach them), a +// table (slot 35) of two 16-byte hardware buffer descriptors written into the title heap's memory, and Dispatch +// (slot 14) of 3x2x2 groups with the slot 67 placeholder bound. Input and output are placed buffers 64 KiB apart +// in one allocation, so both alias this process's memory and the result is read from that memory after the queue's +// fence. dispatch-swapped exchanges the two descriptors (the output then names the buffer without unordered +// access); dispatch-none records everything but the Dispatch. The 320 output words go to X2W_TEST_DISPATCH_OUT. +// dispatch-sampled adds what the sampling variant of the case reads: a committed 1x1 RGBA8 texture filled by +// CopyTextureRegion (list slot 16) and a shader resource view of it (device slot 18) whose token the stand-in +// writes at table byte 64. dispatch-sampled-unbound creates no view, so that entry holds no token. +// dispatch-heap runs the program of startup_gfx2hlsl_heap_record_check.py: a third root constant, 2, indexes the +// 32-byte heap record that holds the input descriptor (heap byte 64). Heap bytes 0 and 32 hold the output's +// descriptor, so an index that is ignored or scaled by 16 names a buffer the dispatch refuses as an input. +// dispatch-heap-outside sets the constant to 0x07ffffff, whose record is past any heap. +// Controls on the recorded state: dispatch-missing-word leaves out the slot 37 call; dispatch-root-changed sets +// another compute root and the first one again after the constants, dispatch-same-root sets the same root again; +// dispatch-reset closes and resets the list after the constants; dispatch-wrong-root records under the other +// root; dispatch-same-buffer names the output buffer as the input too. +static int dispatch_slot67(void* device, const std::string& mode) +{ + constexpr UINT words = 320; + auto* memory = static_cast(VirtualAlloc(nullptr, 0x20000, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)); + if (!memory) return 70; + UINT* const buffers[2] = {memory, memory + 0x10000 / sizeof(UINT)}; + for (UINT i = 0; i < words; ++i) { + buffers[0][i] = 0x8b02a7f1u + i * 0x413b1u; + buffers[1][i] = 0xc5c5c5c5u; + } + const auto word = [](const void* value) { return reinterpret_cast(value); }; + void* placed[2]{}; + UINT descriptors[2][4]{}; + for (int i = 0; i < 2; ++i) { + const D3D12_RESOURCE_DESC desc{D3D12_RESOURCE_DIMENSION_BUFFER, 0, words * sizeof(UINT), 1, 1, 1, DXGI_FORMAT_UNKNOWN, {1, 0}, + D3D12_TEXTURE_LAYOUT_ROW_MAJOR, i ? D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS : D3D12_RESOURCE_FLAG_NONE}; + if (FAILED(static_cast(invoke(device, 133, word(buffers[i]), word(&desc), D3D12_RESOURCE_STATE_COMMON, 0, + word(&__uuidof(ID3D12Resource)), word(&placed[i]))))) return 71; + const UINT64 address = reinterpret_cast(buffers[mode == "dispatch-same-buffer" ? 1 : i]); + const UINT view[4] = {static_cast(address), static_cast(address >> 32) | 4u << 16, words, 0}; + std::memcpy(descriptors[mode == "dispatch-swapped" ? 1 - i : i], view, sizeof(view)); + } + const struct { + D3D12_DESCRIPTOR_HEAP_DESC desc; + UINT64 backing, bytes; + } heap_desc{{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 4, D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE}, 0, 0}; + void *heap = nullptr, *queue = nullptr, *allocator = nullptr, *list = nullptr, *fence = nullptr; + // dispatch-sampled-compute records the same calls on a compute list and queue. + const D3D12_COMMAND_LIST_TYPE list_type = mode == "dispatch-sampled-compute" ? D3D12_COMMAND_LIST_TYPE_COMPUTE : D3D12_COMMAND_LIST_TYPE_DIRECT; + const D3D12_COMMAND_QUEUE_DESC queue_desc{list_type}; + const UINT list_desc[]{static_cast(list_type), 2, 1, 0}; + if (FAILED(static_cast(invoke(device, 14, word(&heap_desc), word(&__uuidof(ID3D12DescriptorHeap)), word(&heap)))) || + FAILED(static_cast(invoke(device, 8, word(&queue_desc), word(&__uuidof(ID3D12CommandQueue)), word(&queue)))) || + FAILED(static_cast(invoke(device, 9, list_type, word(&__uuidof(ID3D12CommandAllocator)), word(&allocator)))) || + FAILED(static_cast(invoke(device, 73, word(list_desc), word(allocator), 0, word(&__uuidof(ID3D12GraphicsCommandList)), word(&list)))) || + FAILED(static_cast(invoke(device, 36, 0, 0, word(&__uuidof(ID3D12Fence)), word(&fence))))) return 72; + const StreamWord cpu = invoke(heap, 9), gpu = invoke(heap, 10); + if (!cpu || !gpu) return 73; + std::memcpy(reinterpret_cast(cpu), descriptors, sizeof(descriptors)); + const bool heap_record = mode.rfind("dispatch-heap", 0) == 0; + if (heap_record) + for (const UINT at : {0u, 32u, 64u}) + std::memcpy(reinterpret_cast(cpu + at), descriptors[at != 64], sizeof(descriptors[0])); + const UINT constants[3] = {0x01234567, 0x9e3779b9, mode == "dispatch-heap-outside" ? 0x07ffffffu : 2u}; + const UINT graphics[2] = {0xdeadbeef, 0xfeedface}; + const auto bind = [&] { + invoke(list, 32, 1, word(&heap)); + invoke(list, 25, word(slot67_pipeline)); + invoke(list, 33, word(mode == "dispatch-wrong-root" ? slot67_other_root : slot67_root)); + }; + if (FAILED(static_cast(invoke(list, 139, word(allocator))))) return 74; + bind(); + if (mode.rfind("dispatch-sampled", 0) == 0) { + const D3D12_RESOURCE_DESC texture_desc{D3D12_RESOURCE_DIMENSION_TEXTURE2D, 0, 1, 1, 1, 1, DXGI_FORMAT_R8G8B8A8_UNORM, {1, 0}}; + const D3D12_RESOURCE_DESC upload_desc{D3D12_RESOURCE_DIMENSION_BUFFER, 0, 256, 1, 1, 1, DXGI_FORMAT_UNKNOWN, {1, 0}, + D3D12_TEXTURE_LAYOUT_ROW_MAJOR}; + void* const texture = make_committed(device, D3D12_HEAP_TYPE_DEFAULT, texture_desc, D3D12_RESOURCE_STATE_COMMON); + void* const upload = make_committed(device, D3D12_HEAP_TYPE_UPLOAD, upload_desc, D3D12_RESOURCE_STATE_GENERIC_READ); + void* texel = nullptr; + if (!texture || !upload || FAILED(static_cast(invoke(upload, 8, 0, 0, word(&texel)))) || !texel) return 80; + const unsigned char rgba[4] = {255, 64, 128, 32}; // the program reads red: 1.0f + std::memcpy(texel, rgba, sizeof(rgba)); + invoke(upload, 9, 0, 0); + D3D12_TEXTURE_COPY_LOCATION image{static_cast(texture), D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX}; + D3D12_TEXTURE_COPY_LOCATION source{static_cast(upload), D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT}; + source.PlacedFootprint = {0, {DXGI_FORMAT_R8G8B8A8_UNORM, 1, 1, 1, 256}}; + invoke(list, 16, word(&image), 0, 0, 0, word(&source), 0); + D3D12_SHADER_RESOURCE_VIEW_DESC view{DXGI_FORMAT_R8G8B8A8_UNORM, D3D12_SRV_DIMENSION_TEXTURE2D, D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING}; + view.Texture2D.MipLevels = 1; + if (mode != "dispatch-sampled-unbound") invoke(device, 18, word(texture), word(&view), cpu + 64); + } + if (mode != "dispatch-missing-word") invoke(list, 37, 0, constants[0], 0); + invoke(list, 40, 0, 2, word(graphics), 0); + invoke(list, 39, 0, 1, word(&constants[1]), 1); + if (mode == "dispatch-root-changed") invoke(list, 33, word(slot67_other_root)); + if (mode == "dispatch-root-changed" || mode == "dispatch-same-root") invoke(list, 33, word(slot67_root)); + if (mode == "dispatch-reset") { + if (FAILED(static_cast(invoke(list, 9))) || FAILED(static_cast(invoke(list, 139, word(allocator))))) return 74; + bind(); + } + if (heap_record) invoke(list, 39, 0, 1, word(&constants[2]), 2); + invoke(list, 35, 1, gpu); + if (mode != "dispatch-none") invoke(list, 14, 3, 2, 2); + if (FAILED(static_cast(invoke(list, 9)))) return 75; + invoke(queue, 10, 1, word(&list)); + if (FAILED(static_cast(invoke(queue, 14, word(fence), 1)))) return 76; + for (const ULONGLONG deadline = GetTickCount64() + 10000; invoke(fence, 8) < 1;) { + if (GetTickCount64() >= deadline) return 78; + Sleep(1); + } + for (UINT i = 0; i < words; ++i) + if (buffers[0][i] != 0x8b02a7f1u + i * 0x413b1u) return 79; // the input must stay as written + x2w_d3d12_compute_census(); + char path[MAX_PATH]; + const DWORD n = GetEnvironmentVariableA("X2W_TEST_DISPATCH_OUT", path, MAX_PATH); + if (!n || n >= MAX_PATH) return 2; + std::ofstream(path, std::ios::binary).write(reinterpret_cast(buffers[1]), words * sizeof(UINT)); + return 0; +} + +// The image store program of startup_compute_image_store_d16_check.py through the stand-in's own list: a committed +// 32x8 RGBA16_FLOAT texture (device slot 127) filled with sentinel halves by CopyTextureRegion (list slot 16), an +// unordered access view of it (device slot 19) whose token the stand-in writes into the title heap at table byte 64, +// three root constants, Dispatch of 2x1x1 groups, and the texture copied to a readback buffer whose 1024 halves go +// to X2W_TEST_DISPATCH_OUT. texture-store-none records no Dispatch; texture-store-denied creates the texture +// without unordered access, so the stand-in records its view as not created. texture-store-uint makes the texture +// and its view RGBA16_UINT; texture-store-self also creates a shader resource view of the texture at table byte 0. +static int texture_slot67(void* device, const std::string& mode) +{ + constexpr UINT width = 32, height = 8, pitch = width * 8, bytes = pitch * height; + const auto word = [](const void* value) { return reinterpret_cast(value); }; + const auto make = [&](D3D12_HEAP_TYPE type, const D3D12_RESOURCE_DESC& desc, D3D12_RESOURCE_STATES state) { + return make_committed(device, type, desc, state); + }; + const DXGI_FORMAT format = mode == "texture-store-uint" ? DXGI_FORMAT_R16G16B16A16_UINT : DXGI_FORMAT_R16G16B16A16_FLOAT; + const D3D12_RESOURCE_DESC texture_desc{D3D12_RESOURCE_DIMENSION_TEXTURE2D, 0, width, height, 1, 1, format, + {1, 0}, D3D12_TEXTURE_LAYOUT_UNKNOWN, + mode == "texture-store-denied" ? D3D12_RESOURCE_FLAG_NONE : D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS}; + const D3D12_RESOURCE_DESC buffer_desc{D3D12_RESOURCE_DIMENSION_BUFFER, 0, bytes, 1, 1, 1, DXGI_FORMAT_UNKNOWN, {1, 0}, + D3D12_TEXTURE_LAYOUT_ROW_MAJOR}; + void* const texture = make(D3D12_HEAP_TYPE_DEFAULT, texture_desc, D3D12_RESOURCE_STATE_COMMON); + void* const upload = make(D3D12_HEAP_TYPE_UPLOAD, buffer_desc, D3D12_RESOURCE_STATE_GENERIC_READ); + void* const readback = make(D3D12_HEAP_TYPE_READBACK, buffer_desc, D3D12_RESOURCE_STATE_COPY_DEST); + void* memory = nullptr; + if (!texture || !upload || !readback || FAILED(static_cast(invoke(upload, 8, 0, 0, word(&memory)))) || !memory) return 71; + for (UINT i = 0; i < bytes / 2; ++i) static_cast(memory)[i] = static_cast(0x5000 + i); + invoke(upload, 9, 0, 0); + const struct { + D3D12_DESCRIPTOR_HEAP_DESC desc; + UINT64 backing, bytes; + } heap_desc{{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 4, D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE}, 0, 0}; + void *heap = nullptr, *queue = nullptr, *allocator = nullptr, *list = nullptr, *fence = nullptr; + const D3D12_COMMAND_QUEUE_DESC queue_desc{}; + const UINT list_desc[]{D3D12_COMMAND_LIST_TYPE_DIRECT, 2, 1, 0}; + if (FAILED(static_cast(invoke(device, 14, word(&heap_desc), word(&__uuidof(ID3D12DescriptorHeap)), word(&heap)))) || + FAILED(static_cast(invoke(device, 8, word(&queue_desc), word(&__uuidof(ID3D12CommandQueue)), word(&queue)))) || + FAILED(static_cast(invoke(device, 9, D3D12_COMMAND_LIST_TYPE_DIRECT, word(&__uuidof(ID3D12CommandAllocator)), word(&allocator)))) || + FAILED(static_cast(invoke(device, 73, word(list_desc), word(allocator), 0, word(&__uuidof(ID3D12GraphicsCommandList)), word(&list)))) || + FAILED(static_cast(invoke(device, 36, 0, 0, word(&__uuidof(ID3D12Fence)), word(&fence))))) return 72; + const StreamWord cpu = invoke(heap, 9), gpu = invoke(heap, 10); + if (!cpu || !gpu) return 73; + const D3D12_UNORDERED_ACCESS_VIEW_DESC view{format, D3D12_UAV_DIMENSION_TEXTURE2D}; + invoke(device, 19, word(texture), 0, word(&view), cpu + 64); + D3D12_SHADER_RESOURCE_VIEW_DESC read{format, D3D12_SRV_DIMENSION_TEXTURE2D, D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING}; + read.Texture2D.MipLevels = 1; + if (mode == "texture-store-self") invoke(device, 18, word(texture), word(&read), cpu); + D3D12_TEXTURE_COPY_LOCATION image{static_cast(texture), D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX}; + D3D12_TEXTURE_COPY_LOCATION source{static_cast(upload), D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT}; + source.PlacedFootprint = {0, {format, width, height, 1, pitch}}; + D3D12_TEXTURE_COPY_LOCATION result = source; + result.pResource = static_cast(readback); + const UINT constants[3] = {1, 2, 3}; + if (FAILED(static_cast(invoke(list, 139, word(allocator))))) return 74; + invoke(list, 32, 1, word(&heap)); + invoke(list, 16, word(&image), 0, 0, 0, word(&source), 0); + invoke(list, 25, word(slot67_pipeline)); + invoke(list, 33, word(slot67_root)); + invoke(list, 39, 0, 3, word(constants), 0); + invoke(list, 35, 1, gpu); + if (mode != "texture-store-none") invoke(list, 14, 2, 1, 1); + invoke(list, 16, word(&result), 0, 0, 0, word(&image), 0); + if (FAILED(static_cast(invoke(list, 9)))) return 75; + invoke(queue, 10, 1, word(&list)); + if (FAILED(static_cast(invoke(queue, 14, word(fence), 1)))) return 76; + for (const ULONGLONG deadline = GetTickCount64() + 10000; invoke(fence, 8) < 1;) { + if (GetTickCount64() >= deadline) return 78; + Sleep(1); + } + x2w_d3d12_compute_census(); + char path[MAX_PATH]; + const DWORD n = GetEnvironmentVariableA("X2W_TEST_DISPATCH_OUT", path, MAX_PATH); + memory = nullptr; + if (!n || n >= MAX_PATH || FAILED(static_cast(invoke(readback, 8, 0, 0, word(&memory)))) || !memory) return 2; + std::ofstream(path, std::ios::binary).write(static_cast(memory), bytes); + invoke(readback, 9, 0, 0); + return 0; +} + static bool create_slot67(void* device, const char* code_path, const char* data_path, const char* state_path, const char* mode) { std::ifstream code_file(code_path, std::ios::binary), data_file(data_path, std::ios::binary), state_file(state_path, std::ios::binary); @@ -170,6 +386,7 @@ static bool create_slot67(void* device, const char* code_path, const char* data_ std::vector state{std::istreambuf_iterator(state_file), {}}; if (code.empty() || data.empty() || state.empty() || !stream_root_signature()) return false; void* root = stream_root_signature(); + slot67_other_root = root; char root_path[MAX_PATH]; const DWORD n = GetEnvironmentVariableA("X2W_TEST_COMPUTE_ROOT", root_path, MAX_PATH); if (n && n < MAX_PATH) { @@ -218,8 +435,11 @@ static bool create_slot67(void* device, const char* code_path, const char* data_ using Create = HRESULT (WINAPI*)(void*, const void*, REFIID, void**); auto create = [&](const void* d) { void* pipeline = nullptr; - return SUCCEEDED(reinterpret_cast((*static_cast(device))[67])(device, d, __uuidof(ID3D12PipelineState), &pipeline)) && + const bool created = SUCCEEDED(reinterpret_cast((*static_cast(device))[67])(device, d, __uuidof(ID3D12PipelineState), &pipeline)) && pipeline; + slot67_pipeline = pipeline; + slot67_root = root; + return created; }; if (m == "order") { if (!create(desc)) return false; @@ -258,7 +478,8 @@ int main(int argc, char** argv) ComPtr adapter; void* device = nullptr; void* pso = nullptr; - const bool hardware = draw && std::strcmp(argv[4], "hardware") == 0; + const bool hardware = (draw && std::strcmp(argv[4], "hardware") == 0) || + GetEnvironmentVariableW(L"X2W_TEST_DISPATCH_HARDWARE", nullptr, 0) != 0; const bool textured = bc7.blocks != nullptr || GetEnvironmentVariableW(L"X2W_TEST_D16_SRV", nullptr, 0) != 0 || GetEnvironmentVariableW(L"X2W_TEST_FORMATTED_BUFFER", nullptr, 0) != 0 || GetEnvironmentVariableW(L"X2W_TEST_FORMATTED_VIEW", nullptr, 0) != 0 || @@ -266,6 +487,10 @@ int main(int argc, char** argv) if (const int rc = prepare_stream_pipeline(argv[1], argv[2], argv[3], hardware, textured, adapter, device, pso)) return rc; // slot67 [case]: WARP device and root only, then slot-67 creations. + if (argc == 9 && std::strcmp(argv[4], "slot67") == 0 && std::strncmp(argv[8], "dispatch", 8) == 0) + return create_slot67(device, argv[5], argv[6], argv[7], argv[8]) ? dispatch_slot67(device, argv[8]) : 10; + if (argc == 9 && std::strcmp(argv[4], "slot67") == 0 && std::strncmp(argv[8], "texture", 7) == 0) + return create_slot67(device, argv[5], argv[6], argv[7], argv[8]) ? texture_slot67(device, argv[8]) : 10; if ((argc == 8 || argc == 9) && std::strcmp(argv[4], "slot67") == 0) return create_slot67(device, argv[5], argv[6], argv[7], argc == 9 ? argv[8] : "valid") ? 0 : 10; if (GetEnvironmentVariableW(L"X2W_TEST_TRUNCATED_ONLY", nullptr, 0)) return 0; diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index 1c20f5c682..6fd5a09724 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -2708,6 +2708,8 @@ def translate(self): } self.descriptor_block_first = 0 self.uniform_expr = {} # proven VGPR -> uniform HLSL expression over scalars that defined it + self.heap_index = {} # SGPR -> what its word is for a resource-heap s_load (see heap_record) + self.heap_index_was = {} # the marks the current instruction's destinations held before it self.since_join = None # SGPRs proven uniform since the last branch target (None: none reached) self.defined_uniform_s = set(init_entry_uniform) self.bad_sgprs = set() @@ -2736,6 +2738,7 @@ def translate(self): # branch-free program is past it too (dead code). self.past_entry = bool(self.blocks) or 0 in targets if off in targets: + self.heap_index.clear() # another path into the join may hold a different word pre_uniform = { r for r in (self.defined_uniform_s if self.since_join is None else self.since_join) if r not in self.varying_s and r not in self.masks @@ -3027,6 +3030,11 @@ def one(self, name, asm): if sources and all(self.uniform_source(tok) for tok in sources): dst = candidate[1] self.last_v = None + if hasattr(self, 'heap_index'): # unit probes build a Stage without the tracking state + # Any write ends a register's mark; the lowering below sets the new one, if any. + wrote = scalar_destinations(name, asm) + wrote = set(self.heap_index) if 'any' in wrote else wrote & set(self.heap_index) + self.heap_index_was = {r: self.heap_index.pop(r) for r in wrote} term = self.lower(base, asm, ops, mods) uniform_written = self._uniform_written if self.tracks_uniformity() and getattr(self, 'since_join', None) is not None and wrote_s: @@ -3899,6 +3907,15 @@ def known(tok): self.scc_effect = 'a lane-mask complement' if self.tracks_uniformity(): self.scc_uniform = False + if (base == 's_lshl_b32' and hasattr(self, 'heap_index') and re.fullmatch(r'0x[0-9a-f]+|[0-9]+', srcs[1]) + and int(srcs[1], 0) == 5): + # index << 5 is the byte offset of a 32-byte resource-heap record. The index is named only when it is a + # root constant word (the dispatch knows it) or a word an s_buffer_load wrote (refused by name). + r = reg_range(srcs[0]) + if syms[0] and syms[0][0] == 'ud' and self.pipe.uds[syms[0][1]][0] == 'rootconst': + self.heap_index[d] = self.pipe.uds[syms[0][1]] + elif r and r[0] == 's' and {**self.heap_index, **self.heap_index_was}.get(r[1]) == ('bufword',): + self.heap_index[d] = ('buffer',) if is_mask: self.masks.add(d) if pair and base != 's_mov_b64': @@ -4260,8 +4277,31 @@ def op_s_load_dwordx4(self, ops, mods, count=4): self.sym[dst[1] + i] = ('const', 0, 'unassigned') self.pipe.notes.add('dynamic sampler index replaced by a default sampler') return + if p[1] == ('resheap',) and getattr(self, 'kind', None) == 'cs': + return self.heap_record(dst, base, token, imm, count) raise Unsupported('s_load with a register offset through %s' % (p[1],)) + def heap_record(self, dst, base, token, imm, count): + """s_load_dwordx4 D, , R in a compute program, where R is a root constant word + shifted left by 5 with no later write of R and no branch target in between: D is the buffer descriptor in + the 32-byte heap record that the root constant indexes. The manifest names the root constant; the dispatch + reads the record. Only this exact form is modelled.""" + what = 's_load of a resource heap record' + r = reg_range(token) + index = getattr(self, 'heap_index', {}).get(r[1]) if r and r[0] == 's' and r[1] == r[2] else None + if index == ('buffer',): + raise Unsupported('%s whose index is read from a buffer' % what) + if not index or index[0] != 'rootconst': + raise Unsupported('%s whose offset is not a root constant shifted left by 5 since the last branch target' % what) + if count != 4: + raise Unsupported('%s of %d dwords' % (what, count)) + if imm is not None: + raise Unsupported('%s with offset:%#x' % (what, imm)) + if self.sym.get(base[2]) != ('const', 0): + raise Unsupported('%s through a pointer whose high word is not a constant zero' % what) + for i in range(count): + self.sym[dst[1] + i] = ('desc', ('resheap',) + index[1:], 0, i) + def op_s_bfm_b32(self, ops, mods): """Fold constant bitfield masks: titles build inline sampler words with them.""" if len(ops) != 3: @@ -4422,6 +4462,8 @@ def op_s_buffer_load_dword(self, ops, mods, count=1): self.set_s(dst[1] + i, '%s.Load(%s + %d)' % (buf, offset, extra + 4 * i), uniform=uniform) if is_lit: self.sym[dst[1] + i] = ('fixed_buffer_word',) + if hasattr(self, 'heap_index'): + self.heap_index[dst[1] + i] = ('bufword',) def op_s_buffer_load_dwordx2(self, ops, mods): self.op_s_buffer_load_dword(ops, mods, 2) @@ -7897,10 +7939,14 @@ def manifest(self): where = 'table %d %d' % (source[1], off or 0) elif source[0] == 'root': where = 'root %d' % source[1] + elif source[0] == 'resheap' and len(source) == 3 and r['kind'] == 'buf': + where = 'heap rootconst %d %d' % source[1:] # the 32-byte heap record that root constant word indexes else: raise Unsupported('resource through %s' % (source,)) lines.append('srv %d %s %s' % (r['index'], r['kind'], where)) for (source, off), r in self.uavs.items(): + if source[0] != 'table': + raise Unsupported('store through %s' % (source,)) where = 'table %d %d' % (source[1], off) if r['kind'] == 'raw': lines.append('uav %d %s' % (r['index'], where))