From da047d5c899e749c668789059edfdd78e2191214 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Sat, 28 Nov 2026 23:31:07 +0000 Subject: [PATCH 01/12] runtime: opt-in immediate slot 57 mesh for indirect DispatchMesh X2W_MESH57_DERIVE_STATE=1 builds one desktop mesh pipeline from a single immediate GS_ALLOC_REQ when no reviewed profile was opened, then the existing ExecuteIndirect path forwards it. The switch off leaves every current refusal unchanged. Refs #870 Refs #2413 Co-authored-by: SimSalabimse --- CMakeLists.txt | 11 ++ docs/experiments/native-fixed-mesh57.md | 18 +++ docs/startup-runtime.md | 1 + src/startup_stubs/d3d12_capture.inl | 2 + src/startup_stubs/d3d12_xs_device.cpp | 19 +++ src/startup_stubs/mesh57_alloc.h | 100 ++++++++++++++++ src/startup_stubs/native_mesh57.inl | 148 ++++++++++++++++++++++++ tests/mesh57_derive_alloc_check.cpp | 94 +++++++++++++++ tests/startup_indirect_draw_indexed.cpp | 121 ++++++++++++++++++- 9 files changed, 512 insertions(+), 2 deletions(-) create mode 100644 src/startup_stubs/mesh57_alloc.h create mode 100644 tests/mesh57_derive_alloc_check.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index e3425e05f6..581b84f1a6 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1935,6 +1935,11 @@ foreach(backend IN ITEMS warp hardware) set_tests_properties(startup_mesh_xmem_writer_${backend} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77 ENVIRONMENT "X2W_MESH86_FIXTURE_XMEM=$") endforeach() +add_executable(mesh57_derive_alloc_check tests/mesh57_derive_alloc_check.cpp src/gfx1013_isa.cpp) +target_include_directories(mesh57_derive_alloc_check PRIVATE src src/startup_stubs) +target_compile_features(mesh57_derive_alloc_check PRIVATE cxx_std_17) +add_test(NAME mesh57_derive_alloc COMMAND mesh57_derive_alloc_check) + get_filename_component(DXC_BIN_DIR "${DXC_EXECUTABLE}" DIRECTORY) file(GENERATE OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/x2w-dxc-dir.txt" CONTENT "${DXC_BIN_DIR}\n") @@ -1943,6 +1948,12 @@ if(TARGET compile_dxil AND EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${ add_test(NAME native_fixed_mesh57_${backend} COMMAND startup_indirect_draw_indexed ${backend} mesh) set_tests_properties(native_fixed_mesh57_${backend} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77 ENVIRONMENT "X2W_TEST_NATIVE_MESH57=1;X2W_NATIVE_SHADERS=${DXC_BIN_DIR}") + foreach(mode derived derived-off derived-bad derived-depth derived-reviewed) + add_test(NAME startup_indirect_mesh_${mode}_${backend} + COMMAND startup_indirect_draw_indexed ${backend} mesh-${mode}) + set_tests_properties(startup_indirect_mesh_${mode}_${backend} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77 + ENVIRONMENT "X2W_NATIVE_SHADERS=${DXC_BIN_DIR}") + endforeach() add_test(NAME native_fixed_mesh57_mrt_${backend} COMMAND startup_indirect_draw_indexed ${backend} mesh) set_tests_properties(native_fixed_mesh57_mrt_${backend} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77 ENVIRONMENT "X2W_TEST_NATIVE_MESH57=1;X2W_TEST_NATIVE_MESH57_MRT=1;X2W_NATIVE_SHADERS=${DXC_BIN_DIR}") diff --git a/docs/experiments/native-fixed-mesh57.md b/docs/experiments/native-fixed-mesh57.md index dcb0755f22..d0251f1207 100644 --- a/docs/experiments/native-fixed-mesh57.md +++ b/docs/experiments/native-fixed-mesh57.md @@ -88,3 +88,21 @@ pixel entry. A creation archive alone preserves the two register blocks but does not assign hardware register meanings to their offsets. Reproduce the source-built positive and altered-stage controls with `ctest --preset dev --no-tests=error -R '^native_direct_mesh$'`. + +## Opt-in immediate allocation + +`X2W_MESH57_DERIVE_STATE=1`, together with `X2W_NATIVE_SHADERS` and `X2W_SHADER_CACHE`, can build one desktop mesh pipeline for a direct `DispatchMesh` `ExecuteIndirect` when no reviewed `.mesh57-state` file was opened for that pipeline. The switch does not change the reviewed profile. With the switch unset, the indirect call keeps the existing refusal. + +The accepted program writes `m0` with one `s_mov_b32` of an integer immediate and the next instruction is the only `s_sendmsg` `GS_ALLOC_REQ` (`0xbf900009`). The immediate is `(primitives << 12) | vertices`, both counts are in 1..64, and the high byte is clear. A group-memory count exchange (`0xbf8a0000`) or an `s_mov_b32` of `exec_lo` is refused. The derived layout is one wave64 group of 64 threads, triangle topology, and group stride 0. Stride 0 is accepted because this program does not read the group id; the lowerer skips that multiply. The pixel shader must be a constant `MRT0` export with no resource bindings, and the guest root must be empty. + +Fixed function state comes from state block A. The mesh layout word at `+0x004` must be 6. Blend words are read at the mesh shift (`+0x54` on top of `+0xD0`). Depth and stencil must decode as disabled; an enabled test is refused rather than given a guessed depth format. The color target is the one single-sample target bound on that direct list, with a viewport and a scissor and no depth view. The rasterizer is solid, cull none, and depth clip. Those three values are not read from the register block. A `.mesh57-state` file that is present, including one whose bytes do not match, keeps the reviewed path and this switch does not create a pipeline. + +A failed derivation is remembered for that pipeline. Attachment and root mismatches are not: a later direct list can still be the first accepted call. The desktop pipeline then keeps the color format of that call. + +From the x64 Windows build environment, with DXC available to the native shader stand-in: + +```powershell +ctest --preset dev -j 1 --no-tests=error -R "mesh57_derive_alloc|startup_indirect_mesh_derived" +``` + +`startup_indirect_mesh_derived_{warp,hardware}` forwards one group and reads a white texel at `(2,0)` on a 4 by 2 target. `derived-off` leaves the switch unset. `derived-bad` has no immediate allocation. `derived-depth` enables the depth test in the register block. `derived-reviewed` supplies a profile file that does not match. Those four leave the clear color. Each returns 77 when mesh shaders or the command signature are unavailable. `mesh57_derive_alloc` checks the allocation reader without a device. diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index 23ea9587e7..33fd945490 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -1734,6 +1734,7 @@ ctest --preset dev --no-tests=error -R '^startup_hook_(window|overlap)$' -V | `X2W_PIPELINE_COLOUR=1` | diagnostic only, debug switch, in render mode: a `DrawInstanced`, `DrawIndexedInstanced` or `ExecuteIndirect` draw that draws nothing gets one flat marker tile in render target 0, in a colour taken from its pipeline key, and logs `x2w-draw colour #rrggbb for ` once per key ([details](experiments/pipeline-colour-fallback.md)). Not a fallback: the refused draw still draws nothing, and the tiles can tint later passes. Unset, nothing is drawn or logged | | `X2W_SHADER_CACHE=` | translation cache: the runtime writes source requests `req_.{a,b,root}`, when needed RTV variants `req_.rtv`, and for device slot 67 compute pipelines `req_.{desc,sa,sb,data,root,c67}` (see [Compute pipeline requests](#compute-pipeline-requests)). A console pipeline that an `ExecuteIndirect` draw (list slot 61) refuses writes the same request as a direct draw, once per pipeline, and draws nothing (`startup_indirect_requests_warp`). Only direct draws poll for its manifest, so such a pipeline stays in the `missing` count until a direct draw uses it; the `x2w-render totals` line counts `pipelines first looked up by ExecuteIndirect N`. This is a per-process lookup count. Check for the ready marker `req_.a` to confirm a complete request is available. Run `tools/startup/gfx2hlsl.py --pending ` while the process is running, or start the run with `run.ps1 -Translate` (see [Translating shaders during a run](#translating-shaders-during-a-run)). Active draws poll for an absent manifest at most once per second per pipeline and use the published translation on a subsequent draw. The translator compiles `.vs.cso` and `.ps.cso` with `fxc.exe`: `X2W_FXC`, else the Windows SDK 10.0.26100.0 copy, else the newest `Windows Kits\10\bin\\x64`, else `PATH`. When none exists it writes `.fail` naming `X2W_FXC` without publishing a new manifest. `X2W_FXC=` (empty) publishes the manifest alone. Rerun `--pending` with compilation enabled to fill in missing bytecode for an existing manifest. At its first native slot-57 profile lookup the runtime lists the directory's top-level file names once and logs `x2w-draw cache index: names in ms` (`src/startup_stubs/cache_index.h`). A `.mesh57-state` profile is opened only when that listing has its name, so a profile written while the process runs is read by the next process. Manifests and every other cache file are still looked up on disk. | | `X2W_NATIVE_SHADERS=` (`run.ps1 -NativeShaders `) | experimental, in render mode: translates device slot 67 compute requests in the stand-in with the C++ compiler; `` holds `dxcompiler.dll` and `dxil.dll`. See [Translating compute programs in the stand-in](#translating-compute-programs-in-the-stand-in) | +| `X2W_MESH57_DERIVE_STATE=1` | experimental, with `X2W_NATIVE_SHADERS` and `X2W_SHADER_CACHE`: a direct `DispatchMesh` `ExecuteIndirect` may build one desktop mesh pipeline from an immediate `GS_ALLOC_REQ` and the bound color target when no `.mesh57-state` file was opened. Depth, stencil, a non-empty root, and any other allocation shape stay refused. The rasterizer is not taken from the register block. See [Opt-in immediate allocation](experiments/native-fixed-mesh57.md#opt-in-immediate-allocation) | | `X2W_D3D12_LINEAR_BUFFERS=1` or `=copy` | opt-in backing for linear buffers placed at a title address (device slot 133, initial state `COMMON`): shared where the adapter, extent and memory allow it (private allocations larger than 256 MiB are skipped only with `X2W_D3D12_CAP_EXISTING_HEAP=1`), otherwise copied from title memory at each submission, otherwise the default backing is kept and the refusal recorded; `copy` never shares. Unset or `0`, slot 133 keeps its default backing. See [Linear buffer backing (device slot 133, opt-in)](#linear-buffer-backing-device-slot-133-opt-in) | | `X2W_D3D12_CAP_EXISTING_HEAP=1` | opt-in 256 MiB (`unplaced_existing_heap_allowed`) allocation-size cap on `OpenExistingHeapFromAddress` in device slot 133 (`startup_slot133_heap_cap_*`). Unset (default), private allocations larger than 256 MiB keep the formerly aliased path: a capped copied placement is refused by `CopyBufferRegion` (list slot 15) as `title_backed_source`, losing a late guest write made after recording and before submit. Set, allocations larger than 256 MiB skip `OpenExistingHeapFromAddress` so multi-GiB startup blocks are not pinned in `WorkingSetSize` and `NonLocal` GPU memory | | `X2W_D3D12_ROOT_SRV_AT_DRAW=1` | opt-in, render mode: a graphics root SRV (slot 44) without an upload mapping is not copied into the upload ring, since no draw reads that desktop binding (default: a 64 KiB copy at every slot 44 call). Translated draws copy the SRV themselves and are unaffected (`startup_root_srv_draw_*`). See [the experiment note](experiments/startup-root-srv-at-draw.md) | diff --git a/src/startup_stubs/d3d12_capture.inl b/src/startup_stubs/d3d12_capture.inl index bb75a9b805..d281260425 100644 --- a/src/startup_stubs/d3d12_capture.inl +++ b/src/startup_stubs/d3d12_capture.inl @@ -48,6 +48,8 @@ struct PipelineInfo { mutable std::vector mesh57_pixel_spans; mutable UINT mesh57_heap_word = UINT_MAX; // R32_UINT at guest root constant[heap_word] & 1023. mutable std::vector mesh57_reads; // Host SRV register order. + mutable bool mesh57_reviewed_present = false; // A .mesh57-state file was opened for this pipeline. + mutable const char* mesh57_derive_reason = nullptr; // Opt-in derivation refused this pipeline for good. }; struct ViewRecord { // Capture the guest descriptor layout, independent of the desktop SDK. diff --git a/src/startup_stubs/d3d12_xs_device.cpp b/src/startup_stubs/d3d12_xs_device.cpp index 3f8808e3a2..abea4124c1 100644 --- a/src/startup_stubs/d3d12_xs_device.cpp +++ b/src/startup_stubs/d3d12_xs_device.cpp @@ -92,6 +92,7 @@ #include "gfx1013_compute_native.h" #include "gfx1013_pixel.h" #include "mesh_shader_pipeline.h" +#include "mesh57_alloc.h" #include #include "native_buffer_store_view.h" #include "shader_dxil_compiler.h" @@ -3738,6 +3739,10 @@ bool root_srv_at_draw() } LONG root_srv_copies_skipped, root_srv_copies_made; +#ifdef X2W_NATIVE_SHADERS +const char* derive_slot57_mesh(Wrapper* pipeline, Pass& pass); +#endif + void __stdcall list_execute_indirect(Wrapper* self, void* signature, UINT count, void* argument, u64 offset, void* count_buffer, u64 count_offset) { @@ -3818,6 +3823,20 @@ void __stdcall list_execute_indirect(Wrapper* self, void* signature, UINT count, if (indexed) bytes = sizeof(D3D12_DRAW_INDEXED_ARGUMENTS); else if (mesh) bytes = sizeof(D3D12_DISPATCH_MESH_ARGUMENTS); else bytes = sizeof(D3D12_DRAW_ARGUMENTS); +#ifdef X2W_NATIVE_SHADERS + // Opt-in only. A reviewed .mesh57-state profile is unchanged. With the switch off this + // block does not run and the refusal below stays the one every existing fixture expects. + if (mesh && type == D3D12_COMMAND_LIST_TYPE_DIRECT && pass.pipeline && !pass.pipeline->own().real && + x2w_local::env_on("X2W_MESH57_DERIVE_STATE")) { + if (const char* why = derive_slot57_mesh(pass.pipeline, pass)) { + static LONG derived_mesh_refusals; + if (first_calls(derived_mesh_refusals, 16)) + log("x2w-render derived slot57 mesh refused: %s", why); + } else if (pass.pipeline->own().real) { + pass.indirect_graphics = pass.pipeline->own().indirect_graphics; + } + } +#endif if (type != D3D12_COMMAND_LIST_TYPE_DIRECT || (!translated && (!pass.indirect_graphics.root || (pass.indirect_graphics.constant_guest == UINT_MAX && pass.indirect_graphics.root != pass.graphics_root) || pass.indirect_graphics.mesh != mesh))) { diff --git a/src/startup_stubs/mesh57_alloc.h b/src/startup_stubs/mesh57_alloc.h new file mode 100644 index 0000000000..c6baa5ba62 --- /dev/null +++ b/src/startup_stubs/mesh57_alloc.h @@ -0,0 +1,100 @@ +// Opt-in slot 57 mesh layout for X2W_MESH57_DERIVE_STATE. +// +// A reviewed .mesh57-state profile still owns the MS entry layout. This reader accepts only the +// smallest program the mesh lowerer already runs: one s_mov_b32 of an integer immediate into m0 +// immediately before the only s_sendmsg GS_ALLOC_REQ (0xbf900009). The immediate is +// (primitives << 12) | vertices. Anything else, including the group-memory count exchange, stays +// refused so a captured program cannot invent threads, a wave size, or a group stride. +#pragma once + +#include "gfx1013_isa.h" + +#include +#include +#include +#include +#include + +namespace x2w_startup { + +struct MeshDerivedLayout { + unsigned threads = 0; + unsigned vertices = 0; + unsigned primitives = 0; + unsigned topology = 0; + unsigned group_stride = 0; + unsigned wave_size = 0; +}; + +// One wave64 group. group_stride stays 0: the accepted program does not read the group id, and the +// lowerer skips that multiply when the stride is 0. Returns empty when the program is not the +// single immediate allocation above, or when either count is outside 1..64. +inline std::optional derive_immediate_mesh_layout(std::string_view code) noexcept +{ + if (code.empty() || code.size() % 4 != 0) + return std::nullopt; + try { + bool previous_immediate = false; + std::uint32_t previous_word = 0; + unsigned allocations = 0; + unsigned vertices = 0; + unsigned primitives = 0; + bool wave32 = false; + bool exchange = false; + for (unsigned pc = 0; pc < code.size();) { + std::uint32_t raw = 0; + std::memcpy(&raw, code.data() + pc, sizeof(raw)); + const auto inst = x2w::gfx1013::instruction(code, pc); + if (inst.size == 0 || pc + inst.size > code.size()) + return std::nullopt; + if (raw == 0xbf8a0000u) + exchange = true; + if (raw == 0xbf900009u) { + if (!previous_immediate) + return std::nullopt; + const unsigned next_vertices = previous_word & 4095u; + const unsigned next_primitives = (previous_word >> 12) & 4095u; + if ((previous_word >> 24) != 0 || next_vertices == 0 || next_primitives == 0 || + next_vertices > 64u || next_primitives > 64u) + return std::nullopt; + vertices = next_vertices; + primitives = next_primitives; + ++allocations; + } + previous_immediate = false; + previous_word = 0; + if (inst.form == x2w::gfx1013::Form::sop1 && inst.name == "s_mov_b32") { + const unsigned dst = (raw >> 16) & 127u; + const unsigned src = raw & 255u; + if (dst == 126u) + wave32 = true; + if (dst == 124u) { + if (src >= 128u && src <= 192u) { + previous_immediate = true; + previous_word = static_cast(src - 128u); + } else if (src == 255u && inst.size >= 8u) { + std::uint32_t literal = 0; + std::memcpy(&literal, code.data() + pc + 4, sizeof(literal)); + previous_immediate = true; + previous_word = literal; + } + } + } + pc += inst.size; + } + if (allocations != 1 || wave32 || exchange) + return std::nullopt; + MeshDerivedLayout layout; + layout.threads = 64; + layout.vertices = vertices; + layout.primitives = primitives; + layout.topology = 2; + layout.group_stride = 0; + layout.wave_size = 64; + return layout; + } catch (...) { + return std::nullopt; + } +} + +} // namespace x2w_startup diff --git a/src/startup_stubs/native_mesh57.inl b/src/startup_stubs/native_mesh57.inl index 8acc02e78f..0f975d8832 100644 --- a/src/startup_stubs/native_mesh57.inl +++ b/src/startup_stubs/native_mesh57.inl @@ -259,6 +259,9 @@ void prepare_native_mesh57(Wrapper* pipeline) std::ifstream file(std::filesystem::path(path), std::ios::binary); if (!file) return; + // A present profile keeps the reviewed gate even when its bytes do not match. The opt-in + // derivation below must not replace a file a person already supplied. + info->mesh57_reviewed_present = true; try { x2w_startup::Mesh57Profile profile{}; if (!file.read(reinterpret_cast(&profile), sizeof(profile))) @@ -466,4 +469,149 @@ void prepare_native_mesh57(Wrapper* pipeline) log("x2w-render native slot57 mesh %016llx refused: %s", key, e.what()); } } + +// Builds one desktop mesh PSO for a direct DispatchMesh when X2W_MESH57_DERIVE_STATE=1 and no +// reviewed profile was opened. Returns nullptr after publishing the PSO, or a stable reason. +// A reason that depends on the command list (attachments, the bound root) is not remembered. +const char* derive_slot57_mesh(Wrapper* pipeline, Pass& pass) +{ + if (!pipeline || pipeline->own().real) + return nullptr; + const auto* info = pipeline_info(pipeline); + if (!info) + return "derived mesh has no captured pipeline"; + if (info->mesh57_derive_reason) + return info->mesh57_derive_reason; + auto remember = [&](const char* why) { + info->mesh57_derive_reason = why; + return why; + }; + wchar_t sdk[MAX_PATH]; + const DWORD sdk_length = GetEnvironmentVariableW(L"X2W_NATIVE_SHADERS", sdk, MAX_PATH); + if (!sdk_length || sdk_length >= MAX_PATH) + return "derived mesh needs the native shader compiler"; + wchar_t cache[MAX_PATH]; + const DWORD cache_length = GetEnvironmentVariableW(L"X2W_SHADER_CACHE", cache, MAX_PATH); + if (!cache_length || cache_length >= MAX_PATH) + return "derived mesh needs a shader cache"; + if (info->path != 57 || !info->fixed_ms || !info->fixed_ps || info->desc.size() != 0x300) + return remember("derived mesh needs a fixed slot 57 pair"); + if (info->mesh57_reviewed_present) + return remember("a reviewed mesh profile is present"); + u64 fields[0x300 / sizeof(u64)]{}; + std::memcpy(fields, info->desc.data(), sizeof(fields)); + auto* root = as_wrapper(reinterpret_cast(fields[0])); + if (!root || root->own().kind != root_signature_kind || !root->own().real || !root_info(root) || + fields[2] != info->state_a.size() || fields[4] != info->state_b.size()) + return remember("derived mesh root or state lengths do not match"); + if (!root_info(root)->empty() || root_heap_flags(root)) + return remember("derived mesh keeps a non-empty guest root refused"); + if (info->state_a.size() < x2w_pipeline_state::a_layout + 4) + return remember("derived mesh state block is short"); + std::uint32_t layout_word = 0; + std::memcpy(&layout_word, info->state_a.data() + x2w_pipeline_state::a_layout, sizeof(layout_word)); + if (layout_word != x2w_pipeline_state::a_layout_mesh) + return remember("derived mesh requires the mesh layout word"); + const std::size_t shift = x2w_pipeline_state::a_mesh_shift; + if (info->state_a.size() < shift) + return remember("derived mesh state block is short"); + D3D12_BLEND_DESC blend{}; + const char* blend_why = nullptr; + // Blend words sit at +0xD0 in the vertex layout. The mesh layout shifts every field from +0x058 + // by +0x54, and the blend reader does not apply that shift itself. + if (!x2w_startup::state_block_blend(info->state_a.data() + shift, info->state_a.size() - shift, false, &blend, &blend_why)) + return remember(blend_why ? blend_why : "derived mesh blend was refused"); + x2w_pipeline_state::DepthStencilWords depth_words; + if (!x2w_pipeline_state::read_depth_stencil_words(info->state_a.data(), info->state_a.size(), depth_words)) + return remember("derived mesh state block is short for depth"); + const x2w_pipeline_state::DepthStencil depth = x2w_pipeline_state::decode_depth_stencil( + depth_words.depth, depth_words.stencil, depth_words.refmask, depth_words.refmask_bf); + if (!depth.ok) + return remember(depth.reason ? depth.reason : "derived mesh depth state was refused"); + if (depth.desc.DepthEnable || depth.desc.StencilEnable) + return remember("derived mesh keeps depth and stencil disabled"); + auto* desktop = static_cast(root->own().real); + if (!pass.targets_bound || !pass.viewport_set || !pass.scissor_set || !pass.targets_single_sample || + pass.target_count != 1 || !pass.target0 || pass.dsv_format != DXGI_FORMAT_UNKNOWN || + pass.target_formats[0] == DXGI_FORMAT_UNKNOWN) + return "derived mesh needs one single-sample color target, a viewport and a scissor"; + if (!pass.graphics_root || pass.graphics_root != desktop || pass.root != root_info(root) || pass.root_heap_flags) + return "derived mesh root is not the bound empty desktop root"; + const std::string ms(info->fixed_ms->begin(), info->fixed_ms->end()); + const auto layout = x2w_startup::derive_immediate_mesh_layout(ms); + if (!layout) + return remember("derived mesh needs one immediate allocation"); + try { + x2w::MeshStageLayout mesh_layout; + mesh_layout.threads = layout->threads; + mesh_layout.max_vertices = layout->vertices; + mesh_layout.max_primitives = layout->primitives; + mesh_layout.topology = layout->topology; + mesh_layout.group_stride = layout->group_stride; + mesh_layout.wave32 = false; + auto native = x2w::translate_mesh_program(ms, mesh_layout); + if (!native.constants.empty() || !native.bindings.empty() || !native.samplers.empty() || native.sampler_heap || + !native.mesh_heap_reads.empty()) + return remember("derived mesh program needs root or heap bindings"); + const std::string ps(info->fixed_ps->begin(), info->fixed_ps->end()); + const std::string ps_ir = x2w::direct_gfx1013_constant_pixel(ps); + auto compiler = x2w::ShaderDxilCompiler::runtime_worker(sdk); + const auto cache_dir = std::filesystem::path(cache); + const auto ms_output = compiler.compile(native.dxil_ir, L"ms_6_6", cache_dir, x2w::ShaderSourceFormat::dxil_ir); + const auto ps_output = compiler.compile(ps_ir, L"ps_6_6", cache_dir, x2w::ShaderSourceFormat::dxil_ir); + x2w::meshlet::MeshOnlyPipelineStream stream{}; + stream.root_signature.value = reinterpret_cast(root); + stream.ms.value.pShaderBytecode = ms_output.dxil.data(); + stream.ms.value.BytecodeLength = ms_output.dxil.size(); + stream.ps.value.pShaderBytecode = ps_output.dxil.data(); + stream.ps.value.BytecodeLength = ps_output.dxil.size(); + stream.blend.value = blend; + stream.sample_mask.value = UINT_MAX; + stream.rasterizer.value = x2w_startup::default_pso_rasterizer(); + stream.depth_stencil.value = depth.desc; + D3D12_RT_FORMAT_ARRAY targets{}; + targets.NumRenderTargets = 1; + targets.RTFormats[0] = pass.target_formats[0]; + stream.rtv_formats.value = targets; + stream.dsv_format.value = DXGI_FORMAT_UNKNOWN; + DXGI_SAMPLE_DESC samples; + samples.Count = 1; + samples.Quality = 0; + stream.sample_desc.value = samples; + stream.topology.value = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE; + D3D12_PIPELINE_STATE_STREAM_DESC desc; + desc.SizeInBytes = sizeof(stream); + desc.pPipelineStateSubobjectStream = &stream; + bool compute = false; + char why[256]{}; + IndirectGraphicsPipeline graphics; + ID3D12RootSignature* pipeline_root = nullptr; + auto* created = build_stream_pipeline(&desc, why, sizeof(why), compute, graphics, pipeline_root, desktop, true); + if (!created) { + log("x2w-render derived slot57 mesh desktop pipeline refused: %s", why); + if (pipeline->own().real) + return nullptr; + return remember("derived mesh desktop pipeline was refused"); + } + auto* pso = static_cast(created); + AcquireSRWLockExclusive(¬e_lock); + if (pipeline->own().real) { + ReleaseSRWLockExclusive(¬e_lock); + pso->Release(); + return nullptr; + } + pipeline->own().indirect_graphics = graphics; + if (pipeline_root) + pipeline->own().pipeline_root = pipeline_root; + pipeline->own().real = pso; + ReleaseSRWLockExclusive(¬e_lock); + log("x2w-render derived slot57 mesh ready"); + return nullptr; + } catch (const std::exception& e) { + log("x2w-render derived slot57 mesh refused: %s", e.what()); + if (pipeline->own().real) + return nullptr; + return remember("derived mesh translation was refused"); + } +} #endif diff --git a/tests/mesh57_derive_alloc_check.cpp b/tests/mesh57_derive_alloc_check.cpp new file mode 100644 index 0000000000..1a8eede361 --- /dev/null +++ b/tests/mesh57_derive_alloc_check.cpp @@ -0,0 +1,94 @@ +// Host check for the opt-in immediate mesh allocation reader. No device and no shader compiler. +#include "mesh57_alloc.h" + +#include +#include +#include +#include +#include + +namespace { +int fail(const char* name) +{ + std::fprintf(stderr, "mesh57 derive alloc: %s\n", name); + return 1; +} + +std::string words_of(const std::uint32_t* words, std::size_t count) +{ + std::string out(count * sizeof(std::uint32_t), '\0'); + if (count) + std::memcpy(out.data(), words, count * sizeof(std::uint32_t)); + return out; +} + +bool accepted(std::string_view code, unsigned vertices, unsigned primitives) +{ + const auto layout = x2w_startup::derive_immediate_mesh_layout(code); + return layout && layout->vertices == vertices && layout->primitives == primitives && + layout->threads == 64 && layout->topology == 2 && layout->group_stride == 0 && + layout->wave_size == 64; +} +} // namespace + +int main() +{ + // Source-built triangle: m0 = (1 primitive << 12) | 3 vertices, then GS_ALLOC_REQ. + const std::uint32_t triangle[] = { + 0xbefc03ffu, 0x1003u, 0xbf900009u, 0xd7650000u, 0x100c1u, 0x36020081u, + 0x2c040081u, 0x7e020d01u, 0x7e040d02u, 0x7e0602f0u, 0x7e0802f2u, 0xf80008cfu, + 0x04030201u, 0x7e0a02ffu, 0x200400u, 0xf8000941u, 0x80808005u, 0xbf810000u}; + if (!accepted(words_of(triangle, sizeof(triangle) / sizeof(triangle[0])), 3, 1)) + return fail("triangle"); + + const std::uint32_t only_alloc[] = {0xbefc03ffu, 0x1003u, 0xbf900009u, 0xbf810000u}; + if (!accepted(words_of(only_alloc, 4), 3, 1)) + return fail("alloc alone"); + + const std::uint32_t endpgm[] = {0xbf810000u}; + if (x2w_startup::derive_immediate_mesh_layout(words_of(endpgm, 1))) + return fail("no allocation"); + + const std::uint32_t gap[] = {0xbefc03ffu, 0x1003u, 0xbf800000u, 0xbf900009u}; + if (x2w_startup::derive_immediate_mesh_layout(words_of(gap, 4))) + return fail("instruction between m0 and GS_ALLOC_REQ"); + + const std::uint32_t twice[] = {0xbefc03ffu, 0x1003u, 0xbf900009u, 0xbefc03ffu, 0x1003u, 0xbf900009u}; + if (x2w_startup::derive_immediate_mesh_layout(words_of(twice, 6))) + return fail("two allocations"); + + const std::uint32_t high[] = {0xbefc03ffu, 0x01001003u, 0xbf900009u}; + if (x2w_startup::derive_immediate_mesh_layout(words_of(high, 3))) + return fail("high byte"); + + const std::uint32_t zero[] = {0xbefc03ffu, 0u, 0xbf900009u}; + if (x2w_startup::derive_immediate_mesh_layout(words_of(zero, 3))) + return fail("zero counts"); + + const std::uint32_t wide[] = {0xbefc03ffu, (1u << 12) | 65u, 0xbf900009u}; + if (x2w_startup::derive_immediate_mesh_layout(words_of(wide, 3))) + return fail("count above one wave"); + + const std::uint32_t exchange[] = {0xbefc03ffu, 0x1003u, 0xbf900009u, 0xbf8a0000u}; + if (x2w_startup::derive_immediate_mesh_layout(words_of(exchange, 4))) + return fail("count exchange"); + + // s_mov_b32 exec_lo, 0. Wave32 writes exec with s_mov_b32; wave64 uses s_mov_b64. + const std::uint32_t wave32_mov = 0xbefe0380u; + std::string wave32_word(sizeof(wave32_mov), '\0'); + std::memcpy(wave32_word.data(), &wave32_mov, sizeof(wave32_mov)); + const auto decoded = x2w::gfx1013::instruction(wave32_word, 0); + if (decoded.name != "s_mov_b32") + return fail("exec_lo encoding"); + const std::uint32_t wave32[] = {wave32_mov, 0xbefc03ffu, 0x1003u, 0xbf900009u}; + if (x2w_startup::derive_immediate_mesh_layout(words_of(wave32, 4))) + return fail("wave32 exec move"); + + const std::uint32_t from_register[] = {0xbefc0300u, 0xbf900009u}; + if (x2w_startup::derive_immediate_mesh_layout(words_of(from_register, 2))) + return fail("m0 from a register"); + + if (x2w_startup::derive_immediate_mesh_layout({})) + return fail("empty"); + return 0; +} diff --git a/tests/startup_indirect_draw_indexed.cpp b/tests/startup_indirect_draw_indexed.cpp index 835026a24a..7d3db15dec 100644 --- a/tests/startup_indirect_draw_indexed.cpp +++ b/tests/startup_indirect_draw_indexed.cpp @@ -21,6 +21,7 @@ #include #include #include +#include #include #include #include @@ -2421,6 +2422,114 @@ static int native_fixed_mesh_fixture(ID3D12Device* device, ID3D12Device* guest, return 0; } +// Opt-in X2W_MESH57_DERIVE_STATE. The source-built triangle has no .mesh57-state file. +// mesh-derived forwards one DispatchMesh and paints (2,0). The other modes must leave the clear color. +static int derived_mesh_fixture(ID3D12Device* device, ID3D12Device* guest, ID3D12RootSignature* writer, const char* mode) +{ + struct CacheCleanup { + std::filesystem::path path; + ~CacheCleanup() + { + std::error_code error; + std::filesystem::remove_all(path, error); + } + }; + const bool enable = std::strcmp(mode, "mesh-derived-off") != 0; + check(SetEnvironmentVariableA("X2W_MESH57_DERIVE_STATE", enable ? "1" : nullptr) ? S_OK : E_FAIL, + "derived mesh switch"); + const auto prefix = "mesh57-derived-" + std::to_string(GetCurrentProcessId()) + "-"; + CacheCleanup cache; + for (unsigned attempt = 0;; ++attempt) { + cache.path = std::filesystem::current_path() / (prefix + std::to_string(attempt)); + if (std::filesystem::create_directory(cache.path)) + break; + } + check(SetEnvironmentVariableW(L"X2W_SHADER_CACHE", cache.path.c_str()) ? S_OK : E_FAIL, "derived mesh cache"); + ComPtr blob; + D3D12_ROOT_SIGNATURE_DESC empty{}; + const auto root = create_root(guest, empty, &blob); + std::vector ms{0xbefc03ffu, 0x1003u, 0xbf900009u, 0xd7650000u, 0x100c1u, 0x36020081u, + 0x2c040081u, 0x7e020d01u, 0x7e040d02u, 0x7e0602f0u, 0x7e0802f2u, 0xf80008cfu, + 0x04030201u, 0x7e0a02ffu, 0x200400u, 0xf8000941u, 0x80808005u, 0xbf810000u}; + if (std::strcmp(mode, "mesh-derived-bad") == 0) + ms.assign(1, 0xbf810000u); + const std::vector ps{0x7e0002f2u, 0xf800180fu, 0u, 0xbf810000u}; + const auto ms_size = ms.size() * sizeof(UINT); + const auto ps_size = ps.size() * sizeof(UINT); + // Long enough for the mesh-shifted blend words (+0x124) and depth words (+0x10C). + constexpr std::size_t state_bytes = 0x144; + std::vector state_a(state_bytes, 0); + const std::uint32_t mesh_layout = 6; + std::memcpy(state_a.data() + 4, &mesh_layout, sizeof(mesh_layout)); + if (std::strcmp(mode, "mesh-derived-depth") == 0) { + const std::uint32_t depth_on = 2; + std::memcpy(state_a.data() + 0x10c, &depth_on, sizeof(depth_on)); + } + std::vector state_b(4, 0); + UINT64 fields[0x300 / sizeof(UINT64)]{}; + fields[2] = state_a.size(); + fields[4] = state_b.size(); + fields[6] = ps_size; + fields[14] = ms_size; + const auto fold = [](UINT64 key, const void* data, size_t n) { + const auto* bytes = static_cast(data); + for (size_t i = 0; i < n; ++i) + key = (key ^ bytes[i]) * 1099511628211ull; + return key; + }; + const char revision[] = "x2w-startup-mesh-57-3"; + UINT64 key = fold(1469598103934665603ull, revision, sizeof(revision) - 1); + const auto extend = [&](UINT64 base, const void* data, UINT64 n) { + return fold(fold(base, &n, sizeof(n)), data, static_cast(n)); + }; + key = extend(key, ms.data(), ms_size); + key = extend(key, ps.data(), ps_size); + key = extend(key, blob->GetBufferPointer(), blob->GetBufferSize()); + const UINT64 variant = extend(extend(extend(key, fields, sizeof(fields)), state_a.data(), state_a.size()), + state_b.data(), state_b.size()); + if (std::strcmp(mode, "mesh-derived-reviewed") == 0) { + char name[64]; + std::snprintf(name, sizeof(name), "%016llx.mesh57-state", static_cast(variant)); + std::ofstream out(cache.path / name, std::ios::binary); + const char marker = 'x'; + out.write(&marker, 1); + if (!out) + return 1; + } + fields[0] = reinterpret_cast(root.Get()); + fields[1] = reinterpret_cast(state_a.data()); + fields[3] = reinterpret_cast(state_b.data()); + fields[5] = reinterpret_cast(ps.data()); + fields[13] = reinterpret_cast(ms.data()); + ComPtr pso; + using Create = HRESULT(WINAPI*)(IUnknown*, const void*, REFIID, void**); + check(slot(guest, 57)(guest, fields, __uuidof(ID3D12PipelineState), reinterpret_cast(pso.GetAddressOf())), + "create derived mesh"); + D3D12_INDIRECT_ARGUMENT_DESC argument{}; + argument.Type = D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH_MESH; + D3D12_COMMAND_SIGNATURE_DESC signature_desc; + signature_desc.ByteStride = static_cast(sizeof(D3D12_DISPATCH_MESH_ARGUMENTS)); + signature_desc.NumArgumentDescs = 1; + signature_desc.pArgumentDescs = &argument; + signature_desc.NodeMask = 0; + ComPtr signature; + if (FAILED(guest->CreateCommandSignature(&signature_desc, nullptr, IID_PPV_ARGS(&signature)))) { + std::puts("indirect mesh capability skip: DispatchMesh signature unavailable"); + return 77; + } + const auto work = writer_pipeline(device, writer, "write_one_mesh_group"); + x2w_startup::Mesh57Profile profile{}; + std::memcpy(profile.magic, "X2WM571", 8); + profile.targets.NumRenderTargets = 1; + profile.targets.RTFormats[0] = format; + profile.blend.RenderTarget[0].RenderTargetWriteMask = D3D12_COLOR_WRITE_ENABLE_ALL; + const int pixels = std::strcmp(mode, "mesh-derived") == 0 ? 1 : 2; + const bool painted = run(device, guest, writer, work.Get(), root.Get(), pso.Get(), signature.Get(), DrawKind::mesh, + false, Refusal::none, mode, nullptr, false, nullptr, false, false, 0, false, false, nullptr, + nullptr, false, pixels, &profile); + return painted ? 0 : 1; +} + int main(int argc, char** argv) try { DrawKind kind = DrawKind::indexed; @@ -2442,6 +2551,12 @@ int main(int argc, char** argv) try SetEnvironmentVariableA("X2W_MESH86_XMEM_SRV", nullptr) ? S_OK : E_FAIL, "enable loose XMem root SRV"); else if (lease_fixture && !lease_arguments) check(SetEnvironmentVariableA("X2W_MESH86_XMEM_SRV", "1") ? S_OK : E_FAIL, "enable mesh XMem handoff"); + const bool derived_off = argc == 3 && std::strcmp(argv[2], "mesh-derived-off") == 0; + const bool derived_bad = argc == 3 && std::strcmp(argv[2], "mesh-derived-bad") == 0; + const bool derived_depth = argc == 3 && std::strcmp(argv[2], "mesh-derived-depth") == 0; + const bool derived_reviewed = argc == 3 && std::strcmp(argv[2], "mesh-derived-reviewed") == 0; + const bool derived_mesh = derived_off || derived_bad || derived_depth || derived_reviewed || + (argc == 3 && std::strcmp(argv[2], "mesh-derived") == 0); const bool console_mesh = argc == 3 && std::strcmp(argv[2], "mesh-console") == 0; const bool desktop_as = argc == 3 && std::strcmp(argv[2], "mesh-amplified") == 0; const bool copy_on = argc == 3 && std::strcmp(argv[2], "copy-provenance") == 0; @@ -2465,10 +2580,10 @@ int main(int argc, char** argv) try const bool count_control = argc == 3 && std::strcmp(argv[2], "count-control") == 0; if ((translated && !translated_indexed) || (argc == 3 && std::strcmp(argv[2], "draw") == 0)) kind = DrawKind::vertices; else if (argc == 3 && std::strcmp(argv[2], "rect") == 0) kind = DrawKind::rect; - else if (lease_arguments || console_mesh || desktop_as || (argc == 3 && std::strcmp(argv[2], "mesh") == 0)) + else if (lease_arguments || console_mesh || desktop_as || derived_mesh || (argc == 3 && std::strcmp(argv[2], "mesh") == 0)) kind = DrawKind::mesh; else if (rect) kind = DrawKind::indexed_rect; - else if (argc != 2 && !count_control && !translated_indexed && !lease_writer) return 2; + else if (argc != 2 && !count_control && !translated_indexed && !lease_writer && !derived_mesh) return 2; const bool indexed = kind == DrawKind::indexed || kind == DrawKind::indexed_rect; const bool mesh = kind == DrawKind::mesh; const bool fixed_create_fixture = mesh && GetEnvironmentVariableA("X2W_FIXED_MESH_CREATE_FIXTURE", nullptr, 0); @@ -2551,6 +2666,8 @@ int main(int argc, char** argv) try const auto writer = create_root(device.Get(), writer_desc); if (mesh && GetEnvironmentVariableA("X2W_TEST_NATIVE_MESH57", nullptr, 0)) return native_fixed_mesh_fixture(device.Get(), guest.Get(), writer.Get(), log_path); + if (derived_mesh) + return derived_mesh_fixture(device.Get(), guest.Get(), writer.Get(), argv[2]); wchar_t mesh86_dir[MAX_PATH]{}; if (mesh && GetEnvironmentVariableW(L"X2W_MESH86_FIXTURE_DIR", mesh86_dir, MAX_PATH)) { const bool depth_only = GetEnvironmentVariableA("X2W_MESH86_FIXTURE_DEPTH", nullptr, 0) != 0; From aaf9c8a806f706ba640b0e62aeedd3f49306a47d Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Sat, 28 Nov 2026 23:35:12 +0000 Subject: [PATCH 02/12] runtime: limit derived mesh forwarding to slot 57 profile misses X2W_MESH57_DERIVE_STATE only attempts a direct DispatchMesh whose pipeline is slot 57 and has no desktop PSO. Draws and other mesh pipelines stay refused. A slot 57 pipeline with no captured stages stays refused too. Refs #870 Refs #2413 Co-authored-by: SimSalabimse --- CMakeLists.txt | 2 +- docs/experiments/native-fixed-mesh57.md | 6 ++++-- docs/startup-runtime.md | 2 +- src/startup_stubs/d3d12_xs_device.cpp | 8 ++++++-- tests/startup_indirect_draw_indexed.cpp | 15 +++++++++++---- 5 files changed, 23 insertions(+), 10 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 581b84f1a6..a80eb2ab3f 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1948,7 +1948,7 @@ if(TARGET compile_dxil AND EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${ add_test(NAME native_fixed_mesh57_${backend} COMMAND startup_indirect_draw_indexed ${backend} mesh) set_tests_properties(native_fixed_mesh57_${backend} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77 ENVIRONMENT "X2W_TEST_NATIVE_MESH57=1;X2W_NATIVE_SHADERS=${DXC_BIN_DIR}") - foreach(mode derived derived-off derived-bad derived-depth derived-reviewed) + foreach(mode derived derived-off derived-bad derived-depth derived-reviewed derived-untranslated) add_test(NAME startup_indirect_mesh_${mode}_${backend} COMMAND startup_indirect_draw_indexed ${backend} mesh-${mode}) set_tests_properties(startup_indirect_mesh_${mode}_${backend} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77 diff --git a/docs/experiments/native-fixed-mesh57.md b/docs/experiments/native-fixed-mesh57.md index d0251f1207..2c67cafc96 100644 --- a/docs/experiments/native-fixed-mesh57.md +++ b/docs/experiments/native-fixed-mesh57.md @@ -91,7 +91,9 @@ source-built positive and altered-stage controls with ## Opt-in immediate allocation -`X2W_MESH57_DERIVE_STATE=1`, together with `X2W_NATIVE_SHADERS` and `X2W_SHADER_CACHE`, can build one desktop mesh pipeline for a direct `DispatchMesh` `ExecuteIndirect` when no reviewed `.mesh57-state` file was opened for that pipeline. The switch does not change the reviewed profile. With the switch unset, the indirect call keeps the existing refusal. +`X2W_MESH57_DERIVE_STATE=1`, together with `X2W_NATIVE_SHADERS` and `X2W_SHADER_CACHE`, can build one desktop mesh pipeline for a direct `DispatchMesh` `ExecuteIndirect` when no reviewed `.mesh57-state` file was opened for that slot 57 pipeline. That is the `graphics/mesh_profile_missing` refusal: a slot 57 mesh with captured stages and no desktop pipeline. The switch does not change the reviewed profile. With the switch unset, the indirect call keeps the existing refusal. `graphics/no_translation` is a different refusal (no captured stages, or the call is not this slot 57 mesh) and this switch does not forward it. + +A startup run on the Windows test PC recorded 653,708 refused `DispatchMesh` `ExecuteIndirect` calls in 420 seconds and forwarded none. Across draw and mesh, the graphics-pipeline census counted `graphics/no_translation` 446,421 and `graphics/mesh_profile_missing` 427,428. This switch is only the second of those, and only the immediate-allocation shape below. Slot 86 meshes with no cached stage stay refused. The accepted program writes `m0` with one `s_mov_b32` of an integer immediate and the next instruction is the only `s_sendmsg` `GS_ALLOC_REQ` (`0xbf900009`). The immediate is `(primitives << 12) | vertices`, both counts are in 1..64, and the high byte is clear. A group-memory count exchange (`0xbf8a0000`) or an `s_mov_b32` of `exec_lo` is refused. The derived layout is one wave64 group of 64 threads, triangle topology, and group stride 0. Stride 0 is accepted because this program does not read the group id; the lowerer skips that multiply. The pixel shader must be a constant `MRT0` export with no resource bindings, and the guest root must be empty. @@ -105,4 +107,4 @@ From the x64 Windows build environment, with DXC available to the native shader ctest --preset dev -j 1 --no-tests=error -R "mesh57_derive_alloc|startup_indirect_mesh_derived" ``` -`startup_indirect_mesh_derived_{warp,hardware}` forwards one group and reads a white texel at `(2,0)` on a 4 by 2 target. `derived-off` leaves the switch unset. `derived-bad` has no immediate allocation. `derived-depth` enables the depth test in the register block. `derived-reviewed` supplies a profile file that does not match. Those four leave the clear color. Each returns 77 when mesh shaders or the command signature are unavailable. `mesh57_derive_alloc` checks the allocation reader without a device. +`startup_indirect_mesh_derived_{warp,hardware}` forwards one group and reads a white texel at `(2,0)` on a 4 by 2 target. `derived-off` leaves the switch unset. `derived-bad` has no immediate allocation. `derived-depth` enables the depth test in the register block. `derived-reviewed` supplies a profile file that does not match. `derived-untranslated` is a slot 57 pipeline with no captured mesh or pixel program, so the switch has nothing to translate. Those five leave the clear color. Each returns 77 when mesh shaders or the command signature are unavailable. `mesh57_derive_alloc` checks the allocation reader without a device. diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index 33fd945490..db3586095f 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -1734,7 +1734,7 @@ ctest --preset dev --no-tests=error -R '^startup_hook_(window|overlap)$' -V | `X2W_PIPELINE_COLOUR=1` | diagnostic only, debug switch, in render mode: a `DrawInstanced`, `DrawIndexedInstanced` or `ExecuteIndirect` draw that draws nothing gets one flat marker tile in render target 0, in a colour taken from its pipeline key, and logs `x2w-draw colour #rrggbb for ` once per key ([details](experiments/pipeline-colour-fallback.md)). Not a fallback: the refused draw still draws nothing, and the tiles can tint later passes. Unset, nothing is drawn or logged | | `X2W_SHADER_CACHE=` | translation cache: the runtime writes source requests `req_.{a,b,root}`, when needed RTV variants `req_.rtv`, and for device slot 67 compute pipelines `req_.{desc,sa,sb,data,root,c67}` (see [Compute pipeline requests](#compute-pipeline-requests)). A console pipeline that an `ExecuteIndirect` draw (list slot 61) refuses writes the same request as a direct draw, once per pipeline, and draws nothing (`startup_indirect_requests_warp`). Only direct draws poll for its manifest, so such a pipeline stays in the `missing` count until a direct draw uses it; the `x2w-render totals` line counts `pipelines first looked up by ExecuteIndirect N`. This is a per-process lookup count. Check for the ready marker `req_.a` to confirm a complete request is available. Run `tools/startup/gfx2hlsl.py --pending ` while the process is running, or start the run with `run.ps1 -Translate` (see [Translating shaders during a run](#translating-shaders-during-a-run)). Active draws poll for an absent manifest at most once per second per pipeline and use the published translation on a subsequent draw. The translator compiles `.vs.cso` and `.ps.cso` with `fxc.exe`: `X2W_FXC`, else the Windows SDK 10.0.26100.0 copy, else the newest `Windows Kits\10\bin\\x64`, else `PATH`. When none exists it writes `.fail` naming `X2W_FXC` without publishing a new manifest. `X2W_FXC=` (empty) publishes the manifest alone. Rerun `--pending` with compilation enabled to fill in missing bytecode for an existing manifest. At its first native slot-57 profile lookup the runtime lists the directory's top-level file names once and logs `x2w-draw cache index: names in ms` (`src/startup_stubs/cache_index.h`). A `.mesh57-state` profile is opened only when that listing has its name, so a profile written while the process runs is read by the next process. Manifests and every other cache file are still looked up on disk. | | `X2W_NATIVE_SHADERS=` (`run.ps1 -NativeShaders `) | experimental, in render mode: translates device slot 67 compute requests in the stand-in with the C++ compiler; `` holds `dxcompiler.dll` and `dxil.dll`. See [Translating compute programs in the stand-in](#translating-compute-programs-in-the-stand-in) | -| `X2W_MESH57_DERIVE_STATE=1` | experimental, with `X2W_NATIVE_SHADERS` and `X2W_SHADER_CACHE`: a direct `DispatchMesh` `ExecuteIndirect` may build one desktop mesh pipeline from an immediate `GS_ALLOC_REQ` and the bound color target when no `.mesh57-state` file was opened. Depth, stencil, a non-empty root, and any other allocation shape stay refused. The rasterizer is not taken from the register block. See [Opt-in immediate allocation](experiments/native-fixed-mesh57.md#opt-in-immediate-allocation) | +| `X2W_MESH57_DERIVE_STATE=1` | experimental, with `X2W_NATIVE_SHADERS` and `X2W_SHADER_CACHE`: addresses `graphics/mesh_profile_missing` for one slot 57 shape. A direct `DispatchMesh` `ExecuteIndirect` may build one desktop mesh pipeline from an immediate `GS_ALLOC_REQ` and the bound color target when captured stages exist and no `.mesh57-state` file was opened. `graphics/no_translation`, slot 86, depth, stencil, a non-empty root, and any other allocation shape stay refused. The rasterizer is not taken from the register block. See [Opt-in immediate allocation](experiments/native-fixed-mesh57.md#opt-in-immediate-allocation) | | `X2W_D3D12_LINEAR_BUFFERS=1` or `=copy` | opt-in backing for linear buffers placed at a title address (device slot 133, initial state `COMMON`): shared where the adapter, extent and memory allow it (private allocations larger than 256 MiB are skipped only with `X2W_D3D12_CAP_EXISTING_HEAP=1`), otherwise copied from title memory at each submission, otherwise the default backing is kept and the refusal recorded; `copy` never shares. Unset or `0`, slot 133 keeps its default backing. See [Linear buffer backing (device slot 133, opt-in)](#linear-buffer-backing-device-slot-133-opt-in) | | `X2W_D3D12_CAP_EXISTING_HEAP=1` | opt-in 256 MiB (`unplaced_existing_heap_allowed`) allocation-size cap on `OpenExistingHeapFromAddress` in device slot 133 (`startup_slot133_heap_cap_*`). Unset (default), private allocations larger than 256 MiB keep the formerly aliased path: a capped copied placement is refused by `CopyBufferRegion` (list slot 15) as `title_backed_source`, losing a late guest write made after recording and before submit. Set, allocations larger than 256 MiB skip `OpenExistingHeapFromAddress` so multi-GiB startup blocks are not pinned in `WorkingSetSize` and `NonLocal` GPU memory | | `X2W_D3D12_ROOT_SRV_AT_DRAW=1` | opt-in, render mode: a graphics root SRV (slot 44) without an upload mapping is not copied into the upload ring, since no draw reads that desktop binding (default: a 64 KiB copy at every slot 44 call). Translated draws copy the SRV themselves and are unaffected (`startup_root_srv_draw_*`). See [the experiment note](experiments/startup-root-srv-at-draw.md) | diff --git a/src/startup_stubs/d3d12_xs_device.cpp b/src/startup_stubs/d3d12_xs_device.cpp index abea4124c1..3079582245 100644 --- a/src/startup_stubs/d3d12_xs_device.cpp +++ b/src/startup_stubs/d3d12_xs_device.cpp @@ -3824,9 +3824,13 @@ void __stdcall list_execute_indirect(Wrapper* self, void* signature, UINT count, else if (mesh) bytes = sizeof(D3D12_DISPATCH_MESH_ARGUMENTS); else bytes = sizeof(D3D12_DRAW_ARGUMENTS); #ifdef X2W_NATIVE_SHADERS - // Opt-in only. A reviewed .mesh57-state profile is unchanged. With the switch off this - // block does not run and the refusal below stays the one every existing fixture expects. + // Opt-in for the graphics/mesh_profile_missing refusal: a direct DispatchMesh whose slot 57 + // pipeline has no desktop PSO and no cached stage. Draws, and any mesh pipeline that is not + // slot 57, stay on the refusal below (graphics/no_translation among them). A reviewed + // .mesh57-state profile is unchanged. With the switch off this block does not run. + const PipelineInfo* derived_info = pass.pipeline ? pipeline_info(pass.pipeline) : nullptr; if (mesh && type == D3D12_COMMAND_LIST_TYPE_DIRECT && pass.pipeline && !pass.pipeline->own().real && + !pass.indirect_graphics.cached_mesh && derived_info && derived_info->path == 57 && x2w_local::env_on("X2W_MESH57_DERIVE_STATE")) { if (const char* why = derive_slot57_mesh(pass.pipeline, pass)) { static LONG derived_mesh_refusals; diff --git a/tests/startup_indirect_draw_indexed.cpp b/tests/startup_indirect_draw_indexed.cpp index 7d3db15dec..baad8d609a 100644 --- a/tests/startup_indirect_draw_indexed.cpp +++ b/tests/startup_indirect_draw_indexed.cpp @@ -2422,7 +2422,7 @@ static int native_fixed_mesh_fixture(ID3D12Device* device, ID3D12Device* guest, return 0; } -// Opt-in X2W_MESH57_DERIVE_STATE. The source-built triangle has no .mesh57-state file. +// Opt-in X2W_MESH57_DERIVE_STATE for a slot 57 mesh with captured stages and no reviewed profile. // mesh-derived forwards one DispatchMesh and paints (2,0). The other modes must leave the clear color. static int derived_mesh_fixture(ID3D12Device* device, ID3D12Device* guest, ID3D12RootSignature* writer, const char* mode) { @@ -2499,8 +2499,14 @@ static int derived_mesh_fixture(ID3D12Device* device, ID3D12Device* guest, ID3D1 fields[0] = reinterpret_cast(root.Get()); fields[1] = reinterpret_cast(state_a.data()); fields[3] = reinterpret_cast(state_b.data()); - fields[5] = reinterpret_cast(ps.data()); - fields[13] = reinterpret_cast(ms.data()); + // No captured stages: the switch must not invent a translation. The call stays refused. + if (std::strcmp(mode, "mesh-derived-untranslated") == 0) { + fields[6] = 0; + fields[14] = 0; + } else { + fields[5] = reinterpret_cast(ps.data()); + fields[13] = reinterpret_cast(ms.data()); + } ComPtr pso; using Create = HRESULT(WINAPI*)(IUnknown*, const void*, REFIID, void**); check(slot(guest, 57)(guest, fields, __uuidof(ID3D12PipelineState), reinterpret_cast(pso.GetAddressOf())), @@ -2555,7 +2561,8 @@ int main(int argc, char** argv) try const bool derived_bad = argc == 3 && std::strcmp(argv[2], "mesh-derived-bad") == 0; const bool derived_depth = argc == 3 && std::strcmp(argv[2], "mesh-derived-depth") == 0; const bool derived_reviewed = argc == 3 && std::strcmp(argv[2], "mesh-derived-reviewed") == 0; - const bool derived_mesh = derived_off || derived_bad || derived_depth || derived_reviewed || + const bool derived_untranslated = argc == 3 && std::strcmp(argv[2], "mesh-derived-untranslated") == 0; + const bool derived_mesh = derived_off || derived_bad || derived_depth || derived_reviewed || derived_untranslated || (argc == 3 && std::strcmp(argv[2], "mesh-derived") == 0); const bool console_mesh = argc == 3 && std::strcmp(argv[2], "mesh-console") == 0; const bool desktop_as = argc == 3 && std::strcmp(argv[2], "mesh-amplified") == 0; From 71a1e477f5cffcbf60ee21b86250e3882545300f Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Sun, 29 Nov 2026 00:01:36 +0000 Subject: [PATCH 03/12] runtime: compile derived slot 57 meshes without the native frontend X2W_MESH57_DXC_DIR supplies dxcompiler.dll and dxil.dll to the slot 57 derivation alone. X2W_NATIVE_SHADERS stays unset for other programs and is only a fallback compiler directory for this path. A missing directory still logs the existing compiler refusal. A present .mesh57-state file is still honored when the native switch did not open it. Refs #870 Refs #2413 Co-authored-by: SimSalabimse --- CMakeLists.txt | 6 ++++ docs/experiments/native-fixed-mesh57.md | 8 +++-- docs/startup-runtime.md | 3 +- src/startup_stubs/native_mesh57.inl | 48 +++++++++++++++++++++++-- tests/startup_indirect_draw_indexed.cpp | 23 +++++++++--- 5 files changed, 79 insertions(+), 9 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index a80eb2ab3f..ceb80ab48c 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1954,6 +1954,12 @@ if(TARGET compile_dxil AND EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${ set_tests_properties(startup_indirect_mesh_${mode}_${backend} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77 ENVIRONMENT "X2W_NATIVE_SHADERS=${DXC_BIN_DIR}") endforeach() + foreach(mode derived-dxc derived-dxc-reviewed) + add_test(NAME startup_indirect_mesh_${mode}_${backend} + COMMAND startup_indirect_draw_indexed ${backend} mesh-${mode}) + set_tests_properties(startup_indirect_mesh_${mode}_${backend} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77 + ENVIRONMENT "X2W_MESH57_DXC_DIR=${DXC_BIN_DIR}") + endforeach() add_test(NAME native_fixed_mesh57_mrt_${backend} COMMAND startup_indirect_draw_indexed ${backend} mesh) set_tests_properties(native_fixed_mesh57_mrt_${backend} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77 ENVIRONMENT "X2W_TEST_NATIVE_MESH57=1;X2W_TEST_NATIVE_MESH57_MRT=1;X2W_NATIVE_SHADERS=${DXC_BIN_DIR}") diff --git a/docs/experiments/native-fixed-mesh57.md b/docs/experiments/native-fixed-mesh57.md index 2c67cafc96..4eb8b262b3 100644 --- a/docs/experiments/native-fixed-mesh57.md +++ b/docs/experiments/native-fixed-mesh57.md @@ -91,7 +91,11 @@ source-built positive and altered-stage controls with ## Opt-in immediate allocation -`X2W_MESH57_DERIVE_STATE=1`, together with `X2W_NATIVE_SHADERS` and `X2W_SHADER_CACHE`, can build one desktop mesh pipeline for a direct `DispatchMesh` `ExecuteIndirect` when no reviewed `.mesh57-state` file was opened for that slot 57 pipeline. That is the `graphics/mesh_profile_missing` refusal: a slot 57 mesh with captured stages and no desktop pipeline. The switch does not change the reviewed profile. With the switch unset, the indirect call keeps the existing refusal. `graphics/no_translation` is a different refusal (no captured stages, or the call is not this slot 57 mesh) and this switch does not forward it. +`X2W_MESH57_DERIVE_STATE=1`, together with `X2W_SHADER_CACHE` and a compiler directory, can build one desktop mesh pipeline for a direct `DispatchMesh` `ExecuteIndirect` when no reviewed `.mesh57-state` file was opened for that slot 57 pipeline. That is the `graphics/mesh_profile_missing` refusal: a slot 57 mesh with captured stages and no desktop pipeline. The switch does not change the reviewed profile. With the switch unset, the indirect call keeps the existing refusal. `graphics/no_translation` is a different refusal (no captured stages, or the call is not this slot 57 mesh) and this switch does not forward it. + +`X2W_MESH57_DXC_DIR` is the directory of `dxcompiler.dll` and `dxil.dll` for this path alone. It does not turn on native translation for other graphics or compute programs. `X2W_NATIVE_SHADERS` is still accepted as the compiler directory for this one pipeline, and setting it also turns that other translation on. When neither directory is set, the call stays refused and the log says `derived mesh needs the native shader compiler`. + +On the Windows test PC at `aed2c0c7`, `X2W_MESH57_DERIVE_STATE=1` with no compiler directory logged that refusal and forwarded nothing. Setting `X2W_NATIVE_SHADERS` compiled this path and also translated other programs, which refused fixed graphics entries and compute views before any `ExecuteIndirect`. A startup run that wants only this path sets `X2W_MESH57_DERIVE_STATE=1`, `X2W_MESH57_DXC_DIR`, and `X2W_SHADER_CACHE`, and leaves `X2W_NATIVE_SHADERS` unset. A startup run on the Windows test PC recorded 653,708 refused `DispatchMesh` `ExecuteIndirect` calls in 420 seconds and forwarded none. Across draw and mesh, the graphics-pipeline census counted `graphics/no_translation` 446,421 and `graphics/mesh_profile_missing` 427,428. This switch is only the second of those, and only the immediate-allocation shape below. Slot 86 meshes with no cached stage stay refused. @@ -107,4 +111,4 @@ From the x64 Windows build environment, with DXC available to the native shader ctest --preset dev -j 1 --no-tests=error -R "mesh57_derive_alloc|startup_indirect_mesh_derived" ``` -`startup_indirect_mesh_derived_{warp,hardware}` forwards one group and reads a white texel at `(2,0)` on a 4 by 2 target. `derived-off` leaves the switch unset. `derived-bad` has no immediate allocation. `derived-depth` enables the depth test in the register block. `derived-reviewed` supplies a profile file that does not match. `derived-untranslated` is a slot 57 pipeline with no captured mesh or pixel program, so the switch has nothing to translate. Those five leave the clear color. Each returns 77 when mesh shaders or the command signature are unavailable. `mesh57_derive_alloc` checks the allocation reader without a device. +`startup_indirect_mesh_derived_{warp,hardware}` forwards one group and reads a white texel at `(2,0)` on a 4 by 2 target. `derived-dxc` does the same with only `X2W_MESH57_DXC_DIR` set, and the process clears `X2W_NATIVE_SHADERS` before the call. `derived-off` leaves the switch unset. `derived-bad` has no immediate allocation. `derived-depth` enables the depth test in the register block. `derived-reviewed` and `derived-dxc-reviewed` supply a profile file that does not match; the second does that with only `X2W_MESH57_DXC_DIR` set. `derived-untranslated` is a slot 57 pipeline with no captured mesh or pixel program, so the switch has nothing to translate. Those six leave the clear color. Each returns 77 when mesh shaders or the command signature are unavailable. `mesh57_derive_alloc` checks the allocation reader without a device. diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index db3586095f..bfd9e30844 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -1734,7 +1734,8 @@ ctest --preset dev --no-tests=error -R '^startup_hook_(window|overlap)$' -V | `X2W_PIPELINE_COLOUR=1` | diagnostic only, debug switch, in render mode: a `DrawInstanced`, `DrawIndexedInstanced` or `ExecuteIndirect` draw that draws nothing gets one flat marker tile in render target 0, in a colour taken from its pipeline key, and logs `x2w-draw colour #rrggbb for ` once per key ([details](experiments/pipeline-colour-fallback.md)). Not a fallback: the refused draw still draws nothing, and the tiles can tint later passes. Unset, nothing is drawn or logged | | `X2W_SHADER_CACHE=` | translation cache: the runtime writes source requests `req_.{a,b,root}`, when needed RTV variants `req_.rtv`, and for device slot 67 compute pipelines `req_.{desc,sa,sb,data,root,c67}` (see [Compute pipeline requests](#compute-pipeline-requests)). A console pipeline that an `ExecuteIndirect` draw (list slot 61) refuses writes the same request as a direct draw, once per pipeline, and draws nothing (`startup_indirect_requests_warp`). Only direct draws poll for its manifest, so such a pipeline stays in the `missing` count until a direct draw uses it; the `x2w-render totals` line counts `pipelines first looked up by ExecuteIndirect N`. This is a per-process lookup count. Check for the ready marker `req_.a` to confirm a complete request is available. Run `tools/startup/gfx2hlsl.py --pending ` while the process is running, or start the run with `run.ps1 -Translate` (see [Translating shaders during a run](#translating-shaders-during-a-run)). Active draws poll for an absent manifest at most once per second per pipeline and use the published translation on a subsequent draw. The translator compiles `.vs.cso` and `.ps.cso` with `fxc.exe`: `X2W_FXC`, else the Windows SDK 10.0.26100.0 copy, else the newest `Windows Kits\10\bin\\x64`, else `PATH`. When none exists it writes `.fail` naming `X2W_FXC` without publishing a new manifest. `X2W_FXC=` (empty) publishes the manifest alone. Rerun `--pending` with compilation enabled to fill in missing bytecode for an existing manifest. At its first native slot-57 profile lookup the runtime lists the directory's top-level file names once and logs `x2w-draw cache index: names in ms` (`src/startup_stubs/cache_index.h`). A `.mesh57-state` profile is opened only when that listing has its name, so a profile written while the process runs is read by the next process. Manifests and every other cache file are still looked up on disk. | | `X2W_NATIVE_SHADERS=` (`run.ps1 -NativeShaders `) | experimental, in render mode: translates device slot 67 compute requests in the stand-in with the C++ compiler; `` holds `dxcompiler.dll` and `dxil.dll`. See [Translating compute programs in the stand-in](#translating-compute-programs-in-the-stand-in) | -| `X2W_MESH57_DERIVE_STATE=1` | experimental, with `X2W_NATIVE_SHADERS` and `X2W_SHADER_CACHE`: addresses `graphics/mesh_profile_missing` for one slot 57 shape. A direct `DispatchMesh` `ExecuteIndirect` may build one desktop mesh pipeline from an immediate `GS_ALLOC_REQ` and the bound color target when captured stages exist and no `.mesh57-state` file was opened. `graphics/no_translation`, slot 86, depth, stencil, a non-empty root, and any other allocation shape stay refused. The rasterizer is not taken from the register block. See [Opt-in immediate allocation](experiments/native-fixed-mesh57.md#opt-in-immediate-allocation) | +| `X2W_MESH57_DXC_DIR=` | experimental, with `X2W_MESH57_DERIVE_STATE=1`: the directory of `dxcompiler.dll` and `dxil.dll` for that one slot 57 derivation. Other graphics and compute programs stay on the non-native path. Unset, the derivation may still use `X2W_NATIVE_SHADERS` when that directory is set. When neither directory is set, the call stays refused (`derived mesh needs the native shader compiler`). See [Opt-in immediate allocation](experiments/native-fixed-mesh57.md#opt-in-immediate-allocation) | +| `X2W_MESH57_DERIVE_STATE=1` | experimental, with `X2W_SHADER_CACHE` and `X2W_MESH57_DXC_DIR` (or `X2W_NATIVE_SHADERS`): addresses `graphics/mesh_profile_missing` for one slot 57 shape. A direct `DispatchMesh` `ExecuteIndirect` may build one desktop mesh pipeline from an immediate `GS_ALLOC_REQ` and the bound color target when captured stages exist and no `.mesh57-state` file was opened. `graphics/no_translation`, slot 86, depth, stencil, a non-empty root, and any other allocation shape stay refused. The rasterizer is not taken from the register block. See [Opt-in immediate allocation](experiments/native-fixed-mesh57.md#opt-in-immediate-allocation) | | `X2W_D3D12_LINEAR_BUFFERS=1` or `=copy` | opt-in backing for linear buffers placed at a title address (device slot 133, initial state `COMMON`): shared where the adapter, extent and memory allow it (private allocations larger than 256 MiB are skipped only with `X2W_D3D12_CAP_EXISTING_HEAP=1`), otherwise copied from title memory at each submission, otherwise the default backing is kept and the refusal recorded; `copy` never shares. Unset or `0`, slot 133 keeps its default backing. See [Linear buffer backing (device slot 133, opt-in)](#linear-buffer-backing-device-slot-133-opt-in) | | `X2W_D3D12_CAP_EXISTING_HEAP=1` | opt-in 256 MiB (`unplaced_existing_heap_allowed`) allocation-size cap on `OpenExistingHeapFromAddress` in device slot 133 (`startup_slot133_heap_cap_*`). Unset (default), private allocations larger than 256 MiB keep the formerly aliased path: a capped copied placement is refused by `CopyBufferRegion` (list slot 15) as `title_backed_source`, losing a late guest write made after recording and before submit. Set, allocations larger than 256 MiB skip `OpenExistingHeapFromAddress` so multi-GiB startup blocks are not pinned in `WorkingSetSize` and `NonLocal` GPU memory | | `X2W_D3D12_ROOT_SRV_AT_DRAW=1` | opt-in, render mode: a graphics root SRV (slot 44) without an upload mapping is not copied into the upload ring, since no draw reads that desktop binding (default: a 64 KiB copy at every slot 44 call). Translated draws copy the SRV themselves and are unaffected (`startup_root_srv_draw_*`). See [the experiment note](experiments/startup-root-srv-at-draw.md) | diff --git a/src/startup_stubs/native_mesh57.inl b/src/startup_stubs/native_mesh57.inl index 0f975d8832..fb95451616 100644 --- a/src/startup_stubs/native_mesh57.inl +++ b/src/startup_stubs/native_mesh57.inl @@ -470,6 +470,49 @@ void prepare_native_mesh57(Wrapper* pipeline) } } +// The directory of dxcompiler.dll and dxil.dll for this path alone. X2W_MESH57_DXC_DIR does not +// turn on native translation for other programs. X2W_NATIVE_SHADERS remains a fallback so a run +// that already set it can still compile this one pipeline. +bool mesh57_derive_compiler_dir(wchar_t* sdk, DWORD capacity) +{ + DWORD length = GetEnvironmentVariableW(L"X2W_MESH57_DXC_DIR", sdk, capacity); + if (!length || length >= capacity) + length = GetEnvironmentVariableW(L"X2W_NATIVE_SHADERS", sdk, capacity); + return length && length < capacity; +} + +// Same variant name prepare_native_mesh57 opens. Used when that function did not run because +// X2W_NATIVE_SHADERS is unset. A present file keeps the reviewed gate; this path does not parse it. +bool mesh57_reviewed_file_present(const PipelineInfo* info) +{ + if (!info || info->path != 57 || !info->fixed_ms || !info->fixed_ps || info->desc.size() != 0x300) + return false; + u64 fields[0x300 / sizeof(u64)]; + std::memcpy(fields, info->desc.data(), sizeof(fields)); + auto* root = as_wrapper(reinterpret_cast(fields[0])); + if (!root || root->own().kind != root_signature_kind || fields[2] != info->state_a.size() || + fields[4] != info->state_b.size()) + return false; + std::vector root_blob; + { + x2w_startup::ExclusiveNoteLock guard(note_lock); + const auto it = root_blobs().find(root); + if (it == root_blobs().end()) + return false; + root_blob = it->second; + } + constexpr char revision[] = "x2w-startup-mesh-57-3"; + const u64 key = fnv_part(root_blob, fnv_part(*info->fixed_ps, fnv_part(*info->fixed_ms, + fnv_bytes(revision, sizeof(revision) - 1)))); + const auto normalized = x2w_startup::normalize_mesh57_descriptor(info->desc); + const auto variant = fnv_part(info->state_b, fnv_part(info->state_a, fnv_part(normalized, key))); + wchar_t path[MAX_PATH]; + if (!cache_path(path, L"", variant, L".mesh57-state")) + return false; + std::ifstream file(std::filesystem::path(path), std::ios::binary); + return static_cast(file); +} + // Builds one desktop mesh PSO for a direct DispatchMesh when X2W_MESH57_DERIVE_STATE=1 and no // reviewed profile was opened. Returns nullptr after publishing the PSO, or a stable reason. // A reason that depends on the command list (attachments, the bound root) is not remembered. @@ -487,8 +530,7 @@ const char* derive_slot57_mesh(Wrapper* pipeline, Pass& pass) return why; }; wchar_t sdk[MAX_PATH]; - const DWORD sdk_length = GetEnvironmentVariableW(L"X2W_NATIVE_SHADERS", sdk, MAX_PATH); - if (!sdk_length || sdk_length >= MAX_PATH) + if (!mesh57_derive_compiler_dir(sdk, MAX_PATH)) return "derived mesh needs the native shader compiler"; wchar_t cache[MAX_PATH]; const DWORD cache_length = GetEnvironmentVariableW(L"X2W_SHADER_CACHE", cache, MAX_PATH); @@ -496,6 +538,8 @@ const char* derive_slot57_mesh(Wrapper* pipeline, Pass& pass) return "derived mesh needs a shader cache"; if (info->path != 57 || !info->fixed_ms || !info->fixed_ps || info->desc.size() != 0x300) return remember("derived mesh needs a fixed slot 57 pair"); + if (!info->mesh57_reviewed_present && mesh57_reviewed_file_present(info)) + info->mesh57_reviewed_present = true; if (info->mesh57_reviewed_present) return remember("a reviewed mesh profile is present"); u64 fields[0x300 / sizeof(u64)]{}; diff --git a/tests/startup_indirect_draw_indexed.cpp b/tests/startup_indirect_draw_indexed.cpp index baad8d609a..437751f5de 100644 --- a/tests/startup_indirect_draw_indexed.cpp +++ b/tests/startup_indirect_draw_indexed.cpp @@ -2423,7 +2423,9 @@ static int native_fixed_mesh_fixture(ID3D12Device* device, ID3D12Device* guest, } // Opt-in X2W_MESH57_DERIVE_STATE for a slot 57 mesh with captured stages and no reviewed profile. -// mesh-derived forwards one DispatchMesh and paints (2,0). The other modes must leave the clear color. +// mesh-derived and mesh-derived-dxc forward one DispatchMesh and paint (2,0). The other modes +// must leave the clear color. mesh-derived-dxc uses only X2W_MESH57_DXC_DIR and clears +// X2W_NATIVE_SHADERS before the call. static int derived_mesh_fixture(ID3D12Device* device, ID3D12Device* guest, ID3D12RootSignature* writer, const char* mode) { struct CacheCleanup { @@ -2437,6 +2439,17 @@ static int derived_mesh_fixture(ID3D12Device* device, ID3D12Device* guest, ID3D1 const bool enable = std::strcmp(mode, "mesh-derived-off") != 0; check(SetEnvironmentVariableA("X2W_MESH57_DERIVE_STATE", enable ? "1" : nullptr) ? S_OK : E_FAIL, "derived mesh switch"); + const bool dxc_only = std::strcmp(mode, "mesh-derived-dxc") == 0 || + std::strcmp(mode, "mesh-derived-dxc-reviewed") == 0; + if (dxc_only) { + wchar_t dir[MAX_PATH]; + const DWORD length = GetEnvironmentVariableW(L"X2W_MESH57_DXC_DIR", dir, MAX_PATH); + if (!length || length >= MAX_PATH) + return 1; + check(SetEnvironmentVariableW(L"X2W_NATIVE_SHADERS", nullptr) ? S_OK : E_FAIL, "clear native shaders"); + if (GetEnvironmentVariableW(L"X2W_NATIVE_SHADERS", nullptr, 0) != 0) + return 1; + } const auto prefix = "mesh57-derived-" + std::to_string(GetCurrentProcessId()) + "-"; CacheCleanup cache; for (unsigned attempt = 0;; ++attempt) { @@ -2487,7 +2500,7 @@ static int derived_mesh_fixture(ID3D12Device* device, ID3D12Device* guest, ID3D1 key = extend(key, blob->GetBufferPointer(), blob->GetBufferSize()); const UINT64 variant = extend(extend(extend(key, fields, sizeof(fields)), state_a.data(), state_a.size()), state_b.data(), state_b.size()); - if (std::strcmp(mode, "mesh-derived-reviewed") == 0) { + if (std::strcmp(mode, "mesh-derived-reviewed") == 0 || std::strcmp(mode, "mesh-derived-dxc-reviewed") == 0) { char name[64]; std::snprintf(name, sizeof(name), "%016llx.mesh57-state", static_cast(variant)); std::ofstream out(cache.path / name, std::ios::binary); @@ -2529,7 +2542,7 @@ static int derived_mesh_fixture(ID3D12Device* device, ID3D12Device* guest, ID3D1 profile.targets.NumRenderTargets = 1; profile.targets.RTFormats[0] = format; profile.blend.RenderTarget[0].RenderTargetWriteMask = D3D12_COLOR_WRITE_ENABLE_ALL; - const int pixels = std::strcmp(mode, "mesh-derived") == 0 ? 1 : 2; + const int pixels = std::strcmp(mode, "mesh-derived") == 0 || std::strcmp(mode, "mesh-derived-dxc") == 0 ? 1 : 2; const bool painted = run(device, guest, writer, work.Get(), root.Get(), pso.Get(), signature.Get(), DrawKind::mesh, false, Refusal::none, mode, nullptr, false, nullptr, false, false, 0, false, false, nullptr, nullptr, false, pixels, &profile); @@ -2562,8 +2575,10 @@ int main(int argc, char** argv) try const bool derived_depth = argc == 3 && std::strcmp(argv[2], "mesh-derived-depth") == 0; const bool derived_reviewed = argc == 3 && std::strcmp(argv[2], "mesh-derived-reviewed") == 0; const bool derived_untranslated = argc == 3 && std::strcmp(argv[2], "mesh-derived-untranslated") == 0; + const bool derived_dxc = argc == 3 && std::strcmp(argv[2], "mesh-derived-dxc") == 0; + const bool derived_dxc_reviewed = argc == 3 && std::strcmp(argv[2], "mesh-derived-dxc-reviewed") == 0; const bool derived_mesh = derived_off || derived_bad || derived_depth || derived_reviewed || derived_untranslated || - (argc == 3 && std::strcmp(argv[2], "mesh-derived") == 0); + derived_dxc || derived_dxc_reviewed || (argc == 3 && std::strcmp(argv[2], "mesh-derived") == 0); const bool console_mesh = argc == 3 && std::strcmp(argv[2], "mesh-console") == 0; const bool desktop_as = argc == 3 && std::strcmp(argv[2], "mesh-amplified") == 0; const bool copy_on = argc == 3 && std::strcmp(argv[2], "copy-provenance") == 0; From 24b5b533d89b84513bf53a9d080132b22ea40622 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Sun, 29 Nov 2026 00:44:25 +0000 Subject: [PATCH 04/12] runtime: count every DispatchMesh derive refusal by reason The opt-in now records each DispatchMesh ExecuteIndirect, including calls that never enter slot 57 derivation. The fixed-pair check reports which clause failed, and the heartbeat prints the counts with one sample per reason. Captured stage bytes stay available for a later attempt while the switch is on. Refs #870 Refs #2413 Co-authored-by: SimSalabimse --- docs/experiments/native-fixed-mesh57.md | 26 ++++ docs/startup-runtime.md | 2 +- src/startup_stubs/d3d12_draw.inl | 8 +- src/startup_stubs/d3d12_xs_device.cpp | 47 +++++-- src/startup_stubs/mesh57_alloc.h | 157 ++++++++++++++++++++++++ src/startup_stubs/native_mesh57.inl | 83 ++++++++++++- tests/mesh57_derive_alloc_check.cpp | 78 ++++++++++++ 7 files changed, 384 insertions(+), 17 deletions(-) diff --git a/docs/experiments/native-fixed-mesh57.md b/docs/experiments/native-fixed-mesh57.md index 4eb8b262b3..33a2ef8f8c 100644 --- a/docs/experiments/native-fixed-mesh57.md +++ b/docs/experiments/native-fixed-mesh57.md @@ -97,6 +97,32 @@ source-built positive and altered-stage controls with On the Windows test PC at `aed2c0c7`, `X2W_MESH57_DERIVE_STATE=1` with no compiler directory logged that refusal and forwarded nothing. Setting `X2W_NATIVE_SHADERS` compiled this path and also translated other programs, which refused fixed graphics entries and compute views before any `ExecuteIndirect`. A startup run that wants only this path sets `X2W_MESH57_DERIVE_STATE=1`, `X2W_MESH57_DXC_DIR`, and `X2W_SHADER_CACHE`, and leaves `X2W_NATIVE_SHADERS` unset. +At `075e4611` the same PC ran 420 seconds with the derive switch and `X2W_MESH57_DXC_DIR` set and `X2W_NATIVE_SHADERS` unset. Menus stayed up. `DispatchMesh` `ExecuteIndirect` still refused 656,186 calls in the graphics-pipeline bucket and forwarded none. The log showed 16 lines, all `derived mesh needs a fixed slot 57 pair`. That 16 is the old log cap, not the number of calls that entered derivation. With the switch on, every `DispatchMesh` `ExecuteIndirect` is now counted, including ones that never enter derivation. + +Derivation still runs only for a direct list whose bound pipeline is slot 57, has no desktop pipeline, and has no cached mesh stage. Anything else is counted and left on the existing refusal: + +- `not a direct list` +- `no pipeline bound` +- `desktop pipeline already set` +- `cached mesh stage` +- `no pipeline record` +- `pipeline is slot 86` (a stream mesh, or a pipeline that already has a slot 86 key) +- `pipeline is a derived slot 55` (the sample's `base` is the slot of the pipeline it was derived from, when that chain stays inside slot 55) +- `pipeline is not slot 57` + +A slot 57 record is a fixed pair only when the captured descriptor is 768 bytes, the vertex span at `+0x48` is empty, the mesh length at `+0x70` is non-zero, and both the mesh and pixel bytes were copied at creation. Otherwise the call is counted under one of: + +- `slot 57 descriptor is shorter than the fixed prefix` (under 120 bytes, so the stage words were not read) +- `slot 57 descriptor is not 768 bytes` +- `slot 57 descriptor has a vertex span` (the capture skips the mesh and pixel copies) +- `slot 57 descriptor has no mesh stage length` +- `slot 57 mesh stage was not captured` (the bytes were unreadable or larger than 1 MiB) +- `slot 57 pixel stage was not captured` (no pixel bytes; a zero pixel span is not a program this path can compile) + +Those six still refuse. The 768-byte rule stays: a shorter descriptor cannot be checked against a reviewed `.mesh57-state` file. While the switch is on, publishing a slot 57 request no longer drops the captured stage bytes, so a later call whose first refusal depended on the command list can still see them. + +The first time a reason is seen, stderr gets one `x2w-render mesh57-derive sample` line: the reason, the creating slot (`path`), the derived-from slot (`base`), descriptor and stage sizes, the vertex, mesh and pixel lengths from the descriptor, the pipeline key, the list type, and whether a desktop pipeline or a slot 86 key is present. The line has no file path. Every 300 presented frames the heartbeat adds `x2w-render mesh57-derive:` with the call count of each reason. `forwarded` is that count when derivation installs a desktop pipeline. + A startup run on the Windows test PC recorded 653,708 refused `DispatchMesh` `ExecuteIndirect` calls in 420 seconds and forwarded none. Across draw and mesh, the graphics-pipeline census counted `graphics/no_translation` 446,421 and `graphics/mesh_profile_missing` 427,428. This switch is only the second of those, and only the immediate-allocation shape below. Slot 86 meshes with no cached stage stay refused. The accepted program writes `m0` with one `s_mov_b32` of an integer immediate and the next instruction is the only `s_sendmsg` `GS_ALLOC_REQ` (`0xbf900009`). The immediate is `(primitives << 12) | vertices`, both counts are in 1..64, and the high byte is clear. A group-memory count exchange (`0xbf8a0000`) or an `s_mov_b32` of `exec_lo` is refused. The derived layout is one wave64 group of 64 threads, triangle topology, and group stride 0. Stride 0 is accepted because this program does not read the group id; the lowerer skips that multiply. The pixel shader must be a constant `MRT0` export with no resource bindings, and the guest root must be empty. diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index bfd9e30844..d82a09c75b 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -1735,7 +1735,7 @@ ctest --preset dev --no-tests=error -R '^startup_hook_(window|overlap)$' -V | `X2W_SHADER_CACHE=` | translation cache: the runtime writes source requests `req_.{a,b,root}`, when needed RTV variants `req_.rtv`, and for device slot 67 compute pipelines `req_.{desc,sa,sb,data,root,c67}` (see [Compute pipeline requests](#compute-pipeline-requests)). A console pipeline that an `ExecuteIndirect` draw (list slot 61) refuses writes the same request as a direct draw, once per pipeline, and draws nothing (`startup_indirect_requests_warp`). Only direct draws poll for its manifest, so such a pipeline stays in the `missing` count until a direct draw uses it; the `x2w-render totals` line counts `pipelines first looked up by ExecuteIndirect N`. This is a per-process lookup count. Check for the ready marker `req_.a` to confirm a complete request is available. Run `tools/startup/gfx2hlsl.py --pending ` while the process is running, or start the run with `run.ps1 -Translate` (see [Translating shaders during a run](#translating-shaders-during-a-run)). Active draws poll for an absent manifest at most once per second per pipeline and use the published translation on a subsequent draw. The translator compiles `.vs.cso` and `.ps.cso` with `fxc.exe`: `X2W_FXC`, else the Windows SDK 10.0.26100.0 copy, else the newest `Windows Kits\10\bin\\x64`, else `PATH`. When none exists it writes `.fail` naming `X2W_FXC` without publishing a new manifest. `X2W_FXC=` (empty) publishes the manifest alone. Rerun `--pending` with compilation enabled to fill in missing bytecode for an existing manifest. At its first native slot-57 profile lookup the runtime lists the directory's top-level file names once and logs `x2w-draw cache index: names in ms` (`src/startup_stubs/cache_index.h`). A `.mesh57-state` profile is opened only when that listing has its name, so a profile written while the process runs is read by the next process. Manifests and every other cache file are still looked up on disk. | | `X2W_NATIVE_SHADERS=` (`run.ps1 -NativeShaders `) | experimental, in render mode: translates device slot 67 compute requests in the stand-in with the C++ compiler; `` holds `dxcompiler.dll` and `dxil.dll`. See [Translating compute programs in the stand-in](#translating-compute-programs-in-the-stand-in) | | `X2W_MESH57_DXC_DIR=` | experimental, with `X2W_MESH57_DERIVE_STATE=1`: the directory of `dxcompiler.dll` and `dxil.dll` for that one slot 57 derivation. Other graphics and compute programs stay on the non-native path. Unset, the derivation may still use `X2W_NATIVE_SHADERS` when that directory is set. When neither directory is set, the call stays refused (`derived mesh needs the native shader compiler`). See [Opt-in immediate allocation](experiments/native-fixed-mesh57.md#opt-in-immediate-allocation) | -| `X2W_MESH57_DERIVE_STATE=1` | experimental, with `X2W_SHADER_CACHE` and `X2W_MESH57_DXC_DIR` (or `X2W_NATIVE_SHADERS`): addresses `graphics/mesh_profile_missing` for one slot 57 shape. A direct `DispatchMesh` `ExecuteIndirect` may build one desktop mesh pipeline from an immediate `GS_ALLOC_REQ` and the bound color target when captured stages exist and no `.mesh57-state` file was opened. `graphics/no_translation`, slot 86, depth, stencil, a non-empty root, and any other allocation shape stay refused. The rasterizer is not taken from the register block. See [Opt-in immediate allocation](experiments/native-fixed-mesh57.md#opt-in-immediate-allocation) | +| `X2W_MESH57_DERIVE_STATE=1` | experimental, with `X2W_SHADER_CACHE` and `X2W_MESH57_DXC_DIR` (or `X2W_NATIVE_SHADERS`): addresses `graphics/mesh_profile_missing` for one slot 57 shape. A direct `DispatchMesh` `ExecuteIndirect` may build one desktop mesh pipeline from an immediate `GS_ALLOC_REQ` and the bound color target when captured stages exist and no `.mesh57-state` file was opened. `graphics/no_translation`, slot 86, slot 55, depth, stencil, a non-empty root, and any other allocation shape stay refused. While the switch is on, every `DispatchMesh` `ExecuteIndirect` is counted: the first use of a reason logs `x2w-render mesh57-derive sample`, and the 300-frame heartbeat logs `x2w-render mesh57-derive:` with the counts. The rasterizer is not taken from the register block. See [Opt-in immediate allocation](experiments/native-fixed-mesh57.md#opt-in-immediate-allocation) | | `X2W_D3D12_LINEAR_BUFFERS=1` or `=copy` | opt-in backing for linear buffers placed at a title address (device slot 133, initial state `COMMON`): shared where the adapter, extent and memory allow it (private allocations larger than 256 MiB are skipped only with `X2W_D3D12_CAP_EXISTING_HEAP=1`), otherwise copied from title memory at each submission, otherwise the default backing is kept and the refusal recorded; `copy` never shares. Unset or `0`, slot 133 keeps its default backing. See [Linear buffer backing (device slot 133, opt-in)](#linear-buffer-backing-device-slot-133-opt-in) | | `X2W_D3D12_CAP_EXISTING_HEAP=1` | opt-in 256 MiB (`unplaced_existing_heap_allowed`) allocation-size cap on `OpenExistingHeapFromAddress` in device slot 133 (`startup_slot133_heap_cap_*`). Unset (default), private allocations larger than 256 MiB keep the formerly aliased path: a capped copied placement is refused by `CopyBufferRegion` (list slot 15) as `title_backed_source`, losing a late guest write made after recording and before submit. Set, allocations larger than 256 MiB skip `OpenExistingHeapFromAddress` so multi-GiB startup blocks are not pinned in `WorkingSetSize` and `NonLocal` GPU memory | | `X2W_D3D12_ROOT_SRV_AT_DRAW=1` | opt-in, render mode: a graphics root SRV (slot 44) without an upload mapping is not copied into the upload ring, since no draw reads that desktop binding (default: a 64 KiB copy at every slot 44 call). Translated draws copy the SRV themselves and are unaffected (`startup_root_srv_draw_*`). See [the experiment note](experiments/startup-root-srv-at-draw.md) | diff --git a/src/startup_stubs/d3d12_draw.inl b/src/startup_stubs/d3d12_draw.inl index 9c1c2b2a2f..5c75f03143 100644 --- a/src/startup_stubs/d3d12_draw.inl +++ b/src/startup_stubs/d3d12_draw.inl @@ -930,8 +930,12 @@ void request_slot57_mesh(Wrapper* pipeline, const std::vector* bo if (first && first_calls(logged, 12)) log("x2w-draw mesh request %016llx: slot57, MS %zu bytes, PS %zu bytes", key, mesh.size(), pixel.size()); - info->fixed_ms.reset(); - info->fixed_ps.reset(); + // The opt-in derivation reads these bytes on a later ExecuteIndirect. A retryable refusal + // (attachments, the bound root) must not become a permanent missing-stage refusal. + if (!x2w_local::env_on("X2W_MESH57_DERIVE_STATE")) { + info->fixed_ms.reset(); + info->fixed_ps.reset(); + } } } diff --git a/src/startup_stubs/d3d12_xs_device.cpp b/src/startup_stubs/d3d12_xs_device.cpp index 3079582245..4d2d4892c7 100644 --- a/src/startup_stubs/d3d12_xs_device.cpp +++ b/src/startup_stubs/d3d12_xs_device.cpp @@ -3741,6 +3741,8 @@ LONG root_srv_copies_skipped, root_srv_copies_made; #ifdef X2W_NATIVE_SHADERS const char* derive_slot57_mesh(Wrapper* pipeline, Pass& pass); +void record_mesh57_derive(const char* reason, Wrapper* pipeline, const PipelineInfo* info, int list_type); +void log_mesh57_derive_census(); #endif void __stdcall list_execute_indirect(Wrapper* self, void* signature, UINT count, void* argument, u64 offset, @@ -3824,20 +3826,38 @@ void __stdcall list_execute_indirect(Wrapper* self, void* signature, UINT count, else if (mesh) bytes = sizeof(D3D12_DISPATCH_MESH_ARGUMENTS); else bytes = sizeof(D3D12_DRAW_ARGUMENTS); #ifdef X2W_NATIVE_SHADERS - // Opt-in for the graphics/mesh_profile_missing refusal: a direct DispatchMesh whose slot 57 - // pipeline has no desktop PSO and no cached stage. Draws, and any mesh pipeline that is not - // slot 57, stay on the refusal below (graphics/no_translation among them). A reviewed - // .mesh57-state profile is unchanged. With the switch off this block does not run. - const PipelineInfo* derived_info = pass.pipeline ? pipeline_info(pass.pipeline) : nullptr; - if (mesh && type == D3D12_COMMAND_LIST_TYPE_DIRECT && pass.pipeline && !pass.pipeline->own().real && - !pass.indirect_graphics.cached_mesh && derived_info && derived_info->path == 57 && - x2w_local::env_on("X2W_MESH57_DERIVE_STATE")) { - if (const char* why = derive_slot57_mesh(pass.pipeline, pass)) { - static LONG derived_mesh_refusals; - if (first_calls(derived_mesh_refusals, 16)) - log("x2w-render derived slot57 mesh refused: %s", why); + // Opt-in for one slot 57 shape. Every DispatchMesh is counted here when the switch is on, + // including calls that never enter derivation. Draws stay on the refusal below. + if (mesh && x2w_local::env_on("X2W_MESH57_DERIVE_STATE")) { + const PipelineInfo* derived_info = pass.pipeline ? pipeline_info(pass.pipeline) : nullptr; + const char* skip = nullptr; + if (type != D3D12_COMMAND_LIST_TYPE_DIRECT) + skip = "not a direct list"; + else if (!pass.pipeline) + skip = "no pipeline bound"; + else if (pass.pipeline->own().real) + skip = "desktop pipeline already set"; + else if (pass.indirect_graphics.cached_mesh) + skip = "cached mesh stage"; + else if (!derived_info) + skip = "no pipeline record"; + else if (derived_info->path != 57) { + if (pass.pipeline->own().mesh86_key || derived_info->path == 86) + skip = "pipeline is slot 86"; + else if (derived_info->path == 55) + skip = "pipeline is a derived slot 55"; + else + skip = "pipeline is not slot 57"; + } + if (skip) { + record_mesh57_derive(skip, pass.pipeline, derived_info, static_cast(type)); + } else if (const char* why = derive_slot57_mesh(pass.pipeline, pass)) { + record_mesh57_derive(why, pass.pipeline, derived_info, static_cast(type)); } else if (pass.pipeline->own().real) { pass.indirect_graphics = pass.pipeline->own().indirect_graphics; + record_mesh57_derive("forwarded", pass.pipeline, pipeline_info(pass.pipeline), static_cast(type)); + } else { + record_mesh57_derive("derivation produced no pipeline", pass.pipeline, derived_info, static_cast(type)); } } #endif @@ -7874,6 +7894,9 @@ HRESULT __stdcall queue_present(Wrapper* self, UINT planes, const void* plane_pa if (n == start) n += std::snprintf(line + n, sizeof(line) - n, " 0"); } log("%s", line); +#ifdef X2W_NATIVE_SHADERS + log_mesh57_derive_census(); +#endif } if (render_mode() && frame % 300 == 0) { // Which command-list slots the title called in the last 300 frames, per frame. diff --git a/src/startup_stubs/mesh57_alloc.h b/src/startup_stubs/mesh57_alloc.h index c6baa5ba62..2701587bc4 100644 --- a/src/startup_stubs/mesh57_alloc.h +++ b/src/startup_stubs/mesh57_alloc.h @@ -11,6 +11,7 @@ #include #include +#include #include #include #include @@ -97,4 +98,160 @@ inline std::optional derive_immediate_mesh_layout(std::string } } +// Why a slot 57 creation record is not the fixed mesh+pixel pair this path can read. +// nullptr means both stages were captured from a 768-byte descriptor with no vertex span. +// The clauses match the capture in note_pipeline: a vertex span, a zero mesh length, or a +// short descriptor leaves the stage pointers empty, and an unreadable stage is dropped. +struct Mesh57PairRecord { + std::size_t desc_bytes = 0; + bool mesh_captured = false; + bool pixel_captured = false; + std::uint64_t vertex_pointer = 0; + std::uint64_t vertex_bytes = 0; + std::uint64_t mesh_length = 0; + std::uint64_t pixel_length = 0; +}; + +inline const char* mesh57_fixed_pair_reason(const Mesh57PairRecord& record) noexcept +{ + if (record.desc_bytes < 15 * sizeof(std::uint64_t)) + return "slot 57 descriptor is shorter than the fixed prefix"; + if (record.desc_bytes != 0x300) + return "slot 57 descriptor is not 768 bytes"; + if (record.vertex_pointer || record.vertex_bytes) + return "slot 57 descriptor has a vertex span"; + if (!record.mesh_length) + return "slot 57 descriptor has no mesh stage length"; + if (!record.mesh_captured) + return "slot 57 mesh stage was not captured"; + if (!record.pixel_captured) + return "slot 57 pixel stage was not captured"; + (void)record.pixel_length; + return nullptr; +} + +// One sample of the bound pipeline for a DispatchMesh ExecuteIndirect the opt-in did not forward. +// Counts are call counts. The sample is the first call that used that reason. +struct Mesh57DeriveSample { + int path = 0; + int base_path = 0; + std::uint64_t key = 0; + std::uint32_t desc_bytes = 0; + std::uint32_t mesh_bytes = 0; + std::uint32_t pixel_bytes = 0; + std::uint32_t state_a = 0; + std::uint32_t state_b = 0; + std::uint32_t vertex_bytes = 0; + std::uint32_t mesh_length = 0; + std::uint32_t pixel_length = 0; + int list_type = 0; + int real = 0; + int mesh86 = 0; +}; + +struct Mesh57DeriveCensus { + static constexpr int capacity = 24; + struct Row { + const char* reason = nullptr; + std::uint64_t calls = 0; + Mesh57DeriveSample sample; + }; + Row rows[capacity]; + int used = 0; + std::uint64_t overflow_calls = 0; + + Mesh57DeriveCensus() + { + for (int i = 0; i < capacity; ++i) + rows[i] = Row(); + } + + // True the first time `reason` is stored. Later calls only add to the count. + // `reason` must be a stable literal; rows compare the pointer. + bool note(const char* reason, const Mesh57DeriveSample& sample) noexcept + { + if (!reason) + return false; + for (int i = 0; i < used; ++i) { + if (rows[i].reason == reason) { + rows[i].calls += 1; + return false; + } + } + if (used >= capacity) { + overflow_calls += 1; + return false; + } + rows[used].reason = reason; + rows[used].calls = 1; + rows[used].sample = sample; + used += 1; + return true; + } + + std::uint64_t total() const noexcept + { + std::uint64_t calls = overflow_calls; + for (int i = 0; i < used; ++i) + calls += rows[i].calls; + return calls; + } +}; + +inline std::size_t mesh57_derive_sample_line(const char* reason, const Mesh57DeriveSample& sample, + char* out, std::size_t cap) noexcept +{ + if (!out || cap == 0) + return 0; + const int n = std::snprintf(out, cap, + "x2w-render mesh57-derive sample reason=%s path=%d base=%d desc=%u ms=%u ps=%u state_a=%u state_b=%u " + "vs=%u ms_len=%u ps_len=%u key=%016llx list=%d real=%d mesh86=%d", + reason ? reason : "", sample.path, sample.base_path, sample.desc_bytes, sample.mesh_bytes, + sample.pixel_bytes, sample.state_a, sample.state_b, sample.vertex_bytes, sample.mesh_length, + sample.pixel_length, static_cast(sample.key), sample.list_type, sample.real, + sample.mesh86); + if (n < 0) { + out[0] = 0; + return 0; + } + if (static_cast(n) >= cap) { + out[cap - 1] = 0; + return cap - 1; + } + return static_cast(n); +} + +inline std::size_t mesh57_derive_summary_line(const Mesh57DeriveCensus& census, char* out, std::size_t cap) noexcept +{ + if (!out || cap == 0) + return 0; + out[0] = 0; + if (!census.total()) + return 0; + int n = std::snprintf(out, cap, "x2w-render mesh57-derive:"); + if (n < 0) { + out[0] = 0; + return 0; + } + for (int i = 0; i < census.used && static_cast(n) + 1 < cap; ++i) { + const int wrote = std::snprintf(out + n, cap - static_cast(n), "%s %s %llu", + i ? ";" : "", census.rows[i].reason ? census.rows[i].reason : "", + static_cast(census.rows[i].calls)); + if (wrote < 0) + break; + if (static_cast(n) + static_cast(wrote) >= cap) { + out[cap - 1] = 0; + return cap - 1; + } + n += wrote; + } + if (census.overflow_calls && static_cast(n) + 1 < cap) { + const int wrote = std::snprintf(out + n, cap - static_cast(n), "; unlisted %llu", + static_cast(census.overflow_calls)); + if (wrote > 0 && static_cast(n) + static_cast(wrote) < cap) + n += wrote; + } + return static_cast(n); +} + } // namespace x2w_startup diff --git a/src/startup_stubs/native_mesh57.inl b/src/startup_stubs/native_mesh57.inl index fb95451616..0ba6eeeb72 100644 --- a/src/startup_stubs/native_mesh57.inl +++ b/src/startup_stubs/native_mesh57.inl @@ -513,6 +513,73 @@ bool mesh57_reviewed_file_present(const PipelineInfo* info) return static_cast(file); } +x2w_startup::Mesh57DeriveCensus mesh57_derive_census; +SRWLOCK mesh57_derive_census_lock = SRWLOCK_INIT; + +std::uint32_t mesh57_derive_u32(std::size_t value) +{ + return value > 0xffffffffu ? 0xffffffffu : static_cast(value); +} + +x2w_startup::Mesh57DeriveSample mesh57_derive_sample(Wrapper* pipeline, const PipelineInfo* info, int list_type) +{ + x2w_startup::Mesh57DeriveSample sample; + sample.list_type = list_type; + if (!pipeline) + return sample; + sample.real = pipeline->own().real ? 1 : 0; + sample.mesh86 = pipeline->own().mesh86_key ? 1 : 0; + sample.key = known_pipeline_key(pipeline); + const PipelineInfo* base = info; + for (int depth = 0; base && base->path == 55 && base->base && depth < 8; ++depth) + base = pipeline_info(base->base); + if (base && base != info) + sample.base_path = base->path; + if (!info) + return sample; + sample.path = info->path; + sample.desc_bytes = mesh57_derive_u32(info->desc.size()); + sample.mesh_bytes = info->fixed_ms ? mesh57_derive_u32(info->fixed_ms->size()) : 0; + sample.pixel_bytes = info->fixed_ps ? mesh57_derive_u32(info->fixed_ps->size()) : 0; + sample.state_a = mesh57_derive_u32(info->state_a.size()); + sample.state_b = mesh57_derive_u32(info->state_b.size()); + if (info->desc.size() >= 15 * sizeof(u64)) { + u64 words[15]; + std::memcpy(words, info->desc.data(), sizeof(words)); + sample.vertex_bytes = mesh57_derive_u32(static_cast(words[10])); + sample.pixel_length = mesh57_derive_u32(static_cast(words[6])); + sample.mesh_length = mesh57_derive_u32(static_cast(words[14])); + } + return sample; +} + +void record_mesh57_derive(const char* reason, Wrapper* pipeline, const PipelineInfo* info, int list_type) +{ + const x2w_startup::Mesh57DeriveSample sample = mesh57_derive_sample(pipeline, info, list_type); + bool first = false; + AcquireSRWLockExclusive(&mesh57_derive_census_lock); + first = mesh57_derive_census.note(reason, sample); + ReleaseSRWLockExclusive(&mesh57_derive_census_lock); + if (!first) + return; + char line[640]; + if (x2w_startup::mesh57_derive_sample_line(reason, sample, line, sizeof(line))) + log("%s", line); +} + +void log_mesh57_derive_census() +{ + if (!x2w_local::env_on("X2W_MESH57_DERIVE_STATE")) + return; + x2w_startup::Mesh57DeriveCensus copy; + AcquireSRWLockShared(&mesh57_derive_census_lock); + copy = mesh57_derive_census; + ReleaseSRWLockShared(&mesh57_derive_census_lock); + char line[2048]; + if (x2w_startup::mesh57_derive_summary_line(copy, line, sizeof(line))) + log("%s", line); +} + // Builds one desktop mesh PSO for a direct DispatchMesh when X2W_MESH57_DERIVE_STATE=1 and no // reviewed profile was opened. Returns nullptr after publishing the PSO, or a stable reason. // A reason that depends on the command list (attachments, the bound root) is not remembered. @@ -536,8 +603,20 @@ const char* derive_slot57_mesh(Wrapper* pipeline, Pass& pass) const DWORD cache_length = GetEnvironmentVariableW(L"X2W_SHADER_CACHE", cache, MAX_PATH); if (!cache_length || cache_length >= MAX_PATH) return "derived mesh needs a shader cache"; - if (info->path != 57 || !info->fixed_ms || !info->fixed_ps || info->desc.size() != 0x300) - return remember("derived mesh needs a fixed slot 57 pair"); + x2w_startup::Mesh57PairRecord pair; + pair.desc_bytes = info->desc.size(); + pair.mesh_captured = static_cast(info->fixed_ms); + pair.pixel_captured = static_cast(info->fixed_ps); + if (info->desc.size() >= 15 * sizeof(u64)) { + u64 words[15]; + std::memcpy(words, info->desc.data(), sizeof(words)); + pair.vertex_pointer = words[9]; + pair.vertex_bytes = words[10]; + pair.pixel_length = words[6]; + pair.mesh_length = words[14]; + } + if (const char* pair_why = x2w_startup::mesh57_fixed_pair_reason(pair)) + return remember(pair_why); if (!info->mesh57_reviewed_present && mesh57_reviewed_file_present(info)) info->mesh57_reviewed_present = true; if (info->mesh57_reviewed_present) diff --git a/tests/mesh57_derive_alloc_check.cpp b/tests/mesh57_derive_alloc_check.cpp index 1a8eede361..06eaa38f38 100644 --- a/tests/mesh57_derive_alloc_check.cpp +++ b/tests/mesh57_derive_alloc_check.cpp @@ -90,5 +90,83 @@ int main() if (x2w_startup::derive_immediate_mesh_layout({})) return fail("empty"); + + x2w_startup::Mesh57PairRecord pair; + pair.desc_bytes = 0x300; + pair.mesh_captured = true; + pair.pixel_captured = true; + pair.mesh_length = 64; + pair.pixel_length = 16; + if (x2w_startup::mesh57_fixed_pair_reason(pair)) + return fail("fixed pair"); + pair.desc_bytes = 64; + if (std::strcmp(x2w_startup::mesh57_fixed_pair_reason(pair), + "slot 57 descriptor is shorter than the fixed prefix") != 0) + return fail("short descriptor"); + pair.desc_bytes = 256; + if (std::strcmp(x2w_startup::mesh57_fixed_pair_reason(pair), + "slot 57 descriptor is not 768 bytes") != 0) + return fail("descriptor length"); + pair.desc_bytes = 0x300; + pair.vertex_pointer = 0x1000; + if (std::strcmp(x2w_startup::mesh57_fixed_pair_reason(pair), + "slot 57 descriptor has a vertex span") != 0) + return fail("vertex span"); + pair.vertex_pointer = 0; + pair.mesh_length = 0; + if (std::strcmp(x2w_startup::mesh57_fixed_pair_reason(pair), + "slot 57 descriptor has no mesh stage length") != 0) + return fail("mesh length"); + pair.mesh_length = 64; + pair.mesh_captured = false; + if (std::strcmp(x2w_startup::mesh57_fixed_pair_reason(pair), + "slot 57 mesh stage was not captured") != 0) + return fail("mesh stage"); + pair.mesh_captured = true; + pair.pixel_captured = false; + if (std::strcmp(x2w_startup::mesh57_fixed_pair_reason(pair), + "slot 57 pixel stage was not captured") != 0) + return fail("pixel stage"); + + x2w_startup::Mesh57DeriveCensus census; + x2w_startup::Mesh57DeriveSample slot86; + slot86.path = 86; + slot86.mesh86 = 1; + slot86.desc_bytes = 512; + if (!census.note("pipeline is slot 86", slot86)) + return fail("first slot 86 note"); + slot86.path = 57; + if (census.note("pipeline is slot 86", slot86) || census.rows[0].calls != 2 || census.rows[0].sample.path != 86) + return fail("slot 86 count keeps the first sample"); + x2w_startup::Mesh57DeriveSample missing_ps; + missing_ps.path = 57; + missing_ps.desc_bytes = 0x300; + missing_ps.mesh_bytes = 128; + if (!census.note("slot 57 pixel stage was not captured", missing_ps) || census.total() != 3) + return fail("pixel stage count"); + char summary[512]; + const auto summary_n = x2w_startup::mesh57_derive_summary_line(census, summary, sizeof(summary)); + if (!summary_n || !std::strstr(summary, "pipeline is slot 86 2") || + !std::strstr(summary, "slot 57 pixel stage was not captured 1") || + std::strncmp(summary, "x2w-render mesh57-derive:", 25) != 0) + return fail("summary"); + char sample[512]; + if (!x2w_startup::mesh57_derive_sample_line(census.rows[0].reason, census.rows[0].sample, sample, sizeof(sample)) || + !std::strstr(sample, "reason=pipeline is slot 86") || !std::strstr(sample, "path=86") || + !std::strstr(sample, "desc=512") || std::strncmp(sample, "x2w-render mesh57-derive sample ", 32) != 0) + return fail("sample"); + x2w_startup::Mesh57DeriveCensus full; + if (!full.note("overflow-probe", slot86)) + return fail("overflow first"); + const char* extras[] = { + "r1", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", + "r11", "r12", "r13", "r14", "r15", "r16", "r17", "r18", "r19", "r20", + "r21", "r22", "r23"}; + for (const char* extra : extras) { + if (!full.note(extra, slot86)) + return fail("fill census"); + } + if (full.note("r24", slot86) || full.overflow_calls != 1 || full.used != full.capacity) + return fail("census overflow"); return 0; } From 9edb8c947d8bb0d491ae26f09f9a4c8deed410a5 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Sun, 29 Nov 2026 00:51:19 +0000 Subject: [PATCH 05/12] runtime: match mesh derive reasons by text, not address MSVC does not give two copies of the same reason string the same address, so the census treated the second note as a new reason and kept that sample. Rows now compare the characters. The host check uses two distinct copies. Refs #870 Refs #2413 Co-authored-by: SimSalabimse --- src/startup_stubs/mesh57_alloc.h | 7 ++++--- tests/mesh57_derive_alloc_check.cpp | 10 ++++++++-- 2 files changed, 12 insertions(+), 5 deletions(-) diff --git a/src/startup_stubs/mesh57_alloc.h b/src/startup_stubs/mesh57_alloc.h index 2701587bc4..14aea8f6e5 100644 --- a/src/startup_stubs/mesh57_alloc.h +++ b/src/startup_stubs/mesh57_alloc.h @@ -166,14 +166,15 @@ struct Mesh57DeriveCensus { rows[i] = Row(); } - // True the first time `reason` is stored. Later calls only add to the count. - // `reason` must be a stable literal; rows compare the pointer. + // True the first time this reason text is stored. Later calls only add to the count. + // The row keeps the first pointer, so that pointer must outlive the census. Matching is by + // text: two copies of the same characters are one reason. String-literal addresses are not. bool note(const char* reason, const Mesh57DeriveSample& sample) noexcept { if (!reason) return false; for (int i = 0; i < used; ++i) { - if (rows[i].reason == reason) { + if (rows[i].reason && std::strcmp(rows[i].reason, reason) == 0) { rows[i].calls += 1; return false; } diff --git a/tests/mesh57_derive_alloc_check.cpp b/tests/mesh57_derive_alloc_check.cpp index 06eaa38f38..b6980db283 100644 --- a/tests/mesh57_derive_alloc_check.cpp +++ b/tests/mesh57_derive_alloc_check.cpp @@ -133,10 +133,16 @@ int main() slot86.path = 86; slot86.mesh86 = 1; slot86.desc_bytes = 512; - if (!census.note("pipeline is slot 86", slot86)) + // Two objects with the same characters. A compiler that does not pool string literals gives + // them different addresses; they are still one reason. + char first_reason[] = "pipeline is slot 86"; + char second_reason[] = "pipeline is slot 86"; + if (&first_reason[0] == &second_reason[0]) + return fail("reason copies are the same object"); + if (!census.note(first_reason, slot86)) return fail("first slot 86 note"); slot86.path = 57; - if (census.note("pipeline is slot 86", slot86) || census.rows[0].calls != 2 || census.rows[0].sample.path != 86) + if (census.note(second_reason, slot86) || census.rows[0].calls != 2 || census.rows[0].sample.path != 86) return fail("slot 86 count keeps the first sample"); x2w_startup::Mesh57DeriveSample missing_ps; missing_ps.path = 57; From 92ca511ba7d7934616ac0f48a5b9e02a0df86092 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Sun, 29 Nov 2026 01:23:31 +0000 Subject: [PATCH 06/12] runtime: bind one derived mesh constant and reuse slot 55 bases A DispatchMesh derivation now copies a single guest constant block of 1..8 dwords into desktop b0, including a heap-indexed root whose only parameter is that block. Descriptor roots and other heap-indexed shapes stay refused by name. A slot 55 pipeline uses its slot 57 base when every patch is a blend record. The heartbeat adds the derived forward count. Co-authored-by: SimSalabimse --- CMakeLists.txt | 2 +- docs/experiments/native-fixed-mesh57.md | 16 ++- docs/startup-runtime.md | 2 +- src/startup_stubs/d3d12_xs_device.cpp | 27 +++-- src/startup_stubs/mesh57_alloc.h | 120 ++++++++++++++++++- src/startup_stubs/native_mesh57.inl | 147 ++++++++++++++++++++++-- tests/mesh57_derive_alloc_check.cpp | 60 +++++++++- tests/startup_indirect_draw_indexed.cpp | 69 ++++++++++- 8 files changed, 408 insertions(+), 35 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index ceb80ab48c..ec62b2d8cd 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1948,7 +1948,7 @@ if(TARGET compile_dxil AND EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${ add_test(NAME native_fixed_mesh57_${backend} COMMAND startup_indirect_draw_indexed ${backend} mesh) set_tests_properties(native_fixed_mesh57_${backend} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77 ENVIRONMENT "X2W_TEST_NATIVE_MESH57=1;X2W_NATIVE_SHADERS=${DXC_BIN_DIR}") - foreach(mode derived derived-off derived-bad derived-depth derived-reviewed derived-untranslated) + foreach(mode derived derived-off derived-bad derived-depth derived-reviewed derived-untranslated derived-root derived-root-unset derived-root-table derived-slot55 derived-slot55-mask) add_test(NAME startup_indirect_mesh_${mode}_${backend} COMMAND startup_indirect_draw_indexed ${backend} mesh-${mode}) set_tests_properties(startup_indirect_mesh_${mode}_${backend} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77 diff --git a/docs/experiments/native-fixed-mesh57.md b/docs/experiments/native-fixed-mesh57.md index 33a2ef8f8c..c33837a792 100644 --- a/docs/experiments/native-fixed-mesh57.md +++ b/docs/experiments/native-fixed-mesh57.md @@ -99,7 +99,7 @@ On the Windows test PC at `aed2c0c7`, `X2W_MESH57_DERIVE_STATE=1` with no compil At `075e4611` the same PC ran 420 seconds with the derive switch and `X2W_MESH57_DXC_DIR` set and `X2W_NATIVE_SHADERS` unset. Menus stayed up. `DispatchMesh` `ExecuteIndirect` still refused 656,186 calls in the graphics-pipeline bucket and forwarded none. The log showed 16 lines, all `derived mesh needs a fixed slot 57 pair`. That 16 is the old log cap, not the number of calls that entered derivation. With the switch on, every `DispatchMesh` `ExecuteIndirect` is now counted, including ones that never enter derivation. -Derivation still runs only for a direct list whose bound pipeline is slot 57, has no desktop pipeline, and has no cached mesh stage. Anything else is counted and left on the existing refusal: +Derivation runs for a direct list whose bound pipeline is slot 57, or slot 55 whose base chain ends at slot 57, when that pipeline has no desktop pipeline and no cached mesh stage. Anything else is counted and left on the existing refusal: - `not a direct list` - `no pipeline bound` @@ -107,7 +107,7 @@ Derivation still runs only for a direct list whose bound pipeline is slot 57, ha - `cached mesh stage` - `no pipeline record` - `pipeline is slot 86` (a stream mesh, or a pipeline that already has a slot 86 key) -- `pipeline is a derived slot 55` (the sample's `base` is the slot of the pipeline it was derived from, when that chain stays inside slot 55) +- `pipeline is a derived slot 55` (the base chain does not end at slot 57) - `pipeline is not slot 57` A slot 57 record is a fixed pair only when the captured descriptor is 768 bytes, the vertex span at `+0x48` is empty, the mesh length at `+0x70` is non-zero, and both the mesh and pixel bytes were copied at creation. Otherwise the call is counted under one of: @@ -121,11 +121,15 @@ A slot 57 record is a fixed pair only when the captured descriptor is 768 bytes, Those six still refuse. The 768-byte rule stays: a shorter descriptor cannot be checked against a reviewed `.mesh57-state` file. While the switch is on, publishing a slot 57 request no longer drops the captured stage bytes, so a later call whose first refusal depended on the command list can still see them. -The first time a reason is seen, stderr gets one `x2w-render mesh57-derive sample` line: the reason, the creating slot (`path`), the derived-from slot (`base`), descriptor and stage sizes, the vertex, mesh and pixel lengths from the descriptor, the pipeline key, the list type, and whether a desktop pipeline or a slot 86 key is present. The line has no file path. Every 300 presented frames the heartbeat adds `x2w-render mesh57-derive:` with the call count of each reason. `forwarded` is that count when derivation installs a desktop pipeline. +The first time a reason is seen, stderr gets one `x2w-render mesh57-derive sample` line: the reason, the creating slot (`path`), the derived-from slot (`base`), descriptor and stage sizes, the vertex, mesh and pixel lengths from the descriptor, the pipeline key, the list type, whether a desktop pipeline or a slot 86 key is present, and the guest root (`root`, `const`, `other`, `heap`). The line has no file path. Every 300 presented frames the heartbeat adds `x2w-render mesh57-derive:` with the call count of each reason, then `x2w-render mesh57-derive forwards:` with the `forwarded` count. That count is the number of calls that installed a desktop pipeline from this path. A startup run on the Windows test PC recorded 653,708 refused `DispatchMesh` `ExecuteIndirect` calls in 420 seconds and forwarded none. Across draw and mesh, the graphics-pipeline census counted `graphics/no_translation` 446,421 and `graphics/mesh_profile_missing` 427,428. This switch is only the second of those, and only the immediate-allocation shape below. Slot 86 meshes with no cached stage stay refused. -The accepted program writes `m0` with one `s_mov_b32` of an integer immediate and the next instruction is the only `s_sendmsg` `GS_ALLOC_REQ` (`0xbf900009`). The immediate is `(primitives << 12) | vertices`, both counts are in 1..64, and the high byte is clear. A group-memory count exchange (`0xbf8a0000`) or an `s_mov_b32` of `exec_lo` is refused. The derived layout is one wave64 group of 64 threads, triangle topology, and group stride 0. Stride 0 is accepted because this program does not read the group id; the lowerer skips that multiply. The pixel shader must be a constant `MRT0` export with no resource bindings, and the guest root must be empty. +The accepted program writes `m0` with one `s_mov_b32` of an integer immediate and the next instruction is the only `s_sendmsg` `GS_ALLOC_REQ` (`0xbf900009`). The immediate is `(primitives << 12) | vertices`, both counts are in 1..64, and the high byte is clear. A group-memory count exchange (`0xbf8a0000`) or an `s_mov_b32` of `exec_lo` is refused. The derived layout is one wave64 group of 64 threads, triangle topology, and group stride 0. Stride 0 is accepted because this program does not read the group id; the lowerer skips that multiply. The pixel shader must be a constant `MRT0` export with no resource bindings. + +An empty guest root is unchanged. One 32-bit constant parameter of 1..8 dwords and no other parameters is bound, including when the guest root is heap indexed: user SGPR s8 is that block, and the draw copies it into a desktop b0 the same way a reviewed constant profile does. The constant words must already be set on the list. The heap base itself is not bound; a shader that reads it is refused by the lowerer. A heap-indexed root with any other shape (`derived mesh guest root is heap indexed`), a descriptor or root descriptor (`derived mesh guest root has descriptors`), or any other constant shape (`derived mesh guest root constants do not fit one user block`) stays refused. Those need a reviewed SGPR map; this path does not invent one. + +A slot 55 pipeline reuses that derived mesh when every patch record is a blend patch (tag 2, 0x14c bytes) or the patch list is empty. The last blend patch replaces the base blend. Any other record stays refused (`slot 55 patches are not applied`). The base's shader, root, and depth rules are unchanged. Fixed function state comes from state block A. The mesh layout word at `+0x004` must be 6. Blend words are read at the mesh shift (`+0x54` on top of `+0xD0`). Depth and stencil must decode as disabled; an enabled test is refused rather than given a guessed depth format. The color target is the one single-sample target bound on that direct list, with a viewport and a scissor and no depth view. The rasterizer is solid, cull none, and depth clip. Those three values are not read from the register block. A `.mesh57-state` file that is present, including one whose bytes do not match, keeps the reviewed path and this switch does not create a pipeline. @@ -137,4 +141,6 @@ From the x64 Windows build environment, with DXC available to the native shader ctest --preset dev -j 1 --no-tests=error -R "mesh57_derive_alloc|startup_indirect_mesh_derived" ``` -`startup_indirect_mesh_derived_{warp,hardware}` forwards one group and reads a white texel at `(2,0)` on a 4 by 2 target. `derived-dxc` does the same with only `X2W_MESH57_DXC_DIR` set, and the process clears `X2W_NATIVE_SHADERS` before the call. `derived-off` leaves the switch unset. `derived-bad` has no immediate allocation. `derived-depth` enables the depth test in the register block. `derived-reviewed` and `derived-dxc-reviewed` supply a profile file that does not match; the second does that with only `X2W_MESH57_DXC_DIR` set. `derived-untranslated` is a slot 57 pipeline with no captured mesh or pixel program, so the switch has nothing to translate. Those six leave the clear color. Each returns 77 when mesh shaders or the command signature are unavailable. `mesh57_derive_alloc` checks the allocation reader without a device. +`startup_indirect_mesh_derived_{warp,hardware}` forwards one group and reads a white texel at `(2,0)` on a 4 by 2 target. `derived-dxc` does the same with only `X2W_MESH57_DXC_DIR` set, and the process clears `X2W_NATIVE_SHADERS` before the call. `derived-root` is that program plus one guest constant at s8, with the word set, and paints the same texel. `derived-slot55` draws through a slot 55 pipeline with no patches and paints the same texel. `derived-off` leaves the switch unset. `derived-bad` has no immediate allocation. `derived-depth` enables the depth test in the register block. `derived-reviewed` and `derived-dxc-reviewed` supply a profile file that does not match; the second does that with only `X2W_MESH57_DXC_DIR` set. `derived-untranslated` is a slot 57 pipeline with no captured mesh or pixel program. `derived-root-unset` omits the constant word. `derived-root-table` uses a descriptor table. `derived-slot55-mask` applies a blend patch with a zero write mask. Those leave the clear color. Each returns 77 when mesh shaders or the command signature are unavailable. `mesh57_derive_alloc` checks the allocation reader, the root decision, the slot 55 patch rule, and the forwards line without a device. + +On the Windows test PC at `f358a2ed`, a 420 second run with `X2W_TRANSLATED_INDIRECT_DRAW=1`, `X2W_MESH57_DERIVE_STATE=1`, and `X2W_MESH57_DXC_DIR` set forwarded nothing. The derive census was `slot 57 pixel stage was not captured` 47823, `derived mesh keeps a non-empty guest root refused` 152144, and `pipeline is a derived slot 55` 180066. The non-empty sample had both stages (mesh 9536 bytes, pixel 4352 bytes). The slot 55 sample was a 332-byte descriptor whose base was slot 57 and whose stage lengths were unread. That root refusal is replaced by the three root reasons above, and a slot 55 call now uses its slot 57 base when the patches are blend records. A 4352-byte pixel is still not a constant export, and a program that is not the one immediate allocation is still refused. diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index d82a09c75b..dfb436175c 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -1735,7 +1735,7 @@ ctest --preset dev --no-tests=error -R '^startup_hook_(window|overlap)$' -V | `X2W_SHADER_CACHE=` | translation cache: the runtime writes source requests `req_.{a,b,root}`, when needed RTV variants `req_.rtv`, and for device slot 67 compute pipelines `req_.{desc,sa,sb,data,root,c67}` (see [Compute pipeline requests](#compute-pipeline-requests)). A console pipeline that an `ExecuteIndirect` draw (list slot 61) refuses writes the same request as a direct draw, once per pipeline, and draws nothing (`startup_indirect_requests_warp`). Only direct draws poll for its manifest, so such a pipeline stays in the `missing` count until a direct draw uses it; the `x2w-render totals` line counts `pipelines first looked up by ExecuteIndirect N`. This is a per-process lookup count. Check for the ready marker `req_.a` to confirm a complete request is available. Run `tools/startup/gfx2hlsl.py --pending ` while the process is running, or start the run with `run.ps1 -Translate` (see [Translating shaders during a run](#translating-shaders-during-a-run)). Active draws poll for an absent manifest at most once per second per pipeline and use the published translation on a subsequent draw. The translator compiles `.vs.cso` and `.ps.cso` with `fxc.exe`: `X2W_FXC`, else the Windows SDK 10.0.26100.0 copy, else the newest `Windows Kits\10\bin\\x64`, else `PATH`. When none exists it writes `.fail` naming `X2W_FXC` without publishing a new manifest. `X2W_FXC=` (empty) publishes the manifest alone. Rerun `--pending` with compilation enabled to fill in missing bytecode for an existing manifest. At its first native slot-57 profile lookup the runtime lists the directory's top-level file names once and logs `x2w-draw cache index: names in ms` (`src/startup_stubs/cache_index.h`). A `.mesh57-state` profile is opened only when that listing has its name, so a profile written while the process runs is read by the next process. Manifests and every other cache file are still looked up on disk. | | `X2W_NATIVE_SHADERS=` (`run.ps1 -NativeShaders `) | experimental, in render mode: translates device slot 67 compute requests in the stand-in with the C++ compiler; `` holds `dxcompiler.dll` and `dxil.dll`. See [Translating compute programs in the stand-in](#translating-compute-programs-in-the-stand-in) | | `X2W_MESH57_DXC_DIR=` | experimental, with `X2W_MESH57_DERIVE_STATE=1`: the directory of `dxcompiler.dll` and `dxil.dll` for that one slot 57 derivation. Other graphics and compute programs stay on the non-native path. Unset, the derivation may still use `X2W_NATIVE_SHADERS` when that directory is set. When neither directory is set, the call stays refused (`derived mesh needs the native shader compiler`). See [Opt-in immediate allocation](experiments/native-fixed-mesh57.md#opt-in-immediate-allocation) | -| `X2W_MESH57_DERIVE_STATE=1` | experimental, with `X2W_SHADER_CACHE` and `X2W_MESH57_DXC_DIR` (or `X2W_NATIVE_SHADERS`): addresses `graphics/mesh_profile_missing` for one slot 57 shape. A direct `DispatchMesh` `ExecuteIndirect` may build one desktop mesh pipeline from an immediate `GS_ALLOC_REQ` and the bound color target when captured stages exist and no `.mesh57-state` file was opened. `graphics/no_translation`, slot 86, slot 55, depth, stencil, a non-empty root, and any other allocation shape stay refused. While the switch is on, every `DispatchMesh` `ExecuteIndirect` is counted: the first use of a reason logs `x2w-render mesh57-derive sample`, and the 300-frame heartbeat logs `x2w-render mesh57-derive:` with the counts. The rasterizer is not taken from the register block. See [Opt-in immediate allocation](experiments/native-fixed-mesh57.md#opt-in-immediate-allocation) | +| `X2W_MESH57_DERIVE_STATE=1` | experimental, with `X2W_SHADER_CACHE` and `X2W_MESH57_DXC_DIR` (or `X2W_NATIVE_SHADERS`): addresses `graphics/mesh_profile_missing` for one slot 57 shape. A direct `DispatchMesh` `ExecuteIndirect` may build one desktop mesh pipeline from an immediate `GS_ALLOC_REQ` and the bound color target when captured stages exist and no `.mesh57-state` file was opened. One guest constant block of 1..8 dwords is copied into desktop b0, including when that root is heap indexed. A slot 55 pipeline whose base is that slot 57 mesh reuses it when every patch is a blend record. `graphics/no_translation`, slot 86, depth, stencil, any other heap-indexed root, a descriptor root, and any other allocation shape stay refused. While the switch is on, every `DispatchMesh` `ExecuteIndirect` is counted: the first use of a reason logs `x2w-render mesh57-derive sample`, and the 300-frame heartbeat logs `x2w-render mesh57-derive:` plus `x2w-render mesh57-derive forwards:`. The rasterizer is not taken from the register block. See [Opt-in immediate allocation](experiments/native-fixed-mesh57.md#opt-in-immediate-allocation) | | `X2W_D3D12_LINEAR_BUFFERS=1` or `=copy` | opt-in backing for linear buffers placed at a title address (device slot 133, initial state `COMMON`): shared where the adapter, extent and memory allow it (private allocations larger than 256 MiB are skipped only with `X2W_D3D12_CAP_EXISTING_HEAP=1`), otherwise copied from title memory at each submission, otherwise the default backing is kept and the refusal recorded; `copy` never shares. Unset or `0`, slot 133 keeps its default backing. See [Linear buffer backing (device slot 133, opt-in)](#linear-buffer-backing-device-slot-133-opt-in) | | `X2W_D3D12_CAP_EXISTING_HEAP=1` | opt-in 256 MiB (`unplaced_existing_heap_allowed`) allocation-size cap on `OpenExistingHeapFromAddress` in device slot 133 (`startup_slot133_heap_cap_*`). Unset (default), private allocations larger than 256 MiB keep the formerly aliased path: a capped copied placement is refused by `CopyBufferRegion` (list slot 15) as `title_backed_source`, losing a late guest write made after recording and before submit. Set, allocations larger than 256 MiB skip `OpenExistingHeapFromAddress` so multi-GiB startup blocks are not pinned in `WorkingSetSize` and `NonLocal` GPU memory | | `X2W_D3D12_ROOT_SRV_AT_DRAW=1` | opt-in, render mode: a graphics root SRV (slot 44) without an upload mapping is not copied into the upload ring, since no draw reads that desktop binding (default: a 64 KiB copy at every slot 44 call). Translated draws copy the SRV themselves and are unaffected (`startup_root_srv_draw_*`). See [the experiment note](experiments/startup-root-srv-at-draw.md) | diff --git a/src/startup_stubs/d3d12_xs_device.cpp b/src/startup_stubs/d3d12_xs_device.cpp index 4d2d4892c7..a553b23dc6 100644 --- a/src/startup_stubs/d3d12_xs_device.cpp +++ b/src/startup_stubs/d3d12_xs_device.cpp @@ -171,6 +171,8 @@ struct IndirectGraphicsPipeline { const std::vector* guest_root_params{}; UINT cached_srv_root = UINT_MAX; UINT constant_guest = UINT_MAX; // Single MS b0 mapped from this guest root under a deferred signature. + // Opt-in derived mesh: constant_guest names one guest constant block, and the guest root is not heap indexed. + bool plain_constants = false; }; // Why a resource is outside the retire class (X2W_D3D12_RELEASE_RETIRED), decided at creation, and why it left it later. @@ -3740,7 +3742,9 @@ bool root_srv_at_draw() LONG root_srv_copies_skipped, root_srv_copies_made; #ifdef X2W_NATIVE_SHADERS -const char* derive_slot57_mesh(Wrapper* pipeline, Pass& pass); +const char* derive_slot57_mesh(Wrapper* pipeline, Pass& pass, const D3D12_BLEND_DESC* blend_override = nullptr, + const PipelineInfo* source = nullptr); +const char* derive_slot55_mesh(Wrapper* pipeline, Pass& pass); void record_mesh57_derive(const char* reason, Wrapper* pipeline, const PipelineInfo* info, int list_type); void log_mesh57_derive_census(); #endif @@ -3841,17 +3845,15 @@ void __stdcall list_execute_indirect(Wrapper* self, void* signature, UINT count, skip = "cached mesh stage"; else if (!derived_info) skip = "no pipeline record"; - else if (derived_info->path != 57) { - if (pass.pipeline->own().mesh86_key || derived_info->path == 86) - skip = "pipeline is slot 86"; - else if (derived_info->path == 55) - skip = "pipeline is a derived slot 55"; - else - skip = "pipeline is not slot 57"; - } + else if (pass.pipeline->own().mesh86_key || derived_info->path == 86) + skip = "pipeline is slot 86"; + else if (derived_info->path != 57 && derived_info->path != 55) + skip = "pipeline is not slot 57"; + const bool slot55 = !skip && derived_info && derived_info->path == 55; if (skip) { record_mesh57_derive(skip, pass.pipeline, derived_info, static_cast(type)); - } else if (const char* why = derive_slot57_mesh(pass.pipeline, pass)) { + } else if (const char* why = slot55 ? derive_slot55_mesh(pass.pipeline, pass) + : derive_slot57_mesh(pass.pipeline, pass)) { record_mesh57_derive(why, pass.pipeline, derived_info, static_cast(type)); } else if (pass.pipeline->own().real) { pass.indirect_graphics = pass.pipeline->own().indirect_graphics; @@ -3892,7 +3894,10 @@ void __stdcall list_execute_indirect(Wrapper* self, void* signature, UINT count, !std::equal(pso.cached_targets, pso.cached_targets + pso.cached_target_count, pass.target_formats)) return refuse("cached mesh requires matching color and depth attachments, viewport and scissor", indirect_other, indirect_other_refusal_code::cached_mesh_attachments); - if (!pass.root || pass.root != pso.guest_root_params || (pass.root_heap_flags != 0) != (pso.constant_guest != UINT_MAX)) + const bool mapped = pso.constant_guest != UINT_MAX; + const bool indexing_matches = (pass.root_heap_flags != 0) == mapped || + (pso.plain_constants && pass.root_heap_flags == 0 && mapped); + if (!pass.root || pass.root != pso.guest_root_params || !indexing_matches) return refuse("cached mesh creation root or indexing mode differs", indirect_graphics_pipeline); for (std::size_t i = 0; i < pass.root->size(); ++i) { if (i == pso.cached_srv_root || (pso.constant_guest != UINT_MAX && i != pso.constant_guest)) continue; diff --git a/src/startup_stubs/mesh57_alloc.h b/src/startup_stubs/mesh57_alloc.h index 14aea8f6e5..d931fe8cf1 100644 --- a/src/startup_stubs/mesh57_alloc.h +++ b/src/startup_stubs/mesh57_alloc.h @@ -147,8 +147,94 @@ struct Mesh57DeriveSample { int list_type = 0; int real = 0; int mesh86 = 0; + // Guest root at creation. type 0 in Mesh57RootParameterView is a 32-bit constant block. + // other counts every parameter that is not one. heap is the heap-indexing flag word. + std::uint32_t root_parameters = 0; + std::uint32_t root_constant_dwords = 0; + std::uint32_t root_other = 0; + std::uint32_t root_heap = 0; }; +// One guest root parameter, without a D3D12 type. type 0 is 32-bit constants and +// constants is that block's dword count. Any other type is not a constant block. +struct Mesh57RootParameterView { + unsigned type = 0; + unsigned constants = 0; +}; + +// User SGPRs for a derived mesh start at s8, one dword per constant, in parameter +// order. That is the layout the mesh lowerer checks against the root signature. +// Only one constant block of 1..8 dwords fits the desktop b0 the draw path already copies. +struct Mesh57RootContract { + unsigned parameters = 0; + unsigned constant_dwords = 0; + unsigned other_parameters = 0; + unsigned heap_flags = 0; + bool bind_constants = false; + unsigned sgpr = 0; +}; + +inline Mesh57RootContract mesh57_root_contract(const Mesh57RootParameterView* params, unsigned count, + unsigned heap_flags) noexcept +{ + Mesh57RootContract out; + out.parameters = count; + out.heap_flags = heap_flags; + out.sgpr = 8; + // A heap-indexing flag does not by itself name a descriptor. One constant block is still + // copied into desktop b0; a shader that also reads the heap is refused by the lowerer. + bool constants_only = count == 1 && params; + if (constants_only) { + out.constant_dwords = params[0].constants; + constants_only = params[0].type == 0 && params[0].constants >= 1 && params[0].constants <= 8 && + out.sgpr <= 106 && params[0].constants <= 106 - out.sgpr; + } + for (unsigned i = 0; i < count; ++i) { + if (!params || params[i].type != 0) + out.other_parameters += 1; + else if (count != 1) + out.constant_dwords += params[i].constants; + } + out.bind_constants = constants_only; + return out; +} + +// nullptr when this root can take the existing empty path or the one-block constant path. +// Anything else stays refused: a descriptor or a heap flag needs a reviewed SGPR map. +inline const char* mesh57_root_bind_reason(const Mesh57RootContract& contract) noexcept +{ + if (contract.bind_constants) + return nullptr; + if (contract.parameters == 0 && contract.heap_flags == 0) + return nullptr; + if (contract.heap_flags) + return "derived mesh guest root is heap indexed"; + if (contract.other_parameters) + return "derived mesh guest root has descriptors"; + if (!contract.bind_constants) + return "derived mesh guest root constants do not fit one user block"; + return nullptr; +} + +// A slot 55 patch list can reuse a slot 57 mesh when it is empty or every record is a +// blend patch. record bytes are the 0x14c blend record (tag word plus the blend state). +// A tag other than 2, or a size that is not a whole number of records, is not applied. +inline const char* mesh57_slot55_patch_reason(const unsigned char* records, std::size_t bytes) noexcept +{ + constexpr std::size_t record = 0x14c; + if (!bytes) + return nullptr; + if (!records || bytes % record) + return "slot 55 patches are not applied"; + for (std::size_t at = 0; at < bytes; at += record) { + std::uint32_t tag = 0; + std::memcpy(&tag, records + at, sizeof(tag)); + if (tag != 2) + return "slot 55 patches are not applied"; + } + return nullptr; +} + struct Mesh57DeriveCensus { static constexpr int capacity = 24; struct Row { @@ -206,11 +292,11 @@ inline std::size_t mesh57_derive_sample_line(const char* reason, const Mesh57Der return 0; const int n = std::snprintf(out, cap, "x2w-render mesh57-derive sample reason=%s path=%d base=%d desc=%u ms=%u ps=%u state_a=%u state_b=%u " - "vs=%u ms_len=%u ps_len=%u key=%016llx list=%d real=%d mesh86=%d", + "vs=%u ms_len=%u ps_len=%u key=%016llx list=%d real=%d mesh86=%d root=%u const=%u other=%u heap=%u", reason ? reason : "", sample.path, sample.base_path, sample.desc_bytes, sample.mesh_bytes, sample.pixel_bytes, sample.state_a, sample.state_b, sample.vertex_bytes, sample.mesh_length, sample.pixel_length, static_cast(sample.key), sample.list_type, sample.real, - sample.mesh86); + sample.mesh86, sample.root_parameters, sample.root_constant_dwords, sample.root_other, sample.root_heap); if (n < 0) { out[0] = 0; return 0; @@ -255,4 +341,34 @@ inline std::size_t mesh57_derive_summary_line(const Mesh57DeriveCensus& census, return static_cast(n); } +// Calls whose reason text is "forwarded": a derived pipeline installed a desktop PSO. +inline std::uint64_t mesh57_derive_forwarded(const Mesh57DeriveCensus& census) noexcept +{ + for (int i = 0; i < census.used; ++i) { + if (census.rows[i].reason && std::strcmp(census.rows[i].reason, "forwarded") == 0) + return census.rows[i].calls; + } + return 0; +} + +inline std::size_t mesh57_derive_forwards_line(const Mesh57DeriveCensus& census, char* out, std::size_t cap) noexcept +{ + if (!out || cap == 0) + return 0; + out[0] = 0; + if (!census.total()) + return 0; + const int n = std::snprintf(out, cap, "x2w-render mesh57-derive forwards: %llu", + static_cast(mesh57_derive_forwarded(census))); + if (n < 0) { + out[0] = 0; + return 0; + } + if (static_cast(n) >= cap) { + out[cap - 1] = 0; + return cap - 1; + } + return static_cast(n); +} + } // namespace x2w_startup diff --git a/src/startup_stubs/native_mesh57.inl b/src/startup_stubs/native_mesh57.inl index 0ba6eeeb72..279a66e87f 100644 --- a/src/startup_stubs/native_mesh57.inl +++ b/src/startup_stubs/native_mesh57.inl @@ -550,6 +550,30 @@ x2w_startup::Mesh57DeriveSample mesh57_derive_sample(Wrapper* pipeline, const Pi sample.pixel_length = mesh57_derive_u32(static_cast(words[6])); sample.mesh_length = mesh57_derive_u32(static_cast(words[14])); } + const PipelineInfo* root_source = info; + for (int depth = 0; root_source && root_source->path == 55 && root_source->base && depth < 8; ++depth) + root_source = pipeline_info(root_source->base); + if (root_source && root_source->desc.size() >= sizeof(u64)) { + u64 root_bits = 0; + std::memcpy(&root_bits, root_source->desc.data(), sizeof(root_bits)); + auto* root = as_wrapper(reinterpret_cast(root_bits)); + if (root && root->own().kind == root_signature_kind) { + sample.root_heap = root_heap_flags(root); + if (const auto* params = root_info(root)) { + sample.root_parameters = mesh57_derive_u32(params->size()); + for (const auto& parameter : *params) { + if (parameter.type == D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS) { + if (sample.root_constant_dwords <= ~std::uint32_t{0} - parameter.constants_count) + sample.root_constant_dwords += parameter.constants_count; + else + sample.root_constant_dwords = ~std::uint32_t{0}; + } else if (sample.root_other != ~std::uint32_t{0}) { + sample.root_other += 1; + } + } + } + } + } return sample; } @@ -578,16 +602,49 @@ void log_mesh57_derive_census() char line[2048]; if (x2w_startup::mesh57_derive_summary_line(copy, line, sizeof(line))) log("%s", line); + if (x2w_startup::mesh57_derive_forwards_line(copy, line, sizeof(line))) + log("%s", line); +} + +const char* derive_slot55_mesh(Wrapper* pipeline, Pass& pass) +{ + if (!pipeline || pipeline->own().real) + return nullptr; + const auto* info = pipeline_info(pipeline); + if (!info) + return "derived mesh has no captured pipeline"; + if (info->mesh57_derive_reason) + return info->mesh57_derive_reason; + Wrapper* base = info->base; + const PipelineInfo* base_info = nullptr; + for (int depth = 0; base && depth < 8; ++depth) { + base_info = pipeline_info(base); + if (!base_info || base_info->path != 55) + break; + base = base_info->base; + base_info = nullptr; + } + if (!base_info || base_info->path != 57) + return "pipeline is a derived slot 55"; + if (const char* patch = x2w_startup::mesh57_slot55_patch_reason(info->desc.data(), info->desc.size())) { + info->mesh57_derive_reason = patch; + return patch; + } + D3D12_BLEND_DESC blend{}; + std::size_t where = 0; + const bool has_blend = x2w_derived_blend::last_blend(info->desc.data(), info->desc.size(), blend, where); + return derive_slot57_mesh(pipeline, pass, has_blend ? &blend : nullptr, base_info); } // Builds one desktop mesh PSO for a direct DispatchMesh when X2W_MESH57_DERIVE_STATE=1 and no // reviewed profile was opened. Returns nullptr after publishing the PSO, or a stable reason. // A reason that depends on the command list (attachments, the bound root) is not remembered. -const char* derive_slot57_mesh(Wrapper* pipeline, Pass& pass) +const char* derive_slot57_mesh(Wrapper* pipeline, Pass& pass, const D3D12_BLEND_DESC* blend_override, + const PipelineInfo* source) { if (!pipeline || pipeline->own().real) return nullptr; - const auto* info = pipeline_info(pipeline); + const auto* info = source ? source : pipeline_info(pipeline); if (!info) return "derived mesh has no captured pipeline"; if (info->mesh57_derive_reason) @@ -627,8 +684,28 @@ const char* derive_slot57_mesh(Wrapper* pipeline, Pass& pass) if (!root || root->own().kind != root_signature_kind || !root->own().real || !root_info(root) || fields[2] != info->state_a.size() || fields[4] != info->state_b.size()) return remember("derived mesh root or state lengths do not match"); - if (!root_info(root)->empty() || root_heap_flags(root)) - return remember("derived mesh keeps a non-empty guest root refused"); + const auto* guest_parameters = root_info(root); + x2w_startup::Mesh57RootParameterView root_views[16]; + unsigned root_view_count = 0; + if (guest_parameters && guest_parameters->size() <= 16) { + root_view_count = static_cast(guest_parameters->size()); + for (unsigned i = 0; i < root_view_count; ++i) { + const auto& parameter = (*guest_parameters)[i]; + root_views[i].type = parameter.type == D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS ? 0u : 1u; + root_views[i].constants = parameter.constants_count; + } + } + const auto root_contract = x2w_startup::mesh57_root_contract( + root_view_count ? root_views : nullptr, root_view_count, root_heap_flags(root)); + if (guest_parameters && guest_parameters->size() > 16) + return remember("derived mesh guest root constants do not fit one user block"); + if (const char* root_why = x2w_startup::mesh57_root_bind_reason(root_contract)) + return remember(root_why); + if (root_contract.bind_constants) { + const auto mask = static_cast((1u << root_views[0].constants) - 1u); + if ((pass.constant_words_bound[0] & mask) != mask) + return "derived mesh root constants are incomplete"; + } if (info->state_a.size() < x2w_pipeline_state::a_layout + 4) return remember("derived mesh state block is short"); std::uint32_t layout_word = 0; @@ -641,8 +718,10 @@ const char* derive_slot57_mesh(Wrapper* pipeline, Pass& pass) D3D12_BLEND_DESC blend{}; const char* blend_why = nullptr; // Blend words sit at +0xD0 in the vertex layout. The mesh layout shifts every field from +0x058 - // by +0x54, and the blend reader does not apply that shift itself. - if (!x2w_startup::state_block_blend(info->state_a.data() + shift, info->state_a.size() - shift, false, &blend, &blend_why)) + // by +0x54, and the blend reader does not apply that shift itself. A slot 55 blend patch replaces it. + if (blend_override) + blend = *blend_override; + else if (!x2w_startup::state_block_blend(info->state_a.data() + shift, info->state_a.size() - shift, false, &blend, &blend_why)) return remember(blend_why ? blend_why : "derived mesh blend was refused"); x2w_pipeline_state::DepthStencilWords depth_words; if (!x2w_pipeline_state::read_depth_stencil_words(info->state_a.data(), info->state_a.size(), depth_words)) @@ -658,8 +737,10 @@ const char* derive_slot57_mesh(Wrapper* pipeline, Pass& pass) pass.target_count != 1 || !pass.target0 || pass.dsv_format != DXGI_FORMAT_UNKNOWN || pass.target_formats[0] == DXGI_FORMAT_UNKNOWN) return "derived mesh needs one single-sample color target, a viewport and a scissor"; - if (!pass.graphics_root || pass.graphics_root != desktop || pass.root != root_info(root) || pass.root_heap_flags) - return "derived mesh root is not the bound empty desktop root"; + ID3D12RootSignature* bound_root = pass.root_heap_flags ? pass.deferred_root : pass.graphics_root; + if (!bound_root || bound_root != desktop || pass.root != root_info(root) || + (pass.root_heap_flags && !root_contract.bind_constants)) + return "derived mesh root is not the bound desktop root"; const std::string ms(info->fixed_ms->begin(), info->fixed_ms->end()); const auto layout = x2w_startup::derive_immediate_mesh_layout(ms); if (!layout) @@ -672,8 +753,25 @@ const char* derive_slot57_mesh(Wrapper* pipeline, Pass& pass) mesh_layout.topology = layout->topology; mesh_layout.group_stride = layout->group_stride; mesh_layout.wave32 = false; - auto native = x2w::translate_mesh_program(ms, mesh_layout); - if (!native.constants.empty() || !native.bindings.empty() || !native.samplers.empty() || native.sampler_heap || + D3D12_ROOT_PARAMETER1 constant_parameter{}; + D3D12_ROOT_SIGNATURE_DESC1 constant_root{}; + if (root_contract.bind_constants) { + mesh_layout.root_inputs.push_back({root_contract.sgpr, 0u, root_views[0].constants}); + constant_parameter.ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS; + constant_parameter.ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL; + constant_parameter.Constants.Num32BitValues = root_views[0].constants; + constant_root.NumParameters = 1; + constant_root.pParameters = &constant_parameter; + } + auto native = root_contract.bind_constants + ? x2w::translate_mesh_program(ms, mesh_layout, constant_root) + : x2w::translate_mesh_program(ms, mesh_layout); + const bool constants_match = !root_contract.bind_constants || + (native.constants.size() == 1 && native.constants[0].root_parameter == 0 && + native.constants[0].first_sgpr == root_contract.sgpr && + native.constants[0].count == root_views[0].constants); + if (!constants_match || (root_contract.bind_constants ? false : !native.constants.empty()) || + !native.bindings.empty() || !native.samplers.empty() || native.sampler_heap || !native.mesh_heap_reads.empty()) return remember("derived mesh program needs root or heap bindings"); const std::string ps(info->fixed_ps->begin(), info->fixed_ps->end()); @@ -707,9 +805,27 @@ const char* derive_slot57_mesh(Wrapper* pipeline, Pass& pass) desc.pPipelineStateSubobjectStream = &stream; bool compute = false; char why[256]{}; + x2w_startup::ComPtr host; + if (root_contract.bind_constants) { + D3D12_ROOT_PARAMETER host_parameter{}; + host_parameter.ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS; + host_parameter.Constants.Num32BitValues = (root_views[0].constants + 3u) & ~3u; + D3D12_ROOT_SIGNATURE_DESC host_desc; + host_desc.NumParameters = 1; + host_desc.pParameters = &host_parameter; + host_desc.NumStaticSamplers = 0; + host_desc.pStaticSamplers = nullptr; + host_desc.Flags = D3D12_ROOT_SIGNATURE_FLAG_NONE; + x2w_startup::ComPtr host_blob; + if (FAILED(D3D12SerializeRootSignature(&host_desc, D3D_ROOT_SIGNATURE_VERSION_1, &host_blob, nullptr)) || + FAILED(device_of(the_device)->CreateRootSignature(0, host_blob->GetBufferPointer(), host_blob->GetBufferSize(), + IID_PPV_ARGS(&host)))) + return remember("derived mesh constant root was refused"); + } IndirectGraphicsPipeline graphics; ID3D12RootSignature* pipeline_root = nullptr; - auto* created = build_stream_pipeline(&desc, why, sizeof(why), compute, graphics, pipeline_root, desktop, true); + auto* created = build_stream_pipeline(&desc, why, sizeof(why), compute, graphics, pipeline_root, + host ? host.Get() : desktop, true); if (!created) { log("x2w-render derived slot57 mesh desktop pipeline refused: %s", why); if (pipeline->own().real) @@ -717,6 +833,15 @@ const char* derive_slot57_mesh(Wrapper* pipeline, Pass& pass) return remember("derived mesh desktop pipeline was refused"); } auto* pso = static_cast(created); + if (root_contract.bind_constants) { + static constexpr GUID lifetime{0xf74c6928, 0xb063, 0x4a00, {0xa5, 0xf0, 0x79, 0xe3, 0x60, 0xa4, 0xf1, 0x09}}; + if (FAILED(pso->SetPrivateDataInterface(lifetime, host.Get()))) { + pso->Release(); + return remember("derived mesh constant root was refused"); + } + graphics.constant_guest = 0; + graphics.plain_constants = root_heap_flags(root) == 0; + } AcquireSRWLockExclusive(¬e_lock); if (pipeline->own().real) { ReleaseSRWLockExclusive(¬e_lock); diff --git a/tests/mesh57_derive_alloc_check.cpp b/tests/mesh57_derive_alloc_check.cpp index b6980db283..73ed5094c3 100644 --- a/tests/mesh57_derive_alloc_check.cpp +++ b/tests/mesh57_derive_alloc_check.cpp @@ -159,8 +159,66 @@ int main() char sample[512]; if (!x2w_startup::mesh57_derive_sample_line(census.rows[0].reason, census.rows[0].sample, sample, sizeof(sample)) || !std::strstr(sample, "reason=pipeline is slot 86") || !std::strstr(sample, "path=86") || - !std::strstr(sample, "desc=512") || std::strncmp(sample, "x2w-render mesh57-derive sample ", 32) != 0) + !std::strstr(sample, "desc=512") || !std::strstr(sample, "root=0") || + !std::strstr(sample, "const=0") || !std::strstr(sample, "other=0") || !std::strstr(sample, "heap=0") || + std::strncmp(sample, "x2w-render mesh57-derive sample ", 32) != 0) return fail("sample"); + x2w_startup::Mesh57RootParameterView one; + one.type = 0; + one.constants = 1; + const auto bound = x2w_startup::mesh57_root_contract(&one, 1, 0); + if (!bound.bind_constants || bound.sgpr != 8 || bound.constant_dwords != 1 || + x2w_startup::mesh57_root_bind_reason(bound)) + return fail("one constant block"); + x2w_startup::Mesh57RootParameterView two[2]; + two[0].type = 0; + two[0].constants = 1; + two[1].type = 0; + two[1].constants = 1; + const auto split = x2w_startup::mesh57_root_contract(two, 2, 0); + if (split.bind_constants || std::strcmp(x2w_startup::mesh57_root_bind_reason(split), + "derived mesh guest root constants do not fit one user block") != 0) + return fail("two constant blocks"); + x2w_startup::Mesh57RootParameterView table; + table.type = 1; + table.constants = 0; + const auto described = x2w_startup::mesh57_root_contract(&table, 1, 0); + if (described.bind_constants || std::strcmp(x2w_startup::mesh57_root_bind_reason(described), + "derived mesh guest root has descriptors") != 0) + return fail("descriptor root"); + const auto heaped = x2w_startup::mesh57_root_contract(&one, 1, 0x8); + if (!heaped.bind_constants || x2w_startup::mesh57_root_bind_reason(heaped)) + return fail("heap plus one constant"); + const auto heap_only = x2w_startup::mesh57_root_contract(nullptr, 0, 0x8); + if (heap_only.bind_constants || std::strcmp(x2w_startup::mesh57_root_bind_reason(heap_only), + "derived mesh guest root is heap indexed") != 0) + return fail("heap only"); + one.constants = 9; + const auto wide_root = x2w_startup::mesh57_root_contract(&one, 1, 0); + if (wide_root.bind_constants || !x2w_startup::mesh57_root_bind_reason(wide_root)) + return fail("wide constant block"); + const auto empty = x2w_startup::mesh57_root_contract(nullptr, 0, 0); + if (empty.bind_constants || x2w_startup::mesh57_root_bind_reason(empty)) + return fail("empty root"); + unsigned char blend_record[0x14c]; + std::memset(blend_record, 0, sizeof(blend_record)); + const std::uint32_t blend_tag = 2; + std::memcpy(blend_record, &blend_tag, sizeof(blend_tag)); + if (x2w_startup::mesh57_slot55_patch_reason(nullptr, 0) || + x2w_startup::mesh57_slot55_patch_reason(blend_record, sizeof(blend_record))) + return fail("blend patch"); + blend_record[0] = 1; + if (std::strcmp(x2w_startup::mesh57_slot55_patch_reason(blend_record, sizeof(blend_record)), + "slot 55 patches are not applied") != 0 || + std::strcmp(x2w_startup::mesh57_slot55_patch_reason(blend_record, 4), + "slot 55 patches are not applied") != 0) + return fail("unknown patch"); + if (!census.note("forwarded", slot86) || x2w_startup::mesh57_derive_forwarded(census) != 1) + return fail("forwarded count"); + char forwards[128]; + if (!x2w_startup::mesh57_derive_forwards_line(census, forwards, sizeof(forwards)) || + std::strcmp(forwards, "x2w-render mesh57-derive forwards: 1") != 0) + return fail("forwards line"); x2w_startup::Mesh57DeriveCensus full; if (!full.note("overflow-probe", slot86)) return fail("overflow first"); diff --git a/tests/startup_indirect_draw_indexed.cpp b/tests/startup_indirect_draw_indexed.cpp index 437751f5de..60cd4a8578 100644 --- a/tests/startup_indirect_draw_indexed.cpp +++ b/tests/startup_indirect_draw_indexed.cpp @@ -1114,6 +1114,11 @@ bool run(ID3D12Device* device, ID3D12Device* guest, ID3D12RootSignature* writer_ ComPtr fixed_source_heap; slot(wrapped, 25)(wrapped, graphics); slot(wrapped, 34)(wrapped, refusal == Refusal::wrong_root ? translated->wrong_root.Get() : graphics_root); + if (label && std::strcmp(label, "mesh-derived-root") == 0) { + using Constants = void (WINAPI*)(IUnknown*, UINT, UINT, const UINT*, UINT); + const UINT value = 0; + slot(wrapped, 40)(wrapped, 0, 1, &value, 0); + } if (leased) { using RootSrv = void (WINAPI*)(IUnknown*, UINT, UINT64); slot(wrapped, 44)(wrapped, 0, leased->address); @@ -2460,10 +2465,31 @@ static int derived_mesh_fixture(ID3D12Device* device, ID3D12Device* guest, ID3D1 check(SetEnvironmentVariableW(L"X2W_SHADER_CACHE", cache.path.c_str()) ? S_OK : E_FAIL, "derived mesh cache"); ComPtr blob; D3D12_ROOT_SIGNATURE_DESC empty{}; + const bool constant_root = std::strcmp(mode, "mesh-derived-root") == 0 || + std::strcmp(mode, "mesh-derived-root-unset") == 0; + const bool table_root = std::strcmp(mode, "mesh-derived-root-table") == 0; + D3D12_ROOT_PARAMETER parameter{}; + D3D12_DESCRIPTOR_RANGE range{}; + if (constant_root) { + parameter.ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS; + parameter.Constants.Num32BitValues = 1; + empty.NumParameters = 1; + empty.pParameters = ¶meter; + } else if (table_root) { + range.RangeType = D3D12_DESCRIPTOR_RANGE_TYPE_SRV; + range.NumDescriptors = 1; + parameter.ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; + parameter.DescriptorTable.NumDescriptorRanges = 1; + parameter.DescriptorTable.pDescriptorRanges = ⦥ + empty.NumParameters = 1; + empty.pParameters = ¶meter; + } const auto root = create_root(guest, empty, &blob); std::vector ms{0xbefc03ffu, 0x1003u, 0xbf900009u, 0xd7650000u, 0x100c1u, 0x36020081u, 0x2c040081u, 0x7e020d01u, 0x7e040d02u, 0x7e0602f0u, 0x7e0802f2u, 0xf80008cfu, 0x04030201u, 0x7e0a02ffu, 0x200400u, 0xf8000941u, 0x80808005u, 0xbf810000u}; + if (constant_root) + ms.insert(ms.begin(), 0xbe890308u); // s_mov_b32 s9, s8. s8 is the one guest constant at user SGPR 8. if (std::strcmp(mode, "mesh-derived-bad") == 0) ms.assign(1, 0xbf810000u); const std::vector ps{0x7e0002f2u, 0xf800180fu, 0u, 0xbf810000u}; @@ -2524,6 +2550,36 @@ static int derived_mesh_fixture(ID3D12Device* device, ID3D12Device* guest, ID3D1 using Create = HRESULT(WINAPI*)(IUnknown*, const void*, REFIID, void**); check(slot(guest, 57)(guest, fields, __uuidof(ID3D12PipelineState), reinterpret_cast(pso.GetAddressOf())), "create derived mesh"); + const bool slot55 = std::strcmp(mode, "mesh-derived-slot55") == 0 || + std::strcmp(mode, "mesh-derived-slot55-mask") == 0; + ComPtr derived; + if (slot55) { + std::vector patch; + const void* patch_bytes = nullptr; + UINT patch_count = 0; + if (std::strcmp(mode, "mesh-derived-slot55-mask") == 0) { + D3D12_BLEND_DESC blend{}; + auto& target = blend.RenderTarget[0]; + target.SrcBlend = D3D12_BLEND_ONE; + target.DestBlend = D3D12_BLEND_ZERO; + target.BlendOp = D3D12_BLEND_OP_ADD; + target.SrcBlendAlpha = D3D12_BLEND_ONE; + target.DestBlendAlpha = D3D12_BLEND_ZERO; + target.BlendOpAlpha = D3D12_BLEND_OP_ADD; + target.LogicOp = D3D12_LOGIC_OP_NOOP; + target.RenderTargetWriteMask = 0; + patch.resize(sizeof(std::uint32_t) + sizeof(blend)); + const std::uint32_t tag = 2; + std::memcpy(patch.data(), &tag, sizeof(tag)); + std::memcpy(patch.data() + sizeof(tag), &blend, sizeof(blend)); + patch_bytes = patch.data(); + patch_count = 1; + } + using Derive = HRESULT (WINAPI*)(IUnknown*, void*, UINT, const void*, REFIID, void**); + check(slot(guest, 55)(guest, pso.Get(), patch_count, patch_bytes, __uuidof(ID3D12PipelineState), + reinterpret_cast(derived.GetAddressOf())), + "create slot 55 mesh"); + } D3D12_INDIRECT_ARGUMENT_DESC argument{}; argument.Type = D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH_MESH; D3D12_COMMAND_SIGNATURE_DESC signature_desc; @@ -2542,8 +2598,10 @@ static int derived_mesh_fixture(ID3D12Device* device, ID3D12Device* guest, ID3D1 profile.targets.NumRenderTargets = 1; profile.targets.RTFormats[0] = format; profile.blend.RenderTarget[0].RenderTargetWriteMask = D3D12_COLOR_WRITE_ENABLE_ALL; - const int pixels = std::strcmp(mode, "mesh-derived") == 0 || std::strcmp(mode, "mesh-derived-dxc") == 0 ? 1 : 2; - const bool painted = run(device, guest, writer, work.Get(), root.Get(), pso.Get(), signature.Get(), DrawKind::mesh, + const int pixels = std::strcmp(mode, "mesh-derived") == 0 || std::strcmp(mode, "mesh-derived-dxc") == 0 || + std::strcmp(mode, "mesh-derived-root") == 0 || std::strcmp(mode, "mesh-derived-slot55") == 0 ? 1 : 2; + const bool painted = run(device, guest, writer, work.Get(), root.Get(), slot55 ? derived.Get() : pso.Get(), + signature.Get(), DrawKind::mesh, false, Refusal::none, mode, nullptr, false, nullptr, false, false, 0, false, false, nullptr, nullptr, false, pixels, &profile); return painted ? 0 : 1; @@ -2577,8 +2635,13 @@ int main(int argc, char** argv) try const bool derived_untranslated = argc == 3 && std::strcmp(argv[2], "mesh-derived-untranslated") == 0; const bool derived_dxc = argc == 3 && std::strcmp(argv[2], "mesh-derived-dxc") == 0; const bool derived_dxc_reviewed = argc == 3 && std::strcmp(argv[2], "mesh-derived-dxc-reviewed") == 0; + const bool derived_root = argc == 3 && (std::strcmp(argv[2], "mesh-derived-root") == 0 || + std::strcmp(argv[2], "mesh-derived-root-unset") == 0 || std::strcmp(argv[2], "mesh-derived-root-table") == 0); + const bool derived_slot55 = argc == 3 && (std::strcmp(argv[2], "mesh-derived-slot55") == 0 || + std::strcmp(argv[2], "mesh-derived-slot55-mask") == 0); const bool derived_mesh = derived_off || derived_bad || derived_depth || derived_reviewed || derived_untranslated || - derived_dxc || derived_dxc_reviewed || (argc == 3 && std::strcmp(argv[2], "mesh-derived") == 0); + derived_dxc || derived_dxc_reviewed || derived_root || derived_slot55 || + (argc == 3 && std::strcmp(argv[2], "mesh-derived") == 0); const bool console_mesh = argc == 3 && std::strcmp(argv[2], "mesh-console") == 0; const bool desktop_as = argc == 3 && std::strcmp(argv[2], "mesh-amplified") == 0; const bool copy_on = argc == 3 && std::strcmp(argv[2], "copy-provenance") == 0; From 577e5dbb6278c2c6f7d26fdad6371f94cdd956e6 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Sun, 29 Nov 2026 01:44:52 +0000 Subject: [PATCH 07/12] runtime: name unknown slot 55 tags and record root parameter types A slot 55 record that is not a blend tag stays refused, and the reason names the tag. The sample lists the first patch tags and sizes and the first guest-root parameter types. A zero pixel length is an empty descriptor span, not a dropped copy. No reviewed mesh user-SGPR map covers a five-parameter heap-indexed root, so that shape stays refused. Co-authored-by: SimSalabimse --- docs/experiments/native-fixed-mesh57.md | 15 +- docs/startup-runtime.md | 2 +- src/startup_stubs/mesh57_alloc.h | 195 ++++++++++++++++++++++-- src/startup_stubs/native_mesh57.inl | 70 ++++++++- tests/mesh57_derive_alloc_check.cpp | 73 ++++++++- 5 files changed, 325 insertions(+), 30 deletions(-) diff --git a/docs/experiments/native-fixed-mesh57.md b/docs/experiments/native-fixed-mesh57.md index c33837a792..eeecdc0fe5 100644 --- a/docs/experiments/native-fixed-mesh57.md +++ b/docs/experiments/native-fixed-mesh57.md @@ -117,11 +117,12 @@ A slot 57 record is a fixed pair only when the captured descriptor is 768 bytes, - `slot 57 descriptor has a vertex span` (the capture skips the mesh and pixel copies) - `slot 57 descriptor has no mesh stage length` - `slot 57 mesh stage was not captured` (the bytes were unreadable or larger than 1 MiB) -- `slot 57 pixel stage was not captured` (no pixel bytes; a zero pixel span is not a program this path can compile) +- `slot 57 pixel stage is absent from the descriptor` (the pixel pointer and the pixel length are both zero; the mesh copy is kept) +- `slot 57 pixel stage was not captured` (the descriptor names a pixel span whose bytes were not kept) -Those six still refuse. The 768-byte rule stays: a shorter descriptor cannot be checked against a reviewed `.mesh57-state` file. While the switch is on, publishing a slot 57 request no longer drops the captured stage bytes, so a later call whose first refusal depended on the command list can still see them. +Those seven still refuse. The 768-byte rule stays: a shorter descriptor cannot be checked against a reviewed `.mesh57-state` file. While the switch is on, publishing a slot 57 request no longer drops the captured stage bytes, so a later call whose first refusal depended on the command list can still see them. -The first time a reason is seen, stderr gets one `x2w-render mesh57-derive sample` line: the reason, the creating slot (`path`), the derived-from slot (`base`), descriptor and stage sizes, the vertex, mesh and pixel lengths from the descriptor, the pipeline key, the list type, whether a desktop pipeline or a slot 86 key is present, and the guest root (`root`, `const`, `other`, `heap`). The line has no file path. Every 300 presented frames the heartbeat adds `x2w-render mesh57-derive:` with the call count of each reason, then `x2w-render mesh57-derive forwards:` with the `forwarded` count. That count is the number of calls that installed a desktop pipeline from this path. +The first time a reason is seen, stderr gets one `x2w-render mesh57-derive sample` line: the reason, the creating slot (`path`), the derived-from slot (`base`), descriptor and stage sizes, the vertex, mesh and pixel lengths from the descriptor, the pipeline key, the list type, whether a desktop pipeline or a slot 86 key is present, the guest root (`root`, `const`, `other`, `heap`), the first parameter types (`params`), and the first slot 55 patch tags and sizes (`patches`). The line has no file path. `params` uses `t` for a descriptor table, `cN` for an N-dword constant block, `cbv`, `srv`, and `uav`. `patches` uses `tag:bytes`. A sample with no root parameters or no patch list prints `-`. Every 300 presented frames the heartbeat adds `x2w-render mesh57-derive:` with the call count of each reason, then `x2w-render mesh57-derive forwards:` with the `forwarded` count. That count is the number of calls that installed a desktop pipeline from this path. A startup run on the Windows test PC recorded 653,708 refused `DispatchMesh` `ExecuteIndirect` calls in 420 seconds and forwarded none. Across draw and mesh, the graphics-pipeline census counted `graphics/no_translation` 446,421 and `graphics/mesh_profile_missing` 427,428. This switch is only the second of those, and only the immediate-allocation shape below. Slot 86 meshes with no cached stage stay refused. @@ -129,7 +130,7 @@ The accepted program writes `m0` with one `s_mov_b32` of an integer immediate an An empty guest root is unchanged. One 32-bit constant parameter of 1..8 dwords and no other parameters is bound, including when the guest root is heap indexed: user SGPR s8 is that block, and the draw copies it into a desktop b0 the same way a reviewed constant profile does. The constant words must already be set on the list. The heap base itself is not bound; a shader that reads it is refused by the lowerer. A heap-indexed root with any other shape (`derived mesh guest root is heap indexed`), a descriptor or root descriptor (`derived mesh guest root has descriptors`), or any other constant shape (`derived mesh guest root constants do not fit one user block`) stays refused. Those need a reviewed SGPR map; this path does not invent one. -A slot 55 pipeline reuses that derived mesh when every patch record is a blend patch (tag 2, 0x14c bytes) or the patch list is empty. The last blend patch replaces the base blend. Any other record stays refused (`slot 55 patches are not applied`). The base's shader, root, and depth rules are unchanged. +A slot 55 pipeline reuses that derived mesh when every patch record is a blend patch (tag 2, 0x14c bytes) or the patch list is empty. The last blend patch replaces the base blend. Tag 2 is the only slot 55 record this repository applies: the graphics path reads that blend descriptor and does not apply any other tag. Depth and raster for a slot 57 base come from its state block, not from a patch tag. A record whose tag is not 2 stays refused, and the reason names that tag (for example `slot 55 patch tag 3 is not applied`). A list whose size is not a whole number of 0x14c records stays `slot 55 patches are not applied`. The sample lists the first records either way. The base's shader, root, and depth rules are unchanged. Fixed function state comes from state block A. The mesh layout word at `+0x004` must be 6. Blend words are read at the mesh shift (`+0x54` on top of `+0xD0`). Depth and stencil must decode as disabled; an enabled test is refused rather than given a guessed depth format. The color target is the one single-sample target bound on that direct list, with a viewport and a scissor and no depth view. The rasterizer is solid, cull none, and depth clip. Those three values are not read from the register block. A `.mesh57-state` file that is present, including one whose bytes do not match, keeps the reviewed path and this switch does not create a pipeline. @@ -144,3 +145,9 @@ ctest --preset dev -j 1 --no-tests=error -R "mesh57_derive_alloc|startup_indirec `startup_indirect_mesh_derived_{warp,hardware}` forwards one group and reads a white texel at `(2,0)` on a 4 by 2 target. `derived-dxc` does the same with only `X2W_MESH57_DXC_DIR` set, and the process clears `X2W_NATIVE_SHADERS` before the call. `derived-root` is that program plus one guest constant at s8, with the word set, and paints the same texel. `derived-slot55` draws through a slot 55 pipeline with no patches and paints the same texel. `derived-off` leaves the switch unset. `derived-bad` has no immediate allocation. `derived-depth` enables the depth test in the register block. `derived-reviewed` and `derived-dxc-reviewed` supply a profile file that does not match; the second does that with only `X2W_MESH57_DXC_DIR` set. `derived-untranslated` is a slot 57 pipeline with no captured mesh or pixel program. `derived-root-unset` omits the constant word. `derived-root-table` uses a descriptor table. `derived-slot55-mask` applies a blend patch with a zero write mask. Those leave the clear color. Each returns 77 when mesh shaders or the command signature are unavailable. `mesh57_derive_alloc` checks the allocation reader, the root decision, the slot 55 patch rule, and the forwards line without a device. On the Windows test PC at `f358a2ed`, a 420 second run with `X2W_TRANSLATED_INDIRECT_DRAW=1`, `X2W_MESH57_DERIVE_STATE=1`, and `X2W_MESH57_DXC_DIR` set forwarded nothing. The derive census was `slot 57 pixel stage was not captured` 47823, `derived mesh keeps a non-empty guest root refused` 152144, and `pipeline is a derived slot 55` 180066. The non-empty sample had both stages (mesh 9536 bytes, pixel 4352 bytes). The slot 55 sample was a 332-byte descriptor whose base was slot 57 and whose stage lengths were unread. That root refusal is replaced by the three root reasons above, and a slot 55 call now uses its slot 57 base when the patches are blend records. A 4352-byte pixel is still not a constant export, and a program that is not the one immediate allocation is still refused. + +On the Windows test PC at `54331137`, the same switches, a 420 second run, forwarded nothing (`x2w-render mesh57-derive forwards: 0`). The census was `derived mesh guest root is heap indexed` 353719, `slot 57 pixel stage was not captured` 130628, and `slot 55 patches are not applied` 514994. The heap-indexed sample was path 57, descriptor 768, mesh 9536, pixel 4352, state A 504, state B 80, root 5, one constant dword, four other parameters, heap 1024. The pixel sample was path 57, mesh 1408, pixel length 0, state A 464, root 5, two constant dwords, four other parameters, heap 3072. The slot 55 sample was one 332-byte record on a slot 57 base with that same five-parameter root and heap 3072. + +The capture copies a pixel stage only when its length is non-zero and the bytes are readable. A zero pointer and a zero length is an empty span: the copy is skipped and the mesh bytes stay. The 1408-byte mesh in that sample was kept, so the pixel words in the creation descriptor were zero. An unreadable non-zero span fails the snapshot and drops both stages; this sample is not that case, and nothing writes the pixel stage after creation. A slot 55 record is state, not a shader. This path does not invent a pixel shader. A zero pixel length is now `slot 57 pixel stage is absent from the descriptor`. + +Heap 1024 is the view-heap flag (`0x400`). Heap 3072 is that flag plus the sampler-heap flag (`0xC00`). No reviewed map in this repository assigns user SGPRs for a five-parameter heap-indexed root on the mesh path. The maps that do exist are different ABIs. Raw graphics, and the reflected graphics path, start user SGPRs at s8: a descriptor table is one SGPR, a 32-bit constant block is one SGPR per dword, and a root CBV, SRV, or UAV is two SGPRs, with the heaps following when their flags are set. That layout is for a graphics stage. Direct compute without a reflected stage starts at s4 with the same parameter packing, and both heap flags occupy the next two SGPRs only when they exactly fill the user SGPR count. The 1024 sample has only the view-heap flag, and s4 is the compute ABI. A reviewed `.mesh57-state` profile stores the SGPR, the root parameter, and the count for that one program. These pipelines have no such file. The missing map is the physical user SGPR of each of the five parameters, and the user SGPR of the resource heap (and of the sampler heap when `0x800` is set). The stored root parameter keeps the type, and for a constant block the dword count; a descriptor table's ranges are not kept. This path does not guess the SGPRs. The sample line records the types so the map can be raised with the measured parameter kinds. diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index dfb436175c..700bf4cc49 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -1735,7 +1735,7 @@ ctest --preset dev --no-tests=error -R '^startup_hook_(window|overlap)$' -V | `X2W_SHADER_CACHE=` | translation cache: the runtime writes source requests `req_.{a,b,root}`, when needed RTV variants `req_.rtv`, and for device slot 67 compute pipelines `req_.{desc,sa,sb,data,root,c67}` (see [Compute pipeline requests](#compute-pipeline-requests)). A console pipeline that an `ExecuteIndirect` draw (list slot 61) refuses writes the same request as a direct draw, once per pipeline, and draws nothing (`startup_indirect_requests_warp`). Only direct draws poll for its manifest, so such a pipeline stays in the `missing` count until a direct draw uses it; the `x2w-render totals` line counts `pipelines first looked up by ExecuteIndirect N`. This is a per-process lookup count. Check for the ready marker `req_.a` to confirm a complete request is available. Run `tools/startup/gfx2hlsl.py --pending ` while the process is running, or start the run with `run.ps1 -Translate` (see [Translating shaders during a run](#translating-shaders-during-a-run)). Active draws poll for an absent manifest at most once per second per pipeline and use the published translation on a subsequent draw. The translator compiles `.vs.cso` and `.ps.cso` with `fxc.exe`: `X2W_FXC`, else the Windows SDK 10.0.26100.0 copy, else the newest `Windows Kits\10\bin\\x64`, else `PATH`. When none exists it writes `.fail` naming `X2W_FXC` without publishing a new manifest. `X2W_FXC=` (empty) publishes the manifest alone. Rerun `--pending` with compilation enabled to fill in missing bytecode for an existing manifest. At its first native slot-57 profile lookup the runtime lists the directory's top-level file names once and logs `x2w-draw cache index: names in ms` (`src/startup_stubs/cache_index.h`). A `.mesh57-state` profile is opened only when that listing has its name, so a profile written while the process runs is read by the next process. Manifests and every other cache file are still looked up on disk. | | `X2W_NATIVE_SHADERS=` (`run.ps1 -NativeShaders `) | experimental, in render mode: translates device slot 67 compute requests in the stand-in with the C++ compiler; `` holds `dxcompiler.dll` and `dxil.dll`. See [Translating compute programs in the stand-in](#translating-compute-programs-in-the-stand-in) | | `X2W_MESH57_DXC_DIR=` | experimental, with `X2W_MESH57_DERIVE_STATE=1`: the directory of `dxcompiler.dll` and `dxil.dll` for that one slot 57 derivation. Other graphics and compute programs stay on the non-native path. Unset, the derivation may still use `X2W_NATIVE_SHADERS` when that directory is set. When neither directory is set, the call stays refused (`derived mesh needs the native shader compiler`). See [Opt-in immediate allocation](experiments/native-fixed-mesh57.md#opt-in-immediate-allocation) | -| `X2W_MESH57_DERIVE_STATE=1` | experimental, with `X2W_SHADER_CACHE` and `X2W_MESH57_DXC_DIR` (or `X2W_NATIVE_SHADERS`): addresses `graphics/mesh_profile_missing` for one slot 57 shape. A direct `DispatchMesh` `ExecuteIndirect` may build one desktop mesh pipeline from an immediate `GS_ALLOC_REQ` and the bound color target when captured stages exist and no `.mesh57-state` file was opened. One guest constant block of 1..8 dwords is copied into desktop b0, including when that root is heap indexed. A slot 55 pipeline whose base is that slot 57 mesh reuses it when every patch is a blend record. `graphics/no_translation`, slot 86, depth, stencil, any other heap-indexed root, a descriptor root, and any other allocation shape stay refused. While the switch is on, every `DispatchMesh` `ExecuteIndirect` is counted: the first use of a reason logs `x2w-render mesh57-derive sample`, and the 300-frame heartbeat logs `x2w-render mesh57-derive:` plus `x2w-render mesh57-derive forwards:`. The rasterizer is not taken from the register block. See [Opt-in immediate allocation](experiments/native-fixed-mesh57.md#opt-in-immediate-allocation) | +| `X2W_MESH57_DERIVE_STATE=1` | experimental, with `X2W_SHADER_CACHE` and `X2W_MESH57_DXC_DIR` (or `X2W_NATIVE_SHADERS`): addresses `graphics/mesh_profile_missing` for one slot 57 shape. A direct `DispatchMesh` `ExecuteIndirect` may build one desktop mesh pipeline from an immediate `GS_ALLOC_REQ` and the bound color target when captured stages exist and no `.mesh57-state` file was opened. One guest constant block of 1..8 dwords is copied into desktop b0, including when that root is heap indexed. A slot 55 pipeline whose base is that slot 57 mesh reuses it when every patch is a blend record. A patch whose tag is not 2 stays refused and the reason names that tag. The sample line lists the first root-parameter types and the first patch tags. A zero pixel length in the descriptor stays refused (`slot 57 pixel stage is absent from the descriptor`). `graphics/no_translation`, slot 86, depth, stencil, any other heap-indexed root, a descriptor root, and any other allocation shape stay refused. While the switch is on, every `DispatchMesh` `ExecuteIndirect` is counted: the first use of a reason logs `x2w-render mesh57-derive sample`, and the 300-frame heartbeat logs `x2w-render mesh57-derive:` plus `x2w-render mesh57-derive forwards:`. The rasterizer is not taken from the register block. See [Opt-in immediate allocation](experiments/native-fixed-mesh57.md#opt-in-immediate-allocation) | | `X2W_D3D12_LINEAR_BUFFERS=1` or `=copy` | opt-in backing for linear buffers placed at a title address (device slot 133, initial state `COMMON`): shared where the adapter, extent and memory allow it (private allocations larger than 256 MiB are skipped only with `X2W_D3D12_CAP_EXISTING_HEAP=1`), otherwise copied from title memory at each submission, otherwise the default backing is kept and the refusal recorded; `copy` never shares. Unset or `0`, slot 133 keeps its default backing. See [Linear buffer backing (device slot 133, opt-in)](#linear-buffer-backing-device-slot-133-opt-in) | | `X2W_D3D12_CAP_EXISTING_HEAP=1` | opt-in 256 MiB (`unplaced_existing_heap_allowed`) allocation-size cap on `OpenExistingHeapFromAddress` in device slot 133 (`startup_slot133_heap_cap_*`). Unset (default), private allocations larger than 256 MiB keep the formerly aliased path: a capped copied placement is refused by `CopyBufferRegion` (list slot 15) as `title_backed_source`, losing a late guest write made after recording and before submit. Set, allocations larger than 256 MiB skip `OpenExistingHeapFromAddress` so multi-GiB startup blocks are not pinned in `WorkingSetSize` and `NonLocal` GPU memory | | `X2W_D3D12_ROOT_SRV_AT_DRAW=1` | opt-in, render mode: a graphics root SRV (slot 44) without an upload mapping is not copied into the upload ring, since no draw reads that desktop binding (default: a 64 KiB copy at every slot 44 call). Translated draws copy the SRV themselves and are unaffected (`startup_root_srv_draw_*`). See [the experiment note](experiments/startup-root-srv-at-draw.md) | diff --git a/src/startup_stubs/mesh57_alloc.h b/src/startup_stubs/mesh57_alloc.h index d931fe8cf1..4d3dced9ee 100644 --- a/src/startup_stubs/mesh57_alloc.h +++ b/src/startup_stubs/mesh57_alloc.h @@ -102,6 +102,7 @@ inline std::optional derive_immediate_mesh_layout(std::string // nullptr means both stages were captured from a 768-byte descriptor with no vertex span. // The clauses match the capture in note_pipeline: a vertex span, a zero mesh length, or a // short descriptor leaves the stage pointers empty, and an unreadable stage is dropped. +// A zero pixel length is an empty span in the descriptor, not a copy that failed. struct Mesh57PairRecord { std::size_t desc_bytes = 0; bool mesh_captured = false; @@ -112,6 +113,32 @@ struct Mesh57PairRecord { std::uint64_t pixel_length = 0; }; +// One stage copy, matching note_pipeline's snapshot. readable is the caller's check of the +// guest bytes; this function does not read them. A zero length and a zero pointer is an empty +// span and the copy is skipped. A zero length with a pointer, or a non-zero length that is +// not readable, fails the copy. note_pipeline then drops both stages. +enum class Mesh57StageCopy : unsigned { empty = 0, copied = 1, unreadable = 2 }; + +inline Mesh57StageCopy mesh57_stage_copy(std::uint64_t pointer, std::uint64_t bytes, bool readable) noexcept +{ + if (!bytes) + return pointer ? Mesh57StageCopy::unreadable : Mesh57StageCopy::empty; + return readable ? Mesh57StageCopy::copied : Mesh57StageCopy::unreadable; +} + +// True when note_pipeline keeps the stage copies. The vertex span must be empty, the mesh +// length must be non-zero, the mesh bytes must have been copied, and neither snapshot failed. +// An empty pixel span is kept with the mesh. An unreadable pixel drops the mesh as well. +inline bool mesh57_fixed_stages_kept(bool vertex_empty, bool mesh_length, Mesh57StageCopy pixel, + Mesh57StageCopy mesh) noexcept +{ + if (!vertex_empty || !mesh_length) + return false; + if (pixel == Mesh57StageCopy::unreadable || mesh == Mesh57StageCopy::unreadable) + return false; + return mesh == Mesh57StageCopy::copied; +} + inline const char* mesh57_fixed_pair_reason(const Mesh57PairRecord& record) noexcept { if (record.desc_bytes < 15 * sizeof(std::uint64_t)) @@ -124,9 +151,11 @@ inline const char* mesh57_fixed_pair_reason(const Mesh57PairRecord& record) noex return "slot 57 descriptor has no mesh stage length"; if (!record.mesh_captured) return "slot 57 mesh stage was not captured"; - if (!record.pixel_captured) + if (!record.pixel_captured) { + if (!record.pixel_length) + return "slot 57 pixel stage is absent from the descriptor"; return "slot 57 pixel stage was not captured"; - (void)record.pixel_length; + } return nullptr; } @@ -153,6 +182,17 @@ struct Mesh57DeriveSample { std::uint32_t root_constant_dwords = 0; std::uint32_t root_other = 0; std::uint32_t root_heap = 0; + // First parameters, in order. type 0 is a descriptor table, 1 is 32-bit constants + // (count is the dword count), 2 is a root CBV, 3 is a root SRV, 4 is a root UAV. + static constexpr int root_param_slots = 8; + int root_param_n = 0; + std::uint8_t root_param_type[root_param_slots]{}; + std::uint32_t root_param_count[root_param_slots]{}; + // First slot 55 patch records. tag is the record's first dword and bytes is its size. + static constexpr int patch_slots = 4; + int patch_n = 0; + std::uint32_t patch_tag[patch_slots]{}; + std::uint32_t patch_size[patch_slots]{}; }; // One guest root parameter, without a D3D12 type. type 0 is 32-bit constants and @@ -216,23 +256,80 @@ inline const char* mesh57_root_bind_reason(const Mesh57RootContract& contract) n return nullptr; } -// A slot 55 patch list can reuse a slot 57 mesh when it is empty or every record is a -// blend patch. record bytes are the 0x14c blend record (tag word plus the blend state). -// A tag other than 2, or a size that is not a whole number of records, is not applied. -inline const char* mesh57_slot55_patch_reason(const unsigned char* records, std::size_t bytes) noexcept +// One slot 55 patch record. The creation path stores fixed 0x14c records. The only tag this +// repository applies is 2, the blend descriptor (derived_blend.h). Other tags are named and refused. +struct Mesh57PatchNote { + std::uint32_t tag = 0; + std::uint32_t bytes = 0; +}; + +enum class Mesh57PatchDecision : unsigned { accept = 0, unaligned = 1, other_tag = 2 }; + +struct Mesh57PatchScan { + Mesh57PatchDecision decision = Mesh57PatchDecision::accept; + std::uint32_t other_tag = 0; + int notes = 0; +}; + +// Writes the first cap records. An empty list is accepted. Every whole record must be tag 2. +// A size that is not a whole number of 0x14c records is unaligned; a trailing partial record is +// still noted when cap allows. The first tag that is not 2 is other_tag. +inline Mesh57PatchScan mesh57_scan_slot55_patches(const unsigned char* records, std::size_t bytes, + Mesh57PatchNote* notes, int cap) noexcept { constexpr std::size_t record = 0x14c; + Mesh57PatchScan scan; if (!bytes) - return nullptr; - if (!records || bytes % record) - return "slot 55 patches are not applied"; - for (std::size_t at = 0; at < bytes; at += record) { + return scan; + if (!records || cap < 0) { + scan.decision = Mesh57PatchDecision::unaligned; + return scan; + } + const bool whole = bytes % record == 0; + const std::size_t whole_bytes = whole ? bytes : bytes - (bytes % record); + for (std::size_t at = 0; at < whole_bytes; at += record) { std::uint32_t tag = 0; std::memcpy(&tag, records + at, sizeof(tag)); - if (tag != 2) - return "slot 55 patches are not applied"; + if (tag != 2 && scan.decision == Mesh57PatchDecision::accept) { + scan.decision = Mesh57PatchDecision::other_tag; + scan.other_tag = tag; + } + if (notes && scan.notes < cap) { + notes[scan.notes].tag = tag; + notes[scan.notes].bytes = static_cast(record); + scan.notes += 1; + } } - return nullptr; + if (!whole) { + const std::size_t rest = bytes - whole_bytes; + std::uint32_t tag = 0; + if (rest >= sizeof(tag)) + std::memcpy(&tag, records + whole_bytes, sizeof(tag)); + if (notes && scan.notes < cap) { + notes[scan.notes].tag = tag; + notes[scan.notes].bytes = rest > 0xffffffffu ? 0xffffffffu : static_cast(rest); + scan.notes += 1; + } + scan.decision = Mesh57PatchDecision::unaligned; + } + return scan; +} + +// Stable text for a tag this path does not apply. The caller keeps the buffer it passes. +inline std::size_t mesh57_slot55_tag_reason(std::uint32_t tag, char* out, std::size_t cap) noexcept +{ + if (!out || cap == 0) + return 0; + const int n = std::snprintf(out, cap, "slot 55 patch tag %u is not applied", tag); + if (n < 0) { + out[0] = 0; + return 0; + } + if (static_cast(n) >= cap) { + out[cap - 1] = 0; + return cap - 1; + } + return static_cast(n); } struct Mesh57DeriveCensus { @@ -285,18 +382,86 @@ struct Mesh57DeriveCensus { } }; +inline void mesh57_write_root_params(const Mesh57DeriveSample& sample, char* out, std::size_t cap) noexcept +{ + if (!out || cap == 0) + return; + out[0] = 0; + if (sample.root_param_n <= 0) { + std::snprintf(out, cap, "-"); + return; + } + std::size_t used = 0; + const int n = sample.root_param_n < Mesh57DeriveSample::root_param_slots + ? sample.root_param_n : Mesh57DeriveSample::root_param_slots; + for (int i = 0; i < n && used + 1 < cap; ++i) { + char piece[16]; + const unsigned type = sample.root_param_type[i]; + const unsigned count = sample.root_param_count[i]; + int wrote = 0; + if (type == 0) + wrote = std::snprintf(piece, sizeof(piece), "t"); + else if (type == 1) + wrote = std::snprintf(piece, sizeof(piece), "c%u", count); + else if (type == 2) + wrote = std::snprintf(piece, sizeof(piece), "cbv"); + else if (type == 3) + wrote = std::snprintf(piece, sizeof(piece), "srv"); + else if (type == 4) + wrote = std::snprintf(piece, sizeof(piece), "uav"); + else + wrote = std::snprintf(piece, sizeof(piece), "p%u", type); + if (wrote <= 0) + break; + const int put = std::snprintf(out + used, cap - used, "%s%s", i ? "," : "", piece); + if (put < 0 || static_cast(put) >= cap - used) { + out[cap - 1] = 0; + return; + } + used += static_cast(put); + } +} + +inline void mesh57_write_patches(const Mesh57DeriveSample& sample, char* out, std::size_t cap) noexcept +{ + if (!out || cap == 0) + return; + out[0] = 0; + if (sample.patch_n <= 0) { + std::snprintf(out, cap, "-"); + return; + } + std::size_t used = 0; + const int n = sample.patch_n < Mesh57DeriveSample::patch_slots ? sample.patch_n : Mesh57DeriveSample::patch_slots; + for (int i = 0; i < n && used + 1 < cap; ++i) { + const int put = std::snprintf(out + used, cap - used, "%s%u:%u", i ? "," : "", + sample.patch_tag[i], sample.patch_size[i]); + if (put < 0 || static_cast(put) >= cap - used) { + out[cap - 1] = 0; + return; + } + used += static_cast(put); + } +} + inline std::size_t mesh57_derive_sample_line(const char* reason, const Mesh57DeriveSample& sample, char* out, std::size_t cap) noexcept { if (!out || cap == 0) return 0; + char params[96]; + char patches[80]; + mesh57_write_root_params(sample, params, sizeof(params)); + mesh57_write_patches(sample, patches, sizeof(patches)); const int n = std::snprintf(out, cap, "x2w-render mesh57-derive sample reason=%s path=%d base=%d desc=%u ms=%u ps=%u state_a=%u state_b=%u " - "vs=%u ms_len=%u ps_len=%u key=%016llx list=%d real=%d mesh86=%d root=%u const=%u other=%u heap=%u", + "vs=%u ms_len=%u ps_len=%u key=%016llx list=%d real=%d mesh86=%d root=%u const=%u other=%u heap=%u " + "params=%s patches=%s", reason ? reason : "", sample.path, sample.base_path, sample.desc_bytes, sample.mesh_bytes, sample.pixel_bytes, sample.state_a, sample.state_b, sample.vertex_bytes, sample.mesh_length, sample.pixel_length, static_cast(sample.key), sample.list_type, sample.real, - sample.mesh86, sample.root_parameters, sample.root_constant_dwords, sample.root_other, sample.root_heap); + sample.mesh86, sample.root_parameters, sample.root_constant_dwords, sample.root_other, sample.root_heap, + params, patches); if (n < 0) { out[0] = 0; return 0; diff --git a/src/startup_stubs/native_mesh57.inl b/src/startup_stubs/native_mesh57.inl index 279a66e87f..4e91cd573a 100644 --- a/src/startup_stubs/native_mesh57.inl +++ b/src/startup_stubs/native_mesh57.inl @@ -550,6 +550,16 @@ x2w_startup::Mesh57DeriveSample mesh57_derive_sample(Wrapper* pipeline, const Pi sample.pixel_length = mesh57_derive_u32(static_cast(words[6])); sample.mesh_length = mesh57_derive_u32(static_cast(words[14])); } + if (info->path == 55) { + x2w_startup::Mesh57PatchNote notes[x2w_startup::Mesh57DeriveSample::patch_slots]; + const auto scan = x2w_startup::mesh57_scan_slot55_patches( + info->desc.data(), info->desc.size(), notes, x2w_startup::Mesh57DeriveSample::patch_slots); + sample.patch_n = scan.notes; + for (int i = 0; i < scan.notes; ++i) { + sample.patch_tag[i] = notes[i].tag; + sample.patch_size[i] = notes[i].bytes; + } + } const PipelineInfo* root_source = info; for (int depth = 0; root_source && root_source->path == 55 && root_source->base && depth < 8; ++depth) root_source = pipeline_info(root_source->base); @@ -562,6 +572,22 @@ x2w_startup::Mesh57DeriveSample mesh57_derive_sample(Wrapper* pipeline, const Pi if (const auto* params = root_info(root)) { sample.root_parameters = mesh57_derive_u32(params->size()); for (const auto& parameter : *params) { + unsigned code = 255; + if (parameter.type == D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE) + code = 0; + else if (parameter.type == D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS) + code = 1; + else if (parameter.type == D3D12_ROOT_PARAMETER_TYPE_CBV) + code = 2; + else if (parameter.type == D3D12_ROOT_PARAMETER_TYPE_SRV) + code = 3; + else if (parameter.type == D3D12_ROOT_PARAMETER_TYPE_UAV) + code = 4; + if (sample.root_param_n < x2w_startup::Mesh57DeriveSample::root_param_slots) { + sample.root_param_type[sample.root_param_n] = static_cast(code); + sample.root_param_count[sample.root_param_n] = parameter.constants_count; + sample.root_param_n += 1; + } if (parameter.type == D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS) { if (sample.root_constant_dwords <= ~std::uint32_t{0} - parameter.constants_count) sample.root_constant_dwords += parameter.constants_count; @@ -586,7 +612,7 @@ void record_mesh57_derive(const char* reason, Wrapper* pipeline, const PipelineI ReleaseSRWLockExclusive(&mesh57_derive_census_lock); if (!first) return; - char line[640]; + char line[1024]; if (x2w_startup::mesh57_derive_sample_line(reason, sample, line, sizeof(line))) log("%s", line); } @@ -606,6 +632,35 @@ void log_mesh57_derive_census() log("%s", line); } +// The census and the pipeline keep the first reason pointer. A formatted tag reason lives in +// this table so that pointer outlives both. Matching is by the characters, not the address. +const char* mesh57_stable_text(const char* text) +{ + static SRWLOCK lock = SRWLOCK_INIT; + struct Kept { char text[80]; }; + static Kept kept[24]; + static int used = 0; + if (!text || !text[0]) + return "slot 55 patch tag is not applied"; + AcquireSRWLockExclusive(&lock); + for (int i = 0; i < used; ++i) { + if (std::strcmp(kept[i].text, text) == 0) { + const char* found = kept[i].text; + ReleaseSRWLockExclusive(&lock); + return found; + } + } + if (used >= 24) { + ReleaseSRWLockExclusive(&lock); + return "slot 55 patch tag is not applied"; + } + std::snprintf(kept[used].text, sizeof(kept[used].text), "%s", text); + const char* stored = kept[used].text; + used += 1; + ReleaseSRWLockExclusive(&lock); + return stored; +} + const char* derive_slot55_mesh(Wrapper* pipeline, Pass& pass) { if (!pipeline || pipeline->own().real) @@ -626,9 +681,16 @@ const char* derive_slot55_mesh(Wrapper* pipeline, Pass& pass) } if (!base_info || base_info->path != 57) return "pipeline is a derived slot 55"; - if (const char* patch = x2w_startup::mesh57_slot55_patch_reason(info->desc.data(), info->desc.size())) { - info->mesh57_derive_reason = patch; - return patch; + const auto patches = x2w_startup::mesh57_scan_slot55_patches(info->desc.data(), info->desc.size(), nullptr, 0); + if (patches.decision == x2w_startup::Mesh57PatchDecision::unaligned) { + info->mesh57_derive_reason = "slot 55 patches are not applied"; + return info->mesh57_derive_reason; + } + if (patches.decision == x2w_startup::Mesh57PatchDecision::other_tag) { + char named[80]; + x2w_startup::mesh57_slot55_tag_reason(patches.other_tag, named, sizeof(named)); + info->mesh57_derive_reason = mesh57_stable_text(named); + return info->mesh57_derive_reason; } D3D12_BLEND_DESC blend{}; std::size_t where = 0; diff --git a/tests/mesh57_derive_alloc_check.cpp b/tests/mesh57_derive_alloc_check.cpp index 73ed5094c3..4683fc634a 100644 --- a/tests/mesh57_derive_alloc_check.cpp +++ b/tests/mesh57_derive_alloc_check.cpp @@ -127,6 +127,22 @@ int main() if (std::strcmp(x2w_startup::mesh57_fixed_pair_reason(pair), "slot 57 pixel stage was not captured") != 0) return fail("pixel stage"); + pair.pixel_length = 0; + if (std::strcmp(x2w_startup::mesh57_fixed_pair_reason(pair), + "slot 57 pixel stage is absent from the descriptor") != 0) + return fail("absent pixel span"); + // The descriptor words are zero, so the copy is skipped and the mesh bytes stay. + // A non-zero span that cannot be read fails the snapshot and drops both stages. + if (x2w_startup::mesh57_stage_copy(0, 0, false) != x2w_startup::Mesh57StageCopy::empty || + !x2w_startup::mesh57_fixed_stages_kept(true, true, x2w_startup::Mesh57StageCopy::empty, + x2w_startup::Mesh57StageCopy::copied)) + return fail("empty pixel keeps the mesh"); + if (x2w_startup::mesh57_stage_copy(0x1000, 1408, false) != x2w_startup::Mesh57StageCopy::unreadable || + x2w_startup::mesh57_fixed_stages_kept(true, true, x2w_startup::Mesh57StageCopy::unreadable, + x2w_startup::Mesh57StageCopy::copied)) + return fail("unreadable pixel drops the mesh"); + if (x2w_startup::mesh57_stage_copy(0, 1408, true) != x2w_startup::Mesh57StageCopy::copied) + return fail("readable pixel is copied"); x2w_startup::Mesh57DeriveCensus census; x2w_startup::Mesh57DeriveSample slot86; @@ -161,8 +177,31 @@ int main() !std::strstr(sample, "reason=pipeline is slot 86") || !std::strstr(sample, "path=86") || !std::strstr(sample, "desc=512") || !std::strstr(sample, "root=0") || !std::strstr(sample, "const=0") || !std::strstr(sample, "other=0") || !std::strstr(sample, "heap=0") || + !std::strstr(sample, "params=-") || !std::strstr(sample, "patches=-") || std::strncmp(sample, "x2w-render mesh57-derive sample ", 32) != 0) return fail("sample"); + x2w_startup::Mesh57DeriveSample typed; + typed.path = 57; + typed.root_parameters = 5; + typed.root_constant_dwords = 1; + typed.root_other = 4; + typed.root_heap = 1024; + typed.root_param_n = 5; + const unsigned typed_codes[] = {0u, 1u, 3u, 2u, 4u}; + const unsigned typed_counts[] = {0u, 1u, 0u, 0u, 0u}; + for (int i = 0; i < 5; ++i) { + typed.root_param_type[i] = static_cast(typed_codes[i]); + typed.root_param_count[i] = typed_counts[i]; + } + typed.patch_n = 1; + typed.patch_tag[0] = 3; + typed.patch_size[0] = 0x14c; + char typed_line[640]; + if (!x2w_startup::mesh57_derive_sample_line("derived mesh guest root is heap indexed", typed, typed_line, + sizeof(typed_line)) || + !std::strstr(typed_line, "params=t,c1,srv,cbv,uav") || !std::strstr(typed_line, "patches=3:332") || + !std::strstr(typed_line, "root=5") || !std::strstr(typed_line, "heap=1024")) + return fail("parameter and patch sample"); x2w_startup::Mesh57RootParameterView one; one.type = 0; one.constants = 1; @@ -204,14 +243,36 @@ int main() std::memset(blend_record, 0, sizeof(blend_record)); const std::uint32_t blend_tag = 2; std::memcpy(blend_record, &blend_tag, sizeof(blend_tag)); - if (x2w_startup::mesh57_slot55_patch_reason(nullptr, 0) || - x2w_startup::mesh57_slot55_patch_reason(blend_record, sizeof(blend_record))) + x2w_startup::Mesh57PatchNote notes[4]; + const auto blend_only = x2w_startup::mesh57_scan_slot55_patches(nullptr, 0, notes, 4); + const auto one_blend = x2w_startup::mesh57_scan_slot55_patches(blend_record, sizeof(blend_record), notes, 4); + if (blend_only.decision != x2w_startup::Mesh57PatchDecision::accept || + one_blend.decision != x2w_startup::Mesh57PatchDecision::accept || one_blend.notes != 1 || + notes[0].tag != 2 || notes[0].bytes != 0x14c) return fail("blend patch"); + unsigned char mixed[0x14c * 2]; + std::memset(mixed, 0, sizeof(mixed)); + std::memcpy(mixed, blend_record, sizeof(blend_record)); + const std::uint32_t other_tag = 3; + std::memcpy(mixed + sizeof(blend_record), &other_tag, sizeof(other_tag)); + const auto mixed_scan = x2w_startup::mesh57_scan_slot55_patches(mixed, sizeof(mixed), notes, 4); + char tag_reason[80]; + if (mixed_scan.decision != x2w_startup::Mesh57PatchDecision::other_tag || mixed_scan.other_tag != 3 || + mixed_scan.notes != 2 || notes[0].tag != 2 || notes[1].tag != 3 || notes[1].bytes != 0x14c || + !x2w_startup::mesh57_slot55_tag_reason(mixed_scan.other_tag, tag_reason, sizeof(tag_reason)) || + std::strcmp(tag_reason, "slot 55 patch tag 3 is not applied") != 0) + return fail("named patch tag"); + char tag_reason_copy[80]; + x2w_startup::mesh57_slot55_tag_reason(3, tag_reason_copy, sizeof(tag_reason_copy)); + if (&tag_reason[0] == &tag_reason_copy[0] || std::strcmp(tag_reason, tag_reason_copy) != 0 || + !census.note(tag_reason, slot86) || census.note(tag_reason_copy, slot86)) + return fail("tag reason text is one reason"); blend_record[0] = 1; - if (std::strcmp(x2w_startup::mesh57_slot55_patch_reason(blend_record, sizeof(blend_record)), - "slot 55 patches are not applied") != 0 || - std::strcmp(x2w_startup::mesh57_slot55_patch_reason(blend_record, 4), - "slot 55 patches are not applied") != 0) + const auto unknown = x2w_startup::mesh57_scan_slot55_patches(blend_record, sizeof(blend_record), notes, 4); + const auto short_list = x2w_startup::mesh57_scan_slot55_patches(blend_record, 4, notes, 4); + if (unknown.decision != x2w_startup::Mesh57PatchDecision::other_tag || unknown.other_tag != 1 || + short_list.decision != x2w_startup::Mesh57PatchDecision::unaligned || short_list.notes != 1 || + notes[0].bytes != 4) return fail("unknown patch"); if (!census.note("forwarded", slot86) || x2w_startup::mesh57_derive_forwarded(census) != 1) return fail("forwarded count"); From 44ccc91d21cf9803caa0c968f106c0cdd162e2f8 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Sun, 29 Nov 2026 12:52:58 +0000 Subject: [PATCH 08/12] runtime: bind a derived mesh only when the program matches Refuse wave32, an unproven thread count, a non-triangle export, a captured rasterizer that is not the bound default, and a constant that is not the word at user SGPR s8. Store a slot 55 refusal on that slot 55 pipeline. The one-constant device modes use a non-zero word in the export, including the heap-indexed root the deferred path binds. The five-parameter heap root stays refused. Co-authored-by: SimSalabimse --- CMakeLists.txt | 2 +- CMakePresets.json | 4 +- docs/experiments/native-fixed-mesh57.md | 14 ++-- docs/startup-runtime.md | 2 +- src/startup_stubs/d3d12_capture.inl | 35 ++++++--- src/startup_stubs/mesh57_alloc.h | 97 +++++++++++++++++++++---- src/startup_stubs/native_mesh57.inl | 70 +++++++++++++----- tests/mesh57_derive_alloc_check.cpp | 40 +++++++++- tests/startup_indirect_draw_indexed.cpp | 87 +++++++++++++++++++--- 9 files changed, 285 insertions(+), 66 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index ec62b2d8cd..86bb02658f 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1948,7 +1948,7 @@ if(TARGET compile_dxil AND EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${ add_test(NAME native_fixed_mesh57_${backend} COMMAND startup_indirect_draw_indexed ${backend} mesh) set_tests_properties(native_fixed_mesh57_${backend} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77 ENVIRONMENT "X2W_TEST_NATIVE_MESH57=1;X2W_NATIVE_SHADERS=${DXC_BIN_DIR}") - foreach(mode derived derived-off derived-bad derived-depth derived-reviewed derived-untranslated derived-root derived-root-unset derived-root-table derived-slot55 derived-slot55-mask) + foreach(mode derived derived-off derived-bad derived-depth derived-reviewed derived-untranslated derived-root derived-root-unset derived-root-zero derived-root-sgpr derived-root-heap derived-root-five derived-root-table derived-slot55 derived-slot55-mask derived-slot55-isolate) add_test(NAME startup_indirect_mesh_${mode}_${backend} COMMAND startup_indirect_draw_indexed ${backend} mesh-${mode}) set_tests_properties(startup_indirect_mesh_${mode}_${backend} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77 diff --git a/CMakePresets.json b/CMakePresets.json index 57f5998522..6f58d0d404 100644 --- a/CMakePresets.json +++ b/CMakePresets.json @@ -29,7 +29,7 @@ "d3d12_sdk_check", "era_heap_check", "xmem_shim", "offscreen_check", "cpu_fuzz_lifted", "cpu_fuzz_lifted_o2", "pe_map", "intake_candidate", "archive_gpu_reader", "archive_codec_gpu", "archive_texture_gpu_lifted", "startup_launch_probe", - "startup_indirect_dispatch", "startup_indirect_draw_indexed", "startup_present_readback_check", + "startup_indirect_dispatch", "startup_indirect_draw_indexed", "mesh57_derive_alloc_check", "startup_present_readback_check", "xmem_shim_test_controls", "startup_stub_xcrdapi", "startup_stub_xcrdapi_break_window_control", "xmem_run_break_readers_check", "xmem_run_break_readers_control", "xmem_cross_call_merge_check", "xmem_placeholder_split_check", "xmem_map_split_first_check", "startup_dstorage_break_window_check", @@ -48,7 +48,7 @@ "displayName": "Windows pull request smoke tests", "filter": { "include": { - "name": "^(bcpack_all_formats(_golden_control)?|startup_bcpack_storage|desktop_root_signature|era_heap_(allocation|failure)|xmem_shim_mapped_pages|cpu_aot_fuzz_smoke|cpu_archive_texture_gpu_warp|dual_uav_warp|spirv_.*_warp|static_exe_intake|descriptor_heap_paging(_swapped)?_warp|startup_launch|startup_tools_lint|startup_gfx2hlsl_cvt_off_f32_i4_controls|startup_gfx2hlsl_sad_hi_msad_controls|startup_indirect_(dispatch|count_split|draw(_indexed)?|mesh(_xmem_arguments(_skip_wait)?)?|counts_control)_warp|startup_indirect_(dispatch|constants|count)_inline_warp|startup_inline_retire_(on|control)_warp|startup_resource_retire_title_inline_warp_debug0|startup_table_lock_(control_)?warp|startup_indirect_mesh_lease_warp_dual(-trace(-disabled)?)?|startup_shader_cache_key|startup_present_readback|xmem_(run_break_readers|cross_call_merge|placeholder_split|map_split_first)(_[a-z_]+)?|startup_dstorage_break_window(_[a-z_]+)?|xmem_page_runs_device(_join)?_warp|linear_buffer_backing_share_warp|startup_stage_package|startup_compute_packed_d16_x_uav_reference)$" + "name": "^(bcpack_all_formats(_golden_control)?|startup_bcpack_storage|desktop_root_signature|era_heap_(allocation|failure)|xmem_shim_mapped_pages|cpu_aot_fuzz_smoke|cpu_archive_texture_gpu_warp|dual_uav_warp|spirv_.*_warp|static_exe_intake|descriptor_heap_paging(_swapped)?_warp|startup_launch|startup_tools_lint|startup_gfx2hlsl_cvt_off_f32_i4_controls|startup_gfx2hlsl_sad_hi_msad_controls|startup_indirect_(dispatch|count_split|draw(_indexed)?|mesh(_xmem_arguments(_skip_wait)?)?|counts_control)_warp|mesh57_derive_alloc|startup_indirect_mesh_derived([-a-z0-9]+)?_warp|startup_indirect_(dispatch|constants|count)_inline_warp|startup_inline_retire_(on|control)_warp|startup_resource_retire_title_inline_warp_debug0|startup_table_lock_(control_)?warp|startup_indirect_mesh_lease_warp_dual(-trace(-disabled)?)?|startup_shader_cache_key|startup_present_readback|xmem_(run_break_readers|cross_call_merge|placeholder_split|map_split_first)(_[a-z_]+)?|startup_dstorage_break_window(_[a-z_]+)?|xmem_page_runs_device(_join)?_warp|linear_buffer_backing_share_warp|startup_stage_package|startup_compute_packed_d16_x_uav_reference)$" } } }, diff --git a/docs/experiments/native-fixed-mesh57.md b/docs/experiments/native-fixed-mesh57.md index eeecdc0fe5..1b2a6ac777 100644 --- a/docs/experiments/native-fixed-mesh57.md +++ b/docs/experiments/native-fixed-mesh57.md @@ -122,17 +122,17 @@ A slot 57 record is a fixed pair only when the captured descriptor is 768 bytes, Those seven still refuse. The 768-byte rule stays: a shorter descriptor cannot be checked against a reviewed `.mesh57-state` file. While the switch is on, publishing a slot 57 request no longer drops the captured stage bytes, so a later call whose first refusal depended on the command list can still see them. -The first time a reason is seen, stderr gets one `x2w-render mesh57-derive sample` line: the reason, the creating slot (`path`), the derived-from slot (`base`), descriptor and stage sizes, the vertex, mesh and pixel lengths from the descriptor, the pipeline key, the list type, whether a desktop pipeline or a slot 86 key is present, the guest root (`root`, `const`, `other`, `heap`), the first parameter types (`params`), and the first slot 55 patch tags and sizes (`patches`). The line has no file path. `params` uses `t` for a descriptor table, `cN` for an N-dword constant block, `cbv`, `srv`, and `uav`. `patches` uses `tag:bytes`. A sample with no root parameters or no patch list prints `-`. Every 300 presented frames the heartbeat adds `x2w-render mesh57-derive:` with the call count of each reason, then `x2w-render mesh57-derive forwards:` with the `forwarded` count. That count is the number of calls that installed a desktop pipeline from this path. +The first time a reason is seen, stderr gets one `x2w-render mesh57-derive sample` line: the reason, the creating slot (`path`), the derived-from slot (`base`), descriptor and stage sizes, the vertex, mesh and pixel lengths from the descriptor, the pipeline key, the list type, whether a desktop pipeline or a slot 86 key is present, the guest root (`root`, `const`, `other`, `heap`), the first parameter types (`params`), the first slot 55 patch tags and sizes (`patches`), and `raster`. The line has no file path. `params` uses `t` for a descriptor table, `cN` for an N-dword constant block, `cbv`, `srv`, and `uav`. `patches` uses `tag:bytes`. A sample with no root parameters or no patch list prints `-`. `raster=0` means no rasterizer was captured, `raster=1` means the captured rasterizer matches the bound default, and `raster=2` means it does not. Every 300 presented frames the heartbeat adds `x2w-render mesh57-derive:` with the call count of each reason, then `x2w-render mesh57-derive forwards:` with the `forwarded` count. That count is the number of calls that installed a desktop pipeline from this path. A startup run on the Windows test PC recorded 653,708 refused `DispatchMesh` `ExecuteIndirect` calls in 420 seconds and forwarded none. Across draw and mesh, the graphics-pipeline census counted `graphics/no_translation` 446,421 and `graphics/mesh_profile_missing` 427,428. This switch is only the second of those, and only the immediate-allocation shape below. Slot 86 meshes with no cached stage stay refused. -The accepted program writes `m0` with one `s_mov_b32` of an integer immediate and the next instruction is the only `s_sendmsg` `GS_ALLOC_REQ` (`0xbf900009`). The immediate is `(primitives << 12) | vertices`, both counts are in 1..64, and the high byte is clear. A group-memory count exchange (`0xbf8a0000`) or an `s_mov_b32` of `exec_lo` is refused. The derived layout is one wave64 group of 64 threads, triangle topology, and group stride 0. Stride 0 is accepted because this program does not read the group id; the lowerer skips that multiply. The pixel shader must be a constant `MRT0` export with no resource bindings. +The accepted program writes `m0` with one `s_mov_b32` of an integer immediate and the next instruction is the only `s_sendmsg` `GS_ALLOC_REQ` (`0xbf900009`). The immediate is `(primitives << 12) | vertices`, both counts are in 1..64, and the high byte is clear. A group-memory count exchange (`0xbf8a0000`) is refused. A 32-bit `exec` write is refused as `derived mesh is wave32`, whether it is `s_mov_b32 exec_lo` or a 32-bit `exec` ALU such as `s_and_b32`. The bound group is one wave of 64 threads, triangle topology, and group stride 0, and the program is forwarded only when it proves that group. `v_mbcnt_lo` of the hardware lane id is the thread-count proof (`derived mesh thread count is not proven` otherwise). A primitive-index export (export target 20) is the triangle proof (`derived mesh topology is not triangles` otherwise). An allocation by itself is not forwarded. Stride 0 is the bound stride; this path does not invent another. The pixel shader must be a constant `MRT0` export with no resource bindings. A one-constant root is bound at user SGPR s8. A program that reads a different SGPR stays refused (`derived mesh constant is not at user SGPR s8`). An empty guest root is unchanged. One 32-bit constant parameter of 1..8 dwords and no other parameters is bound, including when the guest root is heap indexed: user SGPR s8 is that block, and the draw copies it into a desktop b0 the same way a reviewed constant profile does. The constant words must already be set on the list. The heap base itself is not bound; a shader that reads it is refused by the lowerer. A heap-indexed root with any other shape (`derived mesh guest root is heap indexed`), a descriptor or root descriptor (`derived mesh guest root has descriptors`), or any other constant shape (`derived mesh guest root constants do not fit one user block`) stays refused. Those need a reviewed SGPR map; this path does not invent one. -A slot 55 pipeline reuses that derived mesh when every patch record is a blend patch (tag 2, 0x14c bytes) or the patch list is empty. The last blend patch replaces the base blend. Tag 2 is the only slot 55 record this repository applies: the graphics path reads that blend descriptor and does not apply any other tag. Depth and raster for a slot 57 base come from its state block, not from a patch tag. A record whose tag is not 2 stays refused, and the reason names that tag (for example `slot 55 patch tag 3 is not applied`). A list whose size is not a whole number of 0x14c records stays `slot 55 patches are not applied`. The sample lists the first records either way. The base's shader, root, and depth rules are unchanged. +A slot 55 pipeline reuses that derived mesh when every patch record is a blend patch (tag 2, 0x14c bytes) or the patch list is empty. The last blend patch replaces the base blend. Tag 2 is the only slot 55 record this repository applies: the graphics path reads that blend descriptor and does not apply any other tag. Depth for a slot 57 base comes from its state block, not from a patch tag. A record whose tag is not 2 stays refused, and the reason names that tag (for example `slot 55 patch tag 3 is not applied`). A list whose size is not a whole number of 0x14c records stays `slot 55 patches are not applied`. The sample lists the first records either way. That refusal is stored on the slot 55 pipeline. The slot 57 base keeps the derive reason it already had. The base's shader, root, and depth rules are unchanged. -Fixed function state comes from state block A. The mesh layout word at `+0x004` must be 6. Blend words are read at the mesh shift (`+0x54` on top of `+0xD0`). Depth and stencil must decode as disabled; an enabled test is refused rather than given a guessed depth format. The color target is the one single-sample target bound on that direct list, with a viewport and a scissor and no depth view. The rasterizer is solid, cull none, and depth clip. Those three values are not read from the register block. A `.mesh57-state` file that is present, including one whose bytes do not match, keeps the reviewed path and this switch does not create a pipeline. +Fixed function state comes from state block A. The mesh layout word at `+0x004` must be 6. Blend words are read at the mesh shift (`+0x54` on top of `+0xD0`). Depth and stencil must decode as disabled; an enabled test is refused rather than given a guessed depth format. The color target is the one single-sample target bound on that direct list, with a viewport and a scissor and no depth view. The bound rasterizer is solid, cull none, depth clip, and clockwise front faces. A rasterizer captured with the pipeline must match that state (`derived mesh rasterizer does not match the bound state`). Slot 57 creation does not pass a rasterizer, and the guest `PA_SU_SC_MODE_CNTL` word has no established offset in the register block, so this path does not read or guess one. The sample then records `raster=0`. A `.mesh57-state` file that is present, including one whose bytes do not match, keeps the reviewed path and this switch does not create a pipeline. A failed derivation is remembered for that pipeline. Attachment and root mismatches are not: a later direct list can still be the first accepted call. The desktop pipeline then keeps the color format of that call. @@ -142,12 +142,14 @@ From the x64 Windows build environment, with DXC available to the native shader ctest --preset dev -j 1 --no-tests=error -R "mesh57_derive_alloc|startup_indirect_mesh_derived" ``` -`startup_indirect_mesh_derived_{warp,hardware}` forwards one group and reads a white texel at `(2,0)` on a 4 by 2 target. `derived-dxc` does the same with only `X2W_MESH57_DXC_DIR` set, and the process clears `X2W_NATIVE_SHADERS` before the call. `derived-root` is that program plus one guest constant at s8, with the word set, and paints the same texel. `derived-slot55` draws through a slot 55 pipeline with no patches and paints the same texel. `derived-off` leaves the switch unset. `derived-bad` has no immediate allocation. `derived-depth` enables the depth test in the register block. `derived-reviewed` and `derived-dxc-reviewed` supply a profile file that does not match; the second does that with only `X2W_MESH57_DXC_DIR` set. `derived-untranslated` is a slot 57 pipeline with no captured mesh or pixel program. `derived-root-unset` omits the constant word. `derived-root-table` uses a descriptor table. `derived-slot55-mask` applies a blend patch with a zero write mask. Those leave the clear color. Each returns 77 when mesh shaders or the command signature are unavailable. `mesh57_derive_alloc` checks the allocation reader, the root decision, the slot 55 patch rule, and the forwards line without a device. +`startup_indirect_mesh_derived_{warp,hardware}` forwards one group and reads a white texel at `(2,0)` on a 4 by 2 target. `derived-dxc` does the same with only `X2W_MESH57_DXC_DIR` set, and the process clears `X2W_NATIVE_SHADERS` before the call. `derived-root` is that program plus one guest constant at s8. The mesh multiplies the exported x and y by that word, the word is 1.0, and the same texel is white. `derived-root-zero` sets the word to 0 and stays clear. `derived-root-heap` sets the view-heap flag on that one-constant root, so the draw uses the deferred root, and paints the same texel. `derived-root-sgpr` multiplies by s12 instead of s8 and stays clear. `derived-root-five` is three descriptor tables, one root SRV, and one constant, with the view-heap flag, and stays clear. `derived-slot55` draws through a slot 55 pipeline with no patches and paints the same texel. `derived-slot55-isolate` puts a refused blend word on the base. A slot 55 child with no patch stays clear, and a second child of the same base with a blend patch (tag 2, write mask all) paints. `derived-off` leaves the switch unset. `derived-bad` has no immediate allocation. `derived-depth` enables the depth test in the register block. `derived-reviewed` and `derived-dxc-reviewed` supply a profile file that does not match; the second does that with only `X2W_MESH57_DXC_DIR` set. `derived-untranslated` is a slot 57 pipeline with no captured mesh or pixel program. `derived-root-unset` omits the constant word. `derived-root-table` uses a descriptor table. `derived-slot55-mask` applies a blend patch with a zero write mask. Those leave the clear color. Each returns 77 when mesh shaders or the command signature are unavailable. `mesh57_derive_alloc` checks the allocation reader, the wave32 ALU, the missing thread-count and triangle proofs, the rasterizer decision, the root decision, the slot 55 patch rule, and the forwards line without a device. On the Windows test PC at `f358a2ed`, a 420 second run with `X2W_TRANSLATED_INDIRECT_DRAW=1`, `X2W_MESH57_DERIVE_STATE=1`, and `X2W_MESH57_DXC_DIR` set forwarded nothing. The derive census was `slot 57 pixel stage was not captured` 47823, `derived mesh keeps a non-empty guest root refused` 152144, and `pipeline is a derived slot 55` 180066. The non-empty sample had both stages (mesh 9536 bytes, pixel 4352 bytes). The slot 55 sample was a 332-byte descriptor whose base was slot 57 and whose stage lengths were unread. That root refusal is replaced by the three root reasons above, and a slot 55 call now uses its slot 57 base when the patches are blend records. A 4352-byte pixel is still not a constant export, and a program that is not the one immediate allocation is still refused. On the Windows test PC at `54331137`, the same switches, a 420 second run, forwarded nothing (`x2w-render mesh57-derive forwards: 0`). The census was `derived mesh guest root is heap indexed` 353719, `slot 57 pixel stage was not captured` 130628, and `slot 55 patches are not applied` 514994. The heap-indexed sample was path 57, descriptor 768, mesh 9536, pixel 4352, state A 504, state B 80, root 5, one constant dword, four other parameters, heap 1024. The pixel sample was path 57, mesh 1408, pixel length 0, state A 464, root 5, two constant dwords, four other parameters, heap 3072. The slot 55 sample was one 332-byte record on a slot 57 base with that same five-parameter root and heap 3072. -The capture copies a pixel stage only when its length is non-zero and the bytes are readable. A zero pointer and a zero length is an empty span: the copy is skipped and the mesh bytes stay. The 1408-byte mesh in that sample was kept, so the pixel words in the creation descriptor were zero. An unreadable non-zero span fails the snapshot and drops both stages; this sample is not that case, and nothing writes the pixel stage after creation. A slot 55 record is state, not a shader. This path does not invent a pixel shader. A zero pixel length is now `slot 57 pixel stage is absent from the descriptor`. +On the Windows test PC at `35b0d542`, the same switches, a 420 second run, forwarded nothing (`x2w-render mesh57-derive forwards: 0`). Indirect `DispatchMesh` was refused 864129 times and forwarded 0. The census was `derived mesh guest root is heap indexed` 305958 (mesh 9536, pixel 4352, `params=t,t,t,srv,c1`, heap 1024), `slot 57 pixel stage is absent from the descriptor` 111185 (mesh 1408, pixel length 0, `params=t,t,t,srv,c2`, heap 3072), `slot 55 patch tag 1 is not applied` 442686 (`patches=1:332`), and `slot 55 patch tag 0 is not applied` 4300 (`patches=0:332`). The five-parameter heap-indexed root and the slot 55 tags other than 2 stayed refused. Nothing was forwarded. + +`note_pipeline` uses `mesh57_stage_copy` and `mesh57_fixed_stages_kept` for this decision, then copies the bytes. The capture copies a pixel stage only when its length is non-zero and the bytes are readable. A zero pointer and a zero length is an empty span: the copy is skipped and the mesh bytes stay. The 1408-byte mesh in that sample was kept, so the pixel words in the creation descriptor were zero. An unreadable non-zero span fails the snapshot and drops both stages; this sample is not that case, and nothing writes the pixel stage after creation. A slot 55 record is state, not a shader. This path does not invent a pixel shader. A zero pixel length is now `slot 57 pixel stage is absent from the descriptor`. Heap 1024 is the view-heap flag (`0x400`). Heap 3072 is that flag plus the sampler-heap flag (`0xC00`). No reviewed map in this repository assigns user SGPRs for a five-parameter heap-indexed root on the mesh path. The maps that do exist are different ABIs. Raw graphics, and the reflected graphics path, start user SGPRs at s8: a descriptor table is one SGPR, a 32-bit constant block is one SGPR per dword, and a root CBV, SRV, or UAV is two SGPRs, with the heaps following when their flags are set. That layout is for a graphics stage. Direct compute without a reflected stage starts at s4 with the same parameter packing, and both heap flags occupy the next two SGPRs only when they exactly fill the user SGPR count. The 1024 sample has only the view-heap flag, and s4 is the compute ABI. A reviewed `.mesh57-state` profile stores the SGPR, the root parameter, and the count for that one program. These pipelines have no such file. The missing map is the physical user SGPR of each of the five parameters, and the user SGPR of the resource heap (and of the sampler heap when `0x800` is set). The stored root parameter keeps the type, and for a constant block the dword count; a descriptor table's ranges are not kept. This path does not guess the SGPRs. The sample line records the types so the map can be raised with the measured parameter kinds. diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index 700bf4cc49..4e74811ee9 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -1735,7 +1735,7 @@ ctest --preset dev --no-tests=error -R '^startup_hook_(window|overlap)$' -V | `X2W_SHADER_CACHE=` | translation cache: the runtime writes source requests `req_.{a,b,root}`, when needed RTV variants `req_.rtv`, and for device slot 67 compute pipelines `req_.{desc,sa,sb,data,root,c67}` (see [Compute pipeline requests](#compute-pipeline-requests)). A console pipeline that an `ExecuteIndirect` draw (list slot 61) refuses writes the same request as a direct draw, once per pipeline, and draws nothing (`startup_indirect_requests_warp`). Only direct draws poll for its manifest, so such a pipeline stays in the `missing` count until a direct draw uses it; the `x2w-render totals` line counts `pipelines first looked up by ExecuteIndirect N`. This is a per-process lookup count. Check for the ready marker `req_.a` to confirm a complete request is available. Run `tools/startup/gfx2hlsl.py --pending ` while the process is running, or start the run with `run.ps1 -Translate` (see [Translating shaders during a run](#translating-shaders-during-a-run)). Active draws poll for an absent manifest at most once per second per pipeline and use the published translation on a subsequent draw. The translator compiles `.vs.cso` and `.ps.cso` with `fxc.exe`: `X2W_FXC`, else the Windows SDK 10.0.26100.0 copy, else the newest `Windows Kits\10\bin\\x64`, else `PATH`. When none exists it writes `.fail` naming `X2W_FXC` without publishing a new manifest. `X2W_FXC=` (empty) publishes the manifest alone. Rerun `--pending` with compilation enabled to fill in missing bytecode for an existing manifest. At its first native slot-57 profile lookup the runtime lists the directory's top-level file names once and logs `x2w-draw cache index: names in ms` (`src/startup_stubs/cache_index.h`). A `.mesh57-state` profile is opened only when that listing has its name, so a profile written while the process runs is read by the next process. Manifests and every other cache file are still looked up on disk. | | `X2W_NATIVE_SHADERS=` (`run.ps1 -NativeShaders `) | experimental, in render mode: translates device slot 67 compute requests in the stand-in with the C++ compiler; `` holds `dxcompiler.dll` and `dxil.dll`. See [Translating compute programs in the stand-in](#translating-compute-programs-in-the-stand-in) | | `X2W_MESH57_DXC_DIR=` | experimental, with `X2W_MESH57_DERIVE_STATE=1`: the directory of `dxcompiler.dll` and `dxil.dll` for that one slot 57 derivation. Other graphics and compute programs stay on the non-native path. Unset, the derivation may still use `X2W_NATIVE_SHADERS` when that directory is set. When neither directory is set, the call stays refused (`derived mesh needs the native shader compiler`). See [Opt-in immediate allocation](experiments/native-fixed-mesh57.md#opt-in-immediate-allocation) | -| `X2W_MESH57_DERIVE_STATE=1` | experimental, with `X2W_SHADER_CACHE` and `X2W_MESH57_DXC_DIR` (or `X2W_NATIVE_SHADERS`): addresses `graphics/mesh_profile_missing` for one slot 57 shape. A direct `DispatchMesh` `ExecuteIndirect` may build one desktop mesh pipeline from an immediate `GS_ALLOC_REQ` and the bound color target when captured stages exist and no `.mesh57-state` file was opened. One guest constant block of 1..8 dwords is copied into desktop b0, including when that root is heap indexed. A slot 55 pipeline whose base is that slot 57 mesh reuses it when every patch is a blend record. A patch whose tag is not 2 stays refused and the reason names that tag. The sample line lists the first root-parameter types and the first patch tags. A zero pixel length in the descriptor stays refused (`slot 57 pixel stage is absent from the descriptor`). `graphics/no_translation`, slot 86, depth, stencil, any other heap-indexed root, a descriptor root, and any other allocation shape stay refused. While the switch is on, every `DispatchMesh` `ExecuteIndirect` is counted: the first use of a reason logs `x2w-render mesh57-derive sample`, and the 300-frame heartbeat logs `x2w-render mesh57-derive:` plus `x2w-render mesh57-derive forwards:`. The rasterizer is not taken from the register block. See [Opt-in immediate allocation](experiments/native-fixed-mesh57.md#opt-in-immediate-allocation) | +| `X2W_MESH57_DERIVE_STATE=1` | experimental, with `X2W_SHADER_CACHE` and `X2W_MESH57_DXC_DIR` (or `X2W_NATIVE_SHADERS`): addresses `graphics/mesh_profile_missing` for one slot 57 shape. A direct `DispatchMesh` `ExecuteIndirect` may build one desktop mesh pipeline from an immediate `GS_ALLOC_REQ` and the bound color target when captured stages exist and no `.mesh57-state` file was opened. One guest constant block of 1..8 dwords is copied into desktop b0, including when that root is heap indexed. A slot 55 pipeline whose base is that slot 57 mesh reuses it when every patch is a blend record. A patch whose tag is not 2 stays refused and the reason names that tag; that reason is stored on the slot 55 pipeline, not on its slot 57 base. The program is forwarded only when it proves 64 threads, triangle indices, and wave64, and when a one-constant root is the word the mesh reads at user SGPR s8. The sample line lists the first root-parameter types, the first patch tags, and whether a rasterizer was captured. A zero pixel length in the descriptor stays refused (`slot 57 pixel stage is absent from the descriptor`). `graphics/no_translation`, slot 86, depth, stencil, any other heap-indexed root, a descriptor root, and any other allocation shape stay refused. While the switch is on, every `DispatchMesh` `ExecuteIndirect` is counted: the first use of a reason logs `x2w-render mesh57-derive sample`, and the 300-frame heartbeat logs `x2w-render mesh57-derive:` plus `x2w-render mesh57-derive forwards:`. The rasterizer is not taken from the register block. See [Opt-in immediate allocation](experiments/native-fixed-mesh57.md#opt-in-immediate-allocation) | | `X2W_D3D12_LINEAR_BUFFERS=1` or `=copy` | opt-in backing for linear buffers placed at a title address (device slot 133, initial state `COMMON`): shared where the adapter, extent and memory allow it (private allocations larger than 256 MiB are skipped only with `X2W_D3D12_CAP_EXISTING_HEAP=1`), otherwise copied from title memory at each submission, otherwise the default backing is kept and the refusal recorded; `copy` never shares. Unset or `0`, slot 133 keeps its default backing. See [Linear buffer backing (device slot 133, opt-in)](#linear-buffer-backing-device-slot-133-opt-in) | | `X2W_D3D12_CAP_EXISTING_HEAP=1` | opt-in 256 MiB (`unplaced_existing_heap_allowed`) allocation-size cap on `OpenExistingHeapFromAddress` in device slot 133 (`startup_slot133_heap_cap_*`). Unset (default), private allocations larger than 256 MiB keep the formerly aliased path: a capped copied placement is refused by `CopyBufferRegion` (list slot 15) as `title_backed_source`, losing a late guest write made after recording and before submit. Set, allocations larger than 256 MiB skip `OpenExistingHeapFromAddress` so multi-GiB startup blocks are not pinned in `WorkingSetSize` and `NonLocal` GPU memory | | `X2W_D3D12_ROOT_SRV_AT_DRAW=1` | opt-in, render mode: a graphics root SRV (slot 44) without an upload mapping is not copied into the upload ring, since no draw reads that desktop binding (default: a 64 KiB copy at every slot 44 call). Translated draws copy the SRV themselves and are unaffected (`startup_root_srv_draw_*`). See [the experiment note](experiments/startup-root-srv-at-draw.md) | diff --git a/src/startup_stubs/d3d12_capture.inl b/src/startup_stubs/d3d12_capture.inl index d281260425..e7b29f1e97 100644 --- a/src/startup_stubs/d3d12_capture.inl +++ b/src/startup_stubs/d3d12_capture.inl @@ -398,20 +398,31 @@ void note_pipeline(Wrapper* w, int path, const void* base, const void* desc, std if (path == 57 && have >= 15 * sizeof(u64)) { u64 words[15]; std::memcpy(words, info.desc.data(), sizeof(words)); - const auto snapshot = [&](int field, FixedMeshBytes& stage) { + const auto stage_decision = [&](int field) { const auto bytes = words[field + 1]; - if (!bytes) return !words[field]; - const auto* data = reinterpret_cast(words[field]); - if (bytes > (1u << 20) || !x2w_local::readable(data, bytes)) return false; - std::vector copy(static_cast(bytes)); - if (!copy_title_bytes(copy.data(), data, copy.size())) return false; - stage = intern_fixed_mesh_bytes(std::move(copy)); - return true; + const auto pointer = words[field]; + const bool readable = bytes && bytes <= (1u << 20) && + x2w_local::readable(reinterpret_cast(pointer), static_cast(bytes)); + return x2w_startup::mesh57_stage_copy(pointer, bytes, readable); }; - if (!words[9] && !words[10] && words[14] && - (!snapshot(5, info.fixed_ps) || !snapshot(13, info.fixed_ms))) { - info.fixed_ps.reset(); - info.fixed_ms.reset(); + const auto pixel = stage_decision(5); + const auto mesh = stage_decision(13); + if (x2w_startup::mesh57_fixed_stages_kept(!words[9] && !words[10], words[14] != 0, pixel, mesh)) { + const auto copy_stage = [&](int field, FixedMeshBytes& stage) { + const auto bytes = words[field + 1]; + if (!bytes) + return true; + const auto* data = reinterpret_cast(words[field]); + std::vector copy(static_cast(bytes)); + if (!copy_title_bytes(copy.data(), data, copy.size())) + return false; + stage = intern_fixed_mesh_bytes(std::move(copy)); + return true; + }; + if (!copy_stage(5, info.fixed_ps) || !copy_stage(13, info.fixed_ms)) { + info.fixed_ps.reset(); + info.fixed_ms.reset(); + } } } if (path == 57 && have >= 0x28) { diff --git a/src/startup_stubs/mesh57_alloc.h b/src/startup_stubs/mesh57_alloc.h index 4d3dced9ee..7fa4f8b0e8 100644 --- a/src/startup_stubs/mesh57_alloc.h +++ b/src/startup_stubs/mesh57_alloc.h @@ -27,13 +27,21 @@ struct MeshDerivedLayout { unsigned wave_size = 0; }; -// One wave64 group. group_stride stays 0: the accepted program does not read the group id, and the -// lowerer skips that multiply when the stride is 0. Returns empty when the program is not the -// single immediate allocation above, or when either count is outside 1..64. -inline std::optional derive_immediate_mesh_layout(std::string_view code) noexcept +// What this path binds, and why a program that does not match is refused. +// group_stride stays 0: a program that reads the group id is not this layout. +// Returns an empty layout and a stable reason when the program is not the single immediate +// allocation, is wave32, does not prove a 64-thread lane id, or does not export triangle indices. +struct MeshLayoutRead { + std::optional layout; + const char* reason = nullptr; +}; + +inline MeshLayoutRead mesh57_read_layout(std::string_view code) noexcept { + MeshLayoutRead out; + out.reason = "derived mesh needs one immediate allocation"; if (code.empty() || code.size() % 4 != 0) - return std::nullopt; + return out; try { bool previous_immediate = false; std::uint32_t previous_word = 0; @@ -42,22 +50,37 @@ inline std::optional derive_immediate_mesh_layout(std::string unsigned primitives = 0; bool wave32 = false; bool exchange = false; + bool lane_id = false; + bool triangle_export = false; for (unsigned pc = 0; pc < code.size();) { std::uint32_t raw = 0; std::memcpy(&raw, code.data() + pc, sizeof(raw)); const auto inst = x2w::gfx1013::instruction(code, pc); if (inst.size == 0 || pc + inst.size > code.size()) - return std::nullopt; + return out; if (raw == 0xbf8a0000u) exchange = true; + if (inst.name == "v_mbcnt_lo_u32_b32") + lane_id = true; + if (inst.form == x2w::gfx1013::Form::exp && ((raw >> 4) & 63u) == 20u) + triangle_export = true; + if (inst.form == x2w::gfx1013::Form::sop2) { + const unsigned dst = (raw >> 16) & 127u; + // A 32-bit exec update is wave32 even when it is not s_mov_b32 exec_lo. + if (dst == 126u && (inst.name == "s_and_b32" || inst.name == "s_or_b32" || + inst.name == "s_xor_b32" || inst.name == "s_andn2_b32" || + inst.name == "s_orn2_b32" || inst.name == "s_nand_b32" || + inst.name == "s_nor_b32" || inst.name == "s_xnor_b32")) + wave32 = true; + } if (raw == 0xbf900009u) { if (!previous_immediate) - return std::nullopt; + return out; const unsigned next_vertices = previous_word & 4095u; const unsigned next_primitives = (previous_word >> 12) & 4095u; if ((previous_word >> 24) != 0 || next_vertices == 0 || next_primitives == 0 || next_vertices > 64u || next_primitives > 64u) - return std::nullopt; + return out; vertices = next_vertices; primitives = next_primitives; ++allocations; @@ -83,8 +106,24 @@ inline std::optional derive_immediate_mesh_layout(std::string } pc += inst.size; } - if (allocations != 1 || wave32 || exchange) - return std::nullopt; + if (allocations != 1 || exchange) + return out; + if (wave32) { + out.reason = "derived mesh is wave32"; + return out; + } + // The bound group is one wave of 64 threads. v_mbcnt_lo of the hardware lane id is the + // proof this program uses that id. An allocation alone does not say the thread count. + if (!lane_id) { + out.reason = "derived mesh thread count is not proven"; + return out; + } + // The lowerer accepts topology 2 only, and only the primitive-index export (target 20) + // is that triangle list. Any other topology is refused rather than drawn as triangles. + if (!triangle_export) { + out.reason = "derived mesh topology is not triangles"; + return out; + } MeshDerivedLayout layout; layout.threads = 64; layout.vertices = vertices; @@ -92,12 +131,39 @@ inline std::optional derive_immediate_mesh_layout(std::string layout.topology = 2; layout.group_stride = 0; layout.wave_size = 64; - return layout; + out.layout = layout; + out.reason = nullptr; + return out; } catch (...) { - return std::nullopt; + return out; } } +inline std::optional derive_immediate_mesh_layout(std::string_view code) noexcept +{ + return mesh57_read_layout(code).layout; +} + +// The rasterizer this path binds: solid fill, cull none, depth clip, clockwise front faces. +// present is true only when a reviewed capture already stored a rasterizer. The slot 57 +// PA_SU_SC_MODE_CNTL word has no established offset, so this function does not read one. +struct Mesh57RasterizerView { + bool present = false; + bool cull_none = false; + bool solid = false; + bool depth_clip = false; + bool front_ccw = false; +}; + +inline const char* mesh57_rasterizer_reason(const Mesh57RasterizerView& view) noexcept +{ + if (!view.present) + return "derived mesh rasterizer is not in the captured state"; + if (!view.cull_none || !view.solid || !view.depth_clip || view.front_ccw) + return "derived mesh rasterizer does not match the bound state"; + return nullptr; +} + // Why a slot 57 creation record is not the fixed mesh+pixel pair this path can read. // nullptr means both stages were captured from a 768-byte descriptor with no vertex span. // The clauses match the capture in note_pipeline: a vertex span, a zero mesh length, or a @@ -193,6 +259,9 @@ struct Mesh57DeriveSample { int patch_n = 0; std::uint32_t patch_tag[patch_slots]{}; std::uint32_t patch_size[patch_slots]{}; + // 0: no rasterizer was captured. 1: the captured rasterizer matches the bound default. + // 2: a rasterizer was captured and does not match. The guest cull word is not read here. + int raster = 0; }; // One guest root parameter, without a D3D12 type. type 0 is 32-bit constants and @@ -456,12 +525,12 @@ inline std::size_t mesh57_derive_sample_line(const char* reason, const Mesh57Der const int n = std::snprintf(out, cap, "x2w-render mesh57-derive sample reason=%s path=%d base=%d desc=%u ms=%u ps=%u state_a=%u state_b=%u " "vs=%u ms_len=%u ps_len=%u key=%016llx list=%d real=%d mesh86=%d root=%u const=%u other=%u heap=%u " - "params=%s patches=%s", + "params=%s patches=%s raster=%d", reason ? reason : "", sample.path, sample.base_path, sample.desc_bytes, sample.mesh_bytes, sample.pixel_bytes, sample.state_a, sample.state_b, sample.vertex_bytes, sample.mesh_length, sample.pixel_length, static_cast(sample.key), sample.list_type, sample.real, sample.mesh86, sample.root_parameters, sample.root_constant_dwords, sample.root_other, sample.root_heap, - params, patches); + params, patches, sample.raster); if (n < 0) { out[0] = 0; return 0; diff --git a/src/startup_stubs/native_mesh57.inl b/src/startup_stubs/native_mesh57.inl index 4e91cd573a..601cc5675b 100644 --- a/src/startup_stubs/native_mesh57.inl +++ b/src/startup_stubs/native_mesh57.inl @@ -600,6 +600,13 @@ x2w_startup::Mesh57DeriveSample mesh57_derive_sample(Wrapper* pipeline, const Pi } } } + const PipelineInfo* raster_source = root_source ? root_source : info; + if (raster_source && raster_source->has_stream_rasterizer) { + sample.raster = x2w_startup::same_pso_rasterizer( + raster_source->stream_rasterizer, x2w_startup::default_pso_rasterizer()) + ? 1 + : 2; + } return sample; } @@ -706,15 +713,22 @@ const char* derive_slot57_mesh(Wrapper* pipeline, Pass& pass, const D3D12_BLEND_ { if (!pipeline || pipeline->own().real) return nullptr; - const auto* info = source ? source : pipeline_info(pipeline); - if (!info) + // `shaders` is the slot 57 program. `stored` is the pipeline this call is deriving. + // A slot 55 failure is remembered on the slot 55 info. A reason the base already + // has is returned and is not copied. This call does not write the base. + const auto* shaders = source ? source : pipeline_info(pipeline); + const auto* stored = pipeline_info(pipeline); + if (!shaders || !stored) return "derived mesh has no captured pipeline"; - if (info->mesh57_derive_reason) - return info->mesh57_derive_reason; + if (stored->mesh57_derive_reason) + return stored->mesh57_derive_reason; + if (shaders != stored && shaders->mesh57_derive_reason) + return shaders->mesh57_derive_reason; auto remember = [&](const char* why) { - info->mesh57_derive_reason = why; + stored->mesh57_derive_reason = why; return why; }; + const auto* info = shaders; wchar_t sdk[MAX_PATH]; if (!mesh57_derive_compiler_dir(sdk, MAX_PATH)) return "derived mesh needs the native shader compiler"; @@ -736,10 +750,11 @@ const char* derive_slot57_mesh(Wrapper* pipeline, Pass& pass, const D3D12_BLEND_ } if (const char* pair_why = x2w_startup::mesh57_fixed_pair_reason(pair)) return remember(pair_why); - if (!info->mesh57_reviewed_present && mesh57_reviewed_file_present(info)) - info->mesh57_reviewed_present = true; - if (info->mesh57_reviewed_present) + if (shaders->mesh57_reviewed_present || mesh57_reviewed_file_present(shaders)) { + if (shaders == stored) + stored->mesh57_reviewed_present = true; return remember("a reviewed mesh profile is present"); + } u64 fields[0x300 / sizeof(u64)]{}; std::memcpy(fields, info->desc.data(), sizeof(fields)); auto* root = as_wrapper(reinterpret_cast(fields[0])); @@ -804,20 +819,25 @@ const char* derive_slot57_mesh(Wrapper* pipeline, Pass& pass, const D3D12_BLEND_ (pass.root_heap_flags && !root_contract.bind_constants)) return "derived mesh root is not the bound desktop root"; const std::string ms(info->fixed_ms->begin(), info->fixed_ms->end()); - const auto layout = x2w_startup::derive_immediate_mesh_layout(ms); - if (!layout) - return remember("derived mesh needs one immediate allocation"); + const auto read = x2w_startup::mesh57_read_layout(ms); + if (!read.layout) + return remember(read.reason ? read.reason : "derived mesh needs one immediate allocation"); + const auto layout = *read.layout; + if (layout.threads != 64 || layout.wave_size != 64 || layout.topology != 2 || layout.group_stride != 0) + return remember("derived mesh layout is not the bound group"); try { x2w::MeshStageLayout mesh_layout; - mesh_layout.threads = layout->threads; - mesh_layout.max_vertices = layout->vertices; - mesh_layout.max_primitives = layout->primitives; - mesh_layout.topology = layout->topology; - mesh_layout.group_stride = layout->group_stride; - mesh_layout.wave32 = false; + mesh_layout.threads = layout.threads; + mesh_layout.max_vertices = layout.vertices; + mesh_layout.max_primitives = layout.primitives; + mesh_layout.topology = layout.topology; + mesh_layout.group_stride = layout.group_stride; + mesh_layout.wave32 = layout.wave_size == 32; D3D12_ROOT_PARAMETER1 constant_parameter{}; D3D12_ROOT_SIGNATURE_DESC1 constant_root{}; if (root_contract.bind_constants) { + if (root_contract.sgpr != 8) + return remember("derived mesh constant is not at user SGPR s8"); mesh_layout.root_inputs.push_back({root_contract.sgpr, 0u, root_views[0].constants}); constant_parameter.ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS; constant_parameter.ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL; @@ -832,7 +852,9 @@ const char* derive_slot57_mesh(Wrapper* pipeline, Pass& pass, const D3D12_BLEND_ (native.constants.size() == 1 && native.constants[0].root_parameter == 0 && native.constants[0].first_sgpr == root_contract.sgpr && native.constants[0].count == root_views[0].constants); - if (!constants_match || (root_contract.bind_constants ? false : !native.constants.empty()) || + if (root_contract.bind_constants && !constants_match) + return remember("derived mesh constant is not at user SGPR s8"); + if ((root_contract.bind_constants ? false : !native.constants.empty()) || !native.bindings.empty() || !native.samplers.empty() || native.sampler_heap || !native.mesh_heap_reads.empty()) return remember("derived mesh program needs root or heap bindings"); @@ -850,7 +872,14 @@ const char* derive_slot57_mesh(Wrapper* pipeline, Pass& pass, const D3D12_BLEND_ stream.ps.value.BytecodeLength = ps_output.dxil.size(); stream.blend.value = blend; stream.sample_mask.value = UINT_MAX; - stream.rasterizer.value = x2w_startup::default_pso_rasterizer(); + const D3D12_RASTERIZER_DESC bound_raster = x2w_startup::default_pso_rasterizer(); + // A captured stream rasterizer must be the state this path binds. Slot 57 does not + // carry a reviewed PA_SU_SC_MODE_CNTL location, so an absent word is not read and is + // not guessed. The sample records raster=0 in that case. + if (shaders->has_stream_rasterizer && + !x2w_startup::same_pso_rasterizer(shaders->stream_rasterizer, bound_raster)) + return remember("derived mesh rasterizer does not match the bound state"); + stream.rasterizer.value = bound_raster; stream.depth_stencil.value = depth.desc; D3D12_RT_FORMAT_ARRAY targets{}; targets.NumRenderTargets = 1; @@ -921,6 +950,9 @@ const char* derive_slot57_mesh(Wrapper* pipeline, Pass& pass, const D3D12_BLEND_ log("x2w-render derived slot57 mesh refused: %s", e.what()); if (pipeline->own().real) return nullptr; + const std::string text = e.what(); + if (root_contract.bind_constants && text.find("unproven mesh entry register") != std::string::npos) + return remember("derived mesh constant is not at user SGPR s8"); return remember("derived mesh translation was refused"); } } diff --git a/tests/mesh57_derive_alloc_check.cpp b/tests/mesh57_derive_alloc_check.cpp index 4683fc634a..23ad53a406 100644 --- a/tests/mesh57_derive_alloc_check.cpp +++ b/tests/mesh57_derive_alloc_check.cpp @@ -38,13 +38,48 @@ int main() 0xbefc03ffu, 0x1003u, 0xbf900009u, 0xd7650000u, 0x100c1u, 0x36020081u, 0x2c040081u, 0x7e020d01u, 0x7e040d02u, 0x7e0602f0u, 0x7e0802f2u, 0xf80008cfu, 0x04030201u, 0x7e0a02ffu, 0x200400u, 0xf8000941u, 0x80808005u, 0xbf810000u}; - if (!accepted(words_of(triangle, sizeof(triangle) / sizeof(triangle[0])), 3, 1)) + const auto triangle_bytes = words_of(triangle, sizeof(triangle) / sizeof(triangle[0])); + if (!accepted(triangle_bytes, 3, 1)) return fail("triangle"); + const auto triangle_read = x2w_startup::mesh57_read_layout(triangle_bytes); + if (!triangle_read.layout || triangle_read.reason) + return fail("triangle reason"); const std::uint32_t only_alloc[] = {0xbefc03ffu, 0x1003u, 0xbf900009u, 0xbf810000u}; - if (!accepted(words_of(only_alloc, 4), 3, 1)) + const auto alone = x2w_startup::mesh57_read_layout(words_of(only_alloc, 4)); + if (alone.layout || !alone.reason || + std::strcmp(alone.reason, "derived mesh thread count is not proven") != 0) return fail("alloc alone"); + const std::uint32_t no_export[] = {0xbefc03ffu, 0x1003u, 0xbf900009u, 0xd7650000u, 0x100c1u, 0xbf810000u}; + const auto points = x2w_startup::mesh57_read_layout(words_of(no_export, 6)); + if (points.layout || !points.reason || + std::strcmp(points.reason, "derived mesh topology is not triangles") != 0) + return fail("no triangle export"); + + const std::uint32_t wave32_alu[] = {0xbefc03ffu, 0x1003u, 0xbf900009u, 0xd7650000u, 0x100c1u, + 0x877e7e7eu, 0xf8000941u, 0x80808005u, 0xbf810000u}; + const auto alu = x2w_startup::mesh57_read_layout(words_of(wave32_alu, 9)); + if (alu.layout || !alu.reason || std::strcmp(alu.reason, "derived mesh is wave32") != 0) + return fail("wave32 exec alu"); + + x2w_startup::Mesh57RasterizerView absent; + x2w_startup::Mesh57RasterizerView matched; + matched.present = true; + matched.cull_none = true; + matched.solid = true; + matched.depth_clip = true; + x2w_startup::Mesh57RasterizerView culled = matched; + culled.cull_none = false; + if (!x2w_startup::mesh57_rasterizer_reason(absent) || + std::strcmp(x2w_startup::mesh57_rasterizer_reason(absent), + "derived mesh rasterizer is not in the captured state") != 0 || + x2w_startup::mesh57_rasterizer_reason(matched) || + !x2w_startup::mesh57_rasterizer_reason(culled) || + std::strcmp(x2w_startup::mesh57_rasterizer_reason(culled), + "derived mesh rasterizer does not match the bound state") != 0) + return fail("rasterizer"); + const std::uint32_t endpgm[] = {0xbf810000u}; if (x2w_startup::derive_immediate_mesh_layout(words_of(endpgm, 1))) return fail("no allocation"); @@ -178,6 +213,7 @@ int main() !std::strstr(sample, "desc=512") || !std::strstr(sample, "root=0") || !std::strstr(sample, "const=0") || !std::strstr(sample, "other=0") || !std::strstr(sample, "heap=0") || !std::strstr(sample, "params=-") || !std::strstr(sample, "patches=-") || + !std::strstr(sample, "raster=0") || std::strncmp(sample, "x2w-render mesh57-derive sample ", 32) != 0) return fail("sample"); x2w_startup::Mesh57DeriveSample typed; diff --git a/tests/startup_indirect_draw_indexed.cpp b/tests/startup_indirect_draw_indexed.cpp index 60cd4a8578..c98e6ffa25 100644 --- a/tests/startup_indirect_draw_indexed.cpp +++ b/tests/startup_indirect_draw_indexed.cpp @@ -1114,9 +1114,13 @@ bool run(ID3D12Device* device, ID3D12Device* guest, ID3D12RootSignature* writer_ ComPtr fixed_source_heap; slot(wrapped, 25)(wrapped, graphics); slot(wrapped, 34)(wrapped, refusal == Refusal::wrong_root ? translated->wrong_root.Get() : graphics_root); - if (label && std::strcmp(label, "mesh-derived-root") == 0) { + if (label && (std::strcmp(label, "mesh-derived-root") == 0 || + std::strcmp(label, "mesh-derived-root-heap") == 0 || + std::strcmp(label, "mesh-derived-root-sgpr") == 0 || + std::strcmp(label, "mesh-derived-root-zero") == 0)) { using Constants = void (WINAPI*)(IUnknown*, UINT, UINT, const UINT*, UINT); - const UINT value = 0; + // 1.0 keeps the triangle. 0 collapses it, so a constant that never reaches b0 stays clear. + const UINT value = std::strcmp(label, "mesh-derived-root-zero") == 0 ? 0u : 0x3f800000u; slot(wrapped, 40)(wrapped, 0, 1, &value, 0); } if (leased) { @@ -2466,15 +2470,39 @@ static int derived_mesh_fixture(ID3D12Device* device, ID3D12Device* guest, ID3D1 ComPtr blob; D3D12_ROOT_SIGNATURE_DESC empty{}; const bool constant_root = std::strcmp(mode, "mesh-derived-root") == 0 || - std::strcmp(mode, "mesh-derived-root-unset") == 0; + std::strcmp(mode, "mesh-derived-root-unset") == 0 || + std::strcmp(mode, "mesh-derived-root-zero") == 0 || + std::strcmp(mode, "mesh-derived-root-sgpr") == 0 || + std::strcmp(mode, "mesh-derived-root-heap") == 0; + const bool five_root = std::strcmp(mode, "mesh-derived-root-five") == 0; + const bool heap_root = std::strcmp(mode, "mesh-derived-root-heap") == 0; + const bool sgpr_root = std::strcmp(mode, "mesh-derived-root-sgpr") == 0; const bool table_root = std::strcmp(mode, "mesh-derived-root-table") == 0; D3D12_ROOT_PARAMETER parameter{}; D3D12_DESCRIPTOR_RANGE range{}; - if (constant_root) { + D3D12_ROOT_PARAMETER five_parameters[5]{}; + D3D12_DESCRIPTOR_RANGE five_ranges[3]{}; + if (five_root) { + for (UINT i = 0; i < 3; ++i) { + five_ranges[i].RangeType = D3D12_DESCRIPTOR_RANGE_TYPE_SRV; + five_ranges[i].NumDescriptors = 1; + five_parameters[i].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; + five_parameters[i].DescriptorTable.NumDescriptorRanges = 1; + five_parameters[i].DescriptorTable.pDescriptorRanges = &five_ranges[i]; + } + five_parameters[3].ParameterType = D3D12_ROOT_PARAMETER_TYPE_SRV; + five_parameters[4].ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS; + five_parameters[4].Constants.Num32BitValues = 1; + empty.NumParameters = 5; + empty.pParameters = five_parameters; + empty.Flags = D3D12_ROOT_SIGNATURE_FLAG_CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED; + } else if (constant_root) { parameter.ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS; parameter.Constants.Num32BitValues = 1; empty.NumParameters = 1; empty.pParameters = ¶meter; + if (heap_root) + empty.Flags = D3D12_ROOT_SIGNATURE_FLAG_CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED; } else if (table_root) { range.RangeType = D3D12_DESCRIPTOR_RANGE_TYPE_SRV; range.NumDescriptors = 1; @@ -2488,8 +2516,15 @@ static int derived_mesh_fixture(ID3D12Device* device, ID3D12Device* guest, ID3D1 std::vector ms{0xbefc03ffu, 0x1003u, 0xbf900009u, 0xd7650000u, 0x100c1u, 0x36020081u, 0x2c040081u, 0x7e020d01u, 0x7e040d02u, 0x7e0602f0u, 0x7e0802f2u, 0xf80008cfu, 0x04030201u, 0x7e0a02ffu, 0x200400u, 0xf8000941u, 0x80808005u, 0xbf810000u}; - if (constant_root) - ms.insert(ms.begin(), 0xbe890308u); // s_mov_b32 s9, s8. s8 is the one guest constant at user SGPR 8. + if (constant_root) { + // v_mul_f32 of the bound user SGPR into the exported x and y. s8 is that block. + // s12 is a different SGPR and must stay refused. 1.0 keeps coverage; 0 does not. + const UINT scalar = sgpr_root ? 12u : 8u; + const UINT mul_x = (8u << 25) | (1u << 17) | (1u << 9) | scalar; + const UINT mul_y = (8u << 25) | (2u << 17) | (2u << 9) | scalar; + ms.insert(ms.begin() + 9, mul_x); + ms.insert(ms.begin() + 10, mul_y); + } if (std::strcmp(mode, "mesh-derived-bad") == 0) ms.assign(1, 0xbf810000u); const std::vector ps{0x7e0002f2u, 0xf800180fu, 0u, 0xbf810000u}; @@ -2504,6 +2539,10 @@ static int derived_mesh_fixture(ID3D12Device* device, ID3D12Device* guest, ID3D1 const std::uint32_t depth_on = 2; std::memcpy(state_a.data() + 0x10c, &depth_on, sizeof(depth_on)); } + if (std::strcmp(mode, "mesh-derived-slot55-isolate") == 0) { + const std::uint32_t refused_blend = 0x72911433u; + std::memcpy(state_a.data() + 0x124, &refused_blend, sizeof(refused_blend)); + } std::vector state_b(4, 0); UINT64 fields[0x300 / sizeof(UINT64)]{}; fields[2] = state_a.size(); @@ -2598,8 +2637,35 @@ static int derived_mesh_fixture(ID3D12Device* device, ID3D12Device* guest, ID3D1 profile.targets.NumRenderTargets = 1; profile.targets.RTFormats[0] = format; profile.blend.RenderTarget[0].RenderTargetWriteMask = D3D12_COLOR_WRITE_ENABLE_ALL; + if (std::strcmp(mode, "mesh-derived-slot55-isolate") == 0) { + using Derive = HRESULT (WINAPI*)(IUnknown*, void*, UINT, const void*, REFIID, void**); + ComPtr refused_child; + check(slot(guest, 55)(guest, pso.Get(), 0, nullptr, __uuidof(ID3D12PipelineState), + reinterpret_cast(refused_child.GetAddressOf())), + "create refused slot 55"); + D3D12_BLEND_DESC replacement{}; + replacement.RenderTarget[0].RenderTargetWriteMask = D3D12_COLOR_WRITE_ENABLE_ALL; + std::vector patch(sizeof(std::uint32_t) + sizeof(replacement)); + const std::uint32_t tag = 2; + std::memcpy(patch.data(), &tag, sizeof(tag)); + std::memcpy(patch.data() + sizeof(tag), &replacement, sizeof(replacement)); + ComPtr replaced_child; + check(slot(guest, 55)(guest, pso.Get(), 1, patch.data(), __uuidof(ID3D12PipelineState), + reinterpret_cast(replaced_child.GetAddressOf())), + "create replaced slot 55"); + const bool first_clear = run(device, guest, writer, work.Get(), root.Get(), refused_child.Get(), + signature.Get(), DrawKind::mesh, + false, Refusal::none, mode, nullptr, false, nullptr, false, false, 0, false, false, nullptr, + nullptr, false, 2, &profile); + const bool second_paint = run(device, guest, writer, work.Get(), root.Get(), replaced_child.Get(), + signature.Get(), DrawKind::mesh, + false, Refusal::none, mode, nullptr, false, nullptr, false, false, 0, false, false, nullptr, + nullptr, false, 1, &profile); + return first_clear && second_paint ? 0 : 1; + } const int pixels = std::strcmp(mode, "mesh-derived") == 0 || std::strcmp(mode, "mesh-derived-dxc") == 0 || - std::strcmp(mode, "mesh-derived-root") == 0 || std::strcmp(mode, "mesh-derived-slot55") == 0 ? 1 : 2; + std::strcmp(mode, "mesh-derived-root") == 0 || std::strcmp(mode, "mesh-derived-root-heap") == 0 || + std::strcmp(mode, "mesh-derived-slot55") == 0 ? 1 : 2; const bool painted = run(device, guest, writer, work.Get(), root.Get(), slot55 ? derived.Get() : pso.Get(), signature.Get(), DrawKind::mesh, false, Refusal::none, mode, nullptr, false, nullptr, false, false, 0, false, false, nullptr, @@ -2636,9 +2702,12 @@ int main(int argc, char** argv) try const bool derived_dxc = argc == 3 && std::strcmp(argv[2], "mesh-derived-dxc") == 0; const bool derived_dxc_reviewed = argc == 3 && std::strcmp(argv[2], "mesh-derived-dxc-reviewed") == 0; const bool derived_root = argc == 3 && (std::strcmp(argv[2], "mesh-derived-root") == 0 || - std::strcmp(argv[2], "mesh-derived-root-unset") == 0 || std::strcmp(argv[2], "mesh-derived-root-table") == 0); + std::strcmp(argv[2], "mesh-derived-root-unset") == 0 || std::strcmp(argv[2], "mesh-derived-root-table") == 0 || + std::strcmp(argv[2], "mesh-derived-root-zero") == 0 || std::strcmp(argv[2], "mesh-derived-root-sgpr") == 0 || + std::strcmp(argv[2], "mesh-derived-root-heap") == 0 || std::strcmp(argv[2], "mesh-derived-root-five") == 0); const bool derived_slot55 = argc == 3 && (std::strcmp(argv[2], "mesh-derived-slot55") == 0 || - std::strcmp(argv[2], "mesh-derived-slot55-mask") == 0); + std::strcmp(argv[2], "mesh-derived-slot55-mask") == 0 || + std::strcmp(argv[2], "mesh-derived-slot55-isolate") == 0); const bool derived_mesh = derived_off || derived_bad || derived_depth || derived_reviewed || derived_untranslated || derived_dxc || derived_dxc_reviewed || derived_root || derived_slot55 || (argc == 3 && std::strcmp(argv[2], "mesh-derived") == 0); From 6c93fc6f91803ab781c3b6781793985f224aeff0 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Sun, 29 Nov 2026 13:11:10 +0000 Subject: [PATCH 09/12] runtime: include mesh stage helpers in the device object d3d12_xs_device_obj compiles d3d12_capture.inl without X2W_NATIVE_SHADERS. note_pipeline calls the stage-copy helpers, so mesh57_alloc.h is included before that file for every translation unit of d3d12_xs_device.cpp. Co-authored-by: SimSalabimse --- src/startup_stubs/d3d12_xs_device.cpp | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/startup_stubs/d3d12_xs_device.cpp b/src/startup_stubs/d3d12_xs_device.cpp index a553b23dc6..3a954afbe2 100644 --- a/src/startup_stubs/d3d12_xs_device.cpp +++ b/src/startup_stubs/d3d12_xs_device.cpp @@ -88,11 +88,13 @@ #include "startup_stubs/xmem_section_buffer.h" #include "native_buffer_store_view.h" #include "native_compute_output.h" +// Stage-copy helpers used by d3d12_capture.inl. d3d12_xs_device_obj does not define +// X2W_NATIVE_SHADERS, so this include stays outside that block. +#include "mesh57_alloc.h" #ifdef X2W_NATIVE_SHADERS // d3d12_xs_shim only: the C++ shader compiler (startup_stubs/d3d12_compute_dispatch.inl) #include "gfx1013_compute_native.h" #include "gfx1013_pixel.h" #include "mesh_shader_pipeline.h" -#include "mesh57_alloc.h" #include #include "native_buffer_store_view.h" #include "shader_dxil_compiler.h" From 46be84356b6a47aa5053873d6c4b062133e86d4f Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Sun, 29 Nov 2026 13:22:22 +0000 Subject: [PATCH 10/12] tests: give the five-parameter derived root distinct registers The three SRV tables and the root SRV no longer all claim t0 in space 0, so the root signature can be created. The shape stays five parameters with the heap-indexed flag, and that root stays refused. Co-authored-by: SimSalabimse --- tests/startup_indirect_draw_indexed.cpp | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/tests/startup_indirect_draw_indexed.cpp b/tests/startup_indirect_draw_indexed.cpp index c98e6ffa25..cae7ea37ad 100644 --- a/tests/startup_indirect_draw_indexed.cpp +++ b/tests/startup_indirect_draw_indexed.cpp @@ -2483,15 +2483,24 @@ static int derived_mesh_fixture(ID3D12Device* device, ID3D12Device* guest, ID3D1 D3D12_ROOT_PARAMETER five_parameters[5]{}; D3D12_DESCRIPTOR_RANGE five_ranges[3]{}; if (five_root) { + // Three SRV tables, one root SRV, and one constant. Each SRV is t0 in its own space + // so serialize does not see four claims on t0, space 0. The constant is b0. for (UINT i = 0; i < 3; ++i) { five_ranges[i].RangeType = D3D12_DESCRIPTOR_RANGE_TYPE_SRV; five_ranges[i].NumDescriptors = 1; + five_ranges[i].BaseShaderRegister = 0; + five_ranges[i].RegisterSpace = i; + five_ranges[i].OffsetInDescriptorsFromTableStart = 0; five_parameters[i].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; five_parameters[i].DescriptorTable.NumDescriptorRanges = 1; five_parameters[i].DescriptorTable.pDescriptorRanges = &five_ranges[i]; } five_parameters[3].ParameterType = D3D12_ROOT_PARAMETER_TYPE_SRV; + five_parameters[3].Descriptor.ShaderRegister = 0; + five_parameters[3].Descriptor.RegisterSpace = 3; five_parameters[4].ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS; + five_parameters[4].Constants.ShaderRegister = 0; + five_parameters[4].Constants.RegisterSpace = 0; five_parameters[4].Constants.Num32BitValues = 1; empty.NumParameters = 5; empty.pParameters = five_parameters; From 0f69e4edf78cbdd1ea9ff560db1636ee39af6dd7 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Sun, 29 Nov 2026 16:02:02 +0000 Subject: [PATCH 11/12] runtime: prove wave64 before a derived mesh is forwarded A 32-bit exec write, including saveexec and wrexec, stays wave32. Wave size 64 now requires v_mbcnt_hi or a 64-bit exec write. A slot 55 blend patch retries a base blend or pipeline refusal. An absent rasterizer is not a refusal. Co-authored-by: SimSalabimse --- CMakeLists.txt | 2 +- docs/experiments/native-fixed-mesh57.md | 8 +- docs/startup-runtime.md | 2 +- src/startup_stubs/mesh57_alloc.h | 107 +++++++++-- src/startup_stubs/native_mesh57.inl | 6 +- tests/mesh57_derive_alloc_check.cpp | 234 +++++++++++++++++++----- tests/startup_indirect_draw_indexed.cpp | 35 +++- 7 files changed, 322 insertions(+), 72 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 86bb02658f..aa9cc2f5dc 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1948,7 +1948,7 @@ if(TARGET compile_dxil AND EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${ add_test(NAME native_fixed_mesh57_${backend} COMMAND startup_indirect_draw_indexed ${backend} mesh) set_tests_properties(native_fixed_mesh57_${backend} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77 ENVIRONMENT "X2W_TEST_NATIVE_MESH57=1;X2W_NATIVE_SHADERS=${DXC_BIN_DIR}") - foreach(mode derived derived-off derived-bad derived-depth derived-reviewed derived-untranslated derived-root derived-root-unset derived-root-zero derived-root-sgpr derived-root-heap derived-root-five derived-root-table derived-slot55 derived-slot55-mask derived-slot55-isolate) + foreach(mode derived derived-off derived-bad derived-depth derived-reviewed derived-untranslated derived-root derived-root-unset derived-root-zero derived-root-sgpr derived-root-heap derived-root-five derived-root-table derived-slot55 derived-slot55-mask derived-slot55-isolate derived-slot55-base) add_test(NAME startup_indirect_mesh_${mode}_${backend} COMMAND startup_indirect_draw_indexed ${backend} mesh-${mode}) set_tests_properties(startup_indirect_mesh_${mode}_${backend} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77 diff --git a/docs/experiments/native-fixed-mesh57.md b/docs/experiments/native-fixed-mesh57.md index 1b2a6ac777..149d5ab7e5 100644 --- a/docs/experiments/native-fixed-mesh57.md +++ b/docs/experiments/native-fixed-mesh57.md @@ -126,13 +126,13 @@ The first time a reason is seen, stderr gets one `x2w-render mesh57-derive sampl A startup run on the Windows test PC recorded 653,708 refused `DispatchMesh` `ExecuteIndirect` calls in 420 seconds and forwarded none. Across draw and mesh, the graphics-pipeline census counted `graphics/no_translation` 446,421 and `graphics/mesh_profile_missing` 427,428. This switch is only the second of those, and only the immediate-allocation shape below. Slot 86 meshes with no cached stage stay refused. -The accepted program writes `m0` with one `s_mov_b32` of an integer immediate and the next instruction is the only `s_sendmsg` `GS_ALLOC_REQ` (`0xbf900009`). The immediate is `(primitives << 12) | vertices`, both counts are in 1..64, and the high byte is clear. A group-memory count exchange (`0xbf8a0000`) is refused. A 32-bit `exec` write is refused as `derived mesh is wave32`, whether it is `s_mov_b32 exec_lo` or a 32-bit `exec` ALU such as `s_and_b32`. The bound group is one wave of 64 threads, triangle topology, and group stride 0, and the program is forwarded only when it proves that group. `v_mbcnt_lo` of the hardware lane id is the thread-count proof (`derived mesh thread count is not proven` otherwise). A primitive-index export (export target 20) is the triangle proof (`derived mesh topology is not triangles` otherwise). An allocation by itself is not forwarded. Stride 0 is the bound stride; this path does not invent another. The pixel shader must be a constant `MRT0` export with no resource bindings. A one-constant root is bound at user SGPR s8. A program that reads a different SGPR stays refused (`derived mesh constant is not at user SGPR s8`). +The accepted program writes `m0` with one `s_mov_b32` of an integer immediate and the next instruction is the only `s_sendmsg` `GS_ALLOC_REQ` (`0xbf900009`). The immediate is `(primitives << 12) | vertices`, both counts are in 1..64, and the high byte is clear. A group-memory count exchange (`0xbf8a0000`) is refused. Any 32-bit instruction that writes `exec` is refused as `derived mesh is wave32`. That includes `s_mov_b32 exec_lo`, every other 32-bit scalar operation whose destination is `exec_lo` (`s_not_b32`, `s_movk_i32`, `s_cselect_b32`, adds, shifts, and the bitwise SOP2 forms), and the implicit writers `*_saveexec_b32` and `*_wrexec_b32`. Their destination field is the saved register, not `exec`. A 64-bit write of `exec` (`s_mov_b64` and the other 64-bit scalar forms with destination `exec`, and `*_saveexec_b64` / `*_wrexec_b64`) is a wave64 signal. `v_mbcnt_lo` proves the thread index (`derived mesh thread count is not proven` otherwise) and does not prove wave64: lanes 32 and above read as 32. Wave64 also requires `v_mbcnt_hi_u32_b32` or a 64-bit `exec` write. A program with neither is refused as `derived mesh wave size is not proven` and is not given wave size 64. A primitive-index export (export target 20) is the triangle proof (`derived mesh topology is not triangles` otherwise). An allocation by itself is not forwarded. Stride 0 is the bound stride; this path does not invent another. The pixel shader must be a constant `MRT0` export with no resource bindings. A one-constant root is bound at user SGPR s8. A program that reads a different SGPR stays refused (`derived mesh constant is not at user SGPR s8`). An empty guest root is unchanged. One 32-bit constant parameter of 1..8 dwords and no other parameters is bound, including when the guest root is heap indexed: user SGPR s8 is that block, and the draw copies it into a desktop b0 the same way a reviewed constant profile does. The constant words must already be set on the list. The heap base itself is not bound; a shader that reads it is refused by the lowerer. A heap-indexed root with any other shape (`derived mesh guest root is heap indexed`), a descriptor or root descriptor (`derived mesh guest root has descriptors`), or any other constant shape (`derived mesh guest root constants do not fit one user block`) stays refused. Those need a reviewed SGPR map; this path does not invent one. -A slot 55 pipeline reuses that derived mesh when every patch record is a blend patch (tag 2, 0x14c bytes) or the patch list is empty. The last blend patch replaces the base blend. Tag 2 is the only slot 55 record this repository applies: the graphics path reads that blend descriptor and does not apply any other tag. Depth for a slot 57 base comes from its state block, not from a patch tag. A record whose tag is not 2 stays refused, and the reason names that tag (for example `slot 55 patch tag 3 is not applied`). A list whose size is not a whole number of 0x14c records stays `slot 55 patches are not applied`. The sample lists the first records either way. That refusal is stored on the slot 55 pipeline. The slot 57 base keeps the derive reason it already had. The base's shader, root, and depth rules are unchanged. +A slot 55 pipeline reuses that derived mesh when every patch record is a blend patch (tag 2, 0x14c bytes) or the patch list is empty. The last blend patch replaces the base blend. If the base was already derived and remembered a blend refusal, or `derived mesh desktop pipeline was refused`, a later tag 2 child does not inherit that reason: the patch is applied and derivation continues. A base reason from the allocation, the wave size, the root, or any other check is still returned, and it is not copied onto the child. Tag 2 is the only slot 55 record this repository applies: the graphics path reads that blend descriptor and does not apply any other tag. Depth for a slot 57 base comes from its state block, not from a patch tag. A record whose tag is not 2 stays refused, and the reason names that tag (for example `slot 55 patch tag 3 is not applied`). A list whose size is not a whole number of 0x14c records stays `slot 55 patches are not applied`. The sample lists the first records either way. That refusal is stored on the slot 55 pipeline. The slot 57 base keeps the derive reason it already had. The base's shader, root, and depth rules are unchanged. -Fixed function state comes from state block A. The mesh layout word at `+0x004` must be 6. Blend words are read at the mesh shift (`+0x54` on top of `+0xD0`). Depth and stencil must decode as disabled; an enabled test is refused rather than given a guessed depth format. The color target is the one single-sample target bound on that direct list, with a viewport and a scissor and no depth view. The bound rasterizer is solid, cull none, depth clip, and clockwise front faces. A rasterizer captured with the pipeline must match that state (`derived mesh rasterizer does not match the bound state`). Slot 57 creation does not pass a rasterizer, and the guest `PA_SU_SC_MODE_CNTL` word has no established offset in the register block, so this path does not read or guess one. The sample then records `raster=0`. A `.mesh57-state` file that is present, including one whose bytes do not match, keeps the reviewed path and this switch does not create a pipeline. +Fixed function state comes from state block A. The mesh layout word at `+0x004` must be 6. Blend words are read at the mesh shift (`+0x54` on top of `+0xD0`). Depth and stencil must decode as disabled; an enabled test is refused rather than given a guessed depth format. The color target is the one single-sample target bound on that direct list, with a viewport and a scissor and no depth view. The bound rasterizer is solid, cull none, depth clip, and clockwise front faces. A rasterizer captured with the pipeline must match that state (`derived mesh rasterizer does not match the bound state`). Slot 57 creation does not pass a rasterizer, and the guest `PA_SU_SC_MODE_CNTL` word has no established offset in the register block, so this path does not read or guess one. An absent rasterizer is not a refusal: the bound default is used and the sample records `raster=0`. A `.mesh57-state` file that is present, including one whose bytes do not match, keeps the reviewed path and this switch does not create a pipeline. A failed derivation is remembered for that pipeline. Attachment and root mismatches are not: a later direct list can still be the first accepted call. The desktop pipeline then keeps the color format of that call. @@ -142,7 +142,7 @@ From the x64 Windows build environment, with DXC available to the native shader ctest --preset dev -j 1 --no-tests=error -R "mesh57_derive_alloc|startup_indirect_mesh_derived" ``` -`startup_indirect_mesh_derived_{warp,hardware}` forwards one group and reads a white texel at `(2,0)` on a 4 by 2 target. `derived-dxc` does the same with only `X2W_MESH57_DXC_DIR` set, and the process clears `X2W_NATIVE_SHADERS` before the call. `derived-root` is that program plus one guest constant at s8. The mesh multiplies the exported x and y by that word, the word is 1.0, and the same texel is white. `derived-root-zero` sets the word to 0 and stays clear. `derived-root-heap` sets the view-heap flag on that one-constant root, so the draw uses the deferred root, and paints the same texel. `derived-root-sgpr` multiplies by s12 instead of s8 and stays clear. `derived-root-five` is three descriptor tables, one root SRV, and one constant, with the view-heap flag, and stays clear. `derived-slot55` draws through a slot 55 pipeline with no patches and paints the same texel. `derived-slot55-isolate` puts a refused blend word on the base. A slot 55 child with no patch stays clear, and a second child of the same base with a blend patch (tag 2, write mask all) paints. `derived-off` leaves the switch unset. `derived-bad` has no immediate allocation. `derived-depth` enables the depth test in the register block. `derived-reviewed` and `derived-dxc-reviewed` supply a profile file that does not match; the second does that with only `X2W_MESH57_DXC_DIR` set. `derived-untranslated` is a slot 57 pipeline with no captured mesh or pixel program. `derived-root-unset` omits the constant word. `derived-root-table` uses a descriptor table. `derived-slot55-mask` applies a blend patch with a zero write mask. Those leave the clear color. Each returns 77 when mesh shaders or the command signature are unavailable. `mesh57_derive_alloc` checks the allocation reader, the wave32 ALU, the missing thread-count and triangle proofs, the rasterizer decision, the root decision, the slot 55 patch rule, and the forwards line without a device. +`startup_indirect_mesh_derived_{warp,hardware}` forwards one group and reads a white texel at `(2,0)` on a 4 by 2 target. `derived-dxc` does the same with only `X2W_MESH57_DXC_DIR` set, and the process clears `X2W_NATIVE_SHADERS` before the call. `derived-root` is that program plus one guest constant at s8. The mesh multiplies the exported x and y by that word, the word is 1.0, and the same texel is white. `derived-root-zero` sets the word to 0 and stays clear. `derived-root-heap` sets the view-heap flag on that one-constant root, so the draw uses the deferred root, and paints the same texel. `derived-root-sgpr` multiplies by s12 instead of s8 and stays clear. `derived-root-five` is three descriptor tables, one root SRV, and one constant, with the view-heap flag, and stays clear. `derived-slot55` draws through a slot 55 pipeline with no patches and paints the same texel. `derived-slot55-isolate` puts a refused blend word on the base. A slot 55 child with no patch stays clear, and a second child of the same base with a blend patch (tag 2, write mask all) paints. `derived-slot55-base` draws that base first, so the base remembers the blend refusal, then draws a tag 2 child, which paints. `derived-off` leaves the switch unset. `derived-bad` has no immediate allocation. `derived-depth` enables the depth test in the register block. `derived-reviewed` and `derived-dxc-reviewed` supply a profile file that does not match; the second does that with only `X2W_MESH57_DXC_DIR` set. `derived-untranslated` is a slot 57 pipeline with no captured mesh or pixel program. `derived-root-unset` omits the constant word. `derived-root-table` uses a descriptor table. `derived-slot55-mask` applies a blend patch with a zero write mask. Those leave the clear color. Each returns 77 when mesh shaders or the command signature are unavailable. `mesh57_derive_alloc` checks the allocation reader, the 32-bit `exec` writers (including `saveexec` and `wrexec`), the missing thread-count, triangle, and wave64 proofs, the rasterizer decision (an absent rasterizer is not a refusal), the root decision, the slot 55 patch rule, and the forwards line without a device. On the Windows test PC at `f358a2ed`, a 420 second run with `X2W_TRANSLATED_INDIRECT_DRAW=1`, `X2W_MESH57_DERIVE_STATE=1`, and `X2W_MESH57_DXC_DIR` set forwarded nothing. The derive census was `slot 57 pixel stage was not captured` 47823, `derived mesh keeps a non-empty guest root refused` 152144, and `pipeline is a derived slot 55` 180066. The non-empty sample had both stages (mesh 9536 bytes, pixel 4352 bytes). The slot 55 sample was a 332-byte descriptor whose base was slot 57 and whose stage lengths were unread. That root refusal is replaced by the three root reasons above, and a slot 55 call now uses its slot 57 base when the patches are blend records. A 4352-byte pixel is still not a constant export, and a program that is not the one immediate allocation is still refused. diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index 4e74811ee9..9d5de1d0ea 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -1735,7 +1735,7 @@ ctest --preset dev --no-tests=error -R '^startup_hook_(window|overlap)$' -V | `X2W_SHADER_CACHE=` | translation cache: the runtime writes source requests `req_.{a,b,root}`, when needed RTV variants `req_.rtv`, and for device slot 67 compute pipelines `req_.{desc,sa,sb,data,root,c67}` (see [Compute pipeline requests](#compute-pipeline-requests)). A console pipeline that an `ExecuteIndirect` draw (list slot 61) refuses writes the same request as a direct draw, once per pipeline, and draws nothing (`startup_indirect_requests_warp`). Only direct draws poll for its manifest, so such a pipeline stays in the `missing` count until a direct draw uses it; the `x2w-render totals` line counts `pipelines first looked up by ExecuteIndirect N`. This is a per-process lookup count. Check for the ready marker `req_.a` to confirm a complete request is available. Run `tools/startup/gfx2hlsl.py --pending ` while the process is running, or start the run with `run.ps1 -Translate` (see [Translating shaders during a run](#translating-shaders-during-a-run)). Active draws poll for an absent manifest at most once per second per pipeline and use the published translation on a subsequent draw. The translator compiles `.vs.cso` and `.ps.cso` with `fxc.exe`: `X2W_FXC`, else the Windows SDK 10.0.26100.0 copy, else the newest `Windows Kits\10\bin\\x64`, else `PATH`. When none exists it writes `.fail` naming `X2W_FXC` without publishing a new manifest. `X2W_FXC=` (empty) publishes the manifest alone. Rerun `--pending` with compilation enabled to fill in missing bytecode for an existing manifest. At its first native slot-57 profile lookup the runtime lists the directory's top-level file names once and logs `x2w-draw cache index: names in ms` (`src/startup_stubs/cache_index.h`). A `.mesh57-state` profile is opened only when that listing has its name, so a profile written while the process runs is read by the next process. Manifests and every other cache file are still looked up on disk. | | `X2W_NATIVE_SHADERS=` (`run.ps1 -NativeShaders `) | experimental, in render mode: translates device slot 67 compute requests in the stand-in with the C++ compiler; `` holds `dxcompiler.dll` and `dxil.dll`. See [Translating compute programs in the stand-in](#translating-compute-programs-in-the-stand-in) | | `X2W_MESH57_DXC_DIR=` | experimental, with `X2W_MESH57_DERIVE_STATE=1`: the directory of `dxcompiler.dll` and `dxil.dll` for that one slot 57 derivation. Other graphics and compute programs stay on the non-native path. Unset, the derivation may still use `X2W_NATIVE_SHADERS` when that directory is set. When neither directory is set, the call stays refused (`derived mesh needs the native shader compiler`). See [Opt-in immediate allocation](experiments/native-fixed-mesh57.md#opt-in-immediate-allocation) | -| `X2W_MESH57_DERIVE_STATE=1` | experimental, with `X2W_SHADER_CACHE` and `X2W_MESH57_DXC_DIR` (or `X2W_NATIVE_SHADERS`): addresses `graphics/mesh_profile_missing` for one slot 57 shape. A direct `DispatchMesh` `ExecuteIndirect` may build one desktop mesh pipeline from an immediate `GS_ALLOC_REQ` and the bound color target when captured stages exist and no `.mesh57-state` file was opened. One guest constant block of 1..8 dwords is copied into desktop b0, including when that root is heap indexed. A slot 55 pipeline whose base is that slot 57 mesh reuses it when every patch is a blend record. A patch whose tag is not 2 stays refused and the reason names that tag; that reason is stored on the slot 55 pipeline, not on its slot 57 base. The program is forwarded only when it proves 64 threads, triangle indices, and wave64, and when a one-constant root is the word the mesh reads at user SGPR s8. The sample line lists the first root-parameter types, the first patch tags, and whether a rasterizer was captured. A zero pixel length in the descriptor stays refused (`slot 57 pixel stage is absent from the descriptor`). `graphics/no_translation`, slot 86, depth, stencil, any other heap-indexed root, a descriptor root, and any other allocation shape stay refused. While the switch is on, every `DispatchMesh` `ExecuteIndirect` is counted: the first use of a reason logs `x2w-render mesh57-derive sample`, and the 300-frame heartbeat logs `x2w-render mesh57-derive:` plus `x2w-render mesh57-derive forwards:`. The rasterizer is not taken from the register block. See [Opt-in immediate allocation](experiments/native-fixed-mesh57.md#opt-in-immediate-allocation) | +| `X2W_MESH57_DERIVE_STATE=1` | experimental, with `X2W_SHADER_CACHE` and `X2W_MESH57_DXC_DIR` (or `X2W_NATIVE_SHADERS`): addresses `graphics/mesh_profile_missing` for one slot 57 shape. A direct `DispatchMesh` `ExecuteIndirect` may build one desktop mesh pipeline from an immediate `GS_ALLOC_REQ` and the bound color target when captured stages exist and no `.mesh57-state` file was opened. One guest constant block of 1..8 dwords is copied into desktop b0, including when that root is heap indexed. A slot 55 pipeline whose base is that slot 57 mesh reuses it when every patch is a blend record. A tag 2 patch replaces a base reason that came from the blend or from desktop pipeline creation; any other base reason is still inherited and is not copied onto the child. A patch whose tag is not 2 stays refused and the reason names that tag; that reason is stored on the slot 55 pipeline, not on its slot 57 base. The program is forwarded only when `v_mbcnt_lo` proves the thread index, export target 20 proves triangle indices, and `v_mbcnt_hi_u32_b32` or a 64-bit `exec` write proves wave64. A 32-bit `exec` write, including `*_saveexec_b32` and `*_wrexec_b32`, stays `derived mesh is wave32`. A program with no wave64 proof stays `derived mesh wave size is not proven`. A one-constant root is forwarded only when it is the word the mesh reads at user SGPR s8. The sample line lists the first root-parameter types, the first patch tags, and whether a rasterizer was captured. A zero pixel length in the descriptor stays refused (`slot 57 pixel stage is absent from the descriptor`). `graphics/no_translation`, slot 86, depth, stencil, any other heap-indexed root, a descriptor root, and any other allocation shape stay refused. While the switch is on, every `DispatchMesh` `ExecuteIndirect` is counted: the first use of a reason logs `x2w-render mesh57-derive sample`, and the 300-frame heartbeat logs `x2w-render mesh57-derive:` plus `x2w-render mesh57-derive forwards:`. The rasterizer is not taken from the register block. An absent captured rasterizer is not a refusal; a present one that is not the bound default (solid, cull none, depth clip) is. See [Opt-in immediate allocation](experiments/native-fixed-mesh57.md#opt-in-immediate-allocation) | | `X2W_D3D12_LINEAR_BUFFERS=1` or `=copy` | opt-in backing for linear buffers placed at a title address (device slot 133, initial state `COMMON`): shared where the adapter, extent and memory allow it (private allocations larger than 256 MiB are skipped only with `X2W_D3D12_CAP_EXISTING_HEAP=1`), otherwise copied from title memory at each submission, otherwise the default backing is kept and the refusal recorded; `copy` never shares. Unset or `0`, slot 133 keeps its default backing. See [Linear buffer backing (device slot 133, opt-in)](#linear-buffer-backing-device-slot-133-opt-in) | | `X2W_D3D12_CAP_EXISTING_HEAP=1` | opt-in 256 MiB (`unplaced_existing_heap_allowed`) allocation-size cap on `OpenExistingHeapFromAddress` in device slot 133 (`startup_slot133_heap_cap_*`). Unset (default), private allocations larger than 256 MiB keep the formerly aliased path: a capped copied placement is refused by `CopyBufferRegion` (list slot 15) as `title_backed_source`, losing a late guest write made after recording and before submit. Set, allocations larger than 256 MiB skip `OpenExistingHeapFromAddress` so multi-GiB startup blocks are not pinned in `WorkingSetSize` and `NonLocal` GPU memory | | `X2W_D3D12_ROOT_SRV_AT_DRAW=1` | opt-in, render mode: a graphics root SRV (slot 44) without an upload mapping is not copied into the upload ring, since no draw reads that desktop binding (default: a 64 KiB copy at every slot 44 call). Translated draws copy the SRV themselves and are unaffected (`startup_root_srv_draw_*`). See [the experiment note](experiments/startup-root-srv-at-draw.md) | diff --git a/src/startup_stubs/mesh57_alloc.h b/src/startup_stubs/mesh57_alloc.h index 7fa4f8b0e8..12ea711b2b 100644 --- a/src/startup_stubs/mesh57_alloc.h +++ b/src/startup_stubs/mesh57_alloc.h @@ -30,12 +30,48 @@ struct MeshDerivedLayout { // What this path binds, and why a program that does not match is refused. // group_stride stays 0: a program that reads the group id is not this layout. // Returns an empty layout and a stable reason when the program is not the single immediate -// allocation, is wave32, does not prove a 64-thread lane id, or does not export triangle indices. +// allocation, writes exec with a 32-bit instruction, does not prove a 64-thread lane id, +// does not export triangle indices, or does not prove wave64. struct MeshLayoutRead { std::optional layout; const char* reason = nullptr; }; +// SOP1/SOP2/SOPK width, from the opcode name. A trailing _b64/_i64/_u64 writes a pair, +// except names that contain _i32_ (s_bcnt0_i32_b64, s_flbit_i32_i64): those write one +// 32-bit result. s_bitreplicate_b64_b32 writes a pair. The scalar transfer uses this split. +inline bool mesh57_name_ends(std::string_view name, std::string_view suffix) noexcept +{ + return name.size() >= suffix.size() && + name.compare(name.size() - suffix.size(), suffix.size(), suffix) == 0; +} + +inline bool mesh57_name_starts(std::string_view name, std::string_view prefix) noexcept +{ + return name.size() >= prefix.size() && name.compare(0, prefix.size(), prefix) == 0; +} + +inline bool mesh57_scalar_result_is_64(std::string_view name) noexcept +{ + if (name == "s_bitreplicate_b64_b32") + return true; + if (name.find("_i32_") != std::string_view::npos) + return false; + return mesh57_name_ends(name, "_b64") || mesh57_name_ends(name, "_i64") || + mesh57_name_ends(name, "_u64"); +} + +// The SDST field is not a data destination for these names. Compares write SCC. +// s_setpc_b64, s_swappc_b64 and s_rfe_b64 read the register as a PC. +// s_setreg writes a hardware register. Wait and subvector encodings pack a control word. +inline bool mesh57_scalar_sdst_is_not_data(std::string_view name) noexcept +{ + return name == "s_setpc_b64" || name == "s_swappc_b64" || name == "s_rfe_b64" || + name == "s_version" || mesh57_name_starts(name, "s_cmp") || + mesh57_name_starts(name, "s_setreg") || mesh57_name_starts(name, "s_waitcnt") || + mesh57_name_starts(name, "s_subvector"); +} + inline MeshLayoutRead mesh57_read_layout(std::string_view code) noexcept { MeshLayoutRead out; @@ -49,6 +85,7 @@ inline MeshLayoutRead mesh57_read_layout(std::string_view code) noexcept unsigned vertices = 0; unsigned primitives = 0; bool wave32 = false; + bool wave64 = false; bool exchange = false; bool lane_id = false; bool triangle_export = false; @@ -62,15 +99,30 @@ inline MeshLayoutRead mesh57_read_layout(std::string_view code) noexcept exchange = true; if (inst.name == "v_mbcnt_lo_u32_b32") lane_id = true; + // v_mbcnt_lo maps every lane at or above 32 to 32, so it is not a wave64 proof. + // v_mbcnt_hi is the high half of that id. + if (inst.name == "v_mbcnt_hi_u32_b32") + wave64 = true; if (inst.form == x2w::gfx1013::Form::exp && ((raw >> 4) & 63u) == 20u) triangle_export = true; - if (inst.form == x2w::gfx1013::Form::sop2) { - const unsigned dst = (raw >> 16) & 127u; - // A 32-bit exec update is wave32 even when it is not s_mov_b32 exec_lo. - if (dst == 126u && (inst.name == "s_and_b32" || inst.name == "s_or_b32" || - inst.name == "s_xor_b32" || inst.name == "s_andn2_b32" || - inst.name == "s_orn2_b32" || inst.name == "s_nand_b32" || - inst.name == "s_nor_b32" || inst.name == "s_xnor_b32")) + // exec_lo is SGPR 126. A 32-bit write of it, including an implicit saveexec or + // wrexec whose destination field is the saved register, is wave32. A 64-bit write + // of the exec pair is a wave64 signal. + const bool implicit32 = inst.name.find("saveexec_b32") != std::string_view::npos || + inst.name.find("wrexec_b32") != std::string_view::npos; + const bool implicit64 = inst.name.find("saveexec_b64") != std::string_view::npos || + inst.name.find("wrexec_b64") != std::string_view::npos; + if (implicit32) + wave32 = true; + else if (implicit64) + wave64 = true; + else if (!inst.name.empty() && + (inst.form == x2w::gfx1013::Form::sop1 || inst.form == x2w::gfx1013::Form::sop2 || + inst.form == x2w::gfx1013::Form::sopk) && + ((raw >> 16) & 127u) == 126u && !mesh57_scalar_sdst_is_not_data(inst.name)) { + if (mesh57_scalar_result_is_64(inst.name)) + wave64 = true; + else wave32 = true; } if (raw == 0xbf900009u) { @@ -90,8 +142,6 @@ inline MeshLayoutRead mesh57_read_layout(std::string_view code) noexcept if (inst.form == x2w::gfx1013::Form::sop1 && inst.name == "s_mov_b32") { const unsigned dst = (raw >> 16) & 127u; const unsigned src = raw & 255u; - if (dst == 126u) - wave32 = true; if (dst == 124u) { if (src >= 128u && src <= 192u) { previous_immediate = true; @@ -124,6 +174,12 @@ inline MeshLayoutRead mesh57_read_layout(std::string_view code) noexcept out.reason = "derived mesh topology is not triangles"; return out; } + // A 32-bit exec write was already returned above. Reaching here with no 64-bit exec + // write and no v_mbcnt_hi does not prove wave64, so this does not return wave size 64. + if (!wave64) { + out.reason = "derived mesh wave size is not proven"; + return out; + } MeshDerivedLayout layout; layout.threads = 64; layout.vertices = vertices; @@ -147,6 +203,8 @@ inline std::optional derive_immediate_mesh_layout(std::string // The rasterizer this path binds: solid fill, cull none, depth clip, clockwise front faces. // present is true only when a reviewed capture already stored a rasterizer. The slot 57 // PA_SU_SC_MODE_CNTL word has no established offset, so this function does not read one. +// An absent rasterizer is not a refusal. Slot 57 creation does not pass one, and the +// runtime then forwards the bound default. A present rasterizer that is not that default is. struct Mesh57RasterizerView { bool present = false; bool cull_none = false; @@ -158,12 +216,39 @@ struct Mesh57RasterizerView { inline const char* mesh57_rasterizer_reason(const Mesh57RasterizerView& view) noexcept { if (!view.present) - return "derived mesh rasterizer is not in the captured state"; + return nullptr; if (!view.cull_none || !view.solid || !view.depth_clip || view.front_ccw) return "derived mesh rasterizer does not match the bound state"; return nullptr; } +// A slot 55 blend patch can replace these. They are the blend decoder reasons and the two +// derive reasons that were decided from the base blend or from creating the desktop pipeline. +// Any other remembered reason stays in force when a child is derived from that base. +inline bool mesh57_blend_override_replaces(const char* reason) noexcept +{ + if (!reason) + return false; + const char* const replaced[] = { + "derived mesh blend was refused", + "derived mesh desktop pipeline was refused", + "state block A shorter than the blend words", + "dual-source factor on a target other than 0", + "dual-source blend on target 0 with another blending target", + "target mask wider than four components", + "BOTH_SRC_ALPHA / BOTH_INV_SRC_ALPHA factor", + "CONSTANT_ALPHA factor without alpha blend factor support", + "unknown blend factor", + "unknown combine function", + "MIN / MAX with factors other than ONE", + }; + for (const char* item : replaced) { + if (std::strcmp(reason, item) == 0) + return true; + } + return false; +} + // Why a slot 57 creation record is not the fixed mesh+pixel pair this path can read. // nullptr means both stages were captured from a 768-byte descriptor with no vertex span. // The clauses match the capture in note_pipeline: a vertex span, a zero mesh length, or a diff --git a/src/startup_stubs/native_mesh57.inl b/src/startup_stubs/native_mesh57.inl index 601cc5675b..3b2f2e0465 100644 --- a/src/startup_stubs/native_mesh57.inl +++ b/src/startup_stubs/native_mesh57.inl @@ -715,14 +715,16 @@ const char* derive_slot57_mesh(Wrapper* pipeline, Pass& pass, const D3D12_BLEND_ return nullptr; // `shaders` is the slot 57 program. `stored` is the pipeline this call is deriving. // A slot 55 failure is remembered on the slot 55 info. A reason the base already - // has is returned and is not copied. This call does not write the base. + // has is returned and is not copied, except a blend or desktop pipeline reason when + // this call has a blend override. This call does not write the base. const auto* shaders = source ? source : pipeline_info(pipeline); const auto* stored = pipeline_info(pipeline); if (!shaders || !stored) return "derived mesh has no captured pipeline"; if (stored->mesh57_derive_reason) return stored->mesh57_derive_reason; - if (shaders != stored && shaders->mesh57_derive_reason) + if (shaders != stored && shaders->mesh57_derive_reason && + !(blend_override && x2w_startup::mesh57_blend_override_replaces(shaders->mesh57_derive_reason))) return shaders->mesh57_derive_reason; auto remember = [&](const char* why) { stored->mesh57_derive_reason = why; diff --git a/tests/mesh57_derive_alloc_check.cpp b/tests/mesh57_derive_alloc_check.cpp index 23ad53a406..83e790b8f3 100644 --- a/tests/mesh57_derive_alloc_check.cpp +++ b/tests/mesh57_derive_alloc_check.cpp @@ -6,6 +6,7 @@ #include #include #include +#include namespace { int fail(const char* name) @@ -24,26 +25,80 @@ std::string words_of(const std::uint32_t* words, std::size_t count) bool accepted(std::string_view code, unsigned vertices, unsigned primitives) { - const auto layout = x2w_startup::derive_immediate_mesh_layout(code); - return layout && layout->vertices == vertices && layout->primitives == primitives && + const auto read = x2w_startup::mesh57_read_layout(code); + const auto layout = read.layout; + return layout && !read.reason && layout->vertices == vertices && layout->primitives == primitives && layout->threads == 64 && layout->topology == 2 && layout->group_stride == 0 && layout->wave_size == 64; } + +std::string code_from(const std::vector& words) +{ + return words_of(words.data(), words.size()); +} + +bool expect_reason(const char* name, const std::vector& words, const char* reason) +{ + const auto read = x2w_startup::mesh57_read_layout(code_from(words)); + if (read.layout || !read.reason || std::strcmp(read.reason, reason) != 0) { + std::fprintf(stderr, "mesh57 derive alloc: %s got %s\n", name, read.reason ? read.reason : "(null)"); + return false; + } + return true; +} + +// SOP1/SOP2/SOPK fields match gfx1013::instruction. The opcode is the table index. +std::uint32_t sop1_word(unsigned op, unsigned dst, unsigned src) +{ + return (0x17du << 23) | (dst << 16) | (op << 8) | src; +} + +std::uint32_t sop2_word(unsigned op, unsigned dst, unsigned src0, unsigned src1) +{ + return (2u << 30) | (op << 23) | (dst << 16) | (src1 << 8) | src0; +} + +std::uint32_t sopk_word(unsigned op, unsigned dst, unsigned imm) +{ + return (11u << 28) | (op << 23) | (dst << 16) | (imm & 0xffffu); +} + +bool named(std::uint32_t word, const char* name) +{ + std::string bytes(sizeof(word), '\0'); + std::memcpy(bytes.data(), &word, sizeof(word)); + return x2w::gfx1013::instruction(bytes, 0).name == name; +} + +std::vector with_word(std::vector words, std::uint32_t word) +{ + words.insert(words.end() - 1, word); + return words; +} } // namespace int main() { // Source-built triangle: m0 = (1 primitive << 12) | 3 vertices, then GS_ALLOC_REQ. - const std::uint32_t triangle[] = { + // v_mbcnt_hi_u32_b32 v6, exec, 0 is the wave64 proof. v_mbcnt_lo writes v0 and is not that proof. + const std::vector triangle = { 0xbefc03ffu, 0x1003u, 0xbf900009u, 0xd7650000u, 0x100c1u, 0x36020081u, 0x2c040081u, 0x7e020d01u, 0x7e040d02u, 0x7e0602f0u, 0x7e0802f2u, 0xf80008cfu, - 0x04030201u, 0x7e0a02ffu, 0x200400u, 0xf8000941u, 0x80808005u, 0xbf810000u}; - const auto triangle_bytes = words_of(triangle, sizeof(triangle) / sizeof(triangle[0])); - if (!accepted(triangle_bytes, 3, 1)) + 0x04030201u, 0x7e0a02ffu, 0x200400u, 0xf8000941u, 0x80808005u, 0xd7660006u, + 0x000100c1u, 0xbf810000u}; + if (!accepted(code_from(triangle), 3, 1)) return fail("triangle"); - const auto triangle_read = x2w_startup::mesh57_read_layout(triangle_bytes); - if (!triangle_read.layout || triangle_read.reason) - return fail("triangle reason"); + { + std::string hi(8, '\0'); + const std::uint32_t pair[] = {0xd7660006u, 0x000100c1u}; + std::memcpy(hi.data(), pair, sizeof(pair)); + if (x2w::gfx1013::instruction(hi, 0).name != "v_mbcnt_hi_u32_b32") + return fail("mbcnt_hi encoding"); + } + std::vector no_wave64 = triangle; + no_wave64.erase(no_wave64.end() - 3, no_wave64.end() - 1); + if (!expect_reason("no wave64 signal", no_wave64, "derived mesh wave size is not proven")) + return 1; const std::uint32_t only_alloc[] = {0xbefc03ffu, 0x1003u, 0xbf900009u, 0xbf810000u}; const auto alone = x2w_startup::mesh57_read_layout(words_of(only_alloc, 4)); @@ -57,11 +112,17 @@ int main() std::strcmp(points.reason, "derived mesh topology is not triangles") != 0) return fail("no triangle export"); + const char* const wave32_reason = "derived mesh is wave32"; const std::uint32_t wave32_alu[] = {0xbefc03ffu, 0x1003u, 0xbf900009u, 0xd7650000u, 0x100c1u, 0x877e7e7eu, 0xf8000941u, 0x80808005u, 0xbf810000u}; const auto alu = x2w_startup::mesh57_read_layout(words_of(wave32_alu, 9)); - if (alu.layout || !alu.reason || std::strcmp(alu.reason, "derived mesh is wave32") != 0) + if (alu.layout || !alu.reason || std::strcmp(alu.reason, wave32_reason) != 0) return fail("wave32 exec alu"); + const std::uint32_t and_exec = sop2_word(14, 126, 126, 126); + if (!named(and_exec, "s_and_b32") || and_exec != 0x877e7e7eu) + return fail("s_and_b32 encoding"); + if (!expect_reason("wave32 sop2 on triangle", with_word(triangle, and_exec), wave32_reason)) + return 1; x2w_startup::Mesh57RasterizerView absent; x2w_startup::Mesh57RasterizerView matched; @@ -71,60 +132,133 @@ int main() matched.depth_clip = true; x2w_startup::Mesh57RasterizerView culled = matched; culled.cull_none = false; - if (!x2w_startup::mesh57_rasterizer_reason(absent) || - std::strcmp(x2w_startup::mesh57_rasterizer_reason(absent), - "derived mesh rasterizer is not in the captured state") != 0 || + x2w_startup::Mesh57RasterizerView wire = matched; + wire.solid = false; + x2w_startup::Mesh57RasterizerView no_clip = matched; + no_clip.depth_clip = false; + x2w_startup::Mesh57RasterizerView ccw = matched; + ccw.front_ccw = true; + const char* const raster_reason = "derived mesh rasterizer does not match the bound state"; + if (x2w_startup::mesh57_rasterizer_reason(absent) || x2w_startup::mesh57_rasterizer_reason(matched) || !x2w_startup::mesh57_rasterizer_reason(culled) || - std::strcmp(x2w_startup::mesh57_rasterizer_reason(culled), - "derived mesh rasterizer does not match the bound state") != 0) + std::strcmp(x2w_startup::mesh57_rasterizer_reason(culled), raster_reason) != 0 || + !x2w_startup::mesh57_rasterizer_reason(wire) || + std::strcmp(x2w_startup::mesh57_rasterizer_reason(wire), raster_reason) != 0 || + !x2w_startup::mesh57_rasterizer_reason(no_clip) || + std::strcmp(x2w_startup::mesh57_rasterizer_reason(no_clip), raster_reason) != 0 || + !x2w_startup::mesh57_rasterizer_reason(ccw) || + std::strcmp(x2w_startup::mesh57_rasterizer_reason(ccw), raster_reason) != 0) return fail("rasterizer"); - const std::uint32_t endpgm[] = {0xbf810000u}; - if (x2w_startup::derive_immediate_mesh_layout(words_of(endpgm, 1))) - return fail("no allocation"); + const char* const alloc_reason = "derived mesh needs one immediate allocation"; + std::vector no_alloc = triangle; + no_alloc.erase(no_alloc.begin(), no_alloc.begin() + 3); + if (!expect_reason("no allocation", no_alloc, alloc_reason)) + return 1; - const std::uint32_t gap[] = {0xbefc03ffu, 0x1003u, 0xbf800000u, 0xbf900009u}; - if (x2w_startup::derive_immediate_mesh_layout(words_of(gap, 4))) - return fail("instruction between m0 and GS_ALLOC_REQ"); + std::vector gap = triangle; + gap.insert(gap.begin() + 2, 0xbf800000u); + if (!expect_reason("instruction between m0 and GS_ALLOC_REQ", gap, alloc_reason)) + return 1; - const std::uint32_t twice[] = {0xbefc03ffu, 0x1003u, 0xbf900009u, 0xbefc03ffu, 0x1003u, 0xbf900009u}; - if (x2w_startup::derive_immediate_mesh_layout(words_of(twice, 6))) - return fail("two allocations"); + std::vector twice = triangle; + twice.insert(twice.end() - 1, {0xbefc03ffu, 0x1003u, 0xbf900009u}); + if (!expect_reason("two allocations", twice, alloc_reason)) + return 1; - const std::uint32_t high[] = {0xbefc03ffu, 0x01001003u, 0xbf900009u}; - if (x2w_startup::derive_immediate_mesh_layout(words_of(high, 3))) - return fail("high byte"); + std::vector high = triangle; + high[1] = 0x01001003u; + if (!expect_reason("high byte", high, alloc_reason)) + return 1; - const std::uint32_t zero[] = {0xbefc03ffu, 0u, 0xbf900009u}; - if (x2w_startup::derive_immediate_mesh_layout(words_of(zero, 3))) - return fail("zero counts"); + std::vector zero = triangle; + zero[1] = 0; + if (!expect_reason("zero counts", zero, alloc_reason)) + return 1; - const std::uint32_t wide[] = {0xbefc03ffu, (1u << 12) | 65u, 0xbf900009u}; - if (x2w_startup::derive_immediate_mesh_layout(words_of(wide, 3))) - return fail("count above one wave"); + std::vector wide = triangle; + wide[1] = (1u << 12) | 65u; + if (!expect_reason("count above one wave", wide, alloc_reason)) + return 1; - const std::uint32_t exchange[] = {0xbefc03ffu, 0x1003u, 0xbf900009u, 0xbf8a0000u}; - if (x2w_startup::derive_immediate_mesh_layout(words_of(exchange, 4))) - return fail("count exchange"); + if (!expect_reason("count exchange", with_word(triangle, 0xbf8a0000u), alloc_reason)) + return 1; - // s_mov_b32 exec_lo, 0. Wave32 writes exec with s_mov_b32; wave64 uses s_mov_b64. - const std::uint32_t wave32_mov = 0xbefe0380u; - std::string wave32_word(sizeof(wave32_mov), '\0'); - std::memcpy(wave32_word.data(), &wave32_mov, sizeof(wave32_mov)); - const auto decoded = x2w::gfx1013::instruction(wave32_word, 0); - if (decoded.name != "s_mov_b32") + // s_mov_b32 exec_lo, 0. The destination field is exec_lo. + const std::uint32_t wave32_mov = sop1_word(3, 126, 128); + if (!named(wave32_mov, "s_mov_b32") || wave32_mov != 0xbefe0380u) return fail("exec_lo encoding"); - const std::uint32_t wave32[] = {wave32_mov, 0xbefc03ffu, 0x1003u, 0xbf900009u}; - if (x2w_startup::derive_immediate_mesh_layout(words_of(wave32, 4))) - return fail("wave32 exec move"); + if (!expect_reason("wave32 exec move", with_word(triangle, wave32_mov), wave32_reason)) + return 1; + + std::vector from_register = triangle; + from_register[0] = 0xbefc0300u; + if (!expect_reason("m0 from a register", from_register, alloc_reason)) + return 1; + + if (!expect_reason("empty", {}, alloc_reason)) + return 1; + + const std::uint32_t not_exec = sop1_word(7, 126, 126); + if (!named(not_exec, "s_not_b32") || + !expect_reason("s_not_b32 exec_lo", with_word(triangle, not_exec), wave32_reason)) + return fail("s_not_b32 exec_lo"); + const std::uint32_t movk_exec = sopk_word(0, 126, 1); + if (!named(movk_exec, "s_movk_i32") || + !expect_reason("s_movk_i32 exec_lo", with_word(triangle, movk_exec), wave32_reason)) + return fail("s_movk_i32 exec_lo"); + const std::uint32_t cselect_exec = sop2_word(10, 126, 126, 126); + if (!named(cselect_exec, "s_cselect_b32") || + !expect_reason("s_cselect_b32 exec_lo", with_word(triangle, cselect_exec), wave32_reason)) + return fail("s_cselect_b32 exec_lo"); + const std::uint32_t add_exec = sop2_word(0, 126, 126, 126); + if (!named(add_exec, "s_add_u32") || + !expect_reason("s_add_u32 exec_lo", with_word(triangle, add_exec), wave32_reason)) + return fail("s_add_u32 exec_lo"); + const std::uint32_t shift_exec = sop2_word(30, 126, 126, 128); + if (!named(shift_exec, "s_lshl_b32") || + !expect_reason("s_lshl_b32 exec_lo", with_word(triangle, shift_exec), wave32_reason)) + return fail("s_lshl_b32 exec_lo"); + + // Destination is s0, not exec. These forms write exec implicitly. + const struct { + unsigned op; + const char* name; + } saveexec_b32[] = { + {60, "s_and_saveexec_b32"}, {61, "s_or_saveexec_b32"}, {62, "s_xor_saveexec_b32"}, + {63, "s_andn2_saveexec_b32"}, {64, "s_orn2_saveexec_b32"}, {65, "s_nand_saveexec_b32"}, + {66, "s_nor_saveexec_b32"}, {67, "s_xnor_saveexec_b32"}, {68, "s_andn1_saveexec_b32"}, + {69, "s_orn1_saveexec_b32"}, {70, "s_andn1_wrexec_b32"}, {71, "s_andn2_wrexec_b32"}, + }; + for (const auto& form : saveexec_b32) { + const std::uint32_t word = sop1_word(form.op, 0, 126); + if (!named(word, form.name) || + !expect_reason(form.name, with_word(triangle, word), wave32_reason)) + return fail(form.name); + } - const std::uint32_t from_register[] = {0xbefc0300u, 0xbf900009u}; - if (x2w_startup::derive_immediate_mesh_layout(words_of(from_register, 2))) - return fail("m0 from a register"); + // A 64-bit exec write is a wave64 signal. The same triangle without v_mbcnt_hi is accepted. + const std::uint32_t mov64 = sop1_word(4, 126, 126); + if (!named(mov64, "s_mov_b64") || !accepted(code_from(with_word(no_wave64, mov64)), 3, 1)) + return fail("s_mov_b64 exec"); + const std::uint32_t save64 = sop1_word(36, 0, 126); + if (!named(save64, "s_and_saveexec_b64") || !accepted(code_from(with_word(no_wave64, save64)), 3, 1)) + return fail("s_and_saveexec_b64"); + const std::uint32_t cmpk = sopk_word(3, 126, 1); + if (!named(cmpk, "s_cmpk_eq_i32") || !accepted(code_from(with_word(triangle, cmpk)), 3, 1)) + return fail("s_cmpk_eq_i32 reads exec_lo"); - if (x2w_startup::derive_immediate_mesh_layout({})) - return fail("empty"); + if (x2w_startup::mesh57_blend_override_replaces(nullptr) || + !x2w_startup::mesh57_blend_override_replaces( + "CONSTANT_ALPHA factor without alpha blend factor support") || + !x2w_startup::mesh57_blend_override_replaces("derived mesh blend was refused") || + !x2w_startup::mesh57_blend_override_replaces("derived mesh desktop pipeline was refused") || + x2w_startup::mesh57_blend_override_replaces(wave32_reason) || + x2w_startup::mesh57_blend_override_replaces("derived mesh wave size is not proven") || + x2w_startup::mesh57_blend_override_replaces(alloc_reason) || + x2w_startup::mesh57_blend_override_replaces("derived mesh guest root is heap indexed")) + return fail("blend override reasons"); x2w_startup::Mesh57PairRecord pair; pair.desc_bytes = 0x300; diff --git a/tests/startup_indirect_draw_indexed.cpp b/tests/startup_indirect_draw_indexed.cpp index cae7ea37ad..dcbd96c9a3 100644 --- a/tests/startup_indirect_draw_indexed.cpp +++ b/tests/startup_indirect_draw_indexed.cpp @@ -2522,9 +2522,12 @@ static int derived_mesh_fixture(ID3D12Device* device, ID3D12Device* guest, ID3D1 empty.pParameters = ¶meter; } const auto root = create_root(guest, empty, &blob); + // v_mbcnt_hi_u32_b32 v6, exec, 0 sits before s_endpgm. v0 stays the low-half lane id the + // exports use. The high half is the wave64 proof and is not read. std::vector ms{0xbefc03ffu, 0x1003u, 0xbf900009u, 0xd7650000u, 0x100c1u, 0x36020081u, 0x2c040081u, 0x7e020d01u, 0x7e040d02u, 0x7e0602f0u, 0x7e0802f2u, 0xf80008cfu, - 0x04030201u, 0x7e0a02ffu, 0x200400u, 0xf8000941u, 0x80808005u, 0xbf810000u}; + 0x04030201u, 0x7e0a02ffu, 0x200400u, 0xf8000941u, 0x80808005u, 0xd7660006u, + 0x000100c1u, 0xbf810000u}; if (constant_root) { // v_mul_f32 of the bound user SGPR into the exported x and y. s8 is that block. // s12 is a different SGPR and must stay refused. 1.0 keeps coverage; 0 does not. @@ -2548,7 +2551,8 @@ static int derived_mesh_fixture(ID3D12Device* device, ID3D12Device* guest, ID3D1 const std::uint32_t depth_on = 2; std::memcpy(state_a.data() + 0x10c, &depth_on, sizeof(depth_on)); } - if (std::strcmp(mode, "mesh-derived-slot55-isolate") == 0) { + if (std::strcmp(mode, "mesh-derived-slot55-isolate") == 0 || + std::strcmp(mode, "mesh-derived-slot55-base") == 0) { const std::uint32_t refused_blend = 0x72911433u; std::memcpy(state_a.data() + 0x124, &refused_blend, sizeof(refused_blend)); } @@ -2646,6 +2650,30 @@ static int derived_mesh_fixture(ID3D12Device* device, ID3D12Device* guest, ID3D1 profile.targets.NumRenderTargets = 1; profile.targets.RTFormats[0] = format; profile.blend.RenderTarget[0].RenderTargetWriteMask = D3D12_COLOR_WRITE_ENABLE_ALL; + if (std::strcmp(mode, "mesh-derived-slot55-base") == 0) { + // The base is drawn first, so it remembers the blend refusal. The tag 2 child must + // paint rather than stay on that reason. + const bool base_clear = run(device, guest, writer, work.Get(), root.Get(), pso.Get(), + signature.Get(), DrawKind::mesh, + false, Refusal::none, mode, nullptr, false, nullptr, false, false, 0, false, false, nullptr, + nullptr, false, 2, &profile); + D3D12_BLEND_DESC replacement{}; + replacement.RenderTarget[0].RenderTargetWriteMask = D3D12_COLOR_WRITE_ENABLE_ALL; + std::vector patch(sizeof(std::uint32_t) + sizeof(replacement)); + const std::uint32_t tag = 2; + std::memcpy(patch.data(), &tag, sizeof(tag)); + std::memcpy(patch.data() + sizeof(tag), &replacement, sizeof(replacement)); + ComPtr replaced_child; + using Derive = HRESULT (WINAPI*)(IUnknown*, void*, UINT, const void*, REFIID, void**); + check(slot(guest, 55)(guest, pso.Get(), 1, patch.data(), __uuidof(ID3D12PipelineState), + reinterpret_cast(replaced_child.GetAddressOf())), + "create base-then-child slot 55"); + const bool child_paint = run(device, guest, writer, work.Get(), root.Get(), replaced_child.Get(), + signature.Get(), DrawKind::mesh, + false, Refusal::none, mode, nullptr, false, nullptr, false, false, 0, false, false, nullptr, + nullptr, false, 1, &profile); + return base_clear && child_paint ? 0 : 1; + } if (std::strcmp(mode, "mesh-derived-slot55-isolate") == 0) { using Derive = HRESULT (WINAPI*)(IUnknown*, void*, UINT, const void*, REFIID, void**); ComPtr refused_child; @@ -2716,7 +2744,8 @@ int main(int argc, char** argv) try std::strcmp(argv[2], "mesh-derived-root-heap") == 0 || std::strcmp(argv[2], "mesh-derived-root-five") == 0); const bool derived_slot55 = argc == 3 && (std::strcmp(argv[2], "mesh-derived-slot55") == 0 || std::strcmp(argv[2], "mesh-derived-slot55-mask") == 0 || - std::strcmp(argv[2], "mesh-derived-slot55-isolate") == 0); + std::strcmp(argv[2], "mesh-derived-slot55-isolate") == 0 || + std::strcmp(argv[2], "mesh-derived-slot55-base") == 0); const bool derived_mesh = derived_off || derived_bad || derived_depth || derived_reviewed || derived_untranslated || derived_dxc || derived_dxc_reviewed || derived_root || derived_slot55 || (argc == 3 && std::strcmp(argv[2], "mesh-derived") == 0); From db4eb57129237e1562c7c9ba6f6bf3b3e8975a6a Mon Sep 17 00:00:00 2001 From: SimSalabimse <83839581+SimSalabimse@users.noreply.github.com> Date: Mon, 30 Nov 2026 20:38:16 +0100 Subject: [PATCH 12/12] runtime: pass the full state block A to the mesh blend reader After merging current main, state_block_blend applies the mesh layout shift itself from the tag at +0x004. The derived-mesh path still passed a pointer already advanced by +0x54, so the reader looked for the tag in the wrong place and refused with "unknown state block A layout". Give it the full block. AI-assisted (Cursor) --- src/startup_stubs/native_mesh57.inl | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/startup_stubs/native_mesh57.inl b/src/startup_stubs/native_mesh57.inl index 3257e8224c..ac66887106 100644 --- a/src/startup_stubs/native_mesh57.inl +++ b/src/startup_stubs/native_mesh57.inl @@ -869,11 +869,11 @@ const char* derive_slot57_mesh(Wrapper* pipeline, Pass& pass, const D3D12_BLEND_ return remember("derived mesh state block is short"); D3D12_BLEND_DESC blend{}; const char* blend_why = nullptr; - // Blend words sit at +0xD0 in the vertex layout. The mesh layout shifts every field from +0x058 - // by +0x54, and the blend reader does not apply that shift itself. A slot 55 blend patch replaces it. + // Blend words sit at +0xD0 in the vertex layout and +0x124 in the mesh layout. The blend + // reader applies that shift from the layout word at +0x004. A slot 55 blend patch replaces it. if (blend_override) blend = *blend_override; - else if (!x2w_startup::state_block_blend(info->state_a.data() + shift, info->state_a.size() - shift, false, &blend, &blend_why)) + else if (!x2w_startup::state_block_blend(info->state_a.data(), info->state_a.size(), false, &blend, &blend_why)) return remember(blend_why ? blend_why : "derived mesh blend was refused"); x2w_pipeline_state::DepthStencilWords depth_words; if (!x2w_pipeline_state::read_depth_stencil_words(info->state_a.data(), info->state_a.size(), depth_words))