From 23848bcf5f24dfc791c9ecbebaab27c2f4abbe21 Mon Sep 17 00:00:00 2001 From: djrolfes Date: Tue, 24 Nov 2026 16:42:55 +0100 Subject: [PATCH 1/2] root_signature: model the compute argument block instead of refusing a spill MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Measured on XboxBvhBuilder.dll's 52 programs (their own RTS0 chunks correlated with their disassembly): when a compute root signature does not fit s4..s31, the console puts its arguments in the block behind s[0:1] — every parameter, inline or not, in the inline layout's widths as bytes (root CBV/SRV/UAV 8 B, descriptor table 4 B, 32-bit constants 4 B each, no alignment). A fitting program reads the block too (its dwordx8/dwordx2 loads align to the same bytes), so the block carries the whole layout for every compute signature. The shader normalizes the 40-bit pointer itself (s3 = s1 & 0xff) and resolves its loads through the arena heap base, so no translator change is involved. pack_stage(Stage::Compute) now lays the block out instead of refusing: per-parameter block dwords, the first spilled parameter, and the block size; other stages keep the refusal (their spill is unmeasured). root_signature_test covers the measured shapes (the 9-parameter builder signature spanning 30 dwords, a fitting one, whole-parameter spills, and the mesh-stage refusal); root_sig_contract.py mirrors the same condition with its tests updated. Claimed in the coordination issue as ROOT-SIG-SPILL-MODEL (issue #14). AI-assisted. --- runtime/shims/d3d12_vulkan_device.cpp | 2 +- runtime/src/root_signature.cpp | 26 +++---- runtime/src/root_signature.h | 34 ++++++---- runtime/test/root_signature_test.cpp | 98 ++++++++++++++++++--------- tests/test_root_sig_contract.py | 40 +++++++++-- tools/root_sig_contract.py | 21 ++++-- 6 files changed, 154 insertions(+), 67 deletions(-) diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp index 94e53cfef8..576dde72a1 100644 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ b/runtime/shims/d3d12_vulkan_device.cpp @@ -16456,7 +16456,7 @@ class Device final layout.graphics_ok = graphics_ok; layout.mesh_ok = pixel.ok && mesh.ok; layout.compute_ok = compute.ok; - if (compute.ok && !compute.spill_dwords) layout.compute_arguments_end = compute.end_sgpr; + if (compute.ok && !compute.spills()) layout.compute_arguments_end = compute.end_sgpr; // Vertex, pixel and geometry shaders share the s8 layout and one user-data block (a non-compute stage // refuses a spill, so pixel.ok means every argument is inline). if (pixel.ok) layout.graphics_arguments_end = pixel.end_sgpr; diff --git a/runtime/src/root_signature.cpp b/runtime/src/root_signature.cpp index 41d3f6c5ae..6897e55035 100644 --- a/runtime/src/root_signature.cpp +++ b/runtime/src/root_signature.cpp @@ -55,14 +55,17 @@ StagePackResult pack_stage(const RootSignature& sig, Stage stage) { out.error = "root signature has more than 64 root parameters"; return out; } + // Only compute's spill is measured (docs/d3d12_vulkan.md section 3.5): a signature that does not fit s4..s31 + // puts its arguments in the block behind s[0:1], in the inline layout's widths as bytes. The other stages + // keep the refusal until one of their programs is measured. + const bool model_spill = stage == Stage::Compute; uint64_t cost = 0; // 64-bit, as in pack() uint64_t next = out.base; - uint64_t spill_next = 0; bool spilling = false; + uint64_t block_dwords = 0; std::vector first; - std::vector spill; first.reserve(sig.params.size()); - spill.reserve(sig.params.size()); + out.block_dword.reserve(sig.params.size()); for (size_t i = 0; i < sig.params.size(); ++i) { const RootParameter& p = sig.params[i]; if (p.type != ParamType::Constants && p.type != ParamType::Descriptor && p.type != ParamType::Table) { @@ -76,27 +79,26 @@ StagePackResult pack_stage(const RootSignature& sig, Stage stage) { } // 0 for a constant parameter of 0 values, which then shares its first SGPR with the next parameter. const uint64_t dwords = stage_dwords(p.type, p.num_values); + // The block carries every parameter in order (measured: a fitting program's reads align to its bytes too, + // so the layer fills the whole block for every compute signature, not only the spilled tail). + out.block_dword.push_back(static_cast(block_dwords)); + block_dwords += dwords; if (!spilling && next + dwords <= kMaxUserSgprs) { first.push_back(static_cast(next)); - spill.push_back(kNoSpill); next += dwords; - } else if (stage == Stage::Compute) { - // Compute packs this parameter and every later one contiguously into the spill array behind s[0:1] - // (docs/d3d12_vulkan.md §3.5 & §7). Total spill stays bounded by kMaxD3d12Cost (<= 64 dwords). + } else if (model_spill) { + if (out.spill_start == kNoSgpr) out.spill_start = static_cast(i); spilling = true; first.push_back(kNoSgpr); - spill.push_back(static_cast(spill_next)); - spill_next += dwords; } else { out.error = "root parameter " + std::to_string(i) + " does not fit in the user SGPRs from s" + - std::to_string(out.base) + " (spill array not modelled)"; + std::to_string(out.base) + " (spill unmeasured for this stage)"; return out; } } out.first_sgpr = std::move(first); - out.spill_dword = std::move(spill); out.end_sgpr = static_cast(next); - out.spill_dwords = static_cast(spill_next); + out.block_dwords = static_cast(block_dwords); out.d3d12_cost = static_cast(cost); out.ok = true; return out; diff --git a/runtime/src/root_signature.h b/runtime/src/root_signature.h index 559f4c54d4..b5d5aeb371 100644 --- a/runtime/src/root_signature.h +++ b/runtime/src/root_signature.h @@ -135,10 +135,10 @@ constexpr uint32_t kMaxD3d12Cost = 64; // signature confirms them yet, and visibility is not modelled (every parameter takes its place in every stage). // The graphics bind point uses Stage::Pixel (s8, as vertex and geometry); a mesh shader reads the same dwords // through its translator-side window (docs/d3d12_vulkan.md section 3.5). -// A parameter that does not fit goes to the console's spill array behind s[0:1] (compute, section 7) together with -// every parameter after it. For compute that packed spill array (1 dword per 32-bit constant, 2 per root descriptor, -// 1 per descriptor table, no alignment padding) is modelled in StagePackResult; non-compute stages still refuse spills -// because their spill pointer SGPR is unmeasured. +// A parameter that does not fit goes to the console's argument block behind s[0:1] (compute, section 7) together +// with every parameter after it; for compute the block is modelled (measured on XboxBvhBuilder.dll's programs): +// the inline layout's widths as bytes, every parameter in root-signature order — see StagePackResult. The other +// stages keep the refusal. enum class Stage : uint32_t { Vertex = 0, Pixel = 1, Geometry = 2, Compute = 3, Mesh = 4 }; [[nodiscard]] constexpr uint32_t stage_base(Stage stage) noexcept { @@ -169,24 +169,32 @@ enum class Stage : uint32_t { Vertex = 0, Pixel = 1, Geometry = 2, Compute = 3, } constexpr uint32_t kNoSgpr = 0xFFFFFFFFu; -constexpr uint32_t kNoSpill = 0xFFFFFFFFu; +constexpr uint32_t kNoBlockDword = 0xFFFFFFFFu; struct StagePackResult { bool ok = false; std::string error; // set when !ok; names the refusing parameter Stage stage = Stage::Compute; - uint32_t base = 0; // stage_base(stage) + uint32_t base = 0; // stage_base(stage) std::vector first_sgpr; // per parameter: its first user SGPR (kNoSgpr when spilled or refused) - std::vector spill_dword; // per parameter: dword offset in s[0:1] spill array (kNoSpill when inline) - uint32_t end_sgpr = 0; // one past the last inline SGPR used: the RSRC2 USER_SGPR count - uint32_t spill_dwords = 0; // total dwords in the packed spill array (0 when nothing spills) - uint32_t d3d12_cost = 0; // cost against the 64-dword D3D12 limit + uint32_t end_sgpr = 0; // one past the last SGPR used: the RSRC2 USER_SGPR count the layout implies + uint32_t d3d12_cost = 0; // cost against the 64-dword D3D12 limit + // The argument block behind s[0:1] (measured on XboxBvhBuilder.dll's programs, docs/d3d12_vulkan.md section 3.5): + // every parameter, inline or not, in root-signature order at the inline layout's widths as bytes — a root + // CBV/SRV/UAV 8 B, a descriptor table 4 B, a 32-bit constant 4 B per value, no alignment. block_dword[i] is + // parameter i's first dword in that block (kNoBlockDword when the signature is refused), block_dwords the + // block's size; it is the full inline span in dwords, whether or not the signature fits s4..s31. + uint32_t spill_start = kNoSgpr; // first parameter that did not fit inline (kNoSgpr: all fit) + std::vector block_dword; // per parameter: first dword in the argument block + uint32_t block_dwords = 0; // the argument block's size, in dwords + [[nodiscard]] bool spills() const { return spill_start != kNoSgpr; } }; // Lays the parameters out for `stage` in the console layout. Fails like pack() on more than 64 parameters, an -// unknown parameter type or the 64-dword cost limit. Compute spills any trailing parameters from the first one -// that does not fit whole into spill_dword; non-compute stages refuse any spill. A constant parameter of 0 values -// takes no SGPRs and no spill dwords. +// unknown parameter type or the 64-dword cost limit. Compute signatures that spill keep every parameter after the +// first non-fitting one out of the inline SGPRs; all compute arguments are laid out into the measured argument +// block instead of refused (non-compute stages refuse any spill because theirs is unmeasured). A constant parameter +// of 0 values takes no SGPRs and no block dwords. [[nodiscard]] StagePackResult pack_stage(const RootSignature& sig, Stage stage); // D3D12 cost of one parameter against the 64-dword limit. diff --git a/runtime/test/root_signature_test.cpp b/runtime/test/root_signature_test.cpp index 8ecf580ef0..d7326584dd 100644 --- a/runtime/test/root_signature_test.cpp +++ b/runtime/test/root_signature_test.cpp @@ -143,7 +143,9 @@ int main() { check(!p.ok && p.error.find("64-dword") == std::string::npos && p.error.find("spill") != std::string::npos, "pack_stage: 64 constants pass the cost limit for a pixel shader (refused only as a spill)"); const StagePackResult c = pack_stage(sig, Stage::Compute); - check(c.ok && c.d3d12_cost == 64 && c.spill_dword == std::vector({0}) && c.spill_dwords == 64, + check(c.ok && c.d3d12_cost == 64 && c.spills() && c.spill_start == 0 && + c.first_sgpr == std::vector({kNoSgpr}) && c.end_sgpr == 4 && + c.block_dword == std::vector({0}) && c.block_dwords == 64, "pack_stage: 64 constants pass the cost limit for compute, spilled whole"); sig.params = {consts(32), consts(0), consts(32)}; check(pack(sig).error.find("spill") != std::string::npos, "32 + 0 + 32 constants cost 64, not more"); @@ -467,64 +469,91 @@ int main() { // An empty signature is valid and uses nothing. const StagePackResult empty = pack_stage(RootSignature{}, Stage::Compute); - check(empty.ok && empty.first_sgpr.empty() && empty.spill_dword.empty() && empty.end_sgpr == 4 && - empty.spill_dwords == 0, + check(empty.ok && empty.first_sgpr.empty() && empty.block_dword.empty() && empty.end_sgpr == 4 && + empty.block_dwords == 0 && !empty.spills(), "pack_stage: empty signature"); } - // Compute spills parameters from the first one that does not fit whole from s4..s31 into the packed spill array - // (s[0:1]); non-compute stages still refuse spills. Compute budget is 28 inline SGPRs above s4, mesh 16 above s16. + // pack_stage: compute lays a non-fitting signature into the measured argument block behind s[0:1] instead of + // refusing; the other stages keep the refusal (their spill is unmeasured). Compute has 28 SGPRs above s4, mesh 16. { RootSignature exact; exact.params = {consts(28)}; - const StagePackResult exact_r = pack_stage(exact, Stage::Compute); - check(exact_r.ok && exact_r.end_sgpr == 32 && exact_r.spill_dwords == 0 && - exact_r.spill_dword == std::vector({kNoSpill}), - "pack_stage: 28 constants fill compute inline SGPRs with no spill"); - + const StagePackResult fill = pack_stage(exact, Stage::Compute); + check(fill.ok && fill.first_sgpr == std::vector({4}) && fill.end_sgpr == 32 && + !fill.spills() && fill.block_dwords == 28 && fill.block_dword == std::vector({0}), + "pack_stage: 28 constants fill compute exactly, block spans all of them"); + // The measured XboxBvhBuilder.dll shape (docs/d3d12_vulkan.md section 3.5): 5 root UAVs, 3 root SRVs and + // 14 constants span 30 dwords from s4 — the descriptors stay inline s4..s19 and the constants go to the + // block, which still holds every parameter in the inline layout's widths as bytes. + RootSignature builder; + builder.params = {view(), view(), view(), view(), view(), view(), view(), view(), consts(14)}; + const StagePackResult b = pack_stage(builder, Stage::Compute); + check(b.ok && b.first_sgpr == std::vector( + {4, 6, 8, 10, 12, 14, 16, 18, rt::rootsig::kNoSgpr}) && + b.spills() && b.spill_start == 8 && b.end_sgpr == 20, + "pack_stage: the builder's 30-dword signature spills its constants parameter"); + check(b.block_dword == std::vector( + {0, 2, 4, 6, 8, 10, 12, 14, 16}) && b.block_dwords == 30, + "pack_stage: the argument block is the inline layout in bytes (descriptors 2 dwords, constants 1)"); + // A fitting signature still gets its block layout (measured: a fitting builder program reads the block). + RootSignature fitting; + fitting.params = {view(), view(), consts(16)}; // span 20 from s4: fits + const StagePackResult f = pack_stage(fitting, Stage::Compute); + check(f.ok && !f.spills() && f.first_sgpr == std::vector({4, 6, 8}) && + f.block_dword == std::vector({0, 2, 4}) && f.block_dwords == 20, + "pack_stage: a fitting signature gets both layouts"); + // A view needs two dwords: it spills whole if only s31 remains. RootSignature over; over.params = {consts(27), view()}; // the view would need s31..s32, so it spills const StagePackResult r = pack_stage(over, Stage::Compute); check(r.ok && r.first_sgpr == std::vector({4, kNoSgpr}) && - r.spill_dword == std::vector({kNoSpill, 0}) && r.end_sgpr == 31 && r.spill_dwords == 2, - "pack_stage: compute parameter that does not fit whole spills at offset 0"); + r.spills() && r.spill_start == 1 && r.end_sgpr == 31 && + r.block_dword == std::vector({0, 27}) && r.block_dwords == 29, + "pack_stage: whole-parameter spill keeps its full-block offset"); RootSignature fits_old; fits_old.params = {consts(30)}; // fits pack()'s 32 from s0, spills on compute from s4 const StagePackResult cs_fits = pack_stage(fits_old, Stage::Compute); check(pack(fits_old).ok && cs_fits.ok && cs_fits.first_sgpr == std::vector({kNoSgpr}) && - cs_fits.spill_dword == std::vector({0}) && cs_fits.end_sgpr == 4 && - cs_fits.spill_dwords == 30, + cs_fits.spill_start == 0 && cs_fits.block_dword == std::vector({0}) && + cs_fits.end_sgpr == 4 && cs_fits.block_dwords == 30, "pack_stage: compute inline budget is 28 from s4; 30 constants spill all 30 dwords"); - // Mixed spill without alignment padding: table (1), root view (2), constants (3) pack at 0, 1, 3. + // The full block has no alignment padding before an odd-dword root view. RootSignature mixed_spill; mixed_spill.params = {consts(26), view(), table(), view(), consts(3)}; const StagePackResult ms = pack_stage(mixed_spill, Stage::Compute); check(ms.ok && ms.first_sgpr == std::vector({4, 30, kNoSgpr, kNoSgpr, kNoSgpr}) && - ms.spill_dword == std::vector({kNoSpill, kNoSpill, 0, 1, 3}) && ms.end_sgpr == 32 && - ms.spill_dwords == 6, - "pack_stage: compute spill packs mixed table, unaligned root view, and constants contiguously"); + ms.block_dword == std::vector({0, 26, 28, 29, 31}) && ms.end_sgpr == 32 && + ms.spill_start == 2 && ms.block_dwords == 34, + "pack_stage: compute block packs mixed table, unaligned root view, and constants contiguously"); // Once one parameter spills, every subsequent parameter spills even if a later 1-dword table would fit in s31. RootSignature monotonic; monotonic.params = {consts(27), view(), table()}; const StagePackResult mr = pack_stage(monotonic, Stage::Compute); check(mr.ok && mr.first_sgpr == std::vector({4, kNoSgpr, kNoSgpr}) && - mr.spill_dword == std::vector({kNoSpill, 0, 2}) && mr.end_sgpr == 31 && - mr.spill_dwords == 3, - "pack_stage: first spilling parameter sends every subsequent parameter to the spill array"); + mr.block_dword == std::vector({0, 27, 29}) && mr.end_sgpr == 31 && + mr.spill_start == 1 && mr.block_dwords == 30, + "pack_stage: first spilling parameter sends every subsequent parameter to the block"); // 64-dword D3D12 cost still holds for spilling compute signatures. RootSignature max64; max64.params = {consts(64)}; const StagePackResult m64 = pack_stage(max64, Stage::Compute); - check(m64.ok && m64.end_sgpr == 4 && m64.spill_dwords == 64 && m64.d3d12_cost == 64, + check(m64.ok && m64.end_sgpr == 4 && m64.spills() && m64.block_dwords == 64 && m64.d3d12_cost == 64, "pack_stage: 64-dword spilled compute signature accepted"); + // Mesh keeps the refusal: its spill is unmeasured. + RootSignature mesh_over; + mesh_over.params = {consts(16), table()}; + check(!pack_stage(mesh_over, Stage::Mesh).ok && + pack_stage(mesh_over, Stage::Mesh).error.find("spill unmeasured") != std::string::npos, + "pack_stage: mesh still refuses a spill (unmeasured), and names the reason"); RootSignature tables; tables.params.assign(20, table()); // one dword each: compute s4..s23; pack() needs 40 - check(pack_stage(tables, Stage::Compute).ok && !pack(tables).ok, + check(pack_stage(tables, Stage::Compute).ok && !pack(tables).ok && !pack_stage(tables, Stage::Compute).spills(), "pack_stage: 20 one-dword tables fit compute, which pack() refuses (40 dwords of tables)"); tables.params.assign(16, table()); // fills mesh s16..s31 exactly check(pack_stage(tables, Stage::Mesh).ok, "pack_stage: 16 tables fill the mesh stage exactly"); @@ -593,20 +622,27 @@ int main() { zero.params = {consts(0)}; const StagePackResult lone = pack_stage(zero, Stage::Compute); check(lone.ok && lone.first_sgpr.size() == 1 && lone.first_sgpr[0] == 4 && lone.end_sgpr == 4 && - lone.spill_dwords == 0, + !lone.spills() && lone.block_dword == std::vector({0}) && lone.block_dwords == 0, "pack_stage: zero-value constants accepted"); zero.params = {consts(1), consts(0), table(), consts(0), consts(26)}; const StagePackResult mixed = pack_stage(zero, Stage::Compute); - check(mixed.ok && mixed.first_sgpr.size() == 5 && mixed.first_sgpr[0] == 4 && mixed.first_sgpr[1] == 5 && - mixed.first_sgpr[2] == 5 && mixed.first_sgpr[3] == 6 && mixed.first_sgpr[4] == 6 && - mixed.end_sgpr == 32 && mixed.spill_dwords == 0 && mixed.d3d12_cost == 1 + 1 + 26, + check(mixed.ok && mixed.first_sgpr == std::vector({4, 5, 5, 6, 6}) && mixed.end_sgpr == 32 && + !mixed.spills() && mixed.block_dword == std::vector({0, 1, 1, 2, 2}) && + mixed.block_dwords == 28 && mixed.d3d12_cost == 1 + 1 + 26, "pack_stage: zero-value constants between others fill compute exactly, offsets unchanged"); - // In the compute spill array a zero-value constant takes no dwords either: the next parameter shares its offset. + // Zero-value constants at the s31 boundary do not spill; a following non-zero parameter spills. + zero.params = {consts(28), consts(0)}; + const StagePackResult boundary = pack_stage(zero, Stage::Compute); + check(boundary.ok && !boundary.spills() && boundary.end_sgpr == 32 && + boundary.block_dword == std::vector({0, 28}) && boundary.block_dwords == 28, + "pack_stage: zero-value constants at s31 boundary do not spill"); + // In the compute argument block a zero-value constant takes no dwords either: the next parameter shares its offset. zero.params = {consts(28), table(), consts(0), consts(1)}; const StagePackResult spilled = pack_stage(zero, Stage::Compute); - check(spilled.ok && spilled.end_sgpr == 32 && - spilled.spill_dword == std::vector({kNoSpill, 0, 1, 1}) && spilled.spill_dwords == 2, - "pack_stage: zero-value constants in the compute spill array take no dwords"); + check(spilled.ok && spilled.first_sgpr == std::vector({4, kNoSgpr, kNoSgpr, kNoSgpr}) && + spilled.end_sgpr == 32 && spilled.spills() && spilled.spill_start == 1 && + spilled.block_dword == std::vector({0, 28, 29, 29}) && spilled.block_dwords == 30, + "pack_stage: zero-value constants in the compute argument block take no dwords"); RootSignature costly; costly.params = {consts(32), consts(33)}; const StagePackResult costly_r = pack_stage(costly, Stage::Compute); diff --git a/tests/test_root_sig_contract.py b/tests/test_root_sig_contract.py index a2230e43a4..cf8c5abbba 100644 --- a/tests/test_root_sig_contract.py +++ b/tests/test_root_sig_contract.py @@ -355,17 +355,47 @@ def test_zero_value_constants_take_no_dwords(): assert error == "" and [(d["param"], d["sub"]) for d in dwords[4:]] == [(1, 0), (1, 1), (3, 0)] dwords, error = rsc.pack_layout({"params": [{"type": "constants", "count": 0}]}, "cs") assert error == "" and len(dwords) == 4 + dwords, error = rsc.pack_layout({"params": [{"type": "constants", "count": 28}, + {"type": "constants", "count": 0}]}, "cs") + assert error == "" and len(dwords) == 32 + dwords, error = rsc.pack_layout({"params": [{"type": "constants", "count": 28}, {"type": "table"}, + {"type": "constants", "count": 0}, + {"type": "constants", "count": 1}]}, "cs") + assert error == "" and len(dwords) == 32 + dwords, error = rsc.pack_layout({"params": [{"type": "constants", "count": 64}]}, "cs") + assert error == "" and len(dwords) == 4 + dwords, error = rsc.pack_layout({"params": [{"type": "constants", "count": 64}]}, "ps") + assert dwords == [] and "spill" in error dwords, error = rsc.pack_layout({"params": [{"type": "constants", "count": -1}]}) assert dwords == [] and "count >= 0" in error -def test_console_layout_spill_refused(): +def test_console_layout_spill_goes_to_the_argument_block(): sig = {"version": "1.1", "flags": 0, "params": [{"type": "table"} for _ in range(17)]} - assert rsc.pack_layout(sig, "ms")[1] != "" # 17 one-dword tables past s31 - sig["params"].pop() - assert rsc.pack_layout(sig, "ms")[1] == "" # 16 fill s16..s31 + dwords, error = rsc.pack_layout(sig, "ms") + assert dwords == [] and "spill unsupported" in error # Graphics spill remains unmeasured. + dwords, error = rsc.pack_layout({"params": [{"type": "constants", "count": 29}]}, "cs") - assert dwords == [] and "param 0" in error and "spill" in error + assert error == "" and len(dwords) == 4 # the whole 29-dword parameter spills: none inline + assert all(slot["param"] is None for slot in dwords) + + +def test_console_spill_does_not_resume_inline_placement(): + sig = {"params": [{"type": "constants", "count": 27}, {"type": "uav"}, {"type": "table"}]} + dwords, error = rsc.pack_layout(sig, "cs") + assert error == "" and len(dwords) == 31 + assert all(slot["param"] == 0 for slot in dwords[4:]) + + +@pytest.mark.parametrize("tail", [ + {"type": "constants", "count": 36}, + {"type": "constants", "count": -1}, + {"type": "constants", "count": True}, + {"type": "ufo"}, +]) +def test_console_spill_still_validates_the_remaining_parameters(tail): + dwords, error = rsc.pack_layout({"params": [{"type": "constants", "count": 29}, tail]}, "cs") + assert dwords == [] and error def test_console_reconcile_fsr_reads(): diff --git a/tools/root_sig_contract.py b/tools/root_sig_contract.py index 30cbe2f707..b4dc0d4dee 100644 --- a/tools/root_sig_contract.py +++ b/tools/root_sig_contract.py @@ -44,8 +44,13 @@ def pack_layout(sig, stage=None): stage None: rt::rootsig::pack (from s0, two dwords per table). A stage from STAGE_BASE: rt::rootsig::pack_stage (from the stage base, one dword per table; dwords below the base are {"param": None, "sub": 0, "ptype": "driver"}). - error is set (and dwords empty) on spill, cost overflow or bad input: - refuse, never truncate. + A compute layout stops at the first parameter that does not fit whole: that + parameter and every later one live in the compute argument block behind + s[0:1] (modelled on XboxBvhBuilder.dll's programs, docs/d3d12_vulkan.md + section 3.5), which this SGPR layout does not list. Other stages keep the + refusal: their graphics spill has not been measured. + error is set (and dwords empty) on a non-compute spill, cost overflow or bad + input: refuse, never truncate. """ if stage is not None and stage not in STAGE_BASE: return [], f"no console base for stage {stage!r}" @@ -59,6 +64,7 @@ def pack_layout(sig, stage=None): base = STAGE_BASE[stage] if stage is not None else 0 dwords = [{"param": None, "sub": 0, "ptype": "driver"} for _ in range(base)] cost = 0 + spilling = False params = [dict(p) for p in raw_params] # normalized copy; input untouched if len(params) > 64: return [], "more than 64 root parameters" @@ -82,10 +88,15 @@ def pack_layout(sig, stage=None): cost += cost_add if cost > 64: return [], "exceeds the 64-dword D3D12 cost limit" + if spilling: + continue # Still validate every later parameter and its cost. if len(dwords) + width > 32: - if stage is not None: - return [], (f"param {index} does not fit in the user SGPRs from s{base} " - "(spill array not modelled)") + if stage == "cs": + # Compute's spill is modelled (docs/d3d12_vulkan.md section 3.5): inline placement stops here and + # every parameter from this one lives in the argument block behind s[0:1] — no SGPR dwords for it. + # The block itself is not part of this SGPR layout; the other stages keep the refusal. + spilling = True + continue return [], "needs more than 32 user SGPRs (spill unsupported)" for sub in range(width): dwords.append({"param": index, "sub": sub, "ptype": ptype}) From 25e5c4e4aa29a9d152602a6d8eaafa87eeaedda0 Mon Sep 17 00:00:00 2001 From: djrolfes Date: Tue, 24 Nov 2026 17:46:12 +0100 Subject: [PATCH 2/2] d3d12: snapshot compute arguments into submission-retained arena blocks Fill inline and block layouts with the correct sub-dword offsets; keep whole-tail compute spills and graphics refusals consistent with the contract tool. Upload immutable host-coherent blocks per dispatch execution, retain them on queue timeline slots, and reject missing upload support or allocation failure during preparation. The pointer is a bounded 40-bit console VA, not raw BDA. Add synthetic packing, replay, rollback/lifetime, native GPU and Windows COM readback tests. No translator change or title-level RT correctness claim. ROOT-SIG-SPILL-MODEL, coordination issue #14. AI-assisted. --- docs/d3d12_vulkan.md | 69 +++++-- docs/design.md | 1 + runtime/CMakeLists.txt | 45 +++++ runtime/shims/d3d12_com.cpp | 43 ++--- runtime/shims/d3d12_com.h | 2 + runtime/shims/d3d12_vulkan_device.cpp | 26 ++- runtime/src/command_list.h | 4 + runtime/src/root_signature.cpp | 10 +- runtime/src/root_signature.h | 7 +- runtime/src/vulkan_backend.h | 24 +++ runtime/src/vulkan_replay.h | 28 +++ runtime/test/d3d12_root_arguments_test.cpp | 189 ++++++++++++++++++++ runtime/test/glsl/cs_root_arguments.comp | 28 +++ runtime/test/queue_root_arguments_test.cpp | 151 ++++++++++++++++ runtime/test/replay_root_arguments_test.cpp | 134 ++++++++++++++ runtime/test/root_signature_test.cpp | 21 ++- runtime/test/vk_root_arguments_test.cpp | 100 +++++++++++ tests/test_root_sig_contract.py | 21 ++- 18 files changed, 842 insertions(+), 61 deletions(-) create mode 100644 runtime/test/d3d12_root_arguments_test.cpp create mode 100644 runtime/test/glsl/cs_root_arguments.comp create mode 100644 runtime/test/queue_root_arguments_test.cpp create mode 100644 runtime/test/replay_root_arguments_test.cpp create mode 100644 runtime/test/vk_root_arguments_test.cpp diff --git a/docs/d3d12_vulkan.md b/docs/d3d12_vulkan.md index 91c4fd3334..11bce966c0 100644 --- a/docs/d3d12_vulkan.md +++ b/docs/d3d12_vulkan.md @@ -869,7 +869,7 @@ The compute path, end to end: and an integer field outside 0..2^32−1 reads as 0. - Root signatures use the model already on `main` (`runtime/src/root_signature.h`, `rt::rootsig`): `parse_rts0` reads the serialized blob and `pack()` lays out the 32 user-data dwords by the section 3.5 default mapping, - refusing anything that would spill. `pack_stage()` lays them out in the console layout of one stage (section 3.5, + refusing graphics spills. `pack_stage()` lays them out in the console layout of one stage (section 3.5, D3D-448); the compute bind point uses it. - **GPU address arena** (section 3.3, when the device has `bufferDeviceAddress`): one host-visible, device-addressable buffer, 256 MiB by default (`LEONIDA_ARENA_MB`, at most 4095 MiB, so every VA fits 32-bit @@ -907,10 +907,11 @@ The compute path, end to end: - **`CreateRootSignature`** parses the blob with `parse_rts0` and keeps each parameter's place in two layouts, both the console's (one dword per table; section 3.5, D3D-448): `pack_stage(Stage::Pixel)` for the graphics bind point (from s8; a signature past s31 there keeps `pack()`'s s0 layout, logged) and `pack_stage(Stage::Compute)` for the - compute one (from s4). It also checks + compute one (from s4, plus the full compute argument block; ROOT-SIG-SPILL-MODEL). It also checks `pack_stage(Stage::Mesh)`: a signature past a mesh shader's 16-dword window is logged, and `DispatchMesh` with it - invalidates the list. A signature neither bind point can place (past s31: the spill layout is open; the - translated shaders have no below-base spill-pointer candidates) is refused with both reasons; one only a single layout places is created with a log line, and binding it at the other bind point + invalidates the list. Compute spills use the measured argument block; graphics spills remain unmeasured. + A signature neither bind point can + place is refused with both reasons; one only a single layout places is created with a log line, and binding it at the other bind point invalidates the list. Before that it answers as the host runtime does (`compare_invalid_arguments`, "root signature:", RTX 5070 / 621.14): `S_FALSE` for a null output whatever the blob, then `E_INVALIDARG` for a node other than node 0 or a DXBC @@ -2031,7 +2032,7 @@ Taken together this disagrees with the packing above (from s0, two dwords per ta in root order from the stage base, each while it fits whole, a constant taking one dword per value, a root CBV/SRV/UAV two (its 64-bit VA), a descriptor table **one** (the 32-bit VA of its first descriptor; the heaps live below 4 GiB). A parameter that does not fit goes, with every later one, to the spill array behind `s[0:1]` -(section 7), which is not modelled, so such a signature is refused. How each part is known: +(section 7). Compute models that block below; other stages still refuse an unmeasured spill. How each part is known: - **Compute, base s4: measured three ways.** - The console compiler's output (section 7). - The package's FidelityFX DLL, whose 29 compute containers carry their `RTS0` next to the console-compiled @@ -2068,13 +2069,45 @@ native Windows, RTX 5080). What mesh shaders read below s16 was counted on the 1 s16; three read one 32-bit constant there (`s13` in one, `s15` in two), never a pointer, and they read it as 0 now. Its meaning is not established. A root signature carries both layouts; one that only one of them can place is created, and binding it at the other bind point invalidates the command list (`Close` returns `E_INVALIDARG`). -`s0..s3` of a compute dispatch are the driver's block; the layer leaves them zero (109 CS read `s1` as a constant, -42 `s3`; their meaning is open). +`s0..s3` of a compute dispatch are the driver's block; the layer supplies the argument block's console VA in +`s[0:1]` and leaves `s2..s3` zero. Other system-value meanings remain open. + +**Compute argument block (ROOT-SIG-SPILL-MODEL).** Correlating the 52 `XboxBvhBuilder.dll` programs with their own +`RTS0` signatures and scalar-load offsets establishes a second convention alongside inline-from-s4: a packed +block behind the 40-bit pointer in `s[0:1]`. It holds **all** parameters, not just the overflowing tail, in signature +order: root CBV/SRV/UAV 8 bytes, constants 4 bytes per value, no alignment. A fitting signature reads the block +too. Four non-fitting signatures have eight root views and 14 constants (30 dwords); their loads agree with that +layout. Descriptor tables use the inline width of 4 bytes in the model; a spilling-table program has **not** +been measured. The synthetic tests exercise that width, not its retail provenance. + +`StagePackResult` exposes block offsets for every compute parameter (at most 64 dwords by the D3D12 cost limit). +A parameter that cannot fit whole and every subsequent parameter have no inline placement. Setters maintain both +copies, including constant sub-offsets and address high words; dispatch and dispatch-kind `ExecuteIndirect` snapshot +the block by value. During preparation, each execution uploads a fresh immutable copy into the host-coherent GPU +address arena, with 64 zero padding bytes for wide scalar reads. Replay supplies its **arena offset**, not raw BDA, +in `s[0:1]`: the translator already adds `heap_base`. The queue keeps the allocation until its command-buffer +timeline ticket completes; failed preparation or submission releases unsubmitted ranges. Separate dispatches, +lists, repeat executions and queues never overwrite a shared signature-owned block. Vulkan's host-write to +queue-submit dependency publishes the coherent pre-submit writes; there is no transfer update requiring a +transfer-to-shader barrier. Missing upload support or allocation failure rejects preparation before GPU emission. + +Checks: `root_signature_test` and `tests/test_root_sig_contract.py` cover packing and malformed tails; +`replay_root_arguments_test` covers snapshots, execution-time pointers, indirect dispatch and refusal paths; +`queue_root_arguments_test` checks timeline retention, two queues and preparation/submission failure rollback; +`vk_root_arguments_test` checks the same upload/replay contract with native GPU readback and validation; +`d3d12_root_arguments_test` reads back fitting and spilling blocks through the shader contract, partial setters, +two logical queues, direct/indirect/counted dispatches and repeat execution. These are synthetic tests, **not** +proof that the title's RT startup works. In particular, the meaning of `s4` as a system value in block-reading +builder programs is settled by their dispatch headers, not root packing: all 52 declare four user SGPRs, +TGID_X enabled and TG_SIZE disabled. `s4` is therefore `WorkgroupId.x`; the translator's existing compute +prologue overwrites the push-constant copy there. All 52 generated modules were checked for that initialization, +including the four with non-fitting signatures (local size 32). No translator change or runtime s4 override is +needed for this system input. Inline-from-s4 remains the separate convention used by the FidelityFX signatures. **Measured: a real signature beside the count it produced.** `tools/fspx_unpack.py` decodes `COMPUTE_PGM_RSRC2` of each of the 29 compute programs in `amd_fidelityfx_upscaler_xbox.dll`, and its `USER_SGPR` field is the count the -console launched the dispatch with. Every one of those 29 containers also carries an `RTS0`, which makes this the -only place in the package where a serialized root signature sits beside the dword count it produced +console launched the dispatch with. Every one of those 29 containers also carries an `RTS0`, so a serialized +root signature sits beside the dword count it produced (`tools/rootsig_census.py`). The game's own 26,503 containers carry no `RTS0`, so their read sets cannot be joined with a signature and cannot settle it either. @@ -2108,9 +2141,8 @@ Still open: which CBV index lands in which pair. The four pairs do appear in dec package proves that order, and every parameter in these 29 is `D3D12_SHADER_VISIBILITY_ALL`, so they say nothing about the visibility question below. -Spill policy: a signature needing more than 32 user SGPRs, or more than the 64-dword D3D12 cost limit, is -refused loudly (`pack` returns the offending parameter) instead of being truncated. The console spills through -`__XB_GetRootSignatureSpillPointer`; until that layout is measured, refusing is the only correct behaviour. +Spill policy: compute uses the measured argument block above; graphics spills and signatures exceeding the +64-dword D3D12 cost limit are still refused, never truncated. `pack()` remains the legacy graphics mapping. Measured (D3D-315): zero below-base spill-pointer candidates in the translated shaders. `python -I tools/root_spill_census.py --carve --expect-no-spill` exits 0 on @@ -2137,7 +2169,8 @@ What this does not settle: - **A spill behind a pointer at or above the base.** It reads the same as a table pointer, so the census can't tell the two apart. -The spill layout stays unimplemented: no shader in the translated set reads a candidate a spill could sit behind. +That census covers the main shader set, not the embedded builder programs measured above; it does not contradict +their argument-block reads. Reconciliation: `tools/root_sig_contract.py` checks a candidate root signature against every shader's `user_sgpr_reads` from `spirv/index.json` (const32 vs constant dwords, 64-bit VAs vs view/table pairs) and fails @@ -2232,12 +2265,10 @@ Things that can invalidate this simple model, all **Open**: so the executable's pipeline table would settle it; `tests/test_user_sgpr_census.py` shows that the two models give different counts. Mesh shaders (base s16) and the compute signatures are not covered here. - **Root signature larger than 32 dwords.** D3D12 allows up to 64 dwords. The console has 32 user SGPRs, so a - driver must spill the rest to memory, probably behind a pointer in the user data. The current shader contract has - no representation for that. The likely answer is that this game keeps its root signatures small (bindless - descriptors, a few constants), but it must be measured. If a large root signature appears, the spill layout has - to be reverse-engineered from the shader's loads. Measured on the shader side (D3D-315, spill policy above): - zero below-base spill-pointer candidates in the translated shaders. The root signatures themselves, and how many - exceed the budget, are still to be dumped from the executable. + driver must spill non-fitting parameters to memory. The compute block behind s[0:1] is now measured and + modelled above, including embedded builder programs that use it even when the signature fits. Graphics spill + layout and a census of runtime-created title signatures remain open. The D3D-315 census above covers the main + shader set, not those embedded programs. - **Direct heap indexing.** The bound heap base and stride are not root parameters. Measured (D3D-329, section 3.4): each heap's base reaches the shader as a 32-bit pointer in an entry SGPR, inside the user data for compute (and below `s32` for the graphics stages, whose user count is not measured yet), and the stride is compiled into diff --git a/docs/design.md b/docs/design.md index ebee74ad03..baf6b2cbb2 100644 --- a/docs/design.md +++ b/docs/design.md @@ -308,6 +308,7 @@ How the generated SPIR-V expects the runtime to work: | `s_*_saveexec_b32/b64`, `s_andn1/andn2_wrexec_b32/b64` | RDNA2 ISA SOP1. saveexec: `D = EXEC; EXEC = f(S0, EXEC); SCC = (EXEC != 0)`. wrexec: `EXEC = f(S0, EXEC); D = EXEC`. `f` is one of `and`, `or`, `xor`, `andn1` (`~S0 & EXEC`), `andn2` (`S0 & ~EXEC`), `orn1` (`~S0 \| EXEC`), `orn2` (`S0 \| ~EXEC`), `nand`, `nor`, `xnor`, the table in `Gen.EXEC_LOGIC`. The definitions match `tools/cf_ref.py` `_SAVEEXEC`, the FUZZ-8 model. Each invocation holds its own lane's bit (0 or ~0), so `f` is the bitwise op on that bit. A lane EXEC had off becomes active when `f` gives 1 for it (`nand`, `nor`, `orn1`, `orn2`, `xnor`, ...), as on hardware, and SCC is the wave vote. Until 2026-11-22 only `and`/`or`/`andn2_saveexec` and `andn2_wrexec` were translated. CPU-checked by `tests/semantic/test_saveexec_variants.py` (all ten saveexec kinds in wave32 and wave64, both wrexec kinds, partial EXEC and S0, an empty result, every lane against `cf_ref._SAVEEXEC`) and by `tools/cf_diff.py` (300 programs × wave32/64 still pass). Hardware-verified on native RDNA2 (`gfx1036`, Windows 11, driver `32.0.21045.29003`, wave32 & wave64, 0 mismatches): all 10 `saveexec` kinds and both `wrexec` kinds (`andn1`/`andn2`) match bit-for-bit on non-symmetric masks (`src0 = 0x0F0F0F0F`, `exec = 0x33333333` in wave32; `0x0F0F0F0F_00FF00FF` / `0x33333333_55555555` in wave64), zero-result `SCC = 0`, wave64 upper-32-bit-only `new_exec = 0x00000001_00000000` setting `SCC = 1`, and `sdst == src0` register aliasing (`s4, s4` and `s[4:5], s[4:5]`) reading original `src0` before writing old `EXEC` to `sdst`. **Not GPU-verified** for the seven new kinds. Measured on native gfx1100 (single 8-lane workgroup, 36 programs): all ten `saveexec` kinds and both `wrexec` forms follow `f` for three `S0`/`EXEC` pairs, including lanes `EXEC` had off being switched back on (`nand` with `S0=0x03`, `EXEC=0x0F` leaves `0xFFFFFFFC`, activating lanes 4-7), `D` holding the old `EXEC` for `saveexec` and the new one for `wrexec`, and `SCC` the `EXEC != 0` vote. | | Control flow | Reducible graphs use structured branches and natural loops. Irreducible graphs use the dispatch-loop form, which can also be forced with `--dispatch-loop` for comparisons. The control-flow unit test checks 18,228 generated graphs. Irreducible graphs use node splitting (`cfg_structure.split_irreducible`, up to `min(2*N, N+64)` blocks) and fall back to the dispatch-loop form when capped; it can also be forced with `--dispatch-loop` for comparisons. `cfg_structure.structure`, `cfg_structure.run`, and `rdna2spirv.assemble`'s structured emitter are iterative and hoist each guarded member's dominated tail continuation out of its enclosing guard (exact by strict dominance: no block outside the guard's subtree can target the continuation), keeping `OpSelectionMerge` nesting O(1) on sequential diamond/loop chains instead of nesting O(N) deep and hitting Python's recursion limit on multi-thousand-block shaders (e.g. 2,000 sequential diamonds nest to depth 2 instead of 2,000). The control-flow unit test (`tests/test_cfg_structure.py`) checks 20,000 generated graphs plus 2,000-diamond, 1,200-loop, and 1,500-early-exit chains. `capped_tree()` also runs `cfg_structure.unwrap_known_pc_guards` (shared with `wave64_emulate_opt`) to unwrap tautological `("guard", g, ...)` nodes whenever abstract interpretation proves `%pc == g` on all incoming paths (e.g. post-dominating merge blocks after diamonds and loops); this keeps `ms_wave_info_s3`'s `s_barrier` in uniform top-level control flow (fixing an AMD Windows LLPC `0xC0000005` pipeline-creation crash on AMD Ryzen 5 7600 RDNA2 iGPU driver `24.10.24`, `4096/4096` exact on AMD RDNA2 and RTX 4070 SUPER) and avoids false `needs_barrier_rounds` triggers (`SHADER-STRUCTURED-PC-UNWRAP`). AMD A/B checks compare the two forms for selected pixel shaders with defined test inputs. For shaders that never export colour, the comparison checks pixel coverage. **Nesting is bounded (SHADER-299):** a tree deeper than `MAX_STRUCTURED_DEPTH` (16) is emitted in the dispatch-loop form instead, since `spirv-val` time grows roughly with the cube of the measured nesting depth. **Nesting is bounded (SHADER-299, SHADER-427):** a tree deeper than `MAX_STRUCTURED_DEPTH` (64; `--max-structured-depth N`, 0 = no bound) is emitted in the dispatch-loop form instead, since `spirv-val` time grows roughly with the cube of the measured nesting depth. Before #1904, over the 1.0.2.1 corpus (26,503 modules, `spirv-val` 2026.4): the deepest block of a module is nested 118 constructs deep, 12,963 modules are structured (median 15) and 6,000 of those are deeper than 16; an estimated 85% of the corpus's `spirv-val` time is in modules nested 20 or deeper. Median `spirv-val` time for the same module in each form: depth 20 181 -> 129 ms (1.4x), 30 507 -> 371 (1.4x), 50 1,712 -> 738 (2.3x), 64 2,692 -> 1,163 (2.3x), 77 5,122 -> 1,130 (4.5x), and the deepest (118) 13,683 -> 1,352 ms (10.1x). Depth 5-12 shows no gain (at depth 6 the flat form is slightly slower), which is why the bound first sat at 16. Since #1904 (`cfg_structure` hoists tails) the deepest tree in the corpus is 29: of 12,944 structured modules, 1,031 are deeper than 16 (747 CS, 284 PS), 57 deeper than 20, 24 deeper than 24. For those 1,031 the flat form saves only 12% of `spirv-val` time (1,235 -> 1,091 s summed, slowest module 8.3 -> 5.9 s), while on an RTX 5070 Ti (NVIDIA 621.24) it compiles slower: the 284 pixel shaders 1.67x (827 -> 1,382 s summed, two rounds), four compute modules at depth 19-24 2.0x (297 -> 591 s, 1.6-2.7x each), so the bound now sits above the corpus (SHADER-427). Both forms pass `spirv-val` on a 200-shader slice (200/200 each), and `gen.nesting` records the tree depth. AMD's Windows driver adds a reason to keep the structured form (SHADER-995): on a Radeon gfx1036 iGPU (32.0.21042.62) the dispatch-loop module of `XboxBvhBuilder.dll`'s `LeafRehydration` (tree depth 18, a 581-case switch) takes 34 minutes to create (XXDESIGN), where its structured module is created in 2.9 s; ten other programs of that DLL compile in the dispatch-loop form there in 0.4-40 s, 2.5-5x their structured time ([embedded_shaders.md](embedded_shaders.md), section 7). | | Loop guard | Each loop counts header visits per invocation and exits through its structured merge at `--loop-limit N` (default 65536, zero disables). Counters reset on entry, including nested EXEC retries and atomic loops. A PC-dispatch visit counts a dispatch iteration. Natural exits within the budget preserve their outputs. Five-star-recomp (b12a952) reported a story-load timeout when the shader input made its exit condition unreachable. | +| Compute argument block | Compute supplies the packed argument block's console VA in s[0:1], measured against embedded builder signatures and loads. All explicit root arguments are stored in root order at their inline widths, including arguments that fit in SGPRs. The storage is immutable per execution and retained until GPU completion; synthetic setter, replay, queue-lifetime and GPU readback tests cover the contract ([d3d12_vulkan.md §3.5](d3d12_vulkan.md#35-root-signature-to-user-sgprs), ROOT-SIG-SPILL-MODEL). Graphics spills remain unmeasured. | | User data | **Push constants, 144 bytes:** dwords 0–31 = initial s0–s31 (the user SGPRs the console driver loads from the root signature: descriptor-table pointers, constants and so on), dwords 32–33 = the 64-bit **heap base**, dwords 34–35 = the **code base**: the Xbox VA where the runtime uploaded this shader's whole FSSM blob. `--mesh-compute` modules add dwords 36–37, the output buffer address (152 bytes; see "Mesh shaders as compute"). `--pc-tail-ubo` keeps only dwords 0–31 here (128 bytes) and moves the rest to a uniform block (see "Push-constant tail as a uniform block"). The runtime has to reproduce the console driver's root-signature-to-user-SGPR mapping; that comes from the exe or driver behaviour. **Mesh shaders** read their root SGPRs through the graphics root window: s16..s31 come from dwords 8..23 (where a VS, PS or GS reads s8..s23), s8..s15 are 0, s0..s7 dwords 0..7; the index records `"root_window": {"sgpr": 16, "dword": 8}` (D3D-448-GRAPHICS, `docs/d3d12_vulkan.md` 3.5). Checked by `tests/semantic/test_ms_root_window.py` (MeshEXT and `--mesh-compute`, CPU interpreter) and `d3d12_mesh_test` (RX 9070 XT). | | Direct resource heap | In the matched Prop/Tree BatchCull compute signature the two explicit tables and scalar constant occupy s4–s6. Bind the resource heap's uint32 arena-relative byte address at s7 (push-constant byte 28). The program supplies a zero high word and scales the resource index by 32 bytes. Other stages and signatures consume different SGPRs. See [descriptor heaps and the bindless model](d3d12_vulkan.md#34-descriptor-heaps-and-the-bindless-model) for the evidence and graphics examples. | | Xbox GPU addresses | Shaders build Xbox GPU virtual addresses, and some force the high dword to 0 (descriptor tables in the low 4 GB). Every memory access goes to **heap base + Xbox VA**, so the runtime maps the console's GPU address window into one host buffer-device-address allocation. | diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt index e68ef6c718..436d4f4b6f 100644 --- a/runtime/CMakeLists.txt +++ b/runtime/CMakeLists.txt @@ -3816,6 +3816,28 @@ if(TARGET Vulkan::Headers) set_tests_properties(d3d12_rebound_tables_off PROPERTIES SKIP_RETURN_CODE 77 ENVIRONMENT "LEONIDA_DESC_MIRROR=0") add_test(NAME d3d12_rebound_second_device COMMAND d3d12_title_va_test --rebound-second-device) set_tests_properties(d3d12_rebound_second_device PROPERTIES SKIP_RETURN_CODE 77 ENVIRONMENT "LEONIDA_DESC_MIRROR=1") + foreach(size small large) + if(size STREQUAL "small") + set(root_constants 8) + else() + set(root_constants 27) + endif() + set(LEONIDA_ROOT_${size}_SPV ${CMAKE_CURRENT_BINARY_DIR}/generated/cs_root_${size}.spv) + add_custom_command(OUTPUT ${LEONIDA_ROOT_${size}_SPV} + COMMAND ${Vulkan_GLSLANG_VALIDATOR_EXECUTABLE} -V --target-env vulkan1.3 + -DROOT_CONSTANTS=${root_constants} -o ${LEONIDA_ROOT_${size}_SPV} + ${CMAKE_CURRENT_SOURCE_DIR}/test/glsl/cs_root_arguments.comp + DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/test/glsl/cs_root_arguments.comp VERBATIM) + endforeach() + add_executable(d3d12_root_arguments_test test/d3d12_root_arguments_test.cpp + ${LEONIDA_ROOT_small_SPV} ${LEONIDA_ROOT_large_SPV}) + target_link_libraries(d3d12_root_arguments_test PRIVATE gta6rt_d3d12_com) + target_compile_definitions(d3d12_root_arguments_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX + LEONIDA_ROOT_SMALL_SPV="${LEONIDA_ROOT_small_SPV}" LEONIDA_ROOT_LARGE_SPV="${LEONIDA_ROOT_large_SPV}") + target_compile_options(d3d12_root_arguments_test PRIVATE /W4 /permissive- /utf-8) + add_test(NAME d3d12_root_arguments COMMAND d3d12_root_arguments_test) + set_tests_properties(d3d12_root_arguments PROPERTIES SKIP_RETURN_CODE 77 + FAIL_REGULAR_EXPRESSION "Validation Error;VUID-") # Compute PSOs from FSPX programs (docs/fspx.md): an ACCC container at slot 62 and a bare kind-6 program. add_executable(d3d12_fspx_compute_test test/d3d12_fspx_compute_test.cpp shims/d3d12_xs_device.cpp shims/d3d12_xs_pso_stream.cpp ${LEONIDA_TEST_CS}) target_link_libraries(d3d12_fspx_compute_test PRIVATE gta6rt_d3d12_com) @@ -4403,6 +4425,29 @@ if(TARGET Vulkan::Headers) add_test(NAME replay_khr_as_copy_postbuild COMMAND replay_khr_as_copy_postbuild_test) # PreparedList::wrote_readback and readback_src_stages match the actual producer stage (depth24, rgb96, UAV clear; no GPU). add_executable(replay_readback_stages_test test/replay_readback_stages_test.cpp) + add_executable(replay_root_arguments_test test/replay_root_arguments_test.cpp) + target_link_libraries(replay_root_arguments_test PRIVATE Vulkan::Headers) + add_test(NAME replay_root_arguments COMMAND replay_root_arguments_test) + add_executable(queue_root_arguments_test test/queue_root_arguments_test.cpp) + target_link_libraries(queue_root_arguments_test PRIVATE Vulkan::Headers) + add_test(NAME queue_root_arguments COMMAND queue_root_arguments_test) + find_program(LEONIDA_ROOT_GLSLANG glslangValidator HINTS "$ENV{VULKAN_SDK}/Bin" "$ENV{VULKAN_SDK}/bin") + if(LEONIDA_ROOT_GLSLANG) + set(LEONIDA_ROOT_NATIVE_SPV ${CMAKE_CURRENT_BINARY_DIR}/generated/cs_root_native.spv) + add_custom_command(OUTPUT ${LEONIDA_ROOT_NATIVE_SPV} + COMMAND ${LEONIDA_ROOT_GLSLANG} -V --target-env vulkan1.3 -o ${LEONIDA_ROOT_NATIVE_SPV} + ${CMAKE_CURRENT_SOURCE_DIR}/test/glsl/cs_root_arguments.comp + DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/test/glsl/cs_root_arguments.comp VERBATIM) + add_executable(vk_root_arguments_test test/vk_root_arguments_test.cpp ${LEONIDA_ROOT_NATIVE_SPV}) + target_link_libraries(vk_root_arguments_test PRIVATE Vulkan::Headers ${CMAKE_DL_LIBS}) + target_compile_definitions(vk_root_arguments_test PRIVATE LEONIDA_ROOT_NATIVE_SPV="${LEONIDA_ROOT_NATIVE_SPV}") + if(WIN32) + target_compile_definitions(vk_root_arguments_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + endif() + add_test(NAME vk_root_arguments COMMAND vk_root_arguments_test) + set_tests_properties(vk_root_arguments PROPERTIES SKIP_RETURN_CODE 77 + FAIL_REGULAR_EXPRESSION "Validation Error;VUID-") + endif() target_link_libraries(replay_readback_stages_test PRIVATE Vulkan::Headers) if(WIN32) target_compile_definitions(replay_readback_stages_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) diff --git a/runtime/shims/d3d12_com.cpp b/runtime/shims/d3d12_com.cpp index 4a61ffadbc..c570f61ccd 100644 --- a/runtime/shims/d3d12_com.cpp +++ b/runtime/shims/d3d12_com.cpp @@ -1451,6 +1451,7 @@ class GraphicsCommandList final struct RootState { const RootArgumentLayout* layout = nullptr; std::array data{}; + std::vector block; }; // D3D12 leaves root arguments undefined after a root-signature change; they start at zero here. Setting the @@ -1472,6 +1473,7 @@ class GraphicsCommandList final state.layout = layout; if (layout && (layout->flags & D3D12_ROOT_SIGNATURE_FLAG_CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED)) directly_indexed_ = true; state.data = {}; + state.block.assign(is_compute(state) && layout ? layout->block_dwords : 0, 0); // CreateRootSignature accepted it for the other bind point only (its log line says why). if (layout && !(is_compute(state) ? layout->compute_ok : layout->graphics_ok)) { stub(is_compute(state) ? "SetComputeRootSignature(signature that does not fit the compute layout)" @@ -1497,12 +1499,18 @@ class GraphicsCommandList final return &state.layout->parameters[index]; } - // Dwords beyond the 32 user registers are what the console spills to memory; that layout is still open. - void write(RootState& state, std::uint32_t dword, std::uint32_t value) { - if (dword < rt::rootsig::kMaxUserSgprs) - state.data[dword] = value; - else - stub("root arguments beyond 32 user-data dwords (spill not modelled)"); + // Preserve the sub-dword for both copies (constants with offsets, and both halves of a root view). + void write(RootState& state, const RootArgumentLayout::Parameter& p, std::uint32_t sub, std::uint32_t value) { + const auto first = first_dword(state, p); + if (first != rt::rootsig::kNoSgpr) { + if (first >= state.data.size() || sub >= state.data.size() - first) return check(false); + state.data[first + sub] = value; + } + if (is_compute(state)) { + if (p.block_offset >= state.block.size() || sub >= state.block.size() - p.block_offset) + return check(false); + state.block[p.block_offset + sub] = value; + } } void constants(RootState& state, UINT index, UINT count, const void* data, UINT offset) { @@ -1524,19 +1532,7 @@ class GraphicsCommandList final if (!p) return; if ((count && !data) || std::uint64_t(offset) + count > p->constant_count) return check(false); const auto* values = static_cast(data); - const std::uint32_t first = first_dword(state, *p); - if (first == rt::rootsig::kNoSgpr) return spilled(); - for (UINT i = 0; i < count; ++i) write(state, first + offset + i, values[i]); - } - - // A parameter in the spill array behind s[0:1] (a compute signature past s31: pack_stage gives it no SGPR, only a - // spill_dword): that array is not written yet, so its value is not stored; kNoSgpr plus an offset must never - // reach write(), where it would wrap round to s0. - static void spilled() { - static std::atomic said{false}; - if (!said.exchange(true)) - std::fprintf(stderr, "[rt] d3d12: root arguments in the spill array behind s[0:1] are not stored (the " - "array is not written yet)\n"); + for (UINT i = 0; i < count; ++i) write(state, *p, offset + i, values[i]); } void address(RootState& state, UINT index, std::uint64_t va, rt::rootsig::ParamType type) { @@ -1563,13 +1559,11 @@ class GraphicsCommandList final } if (type != rt::rootsig::ParamType::Descriptor && va && p->table_descriptors) remember_table(va, p->table_descriptors); - const std::uint32_t first = first_dword(state, *p); - if (first == rt::rootsig::kNoSgpr) return spilled(); - write(state, first, std::uint32_t(va)); + write(state, *p, 0, std::uint32_t(va)); // In the console layouts a descriptor table is one dword, the 32-bit VA of its first descriptor (the heaps // live below 4 GiB); a root view keeps both halves. pack()'s graphics layout gives every address two dwords. const bool console = is_compute(state) || state.layout->graphics_console; - if (!(console && type == rt::rootsig::ParamType::Table)) write(state, first + 1, std::uint32_t(va >> 32)); + if (!(console && type == rt::rootsig::ParamType::Table)) write(state, *p, 1, std::uint32_t(va >> 32)); } D3D12_COMMAND_LIST_TYPE type_; @@ -2001,7 +1995,7 @@ class GraphicsCommandList final std::fputc('\n', stderr); } } - check(list_.dispatch({compute_pipeline_, compute_user_data(), x, y, z})); + check(list_.dispatch({compute_pipeline_, compute_user_data(), x, y, z, compute_.block})); } // The views block a draw records. Rebuilt only when the render targets or the bound vertex buffers change. @@ -2112,6 +2106,7 @@ class GraphicsCommandList final note_direct_heap_indexing(compute_.layout); cmd.pipeline = compute_pipeline_; cmd.user_data = compute_user_data(); + cmd.root_arguments = compute_.block; } check(list_.execute_indirect(cmd)); } diff --git a/runtime/shims/d3d12_com.h b/runtime/shims/d3d12_com.h index bb8efa815b..52f4bfcbf0 100644 --- a/runtime/shims/d3d12_com.h +++ b/runtime/shims/d3d12_com.h @@ -562,6 +562,7 @@ struct RootArgumentLayout { // (src/title_va_alias.h) and the submission-time heap refresh. Views are capped at 1024 slots (an unbounded // range counts as 1024) and samplers at the shader-visible sampler heap limit. 0: not a table. std::uint32_t table_descriptors = 0; + std::uint32_t block_offset = rt::rootsig::kNoBlockDword; // compute argument-block dword }; std::vector parameters; std::uint32_t flags = 0; // D3D12_ROOT_SIGNATURE_FLAGS from the serialized blob @@ -577,6 +578,7 @@ struct RootArgumentLayout { // spill, or graphics keeps pack()'s s0 layout). std::uint32_t compute_arguments_end = rt::rootsig::kNoSgpr; std::uint32_t graphics_arguments_end = rt::rootsig::kNoSgpr; + std::uint32_t block_dwords = 0; // full compute layout, including inline parameters; at most 64 }; // For the command list: the argument layout of a root signature from a Vulkan device, and the id it records for a diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp index 576dde72a1..82c777c335 100644 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ b/runtime/shims/d3d12_vulkan_device.cpp @@ -13693,6 +13693,24 @@ class Device final }; leonida::mem_probe::start(std::move(facts)); } + state_.context->set_root_argument_upload( + [this](std::span words, std::uint64_t& va) -> std::shared_ptr { + if (words.empty() || words.size() > rt::rootsig::kMaxD3d12Cost || !state_.arena.mapped) + return {}; + // Immutable per dispatch and per submission. Wide scalar loads may read past the last argument; + // keep one dwordx16 of zeroed padding within this allocation. + const VkDeviceSize bytes = words.size_bytes() + 64; + VkDeviceSize offset = 0; + if (!state_.arena_allocate(bytes, 16, offset, DeviceState::arena_buffer)) return {}; + auto owner = std::shared_ptr(state_.arena.mapped + offset, [this, offset, bytes](void*) { + state_.arena_release(offset, bytes, DeviceState::arena_buffer); + }); + std::memcpy(state_.arena.mapped + offset, words.data(), words.size_bytes()); + std::memset(state_.arena.mapped + offset + words.size_bytes(), 0, 64); + // Translated loads add heap_base themselves: s[0:1] is a console VA, never a raw Vulkan BDA. + va = offset; + return owner; + }); if (info.conditional_rendering) { const auto properties = reinterpret_cast( info.get_instance_proc(info.instance, "vkGetPhysicalDeviceProperties")); @@ -16406,8 +16424,8 @@ class Device final if (container_size != size) return E_INVALIDARG; } // The repository's root-signature model (runtime/src/root_signature.h): parse the RTS0 blob, then pack - // the parameters into the 32 user-data dwords in the console layout. pack_stage() refuses what it cannot - // place (past s31: the console spills those to memory, in a layout that is still open), and so does this. + // the parameters into the 32 user-data dwords in the console layout and a full compute argument block. + // Non-compute spills remain unmeasured and are refused, never silently truncated. const rt::rootsig::DecodeResult parsed = rt::rootsig::parse_rts0(bytes, size); if (!parsed.ok) { std::fprintf(stderr, "[rt] d3d12: root signature not understood: %s\n", parsed.error.c_str()); @@ -16473,8 +16491,10 @@ class Device final } layout.parameters.push_back({parsed.sig.params[i].type, first, parsed.sig.params[i].num_values, compute.ok ? compute.first_sgpr[i] : rt::rootsig::kNoSgpr, - table_descriptor_count(parsed.sig.params[i])}); + table_descriptor_count(parsed.sig.params[i]), + compute.ok ? compute.block_dword[i] : rt::rootsig::kNoBlockDword}); } + layout.block_dwords = compute.ok ? compute.block_dwords : 0; register_static_samplers(parsed.sig); auto* signature = new RootSignature( std::move(layout), leonida::sha256_hex({static_cast(blob), size})); diff --git a/runtime/src/command_list.h b/runtime/src/command_list.h index d7d7396408..226e1cb1ca 100644 --- a/runtime/src/command_list.h +++ b/runtime/src/command_list.h @@ -381,6 +381,9 @@ struct Dispatch { std::uint32_t x; std::uint32_t y; std::uint32_t z; + // Full console compute root arguments, captured at record time. Replay uploads an immutable copy for this + // execution and supplies its console VA in s[0:1]. Empty for ownerless/legacy callers. + std::vector root_arguments; }; // D3D12_VIEWPORT. @@ -648,6 +651,7 @@ struct ExecuteIndirect { // as it is. std::uintptr_t pipeline = 0; std::array user_data{}; + std::vector root_arguments; // DISPATCH kind only, as for Dispatch }; // Triangle geometry descriptor for a BLAS build (ID3D12GraphicsCommandList4::BuildRaytracingAccelerationStructure). diff --git a/runtime/src/root_signature.cpp b/runtime/src/root_signature.cpp index 6897e55035..586049ffbc 100644 --- a/runtime/src/root_signature.cpp +++ b/runtime/src/root_signature.cpp @@ -61,7 +61,6 @@ StagePackResult pack_stage(const RootSignature& sig, Stage stage) { const bool model_spill = stage == Stage::Compute; uint64_t cost = 0; // 64-bit, as in pack() uint64_t next = out.base; - bool spilling = false; uint64_t block_dwords = 0; std::vector first; first.reserve(sig.params.size()); @@ -81,14 +80,15 @@ StagePackResult pack_stage(const RootSignature& sig, Stage stage) { const uint64_t dwords = stage_dwords(p.type, p.num_values); // The block carries every parameter in order (measured: a fitting program's reads align to its bytes too, // so the layer fills the whole block for every compute signature, not only the spilled tail). - out.block_dword.push_back(static_cast(block_dwords)); - block_dwords += dwords; - if (!spilling && next + dwords <= kMaxUserSgprs) { + if (model_spill) { + out.block_dword.push_back(static_cast(block_dwords)); + block_dwords += dwords; + } + if (!out.spills() && next + dwords <= kMaxUserSgprs) { first.push_back(static_cast(next)); next += dwords; } else if (model_spill) { if (out.spill_start == kNoSgpr) out.spill_start = static_cast(i); - spilling = true; first.push_back(kNoSgpr); } else { out.error = "root parameter " + std::to_string(i) + " does not fit in the user SGPRs from s" + diff --git a/runtime/src/root_signature.h b/runtime/src/root_signature.h index b5d5aeb371..0ee63e287b 100644 --- a/runtime/src/root_signature.h +++ b/runtime/src/root_signature.h @@ -3,8 +3,8 @@ // No d3d12.h, no windows.h: this compiles on Linux CI and in the Windows // runtime alike. It models exactly what docs/d3d12_vulkan.md section 3.5 // needs: root parameters in order, static samplers (no dwords), the 64-dword -// D3D12 cost limit, and the 32-dword console user-SGPR budget. Anything that -// does not fit is refused loudly, never guessed (see pack()). +// D3D12 cost limit, and the 32-dword console user-SGPR budget. Compute's argument block is modelled by pack_stage; +// unmeasured graphics spills are refused loudly. // // Numbering follows D3D12 docs: descriptor tables cost 1 dword of the 64-dword // limit, root views (CBV/SRV/UAV) cost 2, 32-bit constants cost their count. @@ -183,7 +183,8 @@ struct StagePackResult { // every parameter, inline or not, in root-signature order at the inline layout's widths as bytes — a root // CBV/SRV/UAV 8 B, a descriptor table 4 B, a 32-bit constant 4 B per value, no alignment. block_dword[i] is // parameter i's first dword in that block (kNoBlockDword when the signature is refused), block_dwords the - // block's size; it is the full inline span in dwords, whether or not the signature fits s4..s31. + // block's size; for compute it is the full span whether or not the signature fits s4..s31 (at most 64). + // Non-compute stages have no block metadata. uint32_t spill_start = kNoSgpr; // first parameter that did not fit inline (kNoSgpr: all fit) std::vector block_dword; // per parameter: first dword in the argument block uint32_t block_dwords = 0; // the argument block's size, in dwords diff --git a/runtime/src/vulkan_backend.h b/runtime/src/vulkan_backend.h index 4e47057f2a..ef038637d9 100644 --- a/runtime/src/vulkan_backend.h +++ b/runtime/src/vulkan_backend.h @@ -1903,6 +1903,15 @@ class VulkanContext { bindless_prepare_ = std::move(prepare); } + // Upload into fresh, host-coherent console-addressable storage. The returned owner releases the range; each + // queue retains it until the submission completes. No range is shared by concurrent dispatches or queues. + using RootArgumentUpload = + std::function(std::span, std::uint64_t&)>; + void set_root_argument_upload(RootArgumentUpload upload) { + std::unique_lock lock(resource_mutex_); + root_argument_upload_ = std::move(upload); + } + // D24_UNORM_S8_UINT stored as D32: copies of its depth plane run a compute pass (vulkan_depth24.h). `allocate` // gives the scratch buffers device-local memory. Without this such a copy is refused as unsupported. void enable_depth24(PFN_vkGetDeviceProcAddr get, Depth24Converter::Allocate allocate, @@ -2417,6 +2426,7 @@ class VulkanContext { std::uint64_t prelude_version_ = 0; std::unique_ptr depth24_; std::unique_ptr scratch_; // copies staged through a buffer (depth <-> colour) + RootArgumentUpload root_argument_upload_; std::function bindless_commit_; std::unordered_map query_pools_; // element pointers stay valid across inserts double timestamp_period_ = 0; @@ -3231,6 +3241,7 @@ class VulkanQueue : private QueueHolds::Holder { ReplayFunctions replay{}; unsigned mesh_draws = 0; std::vector geometry; + std::vector> root_arguments; std::uint64_t captures = 0; for (const auto* list : lists) for (const auto& command : list->commands()) @@ -3271,6 +3282,15 @@ class VulkanQueue : private QueueHolds::Holder { }; } replay.graphics_family = family_ == context_.graphics_family_; + if (context_.root_argument_upload_) { + replay.prepare_root_arguments = [this, &root_arguments](std::span words, + std::uint64_t& va) { + auto owner = context_.root_argument_upload_(words, va); + if (!owner) return false; + root_arguments.push_back(std::move(owner)); + return true; + }; + } replay.queue_stages = kind_ == QueueKind::copy ? detail::queue_stages_copy : kind_ == QueueKind::compute ? detail::queue_stages_compute : 0; @@ -3448,6 +3468,7 @@ class VulkanQueue : private QueueHolds::Holder { recycle_khr_stages(khr_guard.stages); recycle_khr_as_queries(khr_guard.as_queries); geometry.clear(); + root_arguments.clear(); std::shared_ptr demand; if (context_.large_compile_demand_ && compiles.any_large()) demand = context_.large_compile_demand_(); @@ -3804,6 +3825,7 @@ class VulkanQueue : private QueueHolds::Holder { slot->predicated_copy = std::move(copy_batch); slot->counted_dispatch = std::move(counted_batch); slot->indirect_clamp = std::move(clamp_batch); + slot->root_arguments = std::move(root_arguments); queries.commit(); slot->segments = std::move(queries.retained); slot->geometry = std::move(geometry); @@ -4091,6 +4113,7 @@ class VulkanQueue : private QueueHolds::Holder { std::vector khr_instances; // KHR ARRAY_OF_POINTERS staging, same lifetime std::vector khr_as_queries; // KHR postbuild COMPACTED_SIZE query pools, same lifetime std::vector geometry; + std::vector> root_arguments; // immutable compute argument blocks, same lifetime }; struct PendingBindings { @@ -4259,6 +4282,7 @@ class VulkanQueue : private QueueHolds::Holder { if (slot.ticket > done) continue; slot.segments.clear(); slot.geometry.clear(); + slot.root_arguments.clear(); recycle_khr_stages(slot.khr_instances); recycle_khr_as_queries(slot.khr_as_queries); for (VkEvent event : slot.events) diff --git a/runtime/src/vulkan_replay.h b/runtime/src/vulkan_replay.h index f4e8136c4b..09f616e23f 100644 --- a/runtime/src/vulkan_replay.h +++ b/runtime/src/vulkan_replay.h @@ -1348,6 +1348,10 @@ struct ReplayFunctions { // copies go through it, image to buffer to image. Without it such a copy is unsupported. The expanded indices of // an indexed quad list are written there too (prepare_quad_indices). std::function copy_scratch; + // Preparation uploads an immutable copy into host-coherent console-addressable memory. The caller owns and + // retains it until this submission completes, and returns its console VA (loads add heap_base). No transfer + // commands: Vulkan's host-write -> queue-submit dependency makes these pre-submit writes visible to shaders. + std::function, std::uint64_t&)> prepare_root_arguments; // Returns the query heap with that ID, or nullptr; it stays valid while the lists that use it run. std::function query_pool; bool separate_depth_stencil_layouts = false; // must match the LayoutTracker, if one is used @@ -1355,6 +1359,13 @@ struct ReplayFunctions { namespace detail { +inline bool prepare_root_arguments(std::span words, const ReplayFunctions& vk, + std::uint64_t& va) { + return words.empty() || + (words.size() <= 64 && vk.prepare_root_arguments && vk.prepare_root_arguments(words, va) && + va % 4 == 0 && va <= (1ull << 40) - words.size_bytes() - 64); +} + struct QueryResolveRun { VkQueryPool pool = VK_NULL_HANDLE; // null: zero fill for queries that were never ended std::uint32_t first = 0; @@ -1445,6 +1456,7 @@ struct Prepared { QueryPool* queries = nullptr; // query commands: the heap ComputePipeline pipeline; // dispatches PipelineCompiles::Ticket compile = 0; // dispatches: where the pipeline comes from when it was not built yet + std::uint64_t root_argument_va = 0; // this execution's immutable argument block std::uint32_t draw = 0; // draws: its PreparedDraw in PreparedList::draws std::uint32_t depth_uav_copy = UINT32_MAX; bool order_depth_uav = false; @@ -4090,6 +4102,7 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun return ReplayResult::invalid_indirect_arguments; p.source = *cnt; } + if (ind->kind != IndirectKind::dispatch && !ind->root_arguments.empty()) return unsupported_at(__LINE__); if (ind->kind != IndirectKind::dispatch && !vk.external_graphics_scope) continue; // The clamp pass (vulkan_indirect_clamp.h): the arguments are copied on the GPU into scratch with their // values bounded before the indirect command reads them, so a stale or garbage record left by a skipped or @@ -4153,6 +4166,11 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun if (!found) return unresolved_at(__LINE__); if (pipeline->bindless_set && !vk.bind_descriptor_sets) return unsupported_at(__LINE__); } + if (!ind->root_arguments.empty()) { + if (ind->kind != IndirectKind::dispatch || !ind->pipeline || + !detail::prepare_root_arguments(ind->root_arguments, vk, p.root_argument_va)) + return unsupported_at(__LINE__); + } } else if (const auto* build = std::get_if(&command)) { p.khr_instances = 0; if (vk.xdxr_check) { @@ -4277,6 +4295,8 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun continue; } if (pipeline->bindless_set && !vk.bind_descriptor_sets) return unsupported_at(__LINE__); + if (!detail::prepare_root_arguments(dispatch->root_arguments, vk, p.root_argument_va)) + return unsupported_at(__LINE__); } else if (const auto draw = draw_command(command); draw.state) { if (out.draw_count == out.draws.size()) out.draws.emplace_back(); auto& prepared_draw = out.draws[out.draw_count]; @@ -5353,6 +5373,10 @@ inline void emit_commands(const PreparedList& prepared, VkCommandBuffer command_ if (ind->pipeline) { ShaderUserData data{}; std::copy(ind->user_data.begin(), ind->user_data.end(), data.s); + if (!ind->root_arguments.empty()) { + data.s[0] = std::uint32_t(p.root_argument_va); + data.s[1] = std::uint32_t(p.root_argument_va >> 32); + } data.heap_base = vk.heap_base; data.code_base = p.pipeline.code_base; vk.bind_pipeline(command_buffer, VK_PIPELINE_BIND_POINT_COMPUTE, p.pipeline.pipeline); @@ -5473,6 +5497,10 @@ inline void emit_commands(const PreparedList& prepared, VkCommandBuffer command_ {dispatch->x, dispatch->y, dispatch->z}); ShaderUserData data{}; std::copy(dispatch->user_data.begin(), dispatch->user_data.end(), data.s); + if (!dispatch->root_arguments.empty()) { + data.s[0] = std::uint32_t(p.root_argument_va); + data.s[1] = std::uint32_t(p.root_argument_va >> 32); + } data.heap_base = vk.heap_base; data.code_base = p.pipeline.code_base; vk.bind_pipeline(command_buffer, VK_PIPELINE_BIND_POINT_COMPUTE, p.pipeline.pipeline); diff --git a/runtime/test/d3d12_root_arguments_test.cpp b/runtime/test/d3d12_root_arguments_test.cpp new file mode 100644 index 0000000000..81317bab64 --- /dev/null +++ b/runtime/test/d3d12_root_arguments_test.cpp @@ -0,0 +1,189 @@ +// Real GPU readback of fitting and spilling blocks, partial setters, unchanged-signature rebinds, direct and +// indirect dispatch snapshots, repeated execution and two logical queues. No game files or host D3D12 needed +// beyond its root-signature serializer. LEONIDA_VK_VALIDATION=1 enables validation where installed. +#include "vk_test_device.h" +#include "shader_fixture_path.h" +#include "test_temp_dir.h" +#include "d3d12_test_shaders.h" +#include "../shims/d3d12_com.h" +#include "../src/shader_library.h" +#include "../src/title_va_alias.h" +#include +#include + +#define EXPECT(x) do { if (!(x)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #x); return 1; } } while (0) +using namespace d3d12test; + +int main() { + vktest::Device vk; + vk.request_buffer_device_address = true; + const auto status = vk.initialize(); + if (status == vktest::DeviceStatus::unavailable) return 77; + EXPECT(status == vktest::DeviceStatus::ready); + if (!vk.buffer_device_address) return 77; + const testfiles::ScratchDir scratch("leonida_root_arguments_test"); + const auto& dir = scratch.path(); + const auto fitting_program = fssm_program({0x1100u, 0x9812u, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}); + const auto spilling_program = fssm_program({0x1100u, 0x9813u, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}); + EXPECT(testfiles::copy_file(vktest::shader_fixture_path(LEONIDA_ROOT_SMALL_SPV), dir / "small.spv")); + EXPECT(testfiles::copy_file(vktest::shader_fixture_path(LEONIDA_ROOT_LARGE_SPV), dir / "large.spv")); + { + std::ofstream index(dir / "index.json", std::ios::binary); + index << "{"; + for (unsigned i = 0; i < 2; ++i) + index << (i ? "," : "") << "\"" << (i ? "large" : "small") + << "\":{\"stage\":\"cs\",\"fssm_sha256\":\"" << leonida::sha256_hex(i ? spilling_program : fitting_program) + << "\",\"bindings\":[],\"push_constant_bytes\":144,\"local_size\":[1,1,1]," + "\"uses_code_base\":false,\"wave64\":false}"; + index << "}"; + } + rt::d3d12::VulkanDeviceInfo info{}; + info.get_instance_proc = vk.instance_proc; + info.instance = vk.instance; + info.physical = vk.physical; + info.device = vk.device; + info.queue = vk.queue; + info.queue_family = vk.family; + info.buffer_device_address = true; + info.shader_dir = dir.string(); + Ref dev; + EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&dev.p)))); + const auto buffer = [&](Ref& out, UINT bytes, D3D12_HEAP_TYPE type, + D3D12_RESOURCE_STATES state, D3D12_RESOURCE_FLAGS flags = D3D12_RESOURCE_FLAG_NONE) { + const D3D12_HEAP_PROPERTIES heap{type}; + const auto desc = buffer_desc(bytes, flags); + return SUCCEEDED(dev->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, state, nullptr, + IID_PPV_ARGS(&out.p))); + }; + for (UINT count : {8u, 27u}) { + D3D12_DESCRIPTOR_RANGE range{D3D12_DESCRIPTOR_RANGE_TYPE_SRV, 1, 0, 0, 0}; + std::array params{}; + params[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS; + params[0].Constants = {0, 0, count}; + params[1].ParameterType = D3D12_ROOT_PARAMETER_TYPE_CBV; + params[1].Descriptor = {1, 0}; + params[2].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; + params[2].DescriptorTable = {1, &range}; + params[3].ParameterType = D3D12_ROOT_PARAMETER_TYPE_UAV; + params[3].Descriptor = {0, 0}; + D3D12_VERSIONED_ROOT_SIGNATURE_DESC root_desc{}; + root_desc.Version = D3D_ROOT_SIGNATURE_VERSION_1_0; + root_desc.Desc_1_0 = {4, params.data(), 0, nullptr, D3D12_ROOT_SIGNATURE_FLAG_NONE}; + const auto serialized = serialize_root_signature(root_desc); + EXPECT(!serialized.empty()); + Ref root; + EXPECT(SUCCEEDED(dev->CreateRootSignature(0, serialized.data(), serialized.size(), IID_PPV_ARGS(&root.p)))); + const auto* layout = rt::d3d12::root_signature_layout(root.p); + EXPECT(layout && layout->compute_ok && layout->block_dwords == count + 5); + EXPECT(layout->parameters[2].table_descriptors == 1); + EXPECT(layout->parameters[2].block_offset == count + 2); + const auto code = shader_container(count == 8 ? fitting_program : spilling_program); + D3D12_COMPUTE_PIPELINE_STATE_DESC pso_desc{}; + pso_desc.pRootSignature = root.p; + pso_desc.CS = {code.data(), code.size()}; + Ref pso; + EXPECT(SUCCEEDED(dev->CreateComputePipelineState(&pso_desc, IID_PPV_ARGS(&pso.p)))); + const D3D12_INDIRECT_ARGUMENT_DESC arg{D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH}; + const D3D12_COMMAND_SIGNATURE_DESC sig_desc{12, 1, &arg, 0}; + Ref signature; + EXPECT(SUCCEEDED(dev->CreateCommandSignature(&sig_desc, nullptr, IID_PPV_ARGS(&signature.p)))); + Ref indirect; + EXPECT(buffer(indirect, 16, D3D12_HEAP_TYPE_UPLOAD, D3D12_RESOURCE_STATE_GENERIC_READ)); + void* mapped = nullptr; + EXPECT(SUCCEEDED(indirect->Map(0, nullptr, &mapped))); + const UINT indirect_words[] = {2, 3, 4, 1}; // dimensions, then count + std::memcpy(mapped, indirect_words, sizeof indirect_words); + indirect->Unmap(0, nullptr); + std::array, 2> queues; + std::array, 2> allocators; + std::array, 2> lists; + std::array, 2> fences; + std::array, 2> outputs, readbacks; + std::array, 2>, 2> expected{}; + for (UINT q = 0; q < 2; ++q) { + const D3D12_COMMAND_QUEUE_DESC queue_desc{D3D12_COMMAND_LIST_TYPE_DIRECT}; + EXPECT(SUCCEEDED(dev->CreateCommandQueue(&queue_desc, IID_PPV_ARGS(&queues[q].p)))); + EXPECT(SUCCEEDED(dev->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocators[q].p)))); + EXPECT(SUCCEEDED(dev->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocators[q].p, + pso.p, IID_PPV_ARGS(&lists[q].p)))); + EXPECT(SUCCEEDED(dev->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fences[q].p)))); + EXPECT(buffer(outputs[q], 512, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, + D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS)); + EXPECT(buffer(readbacks[q], 512, D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_STATE_COPY_DEST)); + auto* list = lists[q].p; + list->SetComputeRootSignature(root.p); + for (UINT n = 0; n < 2; ++n) { + auto& want = expected[q][n]; + for (UINT i = 0; i < count; ++i) want[i] = 0x1000 + q * 0x100 + n * 0x10 + i; + list->SetComputeRoot32BitConstants(0, count, want.data(), 0); + want[3] = 0xabcd + q + n; + list->SetComputeRoot32BitConstant(0, want[3], 3); + want[5] = 0x7123 + q + n; + want[6] = 0x8123 + q + n; + list->SetComputeRoot32BitConstants(0, 2, want.data() + 5, 5); + const UINT64 cbv = 0x12345678abcdef00ull + q * 256 + n * 16; + // Main zeros unbacked root views. Keep that negative control, then register a synthetic, + // value-only alias to exercise both address halves. The shader never dereferences this CBV. + const UINT64 shader_cbv = n ? 0x12abcdef00ull + q * 256 + n * 16 : 0; + if (n) EXPECT(leonida::title_va_aliases().add(cbv, 65536, shader_cbv)); + list->SetComputeRootConstantBufferView(1, cbv); + if (n) leonida::title_va_aliases().remove(cbv, shader_cbv); + want[count] = UINT(shader_cbv); + want[count + 1] = UINT(shader_cbv >> 32); + want[count + 2] = 0x34567890 + q + n; + list->SetComputeRootDescriptorTable(2, {want[count + 2]}); + const UINT64 dest = outputs[q]->GetGPUVirtualAddress() + n * 256; + list->SetComputeRootUnorderedAccessView(3, dest); + want[count + 3] = UINT(dest); + want[count + 4] = UINT(dest >> 32); + list->SetComputeRootSignature(root.p); // must preserve all values + // The inline model: constants fit; with count 27 all later parameters are block-only. + for (UINT i = 0; i < (count == 27 ? count : count + 5); ++i) want[32 + i] = want[i]; + want[60] = 2; want[61] = 3; want[62] = 4; + if (!q) list->Dispatch(2, 3, 4); + else list->ExecuteIndirect(signature.p, 1, indirect.p, 0, n ? indirect.p : nullptr, n ? 12 : 0); + } + list->SetComputeRoot32BitConstant(0, 0xdeadbeef, 0); // cannot change earlier snapshots + const auto to_copy = transition(outputs[q].p, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, + D3D12_RESOURCE_STATE_COPY_SOURCE); + list->ResourceBarrier(1, &to_copy); + list->CopyBufferRegion(readbacks[q].p, 0, outputs[q].p, 0, 512); + const auto back = transition(outputs[q].p, D3D12_RESOURCE_STATE_COPY_SOURCE, + D3D12_RESOURCE_STATE_UNORDERED_ACCESS); + list->ResourceBarrier(1, &back); + EXPECT(SUCCEEDED(list->Close())); + } + for (UINT run = 1; run <= 2; ++run) { + for (UINT q = 0; q < 2; ++q) { + ID3D12CommandList* batch[] = {lists[q].p}; + queues[q]->ExecuteCommandLists(1, batch); + EXPECT(rt::d3d12::last_execute_result(queues[q].p) == leonida::ReplayResult::success); + EXPECT(SUCCEEDED(queues[q]->Signal(fences[q].p, run))); + } + for (UINT q = 0; q < 2; ++q) { + HANDLE done = CreateEventW(nullptr, FALSE, FALSE, nullptr); + EXPECT(done); + const bool waited = SUCCEEDED(fences[q]->SetEventOnCompletion(run, done)) && + WaitForSingleObject(done, 20000) == WAIT_OBJECT_0; + CloseHandle(done); + EXPECT(waited); + EXPECT(SUCCEEDED(readbacks[q]->Map(0, nullptr, &mapped))); + const auto* words = static_cast(mapped); + // Only written words: the argument block, all 28 inline words, dimensions and padding. + for (UINT n = 0; n < 2; ++n) + for (UINT i = 0; i < 64; ++i) { + if (i >= count + 5 && i < 32) continue; + if (words[n * 64 + i] != expected[q][n][i]) { + std::fprintf(stderr, "constants=%u run=%u queue=%u dispatch=%u word=%u: %08x != %08x\n", + count, run, q, n, i, words[n * 64 + i], expected[q][n][i]); + return 1; + } + } + readbacks[q]->Unmap(0, nullptr); + } + } + } + EXPECT(vk.validation_errors() == 0); + std::puts("root arguments: fitting/spilling, direct/indirect/counted, two queues, repeat execution: OK"); + return 0; +} diff --git a/runtime/test/glsl/cs_root_arguments.comp b/runtime/test/glsl/cs_root_arguments.comp new file mode 100644 index 0000000000..4ca650bec1 --- /dev/null +++ b/runtime/test/glsl/cs_root_arguments.comp @@ -0,0 +1,28 @@ +#version 460 +// Hand-written contract probe, not a retail shader. Read the whole block through heap_base + s[0:1], +// including both address halves, the table, constants and vector-read padding. +#extension GL_EXT_buffer_reference : require +#extension GL_EXT_buffer_reference_uvec2 : require +#ifndef ROOT_CONSTANTS +#define ROOT_CONSTANTS 27 +#endif +layout(local_size_x = 1) in; +layout(buffer_reference, std430, buffer_reference_align = 4) buffer Words { uint w[]; }; +layout(push_constant) uniform UserData { uint s[32]; uvec2 heap_base; uvec2 code_base; } pc; +uvec2 add64(uvec2 a, uvec2 b) { + uint carry; + uint lo = uaddCarry(a.x, b.x, carry); + return uvec2(lo, a.y + b.y + carry); +} +Words at(uvec2 va) { return Words(add64(pc.heap_base, va)); } +void main() { + if (any(notEqual(gl_WorkGroupID, uvec3(0)))) return; + Words args = at(uvec2(pc.s[0], pc.s[1] & 255u)); + Words result = at(uvec2(args.w[ROOT_CONSTANTS + 3], args.w[ROOT_CONSTANTS + 4])); + for (uint i = 0; i < ROOT_CONSTANTS + 5; ++i) result.w[i] = args.w[i]; + for (uint i = 0; i < 28; ++i) result.w[32 + i] = pc.s[4 + i]; + result.w[60] = gl_NumWorkGroups.x; + result.w[61] = gl_NumWorkGroups.y; + result.w[62] = gl_NumWorkGroups.z; + result.w[63] = args.w[ROOT_CONSTANTS + 5 + 15]; // last padding dword +} diff --git a/runtime/test/queue_root_arguments_test.cpp b/runtime/test/queue_root_arguments_test.cpp new file mode 100644 index 0000000000..41583acc09 --- /dev/null +++ b/runtime/test/queue_root_arguments_test.cpp @@ -0,0 +1,151 @@ +// Submission retention and rollback with deterministic fake timeline progress. No Vulkan loader or GPU. +#include "../src/vulkan_backend.h" +#include +#include + +using namespace leonida; +namespace { +int failures = 0, live = 0; +std::uintptr_t next = 100; +std::uint64_t done = 0; +bool fail_submit = false, fail_upload = false; +std::uint32_t upload_attempts = 0, fail_upload_attempt = 0; +std::vector> owners; +template T handle() { return reinterpret_cast(++next); } +void expect(bool ok, const char* what) { + if (!ok) { std::fprintf(stderr, "FAIL: %s\n", what); ++failures; } +} +VkResult VKAPI_CALL pool(VkDevice, const VkCommandPoolCreateInfo*, const VkAllocationCallbacks*, VkCommandPool* p) { + *p = handle(); return VK_SUCCESS; +} +VkResult VKAPI_CALL semaphore(VkDevice, const VkSemaphoreCreateInfo*, const VkAllocationCallbacks*, VkSemaphore* p) { + *p = handle(); return VK_SUCCESS; +} +VkResult VKAPI_CALL allocate(VkDevice, const VkCommandBufferAllocateInfo*, VkCommandBuffer* p) { + *p = handle(); return VK_SUCCESS; +} +VkResult VKAPI_CALL begin(VkCommandBuffer, const VkCommandBufferBeginInfo*) { return VK_SUCCESS; } +VkResult VKAPI_CALL end(VkCommandBuffer) { return VK_SUCCESS; } +VkResult VKAPI_CALL reset(VkCommandBuffer, VkCommandBufferResetFlags) { return VK_SUCCESS; } +VkResult VKAPI_CALL idle(VkQueue) { return VK_SUCCESS; } +VkResult VKAPI_CALL counter(VkDevice, VkSemaphore, std::uint64_t* out) { *out = done; return VK_SUCCESS; } +VkResult VKAPI_CALL submit(VkQueue, std::uint32_t, const VkSubmitInfo*, VkFence) { + return fail_submit ? VK_ERROR_OUT_OF_HOST_MEMORY : VK_SUCCESS; +} +void VKAPI_CALL destroy_pool(VkDevice, VkCommandPool, const VkAllocationCallbacks*) {} +void VKAPI_CALL destroy_semaphore(VkDevice, VkSemaphore, const VkAllocationCallbacks*) {} +void VKAPI_CALL bind(VkCommandBuffer, VkPipelineBindPoint, VkPipeline) {} +ShaderUserData last_push{}; +void VKAPI_CALL push(VkCommandBuffer, VkPipelineLayout, VkShaderStageFlags, std::uint32_t, std::uint32_t size, + const void* data) { + if (size == sizeof(last_push)) std::memcpy(&last_push, data, sizeof(last_push)); +} +void VKAPI_CALL dispatch(VkCommandBuffer, std::uint32_t, std::uint32_t, std::uint32_t) {} +PFN_vkVoidFunction VKAPI_CALL get(VkDevice, const char* name) { +#define PROC(n, f) if (!std::strcmp(name, #n)) return reinterpret_cast(f) + PROC(vkCmdBindPipeline, bind); + PROC(vkCmdPushConstants, push); + PROC(vkCmdDispatch, dispatch); +#undef PROC + return nullptr; +} +} // namespace + +int main() { + VulkanContext context(get, handle(), false); + auto& vk = context.vk; + vk.vkCreateCommandPool = pool; + vk.vkDestroyCommandPool = destroy_pool; + vk.vkCreateSemaphore = semaphore; + vk.vkDestroySemaphore = destroy_semaphore; + vk.vkAllocateCommandBuffers = allocate; + vk.vkBeginCommandBuffer = begin; + vk.vkEndCommandBuffer = end; + vk.vkResetCommandBuffer = reset; + vk.vkGetSemaphoreCounterValue = counter; + vk.vkQueueWaitIdle = idle; + vk.vkQueueSubmit = submit; + context.add_pipeline(1, {handle(), handle()}); + context.set_root_argument_upload([](std::span, std::uint64_t& va) -> std::shared_ptr { + if (++upload_attempts == fail_upload_attempt || fail_upload) return {}; + ++live; + auto owner = std::shared_ptr(new int(0), [](void* p) { delete static_cast(p); --live; }); + owners.emplace_back(owner); + va = owners.size() * 256; + return owner; + }); + CommandList list; + expect(list.dispatch({1, {}, 1, 1, 1, {11, 22}}) && list.close(), "record dispatch"); + const CommandList* lists[] = {&list}; + { + VulkanQueue a(context, handle(), 0), b(context, handle(), 0); + expect(a.execute(lists) == ReplayResult::success && live == 1, "first owner retained after submission"); + expect(a.execute(lists) == ReplayResult::success && live == 2, "repeat execution has independent owner"); + expect(b.execute(lists) == ReplayResult::success && live == 3, "second queue has independent owner"); + expect(!owners[0].expired() && !owners[1].expired() && !owners[2].expired(), "no premature release"); + fail_submit = true; + expect(a.execute(lists) == ReplayResult::unsupported && live == 3, "failed submit releases only new owner"); + expect(owners.back().expired(), "failed submission not retained by prepared storage"); + fail_submit = false; + fail_upload = true; + expect(a.execute(lists) == ReplayResult::unsupported && live == 3, "failed upload leaves in-flight owners"); + fail_upload = false; + CommandList invalid; + expect(invalid.dispatch({1, {}, 1, 1, 1, {33}}) && + invalid.dispatch({1, {}, 1, 1, 1, {44}}) && invalid.close(), "record two valid dispatches"); + const CommandList* bad[] = {&invalid}; + // Main may skip an unresolved pipeline, so inject a real second-upload failure instead. + fail_upload_attempt = upload_attempts + 2; + expect(a.execute(bad) == ReplayResult::unsupported && live == 3, + "later upload failure releases earlier unsubmitted allocation"); + expect(owners.back().expired(), "earlier allocation in the refused batch was released"); + fail_upload_attempt = 0; + done = UINT64_MAX; + expect(a.execute(lists) == ReplayResult::success && live == 2, "completed first queue owners collected"); + expect(owners[0].expired() && owners[1].expired() && !owners[2].expired(), + "collection on one queue cannot retire another queue's owner"); + } + expect(live == 0, "queue destruction releases all remaining owners after idle"); + { + struct DeferredCtx { + VkPipeline pipeline = handle(); + bool built_flag = false; + int builds = 0; + int live_at_build = -1; + } dctx; + ComputePipeline deferred{}; + deferred.layout = handle(); + deferred.build_context = &dctx; + deferred.built = [](void* ctx) { + auto* c = static_cast(ctx); + return c->built_flag ? c->pipeline : VK_NULL_HANDLE; + }; + deferred.build = [](void* ctx) { + auto* c = static_cast(ctx); + ++c->builds; + c->live_at_build = live; + c->built_flag = true; + return c->pipeline; + }; + context.add_pipeline(2, deferred); + CommandList deferred_list; + expect(deferred_list.dispatch({2, {}, 1, 1, 1, {55, 66}}) && deferred_list.close(), + "record deferred compile dispatch"); + const CommandList* dlists[] = {&deferred_list}; + done = 0; + last_push = {}; + VulkanQueue q(context, handle(), 0); + expect(q.execute(dlists) == ReplayResult::success && dctx.builds == 1, + "deferred compile succeeds on re-prepare"); + expect(dctx.live_at_build == 0 && live == 1, + "pass-0 argument block released before compile and only pass-1 block retained"); + expect(owners.size() >= 2 && owners[owners.size() - 2].expired() && !owners.back().expired(), + "pass-0 owner expired while pass-1 owner stays alive"); + const std::uint64_t expected_va = owners.size() * 256; + expect(last_push.s[0] == std::uint32_t(expected_va) && last_push.s[1] == std::uint32_t(expected_va >> 32), + "emitted push constants carry pass-1 argument block VA"); + } + expect(live == 0, "deferred queue destruction releases pass-1 owner"); + std::printf("queue root arguments: %d failures\n", failures); + return failures ? 1 : 0; +} diff --git a/runtime/test/replay_root_arguments_test.cpp b/runtime/test/replay_root_arguments_test.cpp new file mode 100644 index 0000000000..3f1922f7a2 --- /dev/null +++ b/runtime/test/replay_root_arguments_test.cpp @@ -0,0 +1,134 @@ +// Immutable argument snapshots, execution-time console VAs, and preparation failures. No GPU or game data. +#include "../src/vulkan_replay.h" +#include +#include + +using namespace leonida; +namespace { +int failures = 0; +std::vector pushes; +std::vector> groups; +void expect(bool ok, const char* what) { + if (!ok) { std::fprintf(stderr, "FAIL: %s\n", what); ++failures; } +} +VKAPI_ATTR void VKAPI_CALL push(VkCommandBuffer, VkPipelineLayout, VkShaderStageFlags, + std::uint32_t, std::uint32_t size, const void* data) { + expect(size == sizeof(ShaderUserData), "push size unchanged"); + ShaderUserData copy{}; + std::memcpy(©, data, sizeof(copy)); + pushes.push_back(copy); +} +VKAPI_ATTR void VKAPI_CALL dispatch(VkCommandBuffer, std::uint32_t x, std::uint32_t y, std::uint32_t z) { + groups.push_back({x, y, z}); +} +VKAPI_ATTR void VKAPI_CALL bind(VkCommandBuffer, VkPipelineBindPoint, VkPipeline) {} +VKAPI_ATTR void VKAPI_CALL indirect(VkCommandBuffer, VkBuffer, VkDeviceSize) {} +} // namespace + +int main() { + ReplayFunctions vk{}; + vk.bind_pipeline = bind; + vk.push_constants = push; + vk.dispatch = dispatch; + vk.dispatch_indirect = indirect; + const ComputePipeline pipeline{reinterpret_cast(1), reinterpret_cast(2)}; + vk.compute_pipeline = [&](std::uintptr_t) { return &pipeline; }; + vk.heap_base = 0x123400000000ull; + ResourceBinding args{}; + args.buffer = reinterpret_cast(3); + args.size = 12; + const auto resolve = [&](ResourceId) { return &args; }; + std::vector> uploads; + std::uint64_t va = 0x123400; // deliberately unlike heap_base; high bits also tested below + bool allocate = true; + vk.prepare_root_arguments = [&](std::span words, std::uint64_t& out) { + if (!allocate) return false; + uploads.emplace_back(words.begin(), words.end()); + out = va; + va += 0x100; + return true; + }; + CommandList list; + Dispatch first{1, {}, 2, 3, 4, {11, 22, 33}}; + first.user_data[4] = 77; + expect(list.dispatch(first), "record first"); + first.root_arguments[1] = 44; + expect(list.dispatch(first), "record second"); + ExecuteIndirect ind{}; + ind.kind = IndirectKind::dispatch; + ind.argument_buffer = 1; + ind.max_count = 1; + ind.stride = 12; + ind.pipeline = 1; + ind.root_arguments = {55, 66}; + expect(list.execute_indirect(ind) && list.close(), "record indirect and close"); + PreparedList prepared; + expect(prepare(list, resolve, vk, prepared) == ReplayResult::success, "prepare snapshots"); + expect(uploads == std::vector>({{11, 22, 33}, {11, 44, 33}, {55, 66}}), + "all direct and indirect snapshots copied independently"); + emit(prepared, VK_NULL_HANDLE, vk); + expect(groups == std::vector>({{2, 3, 4}, {2, 3, 4}}), + "dispatch dimensions not shifted into block metadata"); + expect(pushes.size() == 3 && pushes[0].s[0] == 0x123400 && pushes[1].s[0] == 0x123500 && + pushes[2].s[0] == 0x123600 && pushes[0].s[1] == 0 && pushes[0].s[4] == 77 && + pushes[0].heap_base == vk.heap_base, + "s0:s1 receive console offsets, inline data and heap base preserved"); + va = 0x1200000000ull; + expect(prepare(list, resolve, vk, prepared) == ReplayResult::success, "repeat execution allocates fresh blocks"); + pushes.clear(); + emit(prepared, VK_NULL_HANDLE, vk); + expect(pushes.size() == 3 && pushes[0].s[0] == 0 && pushes[0].s[1] == 0x12, + "40-bit console pointer high word preserved"); + { + // Main's deferred compile ticket and this execution's argument VA are independent metadata. + int builds = 0; + ComputePipeline pending{}; + pending.layout = pipeline.layout; + pending.build_context = &builds; + pending.build = [](void* context) { + ++*static_cast(context); + return reinterpret_cast(7); + }; + pending.built = [](void* context) { + return *static_cast(context) ? reinterpret_cast(7) : VK_NULL_HANDLE; + }; + PipelineCompiles compiles; + vk.compiles = &compiles; + vk.compute_pipeline = [&](std::uintptr_t) { return &pending; }; + va = 0x123400; + pushes.clear(); + groups.clear(); + expect(prepare(list, resolve, vk, prepared) == ReplayResult::success, + "deferred pipelines prepare immutable root blocks"); + expect(compiles.size() == 1 && builds == 0, "direct and indirect dispatches share one deferred build"); + expect(build_pipelines(compiles, std::span(&prepared, 1), ReplayResult::success, + [](std::size_t count, const std::function& job) { + for (std::size_t i = 0; i < count; ++i) job(i); + }) == ReplayResult::success && builds == 1, + "finish the deferred pipeline before replay"); + emit(prepared, VK_NULL_HANDLE, vk); + expect(pushes.size() == 3 && pushes[0].s[0] == 0x123400 && pushes[1].s[0] == 0x123500 && + pushes[2].s[0] == 0x123600 && groups.size() == 2, + "deferred compile resolution preserves every direct and indirect argument VA"); + vk.compiles = nullptr; + vk.compute_pipeline = [&](std::uintptr_t) { return &pipeline; }; + } + va = vk.heap_base; + expect(prepare(list, resolve, vk, prepared) == ReplayResult::unsupported, "raw BDA is not a 40-bit console VA"); + va = 0x123401; + expect(prepare(list, resolve, vk, prepared) == ReplayResult::unsupported, "misaligned argument block refused"); + allocate = false; + expect(prepare(list, resolve, vk, prepared) == ReplayResult::unsupported, "allocation failure refuses in prepare"); + vk.prepare_root_arguments = {}; + expect(prepare(list, resolve, vk, prepared) == ReplayResult::unsupported, "missing uploader refuses in prepare"); + CommandList bad; + first.root_arguments.resize(65); + expect(bad.dispatch(first) && bad.close(), "record oversized block"); + expect(prepare(bad, resolve, vk, prepared) == ReplayResult::unsupported, "oversized snapshot refused"); + CommandList legacy; + first.root_arguments.clear(); + expect(legacy.dispatch(first) && legacy.close(), "record legacy inline dispatch"); + expect(prepare(legacy, resolve, vk, prepared) == ReplayResult::success, "legacy callers need no uploader"); + std::printf("root argument replay: %d failures\n", failures); + return failures ? 1 : 0; +} diff --git a/runtime/test/root_signature_test.cpp b/runtime/test/root_signature_test.cpp index d7326584dd..a8b0eca763 100644 --- a/runtime/test/root_signature_test.cpp +++ b/runtime/test/root_signature_test.cpp @@ -503,7 +503,7 @@ int main() { check(f.ok && !f.spills() && f.first_sgpr == std::vector({4, 6, 8}) && f.block_dword == std::vector({0, 2, 4}) && f.block_dwords == 20, "pack_stage: a fitting signature gets both layouts"); - // A view needs two dwords: it spills whole if only s31 remains. + // Parameters fit whole or become block-only; an unused inline word is not filled by later parameters. RootSignature over; over.params = {consts(27), view()}; // the view would need s31..s32, so it spills const StagePackResult r = pack_stage(over, Stage::Compute); @@ -643,6 +643,7 @@ int main() { spilled.end_sgpr == 32 && spilled.spills() && spilled.spill_start == 1 && spilled.block_dword == std::vector({0, 28, 29, 29}) && spilled.block_dwords == 30, "pack_stage: zero-value constants in the compute argument block take no dwords"); + // Validation continues after the first block-only parameter. RootSignature costly; costly.params = {consts(32), consts(33)}; const StagePackResult costly_r = pack_stage(costly, Stage::Compute); @@ -651,6 +652,24 @@ int main() { RootSignature many; many.params.assign(65, table()); check(!pack_stage(many, Stage::Compute).ok, "pack_stage: more than 64 parameters rejected"); + RootSignature bad; + bad.params = {consts(29), RootParameter{}}; + bad.params.back().type = static_cast(99); + check(!pack_stage(bad, Stage::Compute).ok, "pack_stage: unknown type after spill rejected"); + bad.params.back() = consts(36); + check(!pack_stage(bad, Stage::Compute).ok, "pack_stage: over-cost constants after spill rejected"); + bad.params.back() = consts(0); + const auto zero_after_spill = pack_stage(bad, Stage::Compute); + check(zero_after_spill.ok && zero_after_spill.spills() && zero_after_spill.spill_start == 0 && + zero_after_spill.first_sgpr == std::vector({kNoSgpr, kNoSgpr}) && + zero_after_spill.block_dword == std::vector({0, 29}) && + zero_after_spill.block_dwords == 29, + "pack_stage: zero constants after spill accepted with zero block dwords"); + RootSignature maximum; + maximum.params.assign(64, table()); + const auto max = pack_stage(maximum, Stage::Compute); + check(max.ok && max.block_dwords == 64 && max.block_dword.back() == 63, + "pack_stage: maximum cost fits the 64-dword snapshot bound"); } if (g_failures != 0) std::printf("%d FAILURES\n", g_failures); diff --git a/runtime/test/vk_root_arguments_test.cpp b/runtime/test/vk_root_arguments_test.cpp new file mode 100644 index 0000000000..03161dfd21 --- /dev/null +++ b/runtime/test/vk_root_arguments_test.cpp @@ -0,0 +1,100 @@ +// Native GPU check of the immutable upload/replay contract under synchronization validation. The Windows COM +// companion tests the setters; this test needs neither Wine nor a title package. +#include "vk_test_device.h" +#include "shader_fixture_path.h" +#include "../src/vulkan_replay.h" +#include +#include + +#define EXPECT(x) do { if (!(x)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #x); return 1; } } while (0) +using namespace leonida; +int main() { + vktest::Device d; + d.request_buffer_device_address = true; + const auto status = d.initialize(); + if (status == vktest::DeviceStatus::unavailable) return 77; + EXPECT(status == vktest::DeviceStatus::ready); + if (!d.buffer_device_address) return 77; + std::ifstream input(vktest::shader_fixture_path(LEONIDA_ROOT_NATIVE_SPV), std::ios::binary | std::ios::ate); + EXPECT(input); + const auto bytes = input.tellg(); + EXPECT(bytes > 0 && bytes % 4 == 0); + std::vector code(std::size_t(bytes) / 4); + input.seekg(0); + EXPECT(input.read(reinterpret_cast(code.data()), bytes)); + VkShaderModuleCreateInfo module_info{VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO}; + module_info.codeSize = std::size_t(bytes); + module_info.pCode = code.data(); + VkShaderModule module = VK_NULL_HANDLE; + EXPECT(d.fn("vkCreateShaderModule")(d.device, &module_info, nullptr, &module) == VK_SUCCESS); + const VkPushConstantRange range{VK_SHADER_STAGE_COMPUTE_BIT, 0, 144}; + VkPipelineLayoutCreateInfo layout_info{VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO}; + layout_info.pushConstantRangeCount = 1; + layout_info.pPushConstantRanges = ⦥ + ComputePipeline pipeline; + EXPECT(d.fn("vkCreatePipelineLayout")(d.device, &layout_info, nullptr, + &pipeline.layout) == VK_SUCCESS); + VkComputePipelineCreateInfo create{VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO}; + create.layout = pipeline.layout; + create.stage = {VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO}; + create.stage.stage = VK_SHADER_STAGE_COMPUTE_BIT; + create.stage.module = module; + create.stage.pName = "main"; + EXPECT(d.fn("vkCreateComputePipelines")(d.device, VK_NULL_HANDLE, 1, &create, + nullptr, &pipeline.pipeline) == VK_SUCCESS); + void* mapped = nullptr; + const VkBuffer arena = d.buffer(16384, VK_BUFFER_USAGE_STORAGE_BUFFER_BIT, &mapped); + EXPECT(arena && mapped); + auto* words = static_cast(mapped); + ReplayFunctions vk{}; + vk.bind_pipeline = d.fn("vkCmdBindPipeline"); + vk.push_constants = d.fn("vkCmdPushConstants"); + vk.dispatch = d.fn("vkCmdDispatch"); + vk.compute_pipeline = [&](std::uintptr_t) { return &pipeline; }; + vk.heap_base = d.device_address(arena); + std::uint64_t next = 8192; + vk.prepare_root_arguments = [&](std::span data, std::uint64_t& va) { + if (data.size() > 64 || next + data.size_bytes() + 64 > 16384) return false; + va = next; + std::memcpy(static_cast(mapped) + next, data.data(), data.size_bytes()); + std::memset(static_cast(mapped) + next + data.size_bytes(), 0, 64); + next += 512; + return true; + }; + CommandList list; + for (std::uint32_t n = 0; n < 4; ++n) { + Dispatch cmd{1, {}, 2, 3, 4, std::vector(32)}; + for (std::uint32_t i = 0; i < 30; ++i) cmd.root_arguments[i] = 1000 * n + i; + cmd.root_arguments[30] = n * 256; // output console VA; all outputs lie below root storage + for (std::uint32_t i = 0; i < 27; ++i) cmd.user_data[4 + i] = cmd.root_arguments[i]; + EXPECT(list.dispatch(cmd)); + } + EXPECT(list.close()); + const auto resolve = [](ResourceId) -> const ResourceBinding* { return nullptr; }; + for (unsigned run = 0; run < 2; ++run) { + PreparedList prepared; + EXPECT(prepare(list, resolve, vk, prepared) == ReplayResult::success); + EXPECT(d.run([&](VkCommandBuffer cb) { + emit(prepared, cb, vk); + VkMemoryBarrier host{VK_STRUCTURE_TYPE_MEMORY_BARRIER}; + host.srcAccessMask = VK_ACCESS_SHADER_WRITE_BIT; + host.dstAccessMask = VK_ACCESS_HOST_READ_BIT; + d.fn("vkCmdPipelineBarrier")(cb, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, + VK_PIPELINE_STAGE_HOST_BIT, 0, 1, &host, 0, nullptr, 0, nullptr); + return true; + })); + for (unsigned n = 0; n < 4; ++n) { + for (unsigned i = 0; i < 30; ++i) EXPECT(words[n * 64 + i] == 1000 * n + i); + EXPECT(words[n * 64 + 30] == n * 256 && words[n * 64 + 31] == 0); + for (unsigned i = 0; i < 27; ++i) EXPECT(words[n * 64 + 32 + i] == 1000 * n + i); + EXPECT(words[n * 64 + 59] == 0 && words[n * 64 + 60] == 2 && words[n * 64 + 61] == 3 && + words[n * 64 + 62] == 4 && words[n * 64 + 63] == 0); + } + } + d.fn("vkDestroyPipeline")(d.device, pipeline.pipeline, nullptr); + d.fn("vkDestroyPipelineLayout")(d.device, pipeline.layout, nullptr); + d.fn("vkDestroyShaderModule")(d.device, module, nullptr); + EXPECT(d.validation_errors() == 0); + std::puts("native root argument GPU readback: 8 snapshots, no validation errors"); + return 0; +} diff --git a/tests/test_root_sig_contract.py b/tests/test_root_sig_contract.py index cf8c5abbba..133998927a 100644 --- a/tests/test_root_sig_contract.py +++ b/tests/test_root_sig_contract.py @@ -362,6 +362,9 @@ def test_zero_value_constants_take_no_dwords(): {"type": "constants", "count": 0}, {"type": "constants", "count": 1}]}, "cs") assert error == "" and len(dwords) == 32 + dwords, error = rsc.pack_layout({"params": [{"type": "constants", "count": 29}, + {"type": "constants", "count": 0}]}, "cs") + assert error == "" and len(dwords) == 4 dwords, error = rsc.pack_layout({"params": [{"type": "constants", "count": 64}]}, "cs") assert error == "" and len(dwords) == 4 dwords, error = rsc.pack_layout({"params": [{"type": "constants", "count": 64}]}, "ps") @@ -379,25 +382,31 @@ def test_console_layout_spill_goes_to_the_argument_block(): assert error == "" and len(dwords) == 4 # the whole 29-dword parameter spills: none inline assert all(slot["param"] is None for slot in dwords) - -def test_console_spill_does_not_resume_inline_placement(): - sig = {"params": [{"type": "constants", "count": 27}, {"type": "uav"}, {"type": "table"}]} + # Do not resume inline placement after the first non-fitting parameter. + sig = {"params": [{"type": "constants", "count": 27}, {"type": "cbv"}, {"type": "table"}]} dwords, error = rsc.pack_layout(sig, "cs") assert error == "" and len(dwords) == 31 - assert all(slot["param"] == 0 for slot in dwords[4:]) @pytest.mark.parametrize("tail", [ - {"type": "constants", "count": 36}, {"type": "constants", "count": -1}, {"type": "constants", "count": True}, + {"type": "constants", "count": 36}, + {"type": "unknown"}, {"type": "ufo"}, ]) -def test_console_spill_still_validates_the_remaining_parameters(tail): +def test_console_spill_validates_the_entire_tail(tail): dwords, error = rsc.pack_layout({"params": [{"type": "constants", "count": 29}, tail]}, "cs") assert dwords == [] and error +def test_console_spill_does_not_resume_inline_placement(): + sig = {"params": [{"type": "constants", "count": 27}, {"type": "uav"}, {"type": "table"}]} + dwords, error = rsc.pack_layout(sig, "cs") + assert error == "" and len(dwords) == 31 + assert all(slot["param"] == 0 for slot in dwords[4:]) + + def test_console_reconcile_fsr_reads(): console, _ = rsc.pack_layout(FSR_SHAPE, "cs") assert rsc.reconcile(FSR_READS, console) == []