From da047d5c899e749c668789059edfdd78e2191214 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Sat, 28 Nov 2026 23:31:07 +0000 Subject: [PATCH 01/24] 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/24] 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/24] 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/24] 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/24] 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/24] 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/24] 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/24] 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/24] 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/24] 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/24] 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 35b3ca2dcf34aec218a29e6218b42dc5fcf0fe48 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Mon, 30 Nov 2026 03:29:16 +0000 Subject: [PATCH 12/24] startup: copy measured slot 57 spans when shader dump is enabled When the shader dump directory is set, slot 57 pipeline creation copies descriptor spans whose live length qword matches the measured packing. Other create paths are unchanged. The copy does not bind mesh counts or write a profile. --- CMakeLists.txt | 14 + src/startup_stubs/d3d12_xs_device.cpp | 28 ++ src/startup_stubs/mesh57_span_dump.h | 145 ++++++++ tests/mesh57_span_dump_check.cpp | 461 ++++++++++++++++++++++++++ tools/startup/mesh57_span_report.py | 429 ++++++++++++++++++++++++ 5 files changed, 1077 insertions(+) create mode 100644 src/startup_stubs/mesh57_span_dump.h create mode 100644 tests/mesh57_span_dump_check.cpp create mode 100644 tools/startup/mesh57_span_report.py diff --git a/CMakeLists.txt b/CMakeLists.txt index f8f5f21084..c5955d5625 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1952,6 +1952,20 @@ target_include_directories(mesh57_derive_alloc_check PRIVATE src src/startup_stu target_compile_features(mesh57_derive_alloc_check PRIVATE cxx_std_17) add_test(NAME mesh57_derive_alloc COMMAND mesh57_derive_alloc_check) +add_executable(mesh57_span_dump_check tests/mesh57_span_dump_check.cpp) +target_include_directories(mesh57_span_dump_check PRIVATE src) +target_compile_features(mesh57_span_dump_check PRIVATE cxx_std_17) +foreach(scenario IN ITEMS unset copied mismatch not-pointer not-readable other) + add_test(NAME mesh57_span_dump_${scenario} + COMMAND mesh57_span_dump_check ${scenario} "${CMAKE_SOURCE_DIR}") + set_tests_properties(mesh57_span_dump_${scenario} PROPERTIES TIMEOUT 30) +endforeach() +if(EXISTS "${INTAKE_PYTHON}") + add_test(NAME mesh57_span_report COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tools/startup/mesh57_span_report.py" --self-test) + set_tests_properties(mesh57_span_report PROPERTIES TIMEOUT 30) +endif() + 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") diff --git a/src/startup_stubs/d3d12_xs_device.cpp b/src/startup_stubs/d3d12_xs_device.cpp index cb1ec97243..9022b252bf 100644 --- a/src/startup_stubs/d3d12_xs_device.cpp +++ b/src/startup_stubs/d3d12_xs_device.cpp @@ -24,6 +24,7 @@ #include "startup_stubs/draw_bmp.h" #include "startup_stubs/pipeline_colour.h" #include "startup_stubs/mesh57_profile.h" +#include "startup_stubs/mesh57_span_dump.h" #include "startup_stubs/cache_index.h" #include "startup_stubs/draw_dump_tracking.h" #include "startup_stubs/present_readback_state.h" @@ -7348,6 +7349,24 @@ void digest_text(const void* container, wchar_t* out) for (int i = 0; i < 16; ++i) swprintf(out + 2 * i, 3, L"%02x", b[i]); } +void write_named_dump(const wchar_t* dir, const char* name, const void* data, std::size_t bytes) +{ + if (!dir || !dir[0] || !name || !name[0] || name[0] == '.' || !data || !bytes) return; + wchar_t wname[80]; + std::size_t i = 0; + for (; name[i] != 0 && i + 1 < sizeof(wname) / sizeof(wname[0]); ++i) { + const unsigned char c = static_cast(name[i]); + if (c < 0x20 || c > 0x7e || c == '\\' || c == '/' || c == ':') return; + wname[i] = static_cast(c); + } + if (name[i] != 0) return; + wname[i] = 0; + wchar_t path[MAX_PATH]; + const int n = swprintf(path, MAX_PATH, L"%s\\%s", dir, wname); + if (n < 0 || n >= MAX_PATH) return; + write_file(path, data, bytes); +} + void dump_containers(const char* what, const void* desc, std::size_t bytes) { wchar_t dir[MAX_PATH]; @@ -7371,6 +7390,14 @@ void dump_containers(const char* what, const void* desc, std::size_t bytes) used += std::snprintf(listing + used, sizeof(listing) - used, "+0x%03llx %ls %u\n", static_cast(i * 8), digest, total); } + if (what && std::strcmp(what, "pipeline") == 0 && bytes == 0x300) { + const auto spans = x2w_startup::dump_mesh57_spans( + true, index, what, words, bytes, x2w_local::readable, + [&](const char* name, const void* data, std::size_t size) { write_named_dump(dir, name, data, size); }); + static LONG mesh57_span_logs; + if (spans.applied && spans.log_line[0] && first_calls(mesh57_span_logs, 4)) + log("%s", spans.log_line); + } wchar_t path[MAX_PATH]; swprintf(path, MAX_PATH, L"%s\\%s_%04ld.bin", dir, what[0] == 's' ? L"stream" : L"compute", index); write_file(path, desc, bytes); @@ -7503,6 +7530,7 @@ HRESULT __stdcall device_create_pipeline_placeholder(Wrapper*, const void* desc, if (!out || !iid) return E_POINTER; *out = nullptr; dump_pipeline("pipeline", N, desc, 0x300); + if constexpr (N == 57) dump_containers("pipeline", desc, 0x300); if (kind_for(*iid) != pipeline_kind) return E_NOINTERFACE; if constexpr (N == 57) { if (x2w_local::env_on("X2W_REFUSE_FIXED_MESH") && is_fixed_mesh57_descriptor(desc)) { diff --git a/src/startup_stubs/mesh57_span_dump.h b/src/startup_stubs/mesh57_span_dump.h new file mode 100644 index 0000000000..565d93d02d --- /dev/null +++ b/src/startup_stubs/mesh57_span_dump.h @@ -0,0 +1,145 @@ +// Measured slot 57 descriptor spans for an already-open shader dump directory. +// A span is copied only when its length qword equals the packing below. +// Nothing is bound and no profile is written. +#pragma once + +#include +#include +#include +#include + +namespace x2w_startup { + +// Same bounds as mesh57_profile.h is_pointer. +inline constexpr bool mesh57_span_is_pointer(std::uint64_t value) noexcept +{ + return value >= 0x10000ull && value < 0x800000000000ull; +} + +inline constexpr bool mesh57_span_length_allowed(std::uint64_t length) noexcept +{ + return length > 0 && length <= 64ull * 1024ull; +} + +struct Mesh57SpanSpec { + int start_q; + int length_q; + std::uint64_t expected; +}; + +// Required pairs first, then optional pairs. Optional pairs use the same rules. +inline constexpr Mesh57SpanSpec kMesh57SpanSpecs[] = { + {7, 8, 720ull}, + {15, 16, 1264ull}, + {45, 46, 480ull}, + {47, 48, 80ull}, + {51, 52, 656ull}, + {59, 60, 1392ull}, + {89, 90, 480ull}, + {91, 92, 80ull}, + {49, 50, 2112ull}, + {57, 58, 10368ull}, + {93, 94, 2112ull}, +}; + +inline constexpr bool mesh57_span_table_ok() noexcept +{ + constexpr int count = static_cast(sizeof(kMesh57SpanSpecs) / sizeof(kMesh57SpanSpecs[0])); + if (count != 11) + return false; + for (int i = 0; i < count; ++i) { + const Mesh57SpanSpec spec = kMesh57SpanSpecs[i]; + if (spec.length_q != spec.start_q + 1) + return false; + if (spec.start_q < 0 || spec.length_q < 0 || spec.length_q >= 96) + return false; + if (spec.start_q == 36 || spec.start_q == 37 || spec.start_q == 80 || spec.start_q == 81 || + spec.start_q == 95) + return false; + if (!mesh57_span_length_allowed(spec.expected)) + return false; + } + return true; +} +static_assert(mesh57_span_table_ok(), "slot 57 span table"); + +struct Mesh57SpanDump { + bool applied = false; + int copied = 0; + char log_line[96]{}; +}; + +// Writes mesh57__q_.bin and mesh57_.txt. +// `readable` is the dump path's readable(pointer, bytes) helper. +// `write` receives a file name, bytes, and size. It must not throw. +// A false `enabled` (dump directory unset) writes nothing. +template +Mesh57SpanDump dump_mesh57_spans(bool enabled, long index, const char* what, const std::uint64_t* words, + std::size_t nbytes, Readable&& readable, Write&& write) +{ + Mesh57SpanDump result; + if (!enabled || what == nullptr || std::strcmp(what, "pipeline") != 0 || nbytes != 0x300 || words == nullptr) + return result; + result.applied = true; + char listing[2048]; + std::size_t used = 0; + for (const Mesh57SpanSpec& spec : kMesh57SpanSpecs) { + const char* reason = "not_pointer"; + bool copy = false; + const void* data = nullptr; + if (static_cast(spec.start_q) >= nbytes / 8 || + static_cast(spec.length_q) >= nbytes / 8) { + reason = "desc_short"; + } else { + const std::uint64_t start = words[spec.start_q]; + const std::uint64_t length = words[spec.length_q]; + if (!mesh57_span_is_pointer(start)) { + reason = "not_pointer"; + } else if (length != spec.expected) { + reason = "length_mismatch"; + } else if (!mesh57_span_length_allowed(length)) { + reason = "length_range"; + } else { + const void* pointer = reinterpret_cast(static_cast(start)); + const auto bytes = static_cast(length); + if (!readable(pointer, bytes)) { + reason = "not_readable"; + } else { + copy = true; + reason = "copied"; + data = pointer; + } + } + } + if (copy && data != nullptr) { + char name[80]; + const int n = std::snprintf(name, sizeof(name), "mesh57_%04ld_q%d_%llu.bin", index, spec.start_q, + static_cast(spec.expected)); + if (n > 0 && static_cast(n) < sizeof(name)) { + write(name, data, static_cast(spec.expected)); + ++result.copied; + } else { + copy = false; + reason = "name"; + } + } + if (used < sizeof(listing)) { + const int wrote = std::snprintf(listing + used, sizeof(listing) - used, "%d %d %llu %s %s\n", spec.start_q, + spec.length_q, static_cast(spec.expected), + copy ? "yes" : "no", reason); + if (wrote > 0 && static_cast(wrote) < sizeof(listing) - used) + used += static_cast(wrote); + } + } + if (used > 0) { + char name[32]; + const int n = std::snprintf(name, sizeof(name), "mesh57_%04ld.txt", index); + if (n > 0 && static_cast(n) < sizeof(name)) + write(name, listing, used); + } + std::snprintf(result.log_line, sizeof(result.log_line), "x2w-pso mesh57 spans index=%ld copied=%d", index, + result.copied); + return result; +} + +} // namespace x2w_startup diff --git a/tests/mesh57_span_dump_check.cpp b/tests/mesh57_span_dump_check.cpp new file mode 100644 index 0000000000..82e3bf49f0 --- /dev/null +++ b/tests/mesh57_span_dump_check.cpp @@ -0,0 +1,461 @@ +// Synthetic slot 57 descriptor. No title bytes. The dump rules live in mesh57_span_dump.h. +#include "startup_stubs/mesh57_span_dump.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +struct TempDir { + std::filesystem::path path; + TempDir() + { + std::mt19937_64 rng{std::random_device{}()}; + path = std::filesystem::temp_directory_path() / ("mesh57-span-" + std::to_string(rng())); + std::filesystem::create_directories(path); + } + ~TempDir() + { + std::error_code ec; + std::filesystem::remove_all(path, ec); + } +}; + +struct Fixture { + std::vector words = std::vector(96, 0); + std::vector> storage; + std::map> by_q; + std::map readable_bytes; + bool bad_readable = false; + + Fixture() { storage.reserve(32); } + + std::uint64_t place(int q, std::size_t n, unsigned char tag, std::size_t readable_n) + { + std::vector bytes(n); + for (std::size_t i = 0; i < n; ++i) + bytes[i] = static_cast(tag + static_cast(i)); + storage.push_back(std::move(bytes)); + const auto& buf = storage.back(); + const auto address = reinterpret_cast(buf.data()); + readable_bytes[address] = readable_n; + by_q[q] = buf; + return static_cast(address); + } +}; + +int g_fails = 0; + +void fail(const char* scenario, const char* why) +{ + std::fprintf(stderr, "mesh57 span dump: %s: %s\n", scenario, why); + ++g_fails; +} + +bool place_span(const char* scenario, Fixture& f, int q, int length_q, bool write_length, std::size_t n, + unsigned char tag, std::size_t readable_n) +{ + const auto address = f.place(q, n, tag, readable_n); + if (!x2w_startup::mesh57_span_is_pointer(address)) { + fail(scenario, "synthetic target is outside is_pointer"); + return false; + } + f.words[static_cast(q)] = address; + if (write_length) + f.words[static_cast(length_q)] = n; + return true; +} + +bool build(const char* scenario, Fixture& f) +{ + unsigned char tag = 1; + for (const auto& spec : x2w_startup::kMesh57SpanSpecs) { + if (!place_span(scenario, f, spec.start_q, spec.length_q, true, static_cast(spec.expected), tag, + static_cast(spec.expected))) + return false; + ++tag; + } + // Same pointer-plus-length shape as the measured pairs, on qwords this path must not copy. + const int decoys[][2] = {{1, 720}, {3, 1264}, {5, 80}, {13, 1392}}; + for (const auto& decoy : decoys) { + if (!place_span(scenario, f, decoy[0], decoy[0] + 1, true, static_cast(decoy[1]), tag, + static_cast(decoy[1]))) + return false; + ++tag; + } + // Large cluster: pointers with no adjacent small length. q37 and q81 are pointers, not lengths. + if (!place_span(scenario, f, 36, 0, false, 1540, tag, 1540)) + return false; + ++tag; + if (!place_span(scenario, f, 37, 0, false, 64, tag, 64)) + return false; + ++tag; + if (!place_span(scenario, f, 80, 0, false, 2260, tag, 2260)) + return false; + ++tag; + if (!place_span(scenario, f, 81, 0, false, 100, tag, 100)) + return false; + ++tag; + if (!place_span(scenario, f, 95, 0, false, 32, tag, 32)) + return false; + const std::uint32_t mark = 1; + auto* raw = reinterpret_cast(f.words.data()); + std::memcpy(raw + 0x110, &mark, sizeof(mark)); + std::memcpy(raw + 0x270, &mark, sizeof(mark)); + return true; +} + +bool leak(const std::string& text, const Fixture& f) +{ + if (text.find("0x") != std::string::npos) + return true; + for (const auto& region : f.readable_bytes) { + char hex[32]; + char dec[32]; + std::snprintf(hex, sizeof(hex), "%llx", static_cast(region.first)); + std::snprintf(dec, sizeof(dec), "%llu", static_cast(region.first)); + if (text.find(hex) != std::string::npos || text.find(dec) != std::string::npos) + return true; + } + return false; +} + +std::string read_text(const std::filesystem::path& path) +{ + std::ifstream in(path, std::ios::binary); + return std::string(std::istreambuf_iterator(in), std::istreambuf_iterator()); +} + +bool run_case(const char* scenario, Fixture& f, bool enabled, const char* what, std::size_t bytes, long index, + const std::vector& copy_qs, const std::map& reasons) +{ + const int fails_before = g_fails; + TempDir dir; + f.bad_readable = false; + auto before = f.words; + auto readable = [&](const void* p, std::size_t n) { + if (!p || n == 0) { + f.bad_readable = true; + return false; + } + const auto address = reinterpret_cast(p); + const auto it = f.readable_bytes.find(address); + if (it == f.readable_bytes.end()) { + f.bad_readable = true; + return false; + } + return n <= it->second; + }; + bool write_failed = false; + auto write = [&](const char* name, const void* data, std::size_t size) { + if (!name || !data || std::strchr(name, '/') || std::strchr(name, '\\')) { + write_failed = true; + return; + } + std::ofstream out(dir.path / name, std::ios::binary); + out.write(static_cast(data), static_cast(size)); + if (!out) + write_failed = true; + }; + const auto result = x2w_startup::dump_mesh57_spans(enabled, index, what, f.words.data(), bytes, readable, write); + if (f.words != before) + fail(scenario, "descriptor was modified"); + if (f.bad_readable) + fail(scenario, "readable called for a pointer that is not a placed target"); + if (write_failed) + fail(scenario, "span write failed"); + if (!enabled || what == nullptr || std::strcmp(what, "pipeline") != 0 || bytes != 0x300) { + if (result.applied || result.copied != 0 || result.log_line[0] != 0) + fail(scenario, "dump ran without a pipeline 0x300 directory"); + if (!std::filesystem::is_empty(dir.path)) + fail(scenario, "span files written when the dump does not apply"); + return g_fails == fails_before; + } + if (!result.applied) + fail(scenario, "pipeline 0x300 dump did not apply"); + char expect_log[96]; + std::snprintf(expect_log, sizeof(expect_log), "x2w-pso mesh57 spans index=%ld copied=%d", index, + static_cast(copy_qs.size())); + if (std::strcmp(result.log_line, expect_log) != 0 || result.copied != static_cast(copy_qs.size())) + fail(scenario, "log line"); + if (leak(result.log_line, f)) + fail(scenario, "log contains a pointer"); + + std::map expect_names; + std::string expect_txt; + for (const auto& spec : x2w_startup::kMesh57SpanSpecs) { + const auto reason_it = reasons.find(spec.start_q); + const char* reason = reason_it == reasons.end() ? "copied" : reason_it->second; + const bool copied = std::strcmp(reason, "copied") == 0; + char line[80]; + std::snprintf(line, sizeof(line), "%d %d %llu %s %s\n", spec.start_q, spec.length_q, + static_cast(spec.expected), copied ? "yes" : "no", reason); + expect_txt += line; + if (!copied) + continue; + char name[80]; + std::snprintf(name, sizeof(name), "mesh57_%04ld_q%d_%llu.bin", index, spec.start_q, + static_cast(spec.expected)); + expect_names[name] = spec.start_q; + } + char txt_name[32]; + std::snprintf(txt_name, sizeof(txt_name), "mesh57_%04ld.txt", index); + expect_names[txt_name] = -1; + + std::map found; + for (const auto& ent : std::filesystem::directory_iterator(dir.path)) + found[ent.path().filename().string()] = ent.path(); + for (const auto& item : found) { + if (!expect_names.count(item.first)) + std::fprintf(stderr, "mesh57 span dump: %s: extra %s\n", scenario, item.first.c_str()); + } + for (const auto& item : expect_names) { + if (!found.count(item.first)) + std::fprintf(stderr, "mesh57 span dump: %s: missing %s\n", scenario, item.first.c_str()); + } + if (found.size() != expect_names.size()) + fail(scenario, "span file set"); + + const std::size_t forbidden[] = {32, 64, 100, 768, 1540, 2260, 4096}; + for (const auto& item : found) { + const auto sz = std::filesystem::file_size(item.second); + for (const auto bad : forbidden) { + if (sz == bad) + fail(scenario, "forbidden span size"); + } + const auto named = expect_names.find(item.first); + if (named == expect_names.end()) + continue; + const int q = named->second; + if (q < 0) { + const auto text = read_text(item.second); + if (text != expect_txt) + fail(scenario, "span listing"); + if (leak(text, f)) + fail(scenario, "listing contains a pointer"); + continue; + } + const auto& want = f.by_q[q]; + const auto got = read_text(item.second); + if (got.size() != want.size() || std::memcmp(got.data(), want.data(), want.size()) != 0) + fail(scenario, "span bytes"); + } + for (const char* banned : {"q95", "q36", "q37", "q80", "q81", "q1_", "q3_", "q5_", "q13_"}) { + for (const auto& item : found) { + if (item.first.find(banned) != std::string::npos) + fail(scenario, "unlisted qword was copied"); + } + } + return g_fails == fails_before; +} + +bool predicates(const char* scenario) +{ + const int before = g_fails; + if (x2w_startup::mesh57_span_is_pointer(0) || x2w_startup::mesh57_span_is_pointer(0xffffull) || + x2w_startup::mesh57_span_is_pointer(0x800000000000ull) || !x2w_startup::mesh57_span_is_pointer(0x10000ull) || + !x2w_startup::mesh57_span_is_pointer(0x7fffffffffffull)) + fail(scenario, "is_pointer bounds"); + if (x2w_startup::mesh57_span_length_allowed(0) || !x2w_startup::mesh57_span_length_allowed(1) || + !x2w_startup::mesh57_span_length_allowed(64ull * 1024ull) || + x2w_startup::mesh57_span_length_allowed(64ull * 1024ull + 1) || + !x2w_startup::mesh57_span_length_allowed(720) || !x2w_startup::mesh57_span_length_allowed(10368)) + fail(scenario, "length range"); + return g_fails == before; +} + +int count_sub(const std::string& text, const char* needle) +{ + int n = 0; + const auto len = std::strlen(needle); + for (std::size_t pos = 0; (pos = text.find(needle, pos)) != std::string::npos; pos += len) + ++n; + return n; +} + +bool source_contract(const char* scenario, const char* root) +{ + const int before = g_fails; + if (!root) { + fail(scenario, "source root"); + return false; + } + const auto text = read_text(std::filesystem::path(root) / "src/startup_stubs/d3d12_xs_device.cpp"); + if (text.empty()) { + fail(scenario, "device source"); + return false; + } + const char* call = "if constexpr (N == 57) dump_containers(\"pipeline\", desc, 0x300);"; + const char* after = "dump_pipeline(\"pipeline\", N, desc, 0x300);\n if constexpr (N == 57) " + "dump_containers(\"pipeline\", desc, 0x300);"; + if (count_sub(text, call) != 1 || count_sub(text, after) != 1) + fail(scenario, "slot 57 dump_containers call"); + if (count_sub(text, "dump_containers(") != 4 || count_sub(text, "dump_containers(\"pipeline\"") != 1 || + count_sub(text, "dump_containers(\"compute\"") != 1 || count_sub(text, "dump_containers(\"stream\"") != 1) + fail(scenario, "dump_containers call sites"); + const auto early = text.find("if (!desc || !shader_dump_dir(dir, MAX_PATH)"); + const auto spans = text.find("dump_mesh57_spans"); + if (early == std::string::npos || spans == std::string::npos || early > spans) + fail(scenario, "span copy is not behind the dump directory check"); + if (count_sub(text, "first_calls(mesh57_span_logs, 4)") != 1 || count_sub(text, "log(\"%s\", spans.log_line)") != 1) + fail(scenario, "span log cap"); + return g_fails == before; +} + +bool scenario_unset() +{ + const char* scenario = "unset"; + Fixture f; + if (!build(scenario, f)) + return false; + const bool ok = run_case(scenario, f, false, "pipeline", 0x300, 3, {}, {}); + if (ok) + std::printf("mesh57 span dump: unset ok\n"); + return ok; +} + +bool scenario_copied() +{ + const char* scenario = "copied"; + Fixture f; + if (!build(scenario, f)) + return false; + std::vector qs; + for (const auto& spec : x2w_startup::kMesh57SpanSpecs) + qs.push_back(spec.start_q); + const bool ok = run_case(scenario, f, true, "pipeline", 0x300, 3, qs, {}); + if (ok) + std::printf("mesh57 span dump: copied ok\n"); + return ok; +} + +bool scenario_mismatch() +{ + const char* scenario = "mismatch"; + Fixture f; + if (!build(scenario, f)) + return false; + f.words[16] = 1263; + std::vector qs; + for (const auto& spec : x2w_startup::kMesh57SpanSpecs) + if (spec.start_q != 15) + qs.push_back(spec.start_q); + const bool ok = run_case(scenario, f, true, "pipeline", 0x300, 3, qs, {{15, "length_mismatch"}}); + if (ok) + std::printf("mesh57 span dump: mismatch ok\n"); + return ok; +} + +bool scenario_not_pointer() +{ + const char* scenario = "not-pointer"; + const std::uint64_t values[] = {0, 0xffffull, 0x800000000000ull}; + for (const auto value : values) { + Fixture f; + if (!build(scenario, f)) + return false; + f.words[7] = value; + std::vector qs; + for (const auto& spec : x2w_startup::kMesh57SpanSpecs) + if (spec.start_q != 7) + qs.push_back(spec.start_q); + if (!run_case(scenario, f, true, "pipeline", 0x300, 3, qs, {{7, "not_pointer"}})) + return false; + } + std::printf("mesh57 span dump: not-pointer ok\n"); + return true; +} + +bool scenario_not_readable() +{ + const char* scenario = "not-readable"; + Fixture f; + if (!build(scenario, f)) + return false; + const auto address = static_cast(f.words[51]); + if (f.readable_bytes[address] != 656) { + fail(scenario, "q51 length"); + return false; + } + f.readable_bytes[address] = 655; + std::vector qs; + for (const auto& spec : x2w_startup::kMesh57SpanSpecs) + if (spec.start_q != 51) + qs.push_back(spec.start_q); + const bool ok = run_case(scenario, f, true, "pipeline", 0x300, 3, qs, {{51, "not_readable"}}); + if (ok) + std::printf("mesh57 span dump: not-readable ok\n"); + return ok; +} + +bool scenario_other(const char* root) +{ + const char* scenario = "other"; + if (!predicates(scenario)) + return false; + Fixture f; + if (!build(scenario, f)) + return false; + const char* wrong_what[] = {"compute", "stream", "Pipeline", "pipeline ", ""}; + for (const char* what : wrong_what) { + if (!run_case(scenario, f, true, what, 0x300, 3, {}, {})) + return false; + } + if (!run_case(scenario, f, true, nullptr, 0x300, 3, {}, {})) + return false; + const std::size_t wrong_size[] = {0, 0x2ff, 0x301, 0x400}; + for (const auto size : wrong_size) { + if (!run_case(scenario, f, true, "pipeline", size, 3, {}, {})) + return false; + } + if (!source_contract(scenario, root)) + return false; + std::printf("mesh57 span dump: other ok\n"); + return true; +} + +} // namespace + +int main(int argc, char** argv) +{ + const char* scenario = argc > 1 ? argv[1] : "all"; + const char* root = argc > 2 ? argv[2] : nullptr; + try { + bool ok = true; + if (std::strcmp(scenario, "all") == 0) { + ok = scenario_unset() && ok; + ok = scenario_copied() && ok; + ok = scenario_mismatch() && ok; + ok = scenario_not_pointer() && ok; + ok = scenario_not_readable() && ok; + ok = scenario_other(root) && ok; + } else if (std::strcmp(scenario, "unset") == 0) { + ok = scenario_unset(); + } else if (std::strcmp(scenario, "copied") == 0) { + ok = scenario_copied(); + } else if (std::strcmp(scenario, "mismatch") == 0) { + ok = scenario_mismatch(); + } else if (std::strcmp(scenario, "not-pointer") == 0) { + ok = scenario_not_pointer(); + } else if (std::strcmp(scenario, "not-readable") == 0) { + ok = scenario_not_readable(); + } else if (std::strcmp(scenario, "other") == 0) { + ok = scenario_other(root); + } else { + std::fprintf(stderr, "mesh57 span dump: unknown scenario\n"); + return 2; + } + return ok && g_fails == 0 ? 0 : 1; + } catch (const std::exception&) { + std::fprintf(stderr, "mesh57 span dump: exception\n"); + return 1; + } +} diff --git a/tools/startup/mesh57_span_report.py b/tools/startup/mesh57_span_report.py new file mode 100644 index 0000000000..b3119ffcf0 --- /dev/null +++ b/tools/startup/mesh57_span_report.py @@ -0,0 +1,429 @@ +#!/usr/bin/env python3 +"""Report measured slot 57 span files. + +Reads mesh57__q_.bin from one directory. Prints the file +size, a known container magic name, and whether the guest shader container +layout identifies MS I/O. The three counts and topology are printed only when +that layout identifies exactly one distinct MS I/O. This tool does not write a +profile and it is not called by the runtime. + +usage: mesh57_span_report.py + mesh57_span_report.py --self-test +""" + +from __future__ import annotations + +import struct +import sys +import tempfile +import zlib +from pathlib import Path + +# Magics guest_shader_container.cpp already recognizes. Printed as names only. +KNOWN_MAGIC = ( + b"DXBC", + b"HASH", + b"PSV0", + b"ISG1", + b"ISGN", + b"OSG1", + b"OSGN", + b"DXIL", + b"XDAT", + b"XBCH", + b"FSSM", +) +STAGE_OFFSETS = (8, 16, 24, 32, 40, 48, 72, 96) +DEAD = 0xDEADBEEFDEADBEEF +MS = 6 + + +class LayoutError(Exception): + pass + + +def u8(buf, off): + if off < 0 or off >= len(buf): + raise LayoutError("short") + return buf[off] + + +def u32(buf, off): + if off < 0 or off + 4 > len(buf): + raise LayoutError("short") + return struct.unpack_from(" len(buf): + raise LayoutError("short") + return struct.unpack_from(" len(buf): + raise LayoutError("short") + return struct.unpack_from(" len(buf): + raise LayoutError("outside") + return buf[off : off + size] + + +def graphics_io(stage, io, code): + def attributes(offset, size, count_at): + count = u32(io, count_at) + if count > 32: + raise LayoutError("too many native shader attributes") + slice_at(io, offset, count * size) + + if stage == 5: + attributes(0x24, 8, 0x124) + u32(io, 0x134) + u32(io, 0x138) + words = u32(io, 0x148) + if words > 10: + raise LayoutError("invalid pixel export patch size") + exports = [] + for mrt in range(8): + at = 0x14C + mrt * 404 + where = u32(io, at) + if where == 0xFFFFFFFF: + continue + slice_at(code, where * 4, 4 * words) + for other_where, other_words in exports: + if words and where < other_where + other_words and other_where < where + words: + raise LayoutError("overlapping pixel export patches") + slice_at(io, at + 4 + 360, 4 * words) + exports.append((where, words)) + return None + attributes(0x24, 5, 0xC4) + attributes(0xC8, 6, 0x188) + if stage == MS: + u32(io, 0x194) + return (u16(io, 0x448), u16(io, 0x44A), u16(io, 0x44C), u8(io, 0x44F)) + return None + + +def parse_native(packed, total): + if slice_at(packed, 0, 4) != b"XBCH" or u32(packed, 4) != 3: + raise LayoutError("unsupported native blob version") + payload = slice_at(packed, 24, u64(packed, 8)) + size = u64(packed, 16) + if size < 16 or size > (16 << 20) or total[0] + size > (64 << 20): + raise LayoutError("native stage size out of range") + total[0] += size + try: + inflated = zlib.decompress(payload) + except zlib.error as exc: + raise LayoutError("native stage inflation failed") from exc + if len(inflated) != size: + raise LayoutError("native stage inflation failed") + if slice_at(inflated, 0, 4) != b"FSSM" or u32(inflated, 4) != 0x101 or u64(inflated, 8) != size - 16: + raise LayoutError("invalid FSSM header") + body = slice_at(inflated, 16, size - 16) + if u64(body, 0) != 6: + raise LayoutError("unknown FSSM slot layout") + found = [] + for stage, at in enumerate(STAGE_OFFSETS): + off = u64(body, at) + if off == DEAD: + continue + record = slice_at(body, off, 84) + if (u32(record, 80) & 1023) > 256: + raise LayoutError("invalid native register count") + code = slice_at(body, u64(record, 0), u64(record, 8)) + if len(code) > (1 << 20) or not code or len(code) % 4: + raise LayoutError("invalid native code size") + for part in (0, 1): + count = u32(record, 56 + part * 4) + if not count: + continue + if count > 65536: + raise LayoutError("native resource layout too large") + slice_at(body, u64(record, 40 + part * 8), count * 20) + if stage == 7: + slice_at(body, off + 84 + 36, 16) + if stage in (4, 5, MS): + io = graphics_io(stage, body[off + 84 :], code) + if stage == MS: + found.append(io) + return found + + +def parse_dxbc(blob): + if slice_at(blob, 0, 4) != b"DXBC" or u32(blob, 24) != len(blob): + raise LayoutError("invalid DXBC length") + count = u32(blob, 28) + if count > 4096: + raise LayoutError("invalid DXBC part count") + offsets = slice_at(blob, 32, 4 * count) + found = [] + total = [0] + for index in range(count): + part = u32(offsets, 4 * index) + data = slice_at(blob, part + 8, u32(blob, part + 4)) + kind = slice_at(blob, part, 4) + if kind != b"DXIL" or len(data) < 36 or data[24:28] != b"XDAT": + continue + entries = u32(data, 28) + if entries > 64: + raise LayoutError("invalid XDAT entry count") + table = slice_at(data, 36, 12 * entries) + for row_at in range(0, 12 * entries, 12): + row = table[row_at : row_at + 12] + if u32(row, 0) != 13: + continue + chunk = slice_at(data, u32(row, 4), u32(row, 8)) + found.extend(parse_native(chunk, total)) + return found + + +def magic_name(data): + if len(data) < 4 or data[:4] not in KNOWN_MAGIC: + return "unknown" + return data[:4].decode("ascii") + + +def ms_records(data): + """Return ('ok', tuples), ('none', ()), or ('unidentified', ()).""" + if len(data) < 4 or data[:4] not in (b"DXBC", b"XBCH"): + return "none", () + try: + found = parse_dxbc(data) if data[:4] == b"DXBC" else parse_native(data, [0]) + except LayoutError: + return "unidentified", () + if not found: + return "none", () + if any(item is None for item in found): + return "unidentified", () + return "ok", tuple(found) + + +def span_files(directory): + files = [] + for path in directory.iterdir(): + name = path.name + if not path.is_file() or not name.startswith("mesh57_") or "_q" not in name or not name.endswith(".bin"): + continue + files.append(path) + return sorted(files, key=lambda item: item.name) + + +def report_directory(directory): + files = span_files(directory) + tuples = [] + unidentified = False + lines = [] + for path in files: + data = path.read_bytes() + status, found = ms_records(data) + if status == "unidentified": + unidentified = True + label = "unidentified" + elif status == "none": + label = "0" + elif len(found) == 1: + label = "1" + tuples.append(found[0]) + else: + label = "many" + tuples.extend(found) + lines.append(f"{path.name} size={len(data)} magic={magic_name(data)} ms_io={label}") + distinct = set(tuples) + if unidentified or len(distinct) != 1: + summary = "ms_io unidentified" if unidentified or distinct else "ms_io none" + else: + threads, vertices, primitives, topology = next(iter(distinct)) + summary = f"ms_io threads={threads} vertices={vertices} primitives={primitives} topology={topology}" + sys.stdout.write("\n".join(lines + [summary]) + "\n") + return 0 + + +def _xbch(threads, vertices, primitives, topology, code=b"\0\0\0\0"): + if not code or len(code) % 4: + raise ValueError("code") + record_off = 104 + io_off = record_off + 84 + code_off = io_off + 0x450 + body = bytearray(code_off + len(code)) + struct.pack_into("", file=sys.stderr) + return 2 + directory = Path(argv[1]) + if not directory.is_dir(): + print("mesh57 span report: span directory is missing", file=sys.stderr) + return 1 + return report_directory(directory) + + +if __name__ == "__main__": + sys.exit(main(sys.argv)) From eefab5d90c6c0bf2f7f27ecf5ba9c1773f24baa0 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Mon, 30 Nov 2026 14:08:51 +0000 Subject: [PATCH 13/24] startup: opt-in slot 57 mesh bounds from the record allocation X2W_MESH57_DERIVED_BOUNDS=1 reads an m0 built by s_lshl and s_or immediately before GS_ALLOC_REQ. The vertex and primitive limits are the record masks plus one, times 2^k, and only when k is 1. The group is the smallest multiple of 64 that covers that limit, matching the direct mesh lane index. SetMeshOutputCounts uses the runtime counts. The immediate m0 reader is unchanged, and the switch defaults off. --- CMakeLists.txt | 5 + docs/experiments/native-fixed-mesh57.md | 20 + docs/startup-runtime.md | 1 + src/gfx1013_compute_native.h | 4 + src/gfx1013_direct_mesh.inl | 74 +++- src/startup_stubs/mesh57_alloc.h | 526 +++++++++++++++++++++++- src/startup_stubs/native_mesh57.inl | 94 ++++- tests/mesh57_record_bounds_check.cpp | 226 ++++++++++ 8 files changed, 941 insertions(+), 9 deletions(-) create mode 100644 tests/mesh57_record_bounds_check.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index c5955d5625..7c3d199d37 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1952,6 +1952,11 @@ target_include_directories(mesh57_derive_alloc_check PRIVATE src src/startup_stu target_compile_features(mesh57_derive_alloc_check PRIVATE cxx_std_17) add_test(NAME mesh57_derive_alloc COMMAND mesh57_derive_alloc_check) +add_executable(mesh57_record_bounds_check tests/mesh57_record_bounds_check.cpp src/gfx1013_isa.cpp) +target_include_directories(mesh57_record_bounds_check PRIVATE src src/startup_stubs) +target_compile_features(mesh57_record_bounds_check PRIVATE cxx_std_17) +add_test(NAME mesh57_record_bounds COMMAND mesh57_record_bounds_check) + add_executable(mesh57_span_dump_check tests/mesh57_span_dump_check.cpp) target_include_directories(mesh57_span_dump_check PRIVATE src) target_compile_features(mesh57_span_dump_check PRIVATE cxx_std_17) diff --git a/docs/experiments/native-fixed-mesh57.md b/docs/experiments/native-fixed-mesh57.md index 149d5ab7e5..77023d552f 100644 --- a/docs/experiments/native-fixed-mesh57.md +++ b/docs/experiments/native-fixed-mesh57.md @@ -152,4 +152,24 @@ On the Windows test PC at `35b0d542`, the same switches, a 420 second run, forwa `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`. +## Opt-in record bounds + +`X2W_MESH57_DERIVED_BOUNDS=1` is a second switch, off by default, and it does nothing unless `X2W_MESH57_DERIVE_STATE=1` is also set. Unset, slot 57 derivation is unchanged, including the heap-indexed root refusal and the immediate `m0` reader. + +Set, `mesh57_read_record_m0_bounds` may supply the output limit for a program the immediate reader refuses. The program has one `s_sendmsg` `GS_ALLOC_REQ`. The two instructions immediately before it are `s_lshl_b32 sX, sP, 12` and `s_or_b32 m0, sX, sV` (either operand order of the `or`). `sV` and `sP` are each `(field & mask) + 1` from one record word: the vertex field is the low mask and the primitive field is that word shifted by the mask width. A `v_readfirstlane` of that sum, and an `s_cselect_b32` of the count against immediate 0, still count as the same value. The per-record maximum is `mask + 1`. + +The entry multiply `k` is accepted only when the caller passes the constant 1. That is the measured entry state for this switch. The reader does not load user data 13, and it does not assign user SGPRs for the five-parameter heap-indexed root. An unknown `k` is `derived mesh record multiply k is unknown`. Any other `k` is `derived mesh record multiply k is not 1`. The limit is the per-record maximum times `2^k`. A product above 256 vertices or 256 primitives is `derived mesh record bound exceeds the mesh output limit`. A 7-bit mask and `k` 1 is 256, which is the D3D12 mesh output limit, so it is accepted. + +The group size comes from `gfx1013_direct_mesh.inl`. That lowerer indexes each vertex and each primitive with `flattenedThreadIdInGroup`, splits a wave64 id into `lane = id & 63` and `wave = id >> 6`, and skips the write when the id is at or past the runtime count. One thread emits one output. The group is the smallest multiple of 64 that covers the larger derived limit: 256 for the 7-bit, `k` 1 case, and 128 for a 6-bit mask. A program with no wave64 proof is refused rather than given a guessed wave width. The direct mesh path allows that group only when this layout sets `record_output_counts`. Every other mesh keeps the 128-thread check. A desktop compiler can still refuse `numthreads` of 256; this path does not lower the group to 128 to hide that. + +`SetMeshOutputCounts` receives the runtime vertex and primitive registers, each limited to the derived maximum, and both become 0 when either is 0. Outputs past the runtime count are not written. The static bound sizes the output arrays. It is not substituted when the registers are unproven. + +The first time a distinct pair is derived this way, stderr gets one `x2w-render mesh57-derive bounds` line: mesh and pixel byte counts, `v`, `p`, `threads`, `pattern=record-m0`, and `k`. The line has no pointer. At most eight distinct lines are kept. The global on-chip budget in the pipeline register block is not a per-shader size and is not read here. + +`mesh57_record_bounds` checks the assembled pattern: the 7-bit limit, the 6-bit limit, an unknown `k`, a `k` other than 1, a mask whose product exceeds 256, the immediate triangle (3 vertices, 1 primitive, 64 threads), and that the immediate reader still refuses the record program. It does not need a device. + +```powershell +ctest --preset dev --no-tests=error -R 'mesh57_record_bounds|mesh57_derive_alloc' +``` + 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 26605d6798..07d94187ce 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -1804,6 +1804,7 @@ ctest --preset dev --no-tests=error -R '^startup_hook_(window|overlap)$' -V | `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 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_MESH57_DERIVED_BOUNDS=1` | experimental, with `X2W_MESH57_DERIVE_STATE=1`. Off by default, and unset it leaves the slot 57 derivation unchanged. Set, a mesh whose `m0` is `s_lshl_b32` by 12 then `s_or_b32` into `m0` immediately before the only `GS_ALLOC_REQ`, with both counts proven as `(field & mask) + 1` from one record word, may use those masks as the output limit. The multiply is `2^k` only when the entry `k` is the constant 1; an unknown `k` or any other `k` stays refused. A product above 256 vertices or 256 primitives stays refused. The group is the smallest multiple of 64 that covers that limit, from the direct mesh lane id (one thread writes one output). The translated shader passes the runtime counts to `SetMeshOutputCounts`. The immediate `m0` reader is unchanged. This switch does not invent a user-SGPR map for a heap-indexed root. See [Opt-in record bounds](experiments/native-fixed-mesh57.md#opt-in-record-bounds) | | `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/gfx1013_compute_native.h b/src/gfx1013_compute_native.h index 136b2fc754..0fb46a7f74 100644 --- a/src/gfx1013_compute_native.h +++ b/src/gfx1013_compute_native.h @@ -220,6 +220,10 @@ struct MeshStageLayout { std::optional resource_heap_sgpr{}; bool validate_uint_heap_reads{}; bool packed_parameters{}; + // Set only by the X2W_MESH57_DERIVED_BOUNDS path. GS_ALLOC_REQ then passes the + // runtime vertex and primitive registers to SetMeshOutputCounts. Left false, + // lower_mesh keeps the immediate m0 allocation. + bool record_output_counts = false; }; NativeComputeShader translate_mesh_pixel_program(std::string_view code, unsigned enable, unsigned address, unsigned wave_size, const D3D12_ROOT_SIGNATURE_DESC1 *root = nullptr); diff --git a/src/gfx1013_direct_mesh.inl b/src/gfx1013_direct_mesh.inl index d768b61ac1..501490fb24 100644 --- a/src/gfx1013_direct_mesh.inl +++ b/src/gfx1013_direct_mesh.inl @@ -4,7 +4,13 @@ NativeComputeShader lower_mesh(const string &code, const MeshStageLayout &layout, const GuestShaderStage *reflected = nullptr, const D3D12_ROOT_SIGNATURE_DESC1 &root = {}) { - if (!layout.threads || layout.threads > 128 || !layout.max_vertices || layout.max_vertices > 256 || + // record_output_counts is the opt-in record-m0 path. Its group is a whole number of + // wave64 waves, up to the D3D12 vertex limit, because each thread writes one output. + // Every other mesh keeps the 128-thread group check. + const unsigned thread_cap = layout.record_output_counts ? 256u : 128u; + if (layout.record_output_counts && layout.threads % 64u) + refuse(0,"mesh record group is not a whole number of wave64 waves"); + if (!layout.threads || layout.threads > thread_cap || !layout.max_vertices || layout.max_vertices > 256 || !layout.max_primitives || layout.max_primitives > 256 || layout.topology != 2 || code.empty() || code.size() % 4) refuse(0,"unsupported mesh group, output dimensions or topology"); @@ -113,6 +119,13 @@ NativeComputeShader lower_mesh(const string &code, const MeshStageLayout &layout bool full_exec = true, allocated = false, position = false, indices = false; std::set parameter_exports; std::optional allocation_word; + // s_lshl by 12 immediately followed by s_or into m0. Used only when record_output_counts is set. + struct RecordM0 { + bool shift = false; + bool joined = false; + unsigned shift_end = 0, shift_dst = 0, shift_src = 0; + unsigned or_at = 0, or_end = 0, or_a = 0, or_b = 0; + } record_m0; unsigned vertices = 0, primitives = 0; string vertex_count, primitive_count, export_limit; std::map upper_bound; @@ -495,6 +508,43 @@ NativeComputeShader lower_mesh(const string &code, const MeshStageLayout &layout continue; } if (raw==0xbf900009) { + if (layout.record_output_counts && record_m0.shift && record_m0.joined && + record_m0.shift_end == record_m0.or_at && record_m0.or_end == pc) { + const bool left = record_m0.or_a == record_m0.shift_dst; + const bool right = record_m0.or_b == record_m0.shift_dst; + if (allocated || left == right) + refuse(pc,"mesh record allocation does not build m0 from the shifted primitive count"); + const unsigned preg = record_m0.shift_src; + const unsigned vreg = left ? record_m0.or_b : record_m0.or_a; + if (preg >= 106 || vreg >= 106 || preg == vreg || preg == record_m0.shift_dst || vreg == record_m0.shift_dst) + refuse(pc,"mesh record allocation counts are not scalar registers"); + const auto runtime_v = alu.read(vreg); + const auto runtime_p = alu.read(preg); + if (runtime_v.empty() || runtime_p.empty()) + refuse(pc,"mesh record allocation counts are not uniform"); + auto limited = [&](const string &value, unsigned cap) { + if (!cap || cap > 256) refuse(pc,"mesh record allocation has no output limit"); + const auto known = upper_bound.find(value); + if (known != upper_bound.end() && known->second > cap) + refuse(pc,"mesh record allocation exceeds declared lane-indexed output range"); + return alu.select(alu.cmp("ule", value, to_string(cap)), value, to_string(cap)); + }; + const unsigned vertex_cap = (std::min)(layout.max_vertices, layout.threads); + const unsigned primitive_cap = (std::min)(layout.max_primitives, layout.threads); + auto vv = limited(runtime_v, vertex_cap); + auto pp = limited(runtime_p, primitive_cap); + // The guest cselect clears both counts when either is zero. Applying it again + // is the same result when the registers already hold that select. + const auto clear = ir.value("or i1 " + alu.cmp("eq", vv, "0") + ", " + alu.cmp("eq", pp, "0")); + vv = alu.select(clear, "0", vv); + pp = alu.select(clear, "0", pp); + ir.invoke("void","setMeshOutputCounts",168,{{"i32",vv},{"i32",pp}},"nounwind"); + vertex_count = vv; + primitive_count = pp; + allocated = true; + pc += 4; + continue; + } if (allocated || !allocation_word) refuse(pc,"mesh allocation requires one uniform, bounded m0 count word"); vertices=*allocation_word & 4095; primitives=(*allocation_word>>12)&4095; if ((*allocation_word>>24) || vertices>layout.max_vertices || primitives>layout.max_primitives || @@ -1077,8 +1127,30 @@ NativeComputeShader lower_mesh(const string &code, const MeshStageLayout &layout const bool high=i.name=="s_pack_hh_b32_b16"; alu.write(i.dst,ir.binary("or",high ? ir.binary("lshr",a,"16") : ir.binary("and",a,"65535"), high ? ir.binary("and",b,"4294901760") : ir.binary("shl",b,"16"))); + } else if (layout.record_output_counts && i.name=="s_or_b32" && i.dst==124 && i.src[0]<106 && i.src[1]<106) { + record_m0.joined = true; + record_m0.or_at = pc; + record_m0.or_end = i.next; + record_m0.or_a = i.src[0]; + record_m0.or_b = i.src[1]; + } else if (layout.record_output_counts && i.name=="s_cselect_b32" && i.dst<106) { + const auto taken = alu.operand32(i, i.src[0]); + const auto other = alu.operand32(i, i.src[1]); + const auto scc = alu.read(128); + const auto value = alu.select(alu.cmp("ne", scc, "0"), taken, other); + state = transfer(i, state, !layout.wave32, true, false, true); + alu.write(i.dst, value); + alu.write(128, ir.value("zext i1 " + alu.cmp("ne", value, "0") + " to i32")); } else if (i.enc==Encoding::Sop2 && i.dst<106 && (i.name=="s_lshr_b32" || i.name=="s_lshl_b32" || i.name=="s_or_b32" || i.name=="s_and_b32")) { + if (layout.record_output_counts && i.name=="s_lshl_b32" && i.src[0]<106) { + if (const auto amount = constant32(i, i.src[1]); amount && *amount == 12u) { + record_m0.shift = true; + record_m0.shift_end = i.next; + record_m0.shift_dst = i.dst; + record_m0.shift_src = i.src[0]; + } + } const auto known=[&](unsigned r) { return constant32(i,r).has_value() || (alu.graphics_registers.count(r) && !alu.graphics_registers.at(r).empty()); diff --git a/src/startup_stubs/mesh57_alloc.h b/src/startup_stubs/mesh57_alloc.h index 12ea711b2b..8e931e8749 100644 --- a/src/startup_stubs/mesh57_alloc.h +++ b/src/startup_stubs/mesh57_alloc.h @@ -1,10 +1,12 @@ // 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 +// A reviewed .mesh57-state profile still owns the MS entry layout. mesh57_read_layout 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. +// mesh57_read_record_m0_bounds is a separate reader for m0 built by s_lshl and s_or. It does not +// change mesh57_read_layout. Callers use it only when X2W_MESH57_DERIVED_BOUNDS=1. #pragma once #include "gfx1013_isa.h" @@ -15,6 +17,7 @@ #include #include #include +#include namespace x2w_startup { @@ -200,6 +203,527 @@ inline std::optional derive_immediate_mesh_layout(std::string return mesh57_read_layout(code).layout; } +// Entry k for the record-m0 reader. k_known is false when the caller does not have +// user data 13 >> 29. The measured entry for the opt-in switch is k == 1; any other +// value is refused. This reader does not invent a k. +struct Mesh57RecordEntry { + bool k_known = false; + unsigned k = 0; +}; + +// Output limits taken from the per-meshlet record, after the multiply by 2^k. +// threads is the group size the direct mesh lane model needs for those limits. +struct Mesh57RecordBounds { + unsigned threads = 0; + unsigned vertices = 0; + unsigned primitives = 0; + unsigned topology = 2; + unsigned group_stride = 0; + unsigned wave_size = 64; + unsigned multiply_k = 0; + const char* pattern = "record-m0"; +}; + +struct Mesh57RecordBoundsRead { + std::optional bounds; + const char* reason = nullptr; +}; + +// Counts the translated shader passes to SetMeshOutputCounts. The bound sizes the +// output arrays. The emitted counts are the runtime values: each record field times +// the multiply factor, or zero when the guest cselect clears both because either +// count is zero. They are not replaced by the bound. +struct Mesh57EmitCounts { + unsigned vertices = 0; + unsigned primitives = 0; +}; + +inline Mesh57EmitCounts mesh57_runtime_mesh_counts(unsigned record_vertices, unsigned record_primitives, + unsigned multiply, bool either_zero) noexcept +{ + Mesh57EmitCounts out; + if (either_zero || multiply == 0 || record_vertices == 0 || record_primitives == 0) + return out; + out.vertices = record_vertices * multiply; + out.primitives = record_primitives * multiply; + return out; +} + +inline std::size_t mesh57_record_bounds_line(const Mesh57RecordBounds& bounds, unsigned mesh_bytes, + unsigned pixel_bytes, char* out, std::size_t cap) noexcept +{ + if (!out || cap == 0) + return 0; + const int n = std::snprintf(out, cap, + "x2w-render mesh57-derive bounds ms=%u ps=%u v=%u p=%u threads=%u pattern=%s k=%u", + mesh_bytes, pixel_bytes, bounds.vertices, bounds.primitives, bounds.threads, + bounds.pattern ? bounds.pattern : "", bounds.multiply_k); + if (n < 0) { + out[0] = 0; + return 0; + } + if (static_cast(n) >= cap) { + out[cap - 1] = 0; + return cap - 1; + } + return static_cast(n); +} + +// m0 built by s_lshl_b32 sX, sP, 12 and s_or_b32 m0, sX, sV immediately before the only +// s_sendmsg GS_ALLOC_REQ. sV and sP must each be (field & mask) + 1 from one record word: +// the vertex field is the low mask and the primitive field is that word shifted by the +// mask width. The per-record maximum is mask + 1. It is multiplied by 2^k only when the +// entry k is the constant 1; otherwise the program is refused. A product above the D3D12 +// mesh output limit (256 vertices, 256 primitives) is refused. +// +// Group size comes from gfx1013_direct_mesh.inl. That lowerer indexes every vertex and +// primitive by flattenedThreadIdInGroup, and it splits a wave64 thread as +// lane = id & 63, wave = id >> 6. The write is emitted only when id < the runtime count, +// so one thread emits one output. The group is therefore the smallest multiple of 64 +// that covers the larger derived bound. A program with no wave64 proof is refused +// rather than given a guessed wave width. mesh57_read_layout is not used here. +inline Mesh57RecordBoundsRead mesh57_read_record_m0_bounds(std::string_view code, + const Mesh57RecordEntry& entry) noexcept +{ + Mesh57RecordBoundsRead out; + out.reason = "derived mesh record allocation was not proven"; + if (code.empty() || code.size() % 4 != 0) + return out; + try { + struct Def { + unsigned kind = 0; // 1 mask, 2 add 1, 3 logical shift right, 4 copy, 5 unknown write + unsigned src = 0; + bool src_vector = false; + unsigned imm = 0; + unsigned width = 0; + }; + // Each write is kept, in order. A copy is read at the copy's own pc, so a later + // reuse of its source register does not erase the count that was moved. + struct Event { + unsigned pc = 0; + unsigned reg = 0; + bool is_vector = false; + Def def{}; + }; + std::vector events; + events.reserve(code.size() / 4u + 1u); + auto put = [&](unsigned at, bool is_vector, unsigned reg, Def def) { + if (is_vector ? reg >= 256u : reg >= 128u) + return; + events.push_back(Event{at, reg, is_vector, def}); + }; + auto wipe = [&](unsigned at, unsigned dst, bool pair) { + const Def unknown{5u, 0u, false, 0u, 0u}; + put(at, false, dst, unknown); + if (pair) + put(at, false, dst + 1u, unknown); + }; + struct Op { + std::string_view name; + unsigned dst = 0; + unsigned src0 = 0; + unsigned src1 = 0; + bool imm0 = false; + bool imm1 = false; + std::uint32_t v0 = 0; + std::uint32_t v1 = 0; + bool vector_dst = false; + }; + Op older{}; + Op newer{}; + bool older_ok = false; + bool newer_ok = false; + unsigned sends = 0; + unsigned send_pc = 0; + bool pattern = false; + unsigned vertex_reg = 0; + unsigned primitive_reg = 0; + bool wave32 = false; + bool wave64 = false; + bool triangle_export = false; + + auto low_mask = [](std::uint32_t imm, unsigned& width) noexcept { + if (!imm || (imm & (imm + 1u)) != 0) + return false; + width = 0; + for (std::uint32_t bit = 1; bit && (imm & bit); bit <<= 1) { + ++width; + if (bit > 0x7fffffffu) + break; + } + return width > 0 && width < 32 && imm == ((1u << width) - 1u); + }; + auto src_imm = [](unsigned src, bool has_literal, std::uint32_t literal, std::uint32_t& imm) noexcept { + if (src >= 128u && src <= 192u) { + imm = src - 128u; + return true; + } + if (src == 255u && has_literal) { + imm = literal; + return true; + } + return false; + }; + auto vgpr = [](unsigned src, unsigned& index) noexcept { + if (src < 256u || src >= 512u) + return false; + index = src - 256u; + return true; + }; + auto note_scalar_binary = [&](unsigned at, const Op& op) { + if (op.dst >= 128u) + return; + const bool pair = mesh57_scalar_result_is_64(op.name); + const bool reg0 = op.src0 < 106u; + const bool reg1 = op.src1 < 106u; + // Selecting the count or zero does not change the maximum. The other + // source has to be the immediate 0; two registers are not guessed. + if (op.name == "s_cselect_b32" && op.dst < 106u) { + const bool zero0 = op.imm0 && op.v0 == 0u; + const bool zero1 = op.imm1 && op.v1 == 0u; + if (zero0 != zero1) { + const unsigned reg = zero0 ? op.src1 : op.src0; + if (reg < 106u) { + put(at, false, op.dst, Def{4u, reg, false, at, 0u}); + return; + } + } + } + if (op.name == "s_and_b32" && op.imm0 != op.imm1) { + const unsigned reg = op.imm0 ? op.src1 : op.src0; + const std::uint32_t mask = op.imm0 ? op.v0 : op.v1; + unsigned width = 0; + if (reg < 106u && low_mask(mask, width)) { + put(at, false, op.dst, Def{1u, reg, false, mask, width}); + return; + } + } + if (op.name == "s_add_u32" && + ((op.imm0 && op.v0 == 1u && reg1) || (op.imm1 && op.v1 == 1u && reg0))) { + const unsigned reg = (op.imm0 && op.v0 == 1u) ? op.src1 : op.src0; + put(at, false, op.dst, Def{2u, reg, false, at, 0u}); + return; + } + if (op.name == "s_lshr_b32" && op.imm1 && op.v1 < 32u && reg0) { + put(at, false, op.dst, Def{3u, op.src0, false, op.v1, 0u}); + return; + } + // Kind 5 is a write this reader does not understand. It is not a record word. + const Def unknown{5u, 0u, false, 0u, 0u}; + put(at, false, op.dst, unknown); + if (pair) + put(at, false, op.dst + 1u, unknown); + }; + auto note_vector_binary = [&](unsigned at, const Op& op) { + if (!op.vector_dst || op.dst >= 256u) + return; + unsigned width = 0; + if (op.name == "v_and_b32" && op.imm0 && !op.imm1 && low_mask(op.v0, width) && op.src1 < 256u) { + put(at, true, op.dst, Def{1u, op.src1, true, op.v0, width}); + return; + } + if (op.name == "v_add_nc_u32" && op.imm0 && !op.imm1 && op.v0 == 1u && op.src1 < 256u) { + put(at, true, op.dst, Def{2u, op.src1, true, at, 0u}); + return; + } + if (op.name == "v_lshrrev_b32" && op.imm0 && !op.imm1 && op.v0 < 32u && op.src1 < 256u) { + put(at, true, op.dst, Def{3u, op.src1, true, op.v0, 0u}); + return; + } + put(at, true, op.dst, Def{5u, 0u, false, 0u, 0u}); + }; + + 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 out; + const bool wide = inst.form == x2w::gfx1013::Form::vop3 || inst.form == x2w::gfx1013::Form::vop3p; + const unsigned base = wide ? 8u : 4u; + const bool has_literal = inst.size == base + 4u; + std::uint32_t literal = 0; + if (has_literal) + std::memcpy(&literal, code.data() + pc + base, sizeof(literal)); + std::uint32_t word1 = 0; + if (inst.size >= 8u) + std::memcpy(&word1, code.data() + pc + 4, sizeof(word1)); + + Op op; + op.name = inst.name; + if (inst.form == x2w::gfx1013::Form::sop2 || inst.form == x2w::gfx1013::Form::sop1 || + inst.form == x2w::gfx1013::Form::sopk) { + op.dst = (raw >> 16) & 127u; + op.src0 = raw & 255u; + op.src1 = (raw >> 8) & 255u; + op.imm0 = src_imm(op.src0, has_literal, literal, op.v0); + op.imm1 = src_imm(op.src1, has_literal, literal, op.v1); + } else if (inst.form == x2w::gfx1013::Form::vop2 || inst.form == x2w::gfx1013::Form::vop1) { + op.dst = (raw >> 17) & 255u; + op.vector_dst = inst.form == x2w::gfx1013::Form::vop2; + op.src0 = raw & 511u; + op.src1 = (raw >> 9) & 255u; + op.imm0 = src_imm(op.src0, has_literal, literal, op.v0); + } else if (inst.form == x2w::gfx1013::Form::vop3) { + op.dst = raw & 255u; + op.src0 = word1 & 511u; + op.src1 = (word1 >> 9) & 511u; + const unsigned abs = (raw >> 8) & 7u; + const unsigned neg = word1 >> 29; + const unsigned scale = (word1 >> 27) & 3u; + const bool clamp = (raw & 0x8000u) != 0; + op.imm0 = !abs && !neg && !scale && !clamp && src_imm(op.src0, has_literal, literal, op.v0); + op.imm1 = !abs && !neg && !scale && !clamp && src_imm(op.src1, has_literal, literal, op.v1); + unsigned vg = 0; + if (!op.imm0 && vgpr(op.src0, vg)) + op.src0 = vg; + else if (!op.imm0) + op.src0 = 512u; + if (!op.imm1 && vgpr(op.src1, vg)) + op.src1 = vg; + else if (!op.imm1) + op.src1 = 512u; + op.vector_dst = inst.name != "v_readfirstlane_b32"; + } + + if (inst.name == "v_mbcnt_hi_u32_b32") + wave64 = true; + if (inst.form == x2w::gfx1013::Form::exp && ((raw >> 4) & 63u) == 20u) + triangle_export = true; + 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 (inst.form == x2w::gfx1013::Form::sop2) + note_scalar_binary(pc, op); + else if (inst.form == x2w::gfx1013::Form::sopk) { + if (op.dst < 128u && !mesh57_scalar_sdst_is_not_data(inst.name)) + wipe(pc, op.dst, mesh57_scalar_result_is_64(inst.name)); + } else if (inst.form == x2w::gfx1013::Form::sop1) { + const bool pair = mesh57_scalar_result_is_64(inst.name); + if (inst.name == "s_mov_b32" && op.dst < 106u && op.src0 < 106u) + put(pc, false, op.dst, Def{4u, op.src0, false, pc, 0u}); + else if (op.dst < 128u) + wipe(pc, op.dst, pair); + } else if (inst.form == x2w::gfx1013::Form::vop1 && inst.name == "v_readfirstlane_b32" && + op.dst < 106u) { + unsigned index = 0; + if (vgpr(op.src0, index)) + put(pc, false, op.dst, Def{4u, index, true, pc, 0u}); + else + put(pc, false, op.dst, Def{5u, 0u, false, 0u, 0u}); + } else if (inst.form == x2w::gfx1013::Form::vop1) { + if (op.dst < 256u) + put(pc, true, op.dst, Def{5u, 0u, false, 0u, 0u}); + } else if (inst.form == x2w::gfx1013::Form::vop2) { + note_vector_binary(pc, op); + } else if (inst.form == x2w::gfx1013::Form::vop3 && inst.name == "v_readfirstlane_b32" && + op.dst < 106u) { + if (op.src0 < 256u) + put(pc, false, op.dst, Def{4u, op.src0, true, pc, 0u}); + else + put(pc, false, op.dst, Def{5u, 0u, false, 0u, 0u}); + } else if (inst.form == x2w::gfx1013::Form::vop3 && + (inst.name == "v_and_b32" || inst.name == "v_add_nc_u32" || inst.name == "v_lshrrev_b32")) { + const unsigned src2 = (word1 >> 18) & 511u; + const bool binary_tail = src2 == 0u || src2 == 128u; + const unsigned abs = (raw >> 8) & 7u; + const unsigned neg = word1 >> 29; + const unsigned scale = (word1 >> 27) & 3u; + const bool clamp = (raw & 0x8000u) != 0; + op.vector_dst = true; + if ((inst.name == "v_and_b32" || inst.name == "v_add_nc_u32") && op.imm1 && !op.imm0 && + op.src0 < 256u) { + op.imm0 = true; + op.v0 = op.v1; + op.src1 = op.src0; + op.imm1 = false; + } + if (!binary_tail || abs || neg || scale || clamp || op.dst >= 256u) { + if (op.dst < 256u) + put(pc, true, op.dst, Def{5u, 0u, false, 0u, 0u}); + } else { + note_vector_binary(pc, op); + } + } else if (inst.form == x2w::gfx1013::Form::vop3 && op.dst < 256u) { + put(pc, true, op.dst, Def{5u, 0u, false, 0u, 0u}); + } + + if (raw == 0xbf900009u) { + ++sends; + pattern = false; + send_pc = pc; + const bool shift = older_ok && older.name == "s_lshl_b32" && older.dst < 106u && + older.src0 < 106u && older.imm1 && older.v1 == 12u; + const bool joined = newer_ok && newer.name == "s_or_b32" && newer.dst == 124u && + newer.src0 < 106u && newer.src1 < 106u; + if (sends == 1 && shift && joined) { + const bool left = newer.src0 == older.dst; + const bool right = newer.src1 == older.dst; + if (left != right) { + primitive_reg = older.src0; + vertex_reg = left ? newer.src1 : newer.src0; + pattern = primitive_reg != vertex_reg && primitive_reg != older.dst && + vertex_reg != older.dst; + } + } + } + older = newer; + older_ok = newer_ok; + newer = op; + newer_ok = true; + pc += inst.size; + } + if (sends != 1 || !pattern) + return out; + + struct Seen { + bool ok = false; + Def def{}; + unsigned pc = 0; + unsigned reg = 0; + bool is_vector = false; + }; + // Latest write of reg strictly before at_pc. Copies remember that pc in imm, + // so the source is the value that was moved, not a later write of the same register. + auto follow = [&](unsigned at_pc, bool is_vector, unsigned reg) noexcept -> Seen { + for (int hop = 0; hop < 6; ++hop) { + if (is_vector ? reg >= 256u : reg >= 128u) + return {}; + bool found = false; + Def def{}; + unsigned def_pc = 0; + for (std::size_t i = events.size(); i > 0; --i) { + const Event& event = events[i - 1]; + if (event.pc < at_pc && event.is_vector == is_vector && event.reg == reg) { + def = event.def; + def_pc = event.pc; + found = true; + break; + } + } + if (!found) + return Seen{true, {}, at_pc, reg, is_vector}; + if (def.kind != 4u) + return Seen{true, def, def_pc, reg, is_vector}; + at_pc = def.imm; + is_vector = def.src_vector; + reg = def.src; + } + return {}; + }; + struct Extract { + bool ok = false; + unsigned width = 0; + unsigned shift = 0; + unsigned record = 0; + bool record_vector = false; + }; + auto as_mask = [&](unsigned at_pc, bool is_vector, unsigned reg, Extract& extracted) noexcept { + const Seen mask = follow(at_pc, is_vector, reg); + if (!mask.ok || mask.def.kind != 1u) + return false; + const Seen inner = follow(mask.pc, mask.def.src_vector, mask.def.src); + if (!inner.ok) + return false; + extracted.ok = true; + extracted.width = mask.def.width; + if (inner.def.kind == 3u) { + const Seen record = follow(inner.pc, inner.def.src_vector, inner.def.src); + if (!record.ok || record.def.kind != 0u) + return false; + extracted.shift = inner.def.imm; + extracted.record = record.reg; + extracted.record_vector = record.is_vector; + return true; + } + if (inner.def.kind != 0u) + return false; + extracted.shift = 0; + extracted.record = inner.reg; + extracted.record_vector = inner.is_vector; + return true; + }; + auto as_count = [&](unsigned reg, Extract& extracted) noexcept { + // The +1 may sit in the scalar count register or in the VGPR that + // v_readfirstlane copied into it. Either is the record count. + const Seen count = follow(send_pc, false, reg); + if (!count.ok || count.def.kind != 2u) + return false; + return as_mask(count.pc, count.def.src_vector, count.def.src, extracted); + }; + Extract vertices; + Extract primitives; + if (!as_count(vertex_reg, vertices) || !as_count(primitive_reg, primitives)) { + out.reason = "derived mesh record mask was not proven"; + return out; + } + if (!vertices.ok || !primitives.ok || vertices.shift != 0 || vertices.width == 0 || + vertices.width != primitives.width || primitives.shift != vertices.width || + vertices.record != primitives.record || vertices.record_vector != primitives.record_vector) { + out.reason = "derived mesh record mask was not proven"; + return out; + } + if (wave32) { + out.reason = "derived mesh record is wave32"; + return out; + } + if (!wave64) { + out.reason = "derived mesh record wave size is not proven"; + return out; + } + if (!triangle_export) { + out.reason = "derived mesh record topology is not triangles"; + return out; + } + if (!entry.k_known) { + out.reason = "derived mesh record multiply k is unknown"; + return out; + } + if (entry.k != 1u) { + out.reason = "derived mesh record multiply k is not 1"; + return out; + } + const unsigned record_max = 1u << vertices.width; + const unsigned long long product = static_cast(record_max) * 2ull; + if (product > 256ull) { + out.reason = "derived mesh record bound exceeds the mesh output limit"; + return out; + } + const unsigned bound = static_cast(product); + constexpr unsigned wave = 64u; + const unsigned threads = ((bound + wave - 1u) / wave) * wave; + Mesh57RecordBounds layout; + layout.threads = threads; + layout.vertices = bound; + layout.primitives = bound; + layout.topology = 2; + layout.group_stride = 0; + layout.wave_size = wave; + layout.multiply_k = entry.k; + layout.pattern = "record-m0"; + out.bounds = layout; + out.reason = nullptr; + return out; + } catch (...) { + return out; + } +} + // 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. diff --git a/src/startup_stubs/native_mesh57.inl b/src/startup_stubs/native_mesh57.inl index 3b2f2e0465..5b177b0829 100644 --- a/src/startup_stubs/native_mesh57.inl +++ b/src/startup_stubs/native_mesh57.inl @@ -705,6 +705,35 @@ const char* derive_slot55_mesh(Wrapper* pipeline, Pass& pass) return derive_slot57_mesh(pipeline, pass, has_blend ? &blend : nullptr, base_info); } +// One line per distinct pair for the record-m0 bounds. The text has byte counts and the +// derived limits only; it does not print a pointer. +void mesh57_log_record_bounds(const x2w_startup::Mesh57RecordBounds& bounds, unsigned mesh_bytes, + unsigned pixel_bytes) +{ + char line[192]{}; + if (!x2w_startup::mesh57_record_bounds_line(bounds, mesh_bytes, pixel_bytes, line, sizeof(line))) + return; + static SRWLOCK seen_lock = SRWLOCK_INIT; + static char seen[8][192]{}; + static unsigned seen_count = 0; + AcquireSRWLockExclusive(&seen_lock); + bool emit = false; + for (unsigned i = 0; i < seen_count; ++i) { + if (std::strcmp(seen[i], line) == 0) { + ReleaseSRWLockExclusive(&seen_lock); + return; + } + } + if (seen_count < 8) { + std::snprintf(seen[seen_count], sizeof(seen[seen_count]), "%s", line); + ++seen_count; + emit = true; + } + ReleaseSRWLockExclusive(&seen_lock); + if (emit) + 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. @@ -778,8 +807,33 @@ const char* derive_slot57_mesh(Wrapper* pipeline, Pass& pass, const D3D12_BLEND_ 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); + // Bounds from the record-m0 pattern. Empty unless X2W_MESH57_DERIVED_BOUNDS=1 and the + // guest code matches. k is the measured entry constant 1; this path does not read an + // unmapped user SGPR to discover it. + std::optional record_bounds; + auto log_record_bounds = [&](const x2w_startup::Mesh57RecordBounds& bounds) { + const unsigned mesh_bytes = info->fixed_ms && info->fixed_ms->size() <= 0xffffffffu + ? static_cast(info->fixed_ms->size()) : 0xffffffffu; + const unsigned pixel_bytes = info->fixed_ps && info->fixed_ps->size() <= 0xffffffffu + ? static_cast(info->fixed_ps->size()) : 0xffffffffu; + mesh57_log_record_bounds(bounds, mesh_bytes, pixel_bytes); + }; + if (const char* root_why = x2w_startup::mesh57_root_bind_reason(root_contract)) { + if (std::strcmp(root_why, "derived mesh guest root is heap indexed") == 0 && + x2w_local::env_on("X2W_MESH57_DERIVED_BOUNDS") && info->fixed_ms) { + const std::string early(info->fixed_ms->begin(), info->fixed_ms->end()); + x2w_startup::Mesh57RecordEntry entry; + entry.k_known = true; + entry.k = 1; + const auto found = x2w_startup::mesh57_read_record_m0_bounds(early, entry); + if (found.bounds) { + record_bounds = *found.bounds; + log_record_bounds(*record_bounds); + } + } + if (!record_bounds) + 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) @@ -822,11 +876,36 @@ const char* derive_slot57_mesh(Wrapper* pipeline, Pass& pass, const D3D12_BLEND_ return "derived mesh root is not the bound desktop root"; const std::string ms(info->fixed_ms->begin(), info->fixed_ms->end()); 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"); + x2w_startup::MeshDerivedLayout layout{}; + bool runtime_counts = false; + if (!read.layout) { + if (!record_bounds && x2w_local::env_on("X2W_MESH57_DERIVED_BOUNDS")) { + x2w_startup::Mesh57RecordEntry entry; + entry.k_known = true; + entry.k = 1; + const auto found = x2w_startup::mesh57_read_record_m0_bounds(ms, entry); + if (found.bounds) { + record_bounds = *found.bounds; + log_record_bounds(*record_bounds); + } + } + if (!record_bounds) + return remember(read.reason ? read.reason : "derived mesh needs one immediate allocation"); + runtime_counts = true; + layout.threads = record_bounds->threads; + layout.vertices = record_bounds->vertices; + layout.primitives = record_bounds->primitives; + layout.topology = record_bounds->topology; + layout.group_stride = record_bounds->group_stride; + layout.wave_size = record_bounds->wave_size; + if (layout.wave_size != 64 || layout.topology != 2 || layout.group_stride != 0 || + !layout.threads || (layout.threads % 64u) != 0 || layout.threads > 256) + return remember("derived mesh record group is not wave64"); + } else { + 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; @@ -835,6 +914,7 @@ const char* derive_slot57_mesh(Wrapper* pipeline, Pass& pass, const D3D12_BLEND_ mesh_layout.topology = layout.topology; mesh_layout.group_stride = layout.group_stride; mesh_layout.wave32 = layout.wave_size == 32; + mesh_layout.record_output_counts = runtime_counts; D3D12_ROOT_PARAMETER1 constant_parameter{}; D3D12_ROOT_SIGNATURE_DESC1 constant_root{}; if (root_contract.bind_constants) { diff --git a/tests/mesh57_record_bounds_check.cpp b/tests/mesh57_record_bounds_check.cpp new file mode 100644 index 0000000000..61152b05b5 --- /dev/null +++ b/tests/mesh57_record_bounds_check.cpp @@ -0,0 +1,226 @@ +// Host check for the opt-in record-m0 mesh bounds. Words are assembled here. +// The immediate m0 reader is called as well, and it is not given this pattern. +#include "mesh57_alloc.h" + +#include +#include +#include +#include +#include +#include +#include + +namespace { +int fail(const char* name) +{ + std::fprintf(stderr, "mesh57 record bounds: %s\n", name); + return 1; +} + +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 vop1_word(unsigned op, unsigned dst, unsigned src) +{ + return (63u << 25) | (dst << 17) | (op << 9) | (src & 511u); +} + +std::uint32_t vop2_word(unsigned op, unsigned dst, unsigned vsrc1, unsigned src0) +{ + return (op << 25) | (dst << 17) | (vsrc1 << 9) | (src0 & 511u); +} + +std::string code_from(const std::vector& words) +{ + std::string out(words.size() * sizeof(std::uint32_t), '\0'); + if (!words.empty()) + std::memcpy(out.data(), words.data(), out.size()); + return out; +} + +bool set_switch(const char* value) +{ +#if defined(_WIN32) + return _putenv_s("X2W_MESH57_DERIVED_BOUNDS", value) == 0; +#else + if (value[0] == 0) + return unsetenv("X2W_MESH57_DERIVED_BOUNDS") == 0; + return setenv("X2W_MESH57_DERIVED_BOUNDS", value, 1) == 0; +#endif +} + +bool names_match(const std::vector& words, const std::vector& names) +{ + const std::string code = code_from(words); + std::size_t index = 0; + for (unsigned pc = 0; pc < code.size();) { + const auto inst = x2w::gfx1013::instruction(code, pc); + if (inst.size == 0 || pc + inst.size > code.size() || index >= names.size() || inst.name != names[index]) { + std::fprintf(stderr, "mesh57 record bounds: at %u got %.*s, expected %s\n", pc, + inst.name.empty() ? 0 : static_cast(inst.name.size()), inst.name.data(), + index < names.size() ? names[index] : "(end)"); + return false; + } + pc += inst.size; + ++index; + } + if (index != names.size()) { + std::fprintf(stderr, "mesh57 record bounds: %zu instructions, expected %zu\n", index, names.size()); + return false; + } + return true; +} + +// Low field (mask + 1) in s18, next field of the same width in s21, then +// s_lshl s22, s21, 12 / s_or m0, s22, s18 / s_sendmsg GS_ALLOC_REQ. +// A later v_mov reuses the add VGPR. s_cselect keeps the count or zero. +std::vector record_program(unsigned mask, unsigned shift) +{ + const unsigned mask_src = mask <= 64u ? 128u + mask : 255u; + const unsigned shift_src = 128u + shift; + std::vector words; + auto append = [&](std::uint32_t word) { words.push_back(word); }; + auto masked = [&](unsigned dst, unsigned src_vgpr) { + append(vop2_word(27, dst, src_vgpr, mask_src)); + if (mask_src == 255u) + append(mask); + }; + masked(1, 0); + append(vop2_word(37, 2, 1, 129)); + append(vop2_word(22, 3, 0, shift_src)); + masked(4, 3); + append(vop2_word(37, 5, 4, 129)); + append(vop1_word(2, 18, 256u + 2u)); + append(vop1_word(2, 21, 256u + 5u)); + append(vop1_word(1, 2, 256u + 7u)); + append(sop2_word(10, 18, 18, 128)); + append(sop2_word(10, 21, 21, 128)); + append(sop2_word(30, 22, 21, 140)); + append(sop2_word(16, 124, 22, 18)); + append(0xbf900009u); + append(sop1_word(4, 126, 126)); + append(0xf8000941u); + append(0x80808005u); + append(0xbf810000u); + return words; +} + +const std::vector record_names = { + "v_and_b32", "v_add_nc_u32", "v_lshrrev_b32", "v_and_b32", "v_add_nc_u32", + "v_readfirstlane_b32", "v_readfirstlane_b32", "v_mov_b32", + "s_cselect_b32", "s_cselect_b32", "s_lshl_b32", "s_or_b32", "s_sendmsg", + "s_mov_b64", "exp", "s_endpgm"}; + +x2w_startup::Mesh57RecordEntry known_k(unsigned k) +{ + x2w_startup::Mesh57RecordEntry entry; + entry.k_known = true; + entry.k = k; + return entry; +} + +bool bounds_are(const x2w_startup::Mesh57RecordBoundsRead& read, unsigned vertices, unsigned primitives, + unsigned threads) +{ + const auto& bounds = read.bounds; + return bounds && !read.reason && bounds->vertices == vertices && bounds->primitives == primitives && + bounds->threads == threads && bounds->topology == 2 && bounds->group_stride == 0 && + bounds->wave_size == 64 && bounds->multiply_k == 1 && bounds->pattern && + std::strcmp(bounds->pattern, "record-m0") == 0; +} + +bool reason_is(const x2w_startup::Mesh57RecordBoundsRead& read, const char* reason) +{ + return !read.bounds && read.reason && std::strcmp(read.reason, reason) == 0; +} +} // namespace + +int main() +{ + const std::vector record = record_program(0x7fu, 7u); + if (!names_match(record, record_names)) + return fail("record encoding"); + const std::string program = code_from(record); + const auto accepted = x2w_startup::mesh57_read_record_m0_bounds(program, known_k(1)); + if (!bounds_are(accepted, 256, 256, 256)) + return fail("record bounds"); + + const std::vector narrower = record_program(0x3fu, 6u); + if (!names_match(narrower, record_names)) + return fail("narrow encoding"); + if (!bounds_are(x2w_startup::mesh57_read_record_m0_bounds(code_from(narrower), known_k(1)), 128, 128, 128)) + return fail("narrow bounds"); + + x2w_startup::Mesh57RecordEntry unknown; + if (!reason_is(x2w_startup::mesh57_read_record_m0_bounds(program, unknown), + "derived mesh record multiply k is unknown")) + return fail("k unknown"); + if (!reason_is(x2w_startup::mesh57_read_record_m0_bounds(program, known_k(2)), + "derived mesh record multiply k is not 1")) + return fail("k is not 1"); + + const std::vector wide = record_program(0xffu, 8u); + if (!names_match(wide, record_names)) + return fail("wide encoding"); + if (!reason_is(x2w_startup::mesh57_read_record_m0_bounds(code_from(wide), known_k(1)), + "derived mesh record bound exceeds the mesh output limit")) + return fail("bound over 256"); + + // The immediate reader still owns this triangle, and it refuses the record program. + const std::vector triangle = { + 0xbefc03ffu, 0x1003u, 0xbf900009u, 0xd7650000u, 0x100c1u, 0x36020081u, + 0x2c040081u, 0x7e020d01u, 0x7e040d02u, 0x7e0602f0u, 0x7e0802f2u, 0xf80008cfu, + 0x04030201u, 0x7e0a02ffu, 0x200400u, 0xf8000941u, 0x80808005u, 0xd7660006u, + 0x000100c1u, 0xbf810000u}; + const auto immediate = x2w_startup::mesh57_read_layout(code_from(triangle)); + if (!immediate.layout || immediate.reason || immediate.layout->vertices != 3 || + immediate.layout->primitives != 1 || immediate.layout->threads != 64 || + immediate.layout->wave_size != 64 || immediate.layout->topology != 2 || + immediate.layout->group_stride != 0) + return fail("immediate triangle"); + const auto immediate_record = x2w_startup::mesh57_read_layout(program); + if (immediate_record.layout || !immediate_record.reason || + std::strcmp(immediate_record.reason, "derived mesh needs one immediate allocation") != 0) + return fail("immediate reader refuses the record program"); + if (!reason_is(x2w_startup::mesh57_read_record_m0_bounds(code_from(triangle), known_k(1)), + "derived mesh record allocation was not proven")) + return fail("record reader refuses the immediate program"); + + // The readers do not consult the switch. The Windows caller does, and only when it is 1. + const auto before = x2w_startup::mesh57_read_layout(program); + if (!set_switch("1")) + return fail("set switch"); + const auto enabled = x2w_startup::mesh57_read_layout(program); + if (!set_switch("")) + return fail("clear switch"); + if (!before.reason || !enabled.reason || std::strcmp(before.reason, enabled.reason) != 0 || + before.layout.has_value() || enabled.layout.has_value()) + return fail("switch does not change the immediate reader"); + + const auto zero = x2w_startup::mesh57_runtime_mesh_counts(128, 64, 2, true); + const auto cleared = x2w_startup::mesh57_runtime_mesh_counts(128, 64, 0, false); + const auto one = x2w_startup::mesh57_runtime_mesh_counts(3, 1, 1, false); + if (zero.vertices || zero.primitives || cleared.vertices || cleared.primitives || + one.vertices != 3 || one.primitives != 1) + return fail("runtime counts"); + + char line[192]; + const auto written = x2w_startup::mesh57_record_bounds_line(*accepted.bounds, 100, 40, line, sizeof(line)); + if (!written || std::strstr(line, "v=256") == nullptr || std::strstr(line, "p=256") == nullptr || + std::strstr(line, "threads=256") == nullptr || std::strstr(line, "pattern=record-m0") == nullptr || + std::strstr(line, "k=1") == nullptr || std::strstr(line, "0x") != nullptr) + return fail("bounds line"); + char tiny[8]; + std::memset(tiny, 0x5a, sizeof(tiny)); + x2w_startup::mesh57_record_bounds_line(*accepted.bounds, 100, 40, tiny, sizeof(tiny)); + if (tiny[sizeof(tiny) - 1] != 0) + return fail("bounds line cap"); + return 0; +} From 0d739d10563622c2ac1a9684ee54cb8133aab14f Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Mon, 30 Nov 2026 14:43:57 +0000 Subject: [PATCH 14/24] startup: carry decoded depth and stencil for derived slot 57 meshes X2W_MESH57_DERIVED_BOUNDS=1 copies the decoded depth-stencil state into the derived mesh pipeline and uses the depth view already bound on the list. The dispatch sets the decoded stencil reference for that command. Depth bounds, differing back-face masks, a multisampled depth buffer, and a stencil test without a stencil plane stay refused. The switch still defaults off. --- CMakeLists.txt | 5 + docs/experiments/native-fixed-mesh57.md | 14 +- docs/startup-runtime.md | 4 +- src/startup_stubs/d3d12_xs_device.cpp | 14 ++ src/startup_stubs/mesh57_derived_depth.h | 294 +++++++++++++++++++++++ src/startup_stubs/native_mesh57.inl | 58 ++++- tests/mesh57_derived_depth_check.cpp | 231 ++++++++++++++++++ 7 files changed, 610 insertions(+), 10 deletions(-) create mode 100644 src/startup_stubs/mesh57_derived_depth.h create mode 100644 tests/mesh57_derived_depth_check.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 7c3d199d37..e21029fadb 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1957,6 +1957,11 @@ target_include_directories(mesh57_record_bounds_check PRIVATE src src/startup_st target_compile_features(mesh57_record_bounds_check PRIVATE cxx_std_17) add_test(NAME mesh57_record_bounds COMMAND mesh57_record_bounds_check) +add_executable(mesh57_derived_depth_check tests/mesh57_derived_depth_check.cpp) +target_include_directories(mesh57_derived_depth_check PRIVATE src) +target_compile_features(mesh57_derived_depth_check PRIVATE cxx_std_17) +add_test(NAME mesh57_derived_depth COMMAND mesh57_derived_depth_check) + add_executable(mesh57_span_dump_check tests/mesh57_span_dump_check.cpp) target_include_directories(mesh57_span_dump_check PRIVATE src) target_compile_features(mesh57_span_dump_check PRIVATE cxx_std_17) diff --git a/docs/experiments/native-fixed-mesh57.md b/docs/experiments/native-fixed-mesh57.md index 77023d552f..114cecc982 100644 --- a/docs/experiments/native-fixed-mesh57.md +++ b/docs/experiments/native-fixed-mesh57.md @@ -132,7 +132,7 @@ An empty guest root is unchanged. One 32-bit constant parameter of 1..8 dwords a 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. 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. +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 unless `X2W_MESH57_DERIVED_BOUNDS=1`; 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. A bound depth view stays refused unless that second switch is on. 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. @@ -173,3 +173,15 @@ ctest --preset dev --no-tests=error -R 'mesh57_record_bounds|mesh57_derive_alloc ``` 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. + +## Derived depth and stencil + +`X2W_MESH57_DERIVED_BOUNDS=1` also lifts the depth refusal in this derivation. With the switch off, an enabled depth or stencil test is still `derived mesh keeps depth and stencil disabled`, and a bound depth view is still refused. The description is the one `decode_depth_stencil` already produces from state block A. It is copied into the mesh pipeline's depth-stencil state. The pipeline depth format is the depth view already bound on that list by `OMSetRenderTargets`, the same bind a translated draw uses. The dispatch sets `OMSetStencilRef` from the decoded reference for that command and then restores the list's reference. One single-sample color target, a viewport and a scissor are still required. + +A form that cannot be copied exactly stays refused, and the reason names it. Depth bounds are not a desktop depth-stencil field. Back-face stencil masks or a reference that differ from the front are not one desktop reference and one pair of masks. A stencil op or compare with no desktop form stays refused. A depth or stencil test with no depth view, a multisampled depth buffer, color and depth sample counts that differ, a zero sample count, and a stencil test whose depth format has no stencil plane stay refused. The format is the bound view's format. This path does not choose one. Those attachment refusals are not remembered: a later list can bind a depth view. A refusal that comes from the pipeline's own registers is remembered. + +`mesh57_derived_depth` checks the register-word mapping, the switch-off refusals, and each of those reasons. It does not need a device. + +```powershell +ctest --preset dev --no-tests=error -R 'mesh57_derived_depth|mesh57_record_bounds|mesh57_derive_alloc' +``` diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index 07d94187ce..c30270d49e 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -1803,8 +1803,8 @@ 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 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_MESH57_DERIVED_BOUNDS=1` | experimental, with `X2W_MESH57_DERIVE_STATE=1`. Off by default, and unset it leaves the slot 57 derivation unchanged. Set, a mesh whose `m0` is `s_lshl_b32` by 12 then `s_or_b32` into `m0` immediately before the only `GS_ALLOC_REQ`, with both counts proven as `(field & mask) + 1` from one record word, may use those masks as the output limit. The multiply is `2^k` only when the entry `k` is the constant 1; an unknown `k` or any other `k` stays refused. A product above 256 vertices or 256 primitives stays refused. The group is the smallest multiple of 64 that covers that limit, from the direct mesh lane id (one thread writes one output). The translated shader passes the runtime counts to `SetMeshOutputCounts`. The immediate `m0` reader is unchanged. This switch does not invent a user-SGPR map for a heap-indexed root. See [Opt-in record bounds](experiments/native-fixed-mesh57.md#opt-in-record-bounds) | +| `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 and stencil unless `X2W_MESH57_DERIVED_BOUNDS=1`, 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_MESH57_DERIVED_BOUNDS=1` | experimental, with `X2W_MESH57_DERIVE_STATE=1`. Off by default, and unset it leaves the slot 57 derivation unchanged. Set, a mesh whose `m0` is `s_lshl_b32` by 12 then `s_or_b32` into `m0` immediately before the only `GS_ALLOC_REQ`, with both counts proven as `(field & mask) + 1` from one record word, may use those masks as the output limit. The multiply is `2^k` only when the entry `k` is the constant 1; an unknown `k` or any other `k` stays refused. A product above 256 vertices or 256 primitives stays refused. The group is the smallest multiple of 64 that covers that limit, from the direct mesh lane id (one thread writes one output). The translated shader passes the runtime counts to `SetMeshOutputCounts`. The immediate `m0` reader is unchanged. This switch does not invent a user-SGPR map for a heap-indexed root. With the switch on, the decoded depth and stencil state is copied into the derived mesh pipeline, the bound depth view's format is the pipeline depth format, and the dispatch sets the decoded stencil reference. Depth bounds, differing back-face masks, a multisampled depth buffer, and a stencil test without a stencil plane stay refused. See [Opt-in record bounds](experiments/native-fixed-mesh57.md#opt-in-record-bounds) | | `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 9022b252bf..b54624e953 100644 --- a/src/startup_stubs/d3d12_xs_device.cpp +++ b/src/startup_stubs/d3d12_xs_device.cpp @@ -33,6 +33,7 @@ #include "startup_stubs/export_write_mask.h" #include "startup_stubs/pso_recipe.h" #include "startup_stubs/depth_state_apply.h" +#include "startup_stubs/mesh57_derived_depth.h" #include "startup_stubs/d16_image_format.h" #include "startup_stubs/formatted_buffer.h" #include "startup_stubs/view_content_token.h" @@ -179,6 +180,9 @@ struct IndirectGraphicsPipeline { 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; + // X2W_MESH57_DERIVED_BOUNDS: the decoded stencil reference is list state. Set for that dispatch only. + bool mesh57_stencil_ref = false; + UINT mesh57_stencil_ref_value = 0; }; // Why a resource is outside the retire class (X2W_D3D12_RELEASE_RETIRED), decided at creation, and why it left it later. @@ -4332,9 +4336,19 @@ void __stdcall list_execute_indirect(Wrapper* self, void* signature, UINT count, if (!leased_arguments && !rect_list) { require_state(self, resource, argument_state); } + // The depth view is the one OMSetRenderTargets already bound on this list, the same bind a + // translated draw uses. The pipeline depth format is that view. The stencil reference is list + // state and is restored after this command, as a decoded draw reference is. + const bool scoped_stencil_ref = graphics && pass.dsv_format != DXGI_FORMAT_UNKNOWN && + pass.indirect_graphics.mesh57_stencil_ref && + pass.indirect_graphics.mesh57_stencil_ref_value != pass.stencil_reference; + if (scoped_stencil_ref) + list->OMSetStencilRef(pass.indirect_graphics.mesh57_stencil_ref_value); const auto red_samples = graphics ? red_producer_draw_before(self, list, "indirect-draw", 0) : RedDrawSamples{}; list->ExecuteIndirect(static_cast(sig->own().real), count, draw_arguments, draw_offset, counts, counts ? count_offset : 0); + if (scoped_stencil_ref) + list->OMSetStencilRef(pass.stencil_reference); if (trace_compute_outputs()) trace_compute_output_use(self, OutputUse::indirect_recorded, "indirect-recorded", argument, 0, offset, span, known_pipeline_key(refusal_pipeline)); diff --git a/src/startup_stubs/mesh57_derived_depth.h b/src/startup_stubs/mesh57_derived_depth.h new file mode 100644 index 0000000000..65e1266dd6 --- /dev/null +++ b/src/startup_stubs/mesh57_derived_depth.h @@ -0,0 +1,294 @@ +// Opt-in depth decision for X2W_MESH57_DERIVED_BOUNDS. +// +// pipeline_state_decode.h already turns DB_DEPTH_CONTROL, DB_STENCIL_CONTROL and the two +// stencil reference words into a D3D12 depth-stencil description. This header repeats that +// field mapping with the desktop enumeration values so the decision can be checked without +// a device, and it decides whether that description may be used. The Windows caller still +// copies the decoder's description into the pipeline. It does not rebuild one from here. +// +// Comparison values are D3D12_COMPARISON_FUNC: 1 NEVER through 8 ALWAYS. +// Depth write is D3D12_DEPTH_WRITE_MASK: 0 ZERO, 1 ALL. +// Stencil ops are D3D12_STENCIL_OP: 1 KEEP through 8 DECR. Zero means the guest op has no +// desktop form. Depth formats are the desktop DXGI values that already count as having a +// stencil plane (D24_UNORM_S8_UINT, D32_FLOAT_S8X24_UINT, and the two typeless forms). +#pragma once + +#include + +namespace x2w_startup { + +struct Mesh57DepthFacts { + bool ok = false; + const char* reason = nullptr; + bool depth_enable = false; + unsigned depth_write = 0; + unsigned depth_func = 8; + bool stencil_enable = false; + unsigned stencil_read_mask = 0xff; + unsigned stencil_write_mask = 0xff; + unsigned front_fail = 1; + unsigned front_depth_fail = 1; + unsigned front_pass = 1; + unsigned front_func = 8; + unsigned back_fail = 1; + unsigned back_depth_fail = 1; + unsigned back_pass = 1; + unsigned back_func = 8; + unsigned stencil_ref = 0; + bool depth_bounds = false; + bool masks_differ = false; +}; + +// targets_single_sample is the list flag the switch-off check already uses: every color +// target and the depth target, when one is bound, are one sample with quality 0. +// color_samples and depth_samples are read from the bound resources only when the switch +// is on. depth_bound is false when the format is known but the resource is not. +struct Mesh57DepthTargets { + bool targets_bound = false; + bool viewport_set = false; + bool scissor_set = false; + bool targets_single_sample = false; + unsigned target_count = 0; + bool has_target0 = false; + unsigned target0_format = 0; + unsigned dsv_format = 0; + bool depth_bound = false; + unsigned color_samples = 1; + unsigned color_quality = 0; + unsigned depth_samples = 1; + unsigned depth_quality = 0; +}; + +struct Mesh57DerivedDepth { + const char* reason = nullptr; + bool remember = false; // pipeline state, not the list: a later list cannot change it + unsigned dsv_format = 0; + bool set_stencil_ref = false; + unsigned stencil_ref = 0; +}; + +constexpr unsigned mesh57_cmp_never = 1; +constexpr unsigned mesh57_cmp_less = 2; +constexpr unsigned mesh57_cmp_equal = 3; +constexpr unsigned mesh57_cmp_less_equal = 4; +constexpr unsigned mesh57_cmp_greater = 5; +constexpr unsigned mesh57_cmp_not_equal = 6; +constexpr unsigned mesh57_cmp_greater_equal = 7; +constexpr unsigned mesh57_cmp_always = 8; + +constexpr unsigned mesh57_sop_keep = 1; +constexpr unsigned mesh57_sop_zero = 2; +constexpr unsigned mesh57_sop_replace = 3; +constexpr unsigned mesh57_sop_incr_sat = 4; +constexpr unsigned mesh57_sop_decr_sat = 5; +constexpr unsigned mesh57_sop_invert = 6; +constexpr unsigned mesh57_sop_incr = 7; +constexpr unsigned mesh57_sop_decr = 8; + +constexpr unsigned mesh57_fmt_r32g8x24_typeless = 19; +constexpr unsigned mesh57_fmt_d32_float_s8x24 = 20; +constexpr unsigned mesh57_fmt_d32_float = 40; +constexpr unsigned mesh57_fmt_r24g8_typeless = 44; +constexpr unsigned mesh57_fmt_d24_unorm_s8 = 45; + +inline bool mesh57_format_has_stencil(unsigned format) noexcept +{ + return format == mesh57_fmt_d24_unorm_s8 || format == mesh57_fmt_d32_float_s8x24 || + format == mesh57_fmt_r24g8_typeless || format == mesh57_fmt_r32g8x24_typeless; +} + +inline unsigned mesh57_bits(std::uint32_t value, unsigned lo, unsigned hi) noexcept +{ + return (value >> lo) & ((1u << (hi - lo + 1u)) - 1u); +} + +inline unsigned mesh57_compare(std::uint32_t frag) noexcept +{ + return (frag & 7u) + 1u; +} + +inline unsigned mesh57_stencil_op(std::uint32_t op, std::uint32_t opval) noexcept +{ + switch (op) { + case 0: return mesh57_sop_keep; + case 1: return mesh57_sop_zero; + case 3: return mesh57_sop_replace; + case 5: return opval == 1u ? mesh57_sop_incr_sat : 0u; + case 6: return opval == 1u ? mesh57_sop_decr_sat : 0u; + case 7: return mesh57_sop_invert; + case 8: return opval == 1u ? mesh57_sop_incr : 0u; + case 9: return opval == 1u ? mesh57_sop_decr : 0u; + default: return 0u; + } +} + +// Same fields as decode_depth_stencil. A disabled test is canonical: depth function ALWAYS, +// and a disabled stencil is KEEP / ALWAYS with both masks 0xFF. +inline Mesh57DepthFacts mesh57_depth_facts(std::uint32_t depth_control, std::uint32_t stencil_control, + std::uint32_t refmask, std::uint32_t refmask_bf) noexcept +{ + Mesh57DepthFacts out; + if (mesh57_bits(depth_control, 30, 31) != 0) { + out.reason = "colour writes tied to the depth result (DB_DEPTH_CONTROL bits 30-31)"; + return out; + } + const bool z = mesh57_bits(depth_control, 1, 1) != 0; + out.depth_enable = z; + out.depth_write = z && mesh57_bits(depth_control, 2, 2) != 0 ? 1u : 0u; + out.depth_func = mesh57_compare(mesh57_bits(depth_control, 4, 6)); + out.depth_bounds = mesh57_bits(depth_control, 3, 3) != 0; + out.stencil_enable = mesh57_bits(depth_control, 0, 0) != 0; + const bool back_own = mesh57_bits(depth_control, 7, 7) != 0; + out.stencil_read_mask = mesh57_bits(refmask, 8, 15); + out.stencil_write_mask = mesh57_bits(refmask, 16, 23); + const unsigned opval = mesh57_bits(refmask, 24, 31); + const unsigned opval_bf = back_own ? mesh57_bits(refmask_bf, 24, 31) : opval; + auto face = [&](unsigned& fail, unsigned& pass, unsigned& depth_fail, unsigned& func, unsigned lo, + unsigned guest_func, unsigned val) { + fail = mesh57_stencil_op(mesh57_bits(stencil_control, lo, lo + 3u), val); + pass = mesh57_stencil_op(mesh57_bits(stencil_control, lo + 4u, lo + 7u), val); + depth_fail = mesh57_stencil_op(mesh57_bits(stencil_control, lo + 8u, lo + 11u), val); + func = mesh57_compare(guest_func); + return fail != 0 && pass != 0 && depth_fail != 0; + }; + const bool front_ok = face(out.front_fail, out.front_pass, out.front_depth_fail, out.front_func, 0, + mesh57_bits(depth_control, 8, 10), opval); + bool back_ok = front_ok; + if (back_own) { + back_ok = face(out.back_fail, out.back_pass, out.back_depth_fail, out.back_func, 12, + mesh57_bits(depth_control, 20, 22), opval_bf); + } else { + out.back_fail = out.front_fail; + out.back_pass = out.front_pass; + out.back_depth_fail = out.front_depth_fail; + out.back_func = out.front_func; + } + if (out.stencil_enable && (!front_ok || !back_ok)) { + out.reason = "stencil op without a D3D12 form (ONES, REPLACE_OP, logic op, or add / subtract by other than one)"; + return out; + } + if (!out.stencil_enable) { + out.stencil_read_mask = 0xff; + out.stencil_write_mask = 0xff; + out.front_fail = out.front_depth_fail = out.front_pass = mesh57_sop_keep; + out.back_fail = out.back_depth_fail = out.back_pass = mesh57_sop_keep; + out.front_func = out.back_func = mesh57_cmp_always; + } else { + out.stencil_ref = mesh57_bits(refmask, 0, 7); + if (back_own && mesh57_bits(refmask_bf, 0, 23) != mesh57_bits(refmask, 0, 23)) + out.masks_differ = true; + } + if (!z) + out.depth_func = mesh57_cmp_always; + out.ok = true; + return out; +} + +inline bool mesh57_cmp_in_range(unsigned func) noexcept +{ + return func >= mesh57_cmp_never && func <= mesh57_cmp_always; +} + +inline bool mesh57_op_in_range(unsigned op) noexcept +{ + return op >= mesh57_sop_keep && op <= mesh57_sop_decr; +} + +inline const char* mesh57_color_target_reason() noexcept +{ + return "derived mesh needs one single-sample color target, a viewport and a scissor"; +} + +// bounds_switch is X2W_MESH57_DERIVED_BOUNDS=1. Off, an enabled test is still +// "derived mesh keeps depth and stencil disabled", and a bound depth view is still refused. +// On, the decoded description is kept. A form this path cannot copy exactly is refused. +inline Mesh57DerivedDepth mesh57_derived_depth(bool bounds_switch, const Mesh57DepthFacts& depth, + const Mesh57DepthTargets& targets) noexcept +{ + Mesh57DerivedDepth out; + if (!bounds_switch) { + if (depth.depth_enable || depth.stencil_enable) { + out.reason = "derived mesh keeps depth and stencil disabled"; + out.remember = true; + return out; + } + if (!targets.targets_bound || !targets.viewport_set || !targets.scissor_set || + !targets.targets_single_sample || targets.target_count != 1 || !targets.has_target0 || + targets.dsv_format != 0 || targets.target0_format == 0) { + out.reason = mesh57_color_target_reason(); + return out; + } + return out; + } + if (!depth.ok) { + out.reason = depth.reason ? depth.reason : "derived mesh depth state was refused"; + out.remember = true; + return out; + } + if (depth.depth_bounds) { + out.reason = "derived mesh depth bounds are not a desktop depth-stencil state"; + out.remember = true; + return out; + } + if (depth.masks_differ) { + out.reason = "derived mesh back-face stencil masks differ from the front"; + out.remember = true; + return out; + } + const bool stencil_ops = !depth.stencil_enable || + (mesh57_cmp_in_range(depth.front_func) && mesh57_cmp_in_range(depth.back_func) && + mesh57_op_in_range(depth.front_fail) && mesh57_op_in_range(depth.front_pass) && + mesh57_op_in_range(depth.front_depth_fail) && mesh57_op_in_range(depth.back_fail) && + mesh57_op_in_range(depth.back_pass) && mesh57_op_in_range(depth.back_depth_fail)); + if (!mesh57_cmp_in_range(depth.depth_func) || !stencil_ops) { + out.reason = "derived mesh depth or stencil op has no D3D12 form"; + out.remember = true; + return out; + } + if (!targets.targets_bound || !targets.viewport_set || !targets.scissor_set || + targets.target_count != 1 || !targets.has_target0 || targets.target0_format == 0) { + out.reason = mesh57_color_target_reason(); + return out; + } + if ((targets.has_target0 && targets.color_samples == 0) || + (targets.depth_bound && targets.depth_samples == 0)) { + out.reason = "derived mesh sample count is unknown"; + return out; + } + if (targets.dsv_format != 0 && !targets.depth_bound) { + out.reason = "derived mesh depth buffer sample count is unknown"; + return out; + } + const bool color_single = targets.color_samples == 1 && targets.color_quality == 0; + const bool depth_msaa = targets.depth_samples != 1 || targets.depth_quality != 0; + const bool samples_differ = targets.depth_samples != targets.color_samples || + targets.depth_quality != targets.color_quality; + if (targets.depth_bound && color_single && depth_msaa) { + out.reason = "derived mesh depth buffer is multisampled"; + return out; + } + if (targets.depth_bound && samples_differ) { + out.reason = "derived mesh color and depth sample counts differ"; + return out; + } + if (!color_single) { + out.reason = "derived mesh needs one single-sample color target"; + return out; + } + if ((depth.depth_enable || depth.stencil_enable) && targets.dsv_format == 0) { + out.reason = "derived mesh depth or stencil test needs a bound depth buffer"; + return out; + } + if (depth.stencil_enable && !mesh57_format_has_stencil(targets.dsv_format)) { + out.reason = "derived mesh stencil test needs a stencil plane in the depth format"; + return out; + } + out.dsv_format = targets.dsv_format; + if (depth.stencil_enable) { + out.set_stencil_ref = true; + out.stencil_ref = depth.stencil_ref & 0xffu; + } + return out; +} + +} // namespace x2w_startup diff --git a/src/startup_stubs/native_mesh57.inl b/src/startup_stubs/native_mesh57.inl index 5b177b0829..d5e8217b3b 100644 --- a/src/startup_stubs/native_mesh57.inl +++ b/src/startup_stubs/native_mesh57.inl @@ -863,13 +863,53 @@ const char* derive_slot57_mesh(Wrapper* pipeline, Pass& pass, const D3D12_BLEND_ 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"); + // X2W_MESH57_DERIVED_BOUNDS=1 keeps this decoded description. Off, an enabled test and a bound + // depth view stay refused with the previous reason strings. + const bool derived_bounds = x2w_local::env_on("X2W_MESH57_DERIVED_BOUNDS"); + x2w_startup::Mesh57DepthFacts depth_facts; + depth_facts.ok = depth.ok; + depth_facts.reason = depth.reason; + depth_facts.depth_enable = depth.desc.DepthEnable != FALSE; + depth_facts.stencil_enable = depth.desc.StencilEnable != FALSE; + depth_facts.depth_bounds = depth.depth_bounds; + depth_facts.masks_differ = depth.masks_differ; + depth_facts.depth_write = depth.desc.DepthWriteMask == D3D12_DEPTH_WRITE_MASK_ALL ? 1u : 0u; + depth_facts.depth_func = static_cast(depth.desc.DepthFunc); + depth_facts.stencil_read_mask = depth.desc.StencilReadMask; + depth_facts.stencil_write_mask = depth.desc.StencilWriteMask; + depth_facts.front_fail = static_cast(depth.desc.FrontFace.StencilFailOp); + depth_facts.front_depth_fail = static_cast(depth.desc.FrontFace.StencilDepthFailOp); + depth_facts.front_pass = static_cast(depth.desc.FrontFace.StencilPassOp); + depth_facts.front_func = static_cast(depth.desc.FrontFace.StencilFunc); + depth_facts.back_fail = static_cast(depth.desc.BackFace.StencilFailOp); + depth_facts.back_depth_fail = static_cast(depth.desc.BackFace.StencilDepthFailOp); + depth_facts.back_pass = static_cast(depth.desc.BackFace.StencilPassOp); + depth_facts.back_func = static_cast(depth.desc.BackFace.StencilFunc); + depth_facts.stencil_ref = depth.stencil_ref; + x2w_startup::Mesh57DepthTargets depth_targets; + depth_targets.targets_bound = pass.targets_bound; + depth_targets.viewport_set = pass.viewport_set; + depth_targets.scissor_set = pass.scissor_set; + depth_targets.targets_single_sample = pass.targets_single_sample; + depth_targets.target_count = pass.target_count; + depth_targets.has_target0 = pass.target0 != nullptr; + depth_targets.target0_format = static_cast(pass.target_formats[0]); + depth_targets.dsv_format = static_cast(pass.dsv_format); + if (derived_bounds && pass.target0) { + const auto color_samples = pass.target0->GetDesc().SampleDesc; + depth_targets.color_samples = color_samples.Count; + depth_targets.color_quality = color_samples.Quality; + } + if (derived_bounds && pass.bound_depth) { + const auto depth_samples = pass.bound_depth->GetDesc().SampleDesc; + depth_targets.depth_samples = depth_samples.Count; + depth_targets.depth_quality = depth_samples.Quality; + depth_targets.depth_bound = true; + } + const auto depth_decision = x2w_startup::mesh57_derived_depth(derived_bounds, depth_facts, depth_targets); + if (depth_decision.reason) + return depth_decision.remember ? remember(depth_decision.reason) : depth_decision.reason; 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"; 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)) @@ -967,7 +1007,7 @@ const char* derive_slot57_mesh(Wrapper* pipeline, Pass& pass, const D3D12_BLEND_ targets.NumRenderTargets = 1; targets.RTFormats[0] = pass.target_formats[0]; stream.rtv_formats.value = targets; - stream.dsv_format.value = DXGI_FORMAT_UNKNOWN; + stream.dsv_format.value = static_cast(depth_decision.dsv_format); DXGI_SAMPLE_DESC samples; samples.Count = 1; samples.Quality = 0; @@ -1015,6 +1055,10 @@ const char* derive_slot57_mesh(Wrapper* pipeline, Pass& pass, const D3D12_BLEND_ graphics.constant_guest = 0; graphics.plain_constants = root_heap_flags(root) == 0; } + if (depth_decision.set_stencil_ref) { + graphics.mesh57_stencil_ref = true; + graphics.mesh57_stencil_ref_value = depth_decision.stencil_ref; + } AcquireSRWLockExclusive(¬e_lock); if (pipeline->own().real) { ReleaseSRWLockExclusive(¬e_lock); diff --git a/tests/mesh57_derived_depth_check.cpp b/tests/mesh57_derived_depth_check.cpp new file mode 100644 index 0000000000..042ca1e813 --- /dev/null +++ b/tests/mesh57_derived_depth_check.cpp @@ -0,0 +1,231 @@ +// Host check for the opt-in derived mesh depth decision. Register words are assembled here. +// The switch-off path keeps the previous refusal strings. +#include "startup_stubs/mesh57_derived_depth.h" + +#include +#include +#include + +namespace { +int fail(const char* name) +{ + std::fprintf(stderr, "mesh57 derived depth: %s\n", name); + return 1; +} + +constexpr std::uint32_t depth_control(bool stencil, bool z, bool z_write, bool bounds, unsigned zfunc, bool backface, + unsigned sfunc, unsigned sfunc_bf) +{ + return static_cast(stencil) | static_cast(z) << 1 | + static_cast(z_write) << 2 | static_cast(bounds) << 3 | (zfunc & 7u) << 4 | + static_cast(backface) << 7 | (sfunc & 7u) << 8 | (sfunc_bf & 7u) << 20; +} + +constexpr std::uint32_t stencil_control(unsigned fail, unsigned zpass, unsigned zfail, unsigned fail_bf, unsigned zpass_bf, + unsigned zfail_bf) +{ + return fail | zpass << 4 | zfail << 8 | fail_bf << 12 | zpass_bf << 16 | zfail_bf << 20; +} + +constexpr std::uint32_t refmask(unsigned test, unsigned mask, unsigned write, unsigned opval) +{ + return test | mask << 8 | write << 16 | opval << 24; +} + +x2w_startup::Mesh57DepthTargets color_target() +{ + x2w_startup::Mesh57DepthTargets targets; + targets.targets_bound = true; + targets.viewport_set = true; + targets.scissor_set = true; + targets.targets_single_sample = true; + targets.target_count = 1; + targets.has_target0 = true; + targets.target0_format = 28; + return targets; +} + +x2w_startup::Mesh57DepthTargets depth_target(unsigned format, unsigned color_samples = 1, unsigned depth_samples = 1, + unsigned color_quality = 0, unsigned depth_quality = 0) +{ + auto targets = color_target(); + targets.dsv_format = format; + targets.depth_bound = true; + targets.color_samples = color_samples; + targets.color_quality = color_quality; + targets.depth_samples = depth_samples; + targets.depth_quality = depth_quality; + targets.targets_single_sample = color_samples == 1 && color_quality == 0 && depth_samples == 1 && depth_quality == 0; + return targets; +} + +bool reason_is(const x2w_startup::Mesh57DerivedDepth& decision, const char* reason, bool remember) +{ + return decision.reason && std::strcmp(decision.reason, reason) == 0 && decision.remember == remember && + !decision.set_stencil_ref && decision.dsv_format == 0; +} + +using x2w_startup::mesh57_cmp_always; +using x2w_startup::mesh57_cmp_equal; +using x2w_startup::mesh57_cmp_greater; +using x2w_startup::mesh57_cmp_greater_equal; +using x2w_startup::mesh57_cmp_less; +using x2w_startup::mesh57_cmp_less_equal; +using x2w_startup::mesh57_cmp_never; +using x2w_startup::mesh57_cmp_not_equal; +using x2w_startup::mesh57_fmt_d24_unorm_s8; +using x2w_startup::mesh57_fmt_d32_float; +using x2w_startup::mesh57_sop_decr; +using x2w_startup::mesh57_sop_decr_sat; +using x2w_startup::mesh57_sop_incr; +using x2w_startup::mesh57_sop_incr_sat; +using x2w_startup::mesh57_sop_invert; +using x2w_startup::mesh57_sop_keep; +using x2w_startup::mesh57_sop_replace; +using x2w_startup::mesh57_sop_zero; +} // namespace + +int main() +{ + const std::uint32_t measured = depth_control(true, true, true, false, 6, true, 7, 7); + const std::uint32_t keep = stencil_control(0, 0, 0, 0, 0, 0); + const std::uint32_t masks = refmask(0x5c, 0xff, 0xff, 1); + const auto facts = x2w_startup::mesh57_depth_facts(measured, keep, masks, masks); + if (!facts.ok || facts.reason || !facts.depth_enable || facts.depth_write != 1 || + facts.depth_func != mesh57_cmp_greater_equal || !facts.stencil_enable || facts.stencil_ref != 0x5c || + facts.stencil_read_mask != 0xff || facts.stencil_write_mask != 0xff || facts.front_func != mesh57_cmp_always || + facts.back_func != mesh57_cmp_always || facts.front_fail != mesh57_sop_keep || facts.back_pass != mesh57_sop_keep || + facts.depth_bounds || facts.masks_differ) + return fail("measured depth and stencil mapping"); + + const unsigned funcs[8] = {mesh57_cmp_never, mesh57_cmp_less, mesh57_cmp_equal, mesh57_cmp_less_equal, + mesh57_cmp_greater, mesh57_cmp_not_equal, mesh57_cmp_greater_equal, mesh57_cmp_always}; + for (unsigned frag = 0; frag < 8; ++frag) { + const auto decoded = x2w_startup::mesh57_depth_facts(depth_control(true, true, true, false, frag, true, frag, 7 - frag), + keep, masks, masks); + if (!decoded.ok || decoded.depth_func != funcs[frag] || decoded.front_func != funcs[frag] || + decoded.back_func != funcs[7 - frag] || decoded.depth_write != 1) + return fail("compare function order"); + } + + const struct { unsigned op; unsigned desktop; } ops[] = {{0, mesh57_sop_keep}, {1, mesh57_sop_zero}, + {3, mesh57_sop_replace}, {5, mesh57_sop_incr_sat}, + {6, mesh57_sop_decr_sat}, {7, mesh57_sop_invert}, + {8, mesh57_sop_incr}, {9, mesh57_sop_decr}}; + for (const auto& op : ops) { + const auto decoded = x2w_startup::mesh57_depth_facts( + depth_control(true, true, false, false, 6, true, 7, 2), stencil_control(op.op, 0, 0, 0, 0, op.op), + refmask(0, 0x28, 0, 1), refmask(0, 0x28, 0, 1)); + if (!decoded.ok || decoded.front_fail != op.desktop || decoded.back_depth_fail != op.desktop || + decoded.stencil_read_mask != 0x28 || decoded.stencil_write_mask != 0 || decoded.back_func != mesh57_cmp_equal) + return fail("stencil op mapping"); + } + + const auto front_only = x2w_startup::mesh57_depth_facts(depth_control(true, false, false, false, 7, false, 3, 0), + stencil_control(0, 8, 0, 9, 9, 9), refmask(1, 0x80, 0x80, 1), + refmask(9, 0, 0, 7)); + if (!front_only.ok || front_only.masks_differ || front_only.back_func != mesh57_cmp_less_equal || + front_only.back_pass != mesh57_sop_incr || front_only.stencil_ref != 1) + return fail("back faces follow the front"); + + const auto ones = x2w_startup::mesh57_depth_facts(depth_control(true, false, false, false, 7, true, 7, 7), + stencil_control(2, 0, 0, 0, 0, 0), masks, masks); + if (ones.ok || !ones.reason || std::strcmp(ones.reason, "stencil op without a D3D12 form (ONES, REPLACE_OP, logic op, or add / subtract by other than one)") != 0) + return fail("ONES refused"); + const auto add_two = x2w_startup::mesh57_depth_facts(depth_control(true, false, false, false, 7, true, 7, 7), + stencil_control(0, 8, 0, 0, 8, 0), refmask(0, 0xff, 0xff, 2), + refmask(0, 0xff, 0xff, 2)); + if (add_two.ok || !add_two.reason) + return fail("add by two refused"); + const auto tied = x2w_startup::mesh57_depth_facts(depth_control(false, true, true, false, 6, false, 7, 7) | 1u << 30, 0, 0, 0); + if (tied.ok || !tied.reason || std::strstr(tied.reason, "bits 30-31") == nullptr) + return fail("colour writes tied to depth refused"); + const auto ignored = x2w_startup::mesh57_depth_facts(depth_control(false, true, true, false, 1, true, 7, 7), + stencil_control(2, 2, 2, 2, 2, 2), 0, 0); + if (!ignored.ok || ignored.stencil_enable || ignored.front_fail != mesh57_sop_keep || ignored.depth_func != mesh57_cmp_less) + return fail("ops of a disabled stencil ignored"); + + const auto off_depth = x2w_startup::mesh57_derived_depth(false, facts, depth_target(mesh57_fmt_d24_unorm_s8)); + if (!reason_is(off_depth, "derived mesh keeps depth and stencil disabled", true)) + return fail("switch off keeps the depth refusal"); + auto disabled = x2w_startup::mesh57_depth_facts(depth_control(false, false, false, false, 1, false, 7, 7), 0, 0, 0); + auto bound = depth_target(mesh57_fmt_d32_float); + const auto off_bound = x2w_startup::mesh57_derived_depth(false, disabled, bound); + if (!reason_is(off_bound, "derived mesh needs one single-sample color target, a viewport and a scissor", false)) + return fail("switch off refuses a bound depth view"); + auto bounds_on = x2w_startup::mesh57_depth_facts(depth_control(false, true, true, true, 6, false, 7, 7), 0, 0, 0); + const auto off_bounds = x2w_startup::mesh57_derived_depth(false, bounds_on, depth_target(mesh57_fmt_d32_float)); + if (!reason_is(off_bounds, "derived mesh keeps depth and stencil disabled", true)) + return fail("switch off does not name depth bounds"); + const auto off_clear = x2w_startup::mesh57_derived_depth(false, disabled, color_target()); + if (off_clear.reason || off_clear.dsv_format || off_clear.set_stencil_ref) + return fail("switch off accepts a disabled test"); + + const auto on = x2w_startup::mesh57_derived_depth(true, facts, depth_target(mesh57_fmt_d24_unorm_s8)); + if (on.reason || on.dsv_format != mesh57_fmt_d24_unorm_s8 || !on.set_stencil_ref || on.stencil_ref != 0x5c) + return fail("switch on carries depth, format and stencil reference"); + auto depth_only = x2w_startup::mesh57_depth_facts(depth_control(false, true, true, false, 6, false, 7, 7), 0, 0, 0); + const auto on_depth = x2w_startup::mesh57_derived_depth(true, depth_only, depth_target(mesh57_fmt_d32_float)); + if (on_depth.reason || on_depth.dsv_format != mesh57_fmt_d32_float || on_depth.set_stencil_ref || + depth_only.depth_func != mesh57_cmp_greater_equal || depth_only.depth_write != 1) + return fail("switch on carries depth without a stencil reference"); + const auto on_disabled_depth = x2w_startup::mesh57_derived_depth(true, disabled, bound); + if (on_disabled_depth.reason || on_disabled_depth.dsv_format != mesh57_fmt_d32_float || on_disabled_depth.set_stencil_ref) + return fail("switch on accepts a bound depth view"); + + const auto on_bounds = x2w_startup::mesh57_derived_depth(true, bounds_on, depth_target(mesh57_fmt_d32_float)); + if (!reason_is(on_bounds, "derived mesh depth bounds are not a desktop depth-stencil state", true)) + return fail("depth bounds refused"); + const auto differ = x2w_startup::mesh57_depth_facts(measured, keep, masks, refmask(0x5c, 0x0f, 0xff, 1)); + if (!differ.ok || !differ.masks_differ || differ.stencil_read_mask != 0xff) + return fail("back masks differ flagged"); + const auto on_masks = x2w_startup::mesh57_derived_depth(true, differ, depth_target(mesh57_fmt_d24_unorm_s8)); + if (!reason_is(on_masks, "derived mesh back-face stencil masks differ from the front", true)) + return fail("differing back-face masks refused"); + const auto on_missing = x2w_startup::mesh57_derived_depth(true, facts, color_target()); + if (!reason_is(on_missing, "derived mesh depth or stencil test needs a bound depth buffer", false)) + return fail("depth test without a depth buffer refused"); + const auto on_msaa = x2w_startup::mesh57_derived_depth(true, facts, depth_target(mesh57_fmt_d24_unorm_s8, 1, 4)); + if (!reason_is(on_msaa, "derived mesh depth buffer is multisampled", false)) + return fail("multisampled depth refused"); + const auto on_mismatch = x2w_startup::mesh57_derived_depth(true, depth_only, depth_target(mesh57_fmt_d32_float, 4, 2)); + if (!reason_is(on_mismatch, "derived mesh color and depth sample counts differ", false)) + return fail("sample counts differ"); + const auto on_color = x2w_startup::mesh57_derived_depth(true, depth_only, depth_target(mesh57_fmt_d32_float, 4, 4)); + if (!reason_is(on_color, "derived mesh needs one single-sample color target", false)) + return fail("multisampled color refused"); + const auto on_plane = x2w_startup::mesh57_derived_depth(true, facts, depth_target(mesh57_fmt_d32_float)); + if (!reason_is(on_plane, "derived mesh stencil test needs a stencil plane in the depth format", false)) + return fail("stencil without a stencil plane refused"); + auto unknown = depth_target(mesh57_fmt_d24_unorm_s8); + unknown.depth_bound = false; + const auto on_unknown = x2w_startup::mesh57_derived_depth(true, facts, unknown); + if (!reason_is(on_unknown, "derived mesh depth buffer sample count is unknown", false)) + return fail("unknown depth sample count refused"); + auto zero_samples = depth_target(mesh57_fmt_d32_float); + zero_samples.depth_samples = 0; + const auto on_zero = x2w_startup::mesh57_derived_depth(true, depth_only, zero_samples); + if (!reason_is(on_zero, "derived mesh sample count is unknown", false)) + return fail("zero sample count refused"); + auto no_viewport = depth_target(mesh57_fmt_d24_unorm_s8); + no_viewport.viewport_set = false; + const auto on_viewport = x2w_startup::mesh57_derived_depth(true, facts, no_viewport); + if (!reason_is(on_viewport, "derived mesh needs one single-sample color target, a viewport and a scissor", false)) + return fail("missing viewport refused"); + + auto bare = facts; + bare.depth_func = 0; + const auto on_compare = x2w_startup::mesh57_derived_depth(true, bare, depth_target(mesh57_fmt_d24_unorm_s8)); + if (!reason_is(on_compare, "derived mesh depth or stencil op has no D3D12 form", true)) + return fail("unsupported compare refused"); + bare = facts; + bare.front_fail = 0; + const auto on_op = x2w_startup::mesh57_derived_depth(true, bare, depth_target(mesh57_fmt_d24_unorm_s8)); + if (!reason_is(on_op, "derived mesh depth or stencil op has no D3D12 form", true)) + return fail("unsupported stencil op refused"); + x2w_startup::Mesh57DepthFacts empty; + const auto on_empty = x2w_startup::mesh57_derived_depth(true, empty, color_target()); + if (!on_empty.reason || std::strcmp(on_empty.reason, "derived mesh depth state was refused") != 0 || !on_empty.remember) + return fail("missing decode refused"); + return 0; +} From 8905a426290baeb51198a7486d92f665e967608e Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Mon, 30 Nov 2026 16:55:57 +0000 Subject: [PATCH 15/24] startup: accept the derived mesh record multiply chain X2W_MESH57_DERIVED_BOUNDS=1 treats v_bfe_u32 as a field extract and accepts v_mul_lo_u32 by min(base + (1 << k), L) - base when k is a logical shift right by 29. The limit stays (mask + 1) * 2^k with the caller-passed k of 1, and a product above 256 stays refused. Unsigned wrap of that subtract is possible; SetMeshOutputCounts still clamps to the derived limit. A color-target refusal logs which condition failed, once per pipeline key. The switch still defaults off. --- docs/experiments/native-fixed-mesh57.md | 14 +- docs/startup-runtime.md | 2 +- src/startup_stubs/mesh57_alloc.h | 234 +++++++++++++++++++++-- src/startup_stubs/mesh57_derived_depth.h | 47 +++++ src/startup_stubs/native_mesh57.inl | 35 +++- tests/mesh57_derived_depth_check.cpp | 51 +++++ tests/mesh57_record_bounds_check.cpp | 106 ++++++++++ 7 files changed, 470 insertions(+), 19 deletions(-) diff --git a/docs/experiments/native-fixed-mesh57.md b/docs/experiments/native-fixed-mesh57.md index 114cecc982..7dc0efd744 100644 --- a/docs/experiments/native-fixed-mesh57.md +++ b/docs/experiments/native-fixed-mesh57.md @@ -156,9 +156,13 @@ On the Windows test PC at `35b0d542`, the same switches, a 420 second run, forwa `X2W_MESH57_DERIVED_BOUNDS=1` is a second switch, off by default, and it does nothing unless `X2W_MESH57_DERIVE_STATE=1` is also set. Unset, slot 57 derivation is unchanged, including the heap-indexed root refusal and the immediate `m0` reader. -Set, `mesh57_read_record_m0_bounds` may supply the output limit for a program the immediate reader refuses. The program has one `s_sendmsg` `GS_ALLOC_REQ`. The two instructions immediately before it are `s_lshl_b32 sX, sP, 12` and `s_or_b32 m0, sX, sV` (either operand order of the `or`). `sV` and `sP` are each `(field & mask) + 1` from one record word: the vertex field is the low mask and the primitive field is that word shifted by the mask width. A `v_readfirstlane` of that sum, and an `s_cselect_b32` of the count against immediate 0, still count as the same value. The per-record maximum is `mask + 1`. +Set, `mesh57_read_record_m0_bounds` may supply the output limit for a program the immediate reader refuses. The program has one `s_sendmsg` `GS_ALLOC_REQ`. The two instructions immediately before it are `s_lshl_b32 sX, sP, 12` and `s_or_b32 m0, sX, sV` (either operand order of the `or`). `sV` and `sP` are each `(field & mask) + 1` from one record word: the vertex field is the low mask and the primitive field is that word shifted by the mask width. `v_bfe_u32` of that word with an immediate offset and width is the same extract as a logical shift by the offset and a mask of `2^width - 1`. A `v_readfirstlane` of that sum, and an `s_cselect_b32` of the count against immediate 0, still count as the same value. The per-record maximum is `mask + 1`. -The entry multiply `k` is accepted only when the caller passes the constant 1. That is the measured entry state for this switch. The reader does not load user data 13, and it does not assign user SGPRs for the five-parameter heap-indexed root. An unknown `k` is `derived mesh record multiply k is unknown`. Any other `k` is `derived mesh record multiply k is not 1`. The limit is the per-record maximum times `2^k`. A product above 256 vertices or 256 primitives is `derived mesh record bound exceeds the mesh output limit`. A 7-bit mask and `k` 1 is 256, which is the D3D12 mesh output limit, so it is accepted. +Between the `+ 1` and the `v_readfirstlane`, the count may be `v_mul_lo_u32` by one scalar. That scalar is accepted only when it is `min(base + (1 << k), L) - base` and the add and the sub name the same base register. The chain is `s_sub_i32` of the min and the base, `s_min_u32` of the sum and `L`, `s_add_u32` of that base and `1 << k`, `s_lshl_b32` of the immediate 1 by a register, and `s_lshr_b32` of some SGPR by 29. That shift is at most 7. The reader matches registers, not fixed numbers. A scalar that is not this chain is `derived mesh record multiply scalar was not proven`. A min whose add uses a different base is `derived mesh record multiply base does not match`. A shift other than 29 is `derived mesh record multiply shift is not 29`. A multiply whose operand is not one scalar register is `derived mesh record multiply operand is not a scalar`. A missing min or add is named the same way. + +The subtract can wrap. The chain does not prove `L >= base`, and it does not prove that `base + (1 << k)` stays inside 32 bits. If `L < base` and the add does not wrap, `min` selects `L` and the subtract underflows, so the multiplier can exceed `2^k`. If the add wraps, the result is also not bounded by `2^k`. `1 << k` itself fits, because the shift amount is a 32-bit value shifted right by 29. The translated `SetMeshOutputCounts` still clamps each runtime count, the post-cselect `v_readfirstlane` of the multiplied value, with an unsigned `ule` select against the derived limit. A wrapped product is not passed above that maximum. + +The entry multiply `k` is accepted only when the caller passes the constant 1. That is the measured entry state for this switch, and it is the `k` in `(mask + 1) * 2^k`. The reader does not load user data 13, and it does not assign user SGPRs for the five-parameter heap-indexed root. An unknown `k` is `derived mesh record multiply k is unknown`. Any other `k` is `derived mesh record multiply k is not 1`. A product above 256 vertices or 256 primitives is `derived mesh record bound exceeds the mesh output limit`. A 7-bit mask and `k` 1 is 256, which is the D3D12 mesh output limit, so it is accepted. The same limit holds when the 7-bit primitive field is a `v_bfe_u32` and both counts are multiplied by the proven scalar. The group size comes from `gfx1013_direct_mesh.inl`. That lowerer indexes each vertex and each primitive with `flattenedThreadIdInGroup`, splits a wave64 id into `lane = id & 63` and `wave = id >> 6`, and skips the write when the id is at or past the runtime count. One thread emits one output. The group is the smallest multiple of 64 that covers the larger derived limit: 256 for the 7-bit, `k` 1 case, and 128 for a 6-bit mask. A program with no wave64 proof is refused rather than given a guessed wave width. The direct mesh path allows that group only when this layout sets `record_output_counts`. Every other mesh keeps the 128-thread check. A desktop compiler can still refuse `numthreads` of 256; this path does not lower the group to 128 to hide that. @@ -166,7 +170,7 @@ The group size comes from `gfx1013_direct_mesh.inl`. That lowerer indexes each v The first time a distinct pair is derived this way, stderr gets one `x2w-render mesh57-derive bounds` line: mesh and pixel byte counts, `v`, `p`, `threads`, `pattern=record-m0`, and `k`. The line has no pointer. At most eight distinct lines are kept. The global on-chip budget in the pipeline register block is not a per-shader size and is not read here. -`mesh57_record_bounds` checks the assembled pattern: the 7-bit limit, the 6-bit limit, an unknown `k`, a `k` other than 1, a mask whose product exceeds 256, the immediate triangle (3 vertices, 1 primitive, 64 threads), and that the immediate reader still refuses the record program. It does not need a device. +`mesh57_record_bounds` checks the assembled pattern: the 7-bit limit, the 6-bit limit, an unknown `k`, a `k` other than 1, a mask whose product exceeds 256, the immediate triangle (3 vertices, 1 primitive, 64 threads), and that the immediate reader still refuses the record program. It also checks the `v_bfe_u32` plus proven `v_mul_lo_u32` chain at the same 256 limit, and the refusals for an unproven scalar, a mismatched base, a shift other than 29, and a multiplied mask whose product exceeds 256. It does not need a device. ```powershell ctest --preset dev --no-tests=error -R 'mesh57_record_bounds|mesh57_derive_alloc' @@ -180,7 +184,9 @@ Heap 1024 is the view-heap flag (`0x400`). Heap 3072 is that flag plus the sampl A form that cannot be copied exactly stays refused, and the reason names it. Depth bounds are not a desktop depth-stencil field. Back-face stencil masks or a reference that differ from the front are not one desktop reference and one pair of masks. A stencil op or compare with no desktop form stays refused. A depth or stencil test with no depth view, a multisampled depth buffer, color and depth sample counts that differ, a zero sample count, and a stencil test whose depth format has no stencil plane stay refused. The format is the bound view's format. This path does not choose one. Those attachment refusals are not remembered: a later list can bind a depth view. A refusal that comes from the pipeline's own registers is remembered. -`mesh57_derived_depth` checks the register-word mapping, the switch-off refusals, and each of those reasons. It does not need a device. +When the switch is on and this color-target check refuses, one `x2w-render mesh57-derive targets` line is logged per pipeline key, and at most eight keys are kept. The line names whether targets are bound, whether the viewport and scissor are set, the color-target count, whether target 0 is present, whether its format is known, and the color and depth sample counts. It has no pointer and no raw word. The census still receives the same refusal string. The switch off does not log the line. + +`mesh57_derived_depth` checks the register-word mapping, the switch-off refusals, each of those reasons, and the target-gap line for a missing bind, viewport, scissor, count, target, format, or sample count. It does not need a device. ```powershell ctest --preset dev --no-tests=error -R 'mesh57_derived_depth|mesh57_record_bounds|mesh57_derive_alloc' diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index c30270d49e..befbb1fe79 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -1804,7 +1804,7 @@ ctest --preset dev --no-tests=error -R '^startup_hook_(window|overlap)$' -V | `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 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 and stencil unless `X2W_MESH57_DERIVED_BOUNDS=1`, 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_MESH57_DERIVED_BOUNDS=1` | experimental, with `X2W_MESH57_DERIVE_STATE=1`. Off by default, and unset it leaves the slot 57 derivation unchanged. Set, a mesh whose `m0` is `s_lshl_b32` by 12 then `s_or_b32` into `m0` immediately before the only `GS_ALLOC_REQ`, with both counts proven as `(field & mask) + 1` from one record word, may use those masks as the output limit. The multiply is `2^k` only when the entry `k` is the constant 1; an unknown `k` or any other `k` stays refused. A product above 256 vertices or 256 primitives stays refused. The group is the smallest multiple of 64 that covers that limit, from the direct mesh lane id (one thread writes one output). The translated shader passes the runtime counts to `SetMeshOutputCounts`. The immediate `m0` reader is unchanged. This switch does not invent a user-SGPR map for a heap-indexed root. With the switch on, the decoded depth and stencil state is copied into the derived mesh pipeline, the bound depth view's format is the pipeline depth format, and the dispatch sets the decoded stencil reference. Depth bounds, differing back-face masks, a multisampled depth buffer, and a stencil test without a stencil plane stay refused. See [Opt-in record bounds](experiments/native-fixed-mesh57.md#opt-in-record-bounds) | +| `X2W_MESH57_DERIVED_BOUNDS=1` | experimental, with `X2W_MESH57_DERIVE_STATE=1`. Off by default, and unset it leaves the slot 57 derivation unchanged. Set, a mesh whose `m0` is `s_lshl_b32` by 12 then `s_or_b32` into `m0` immediately before the only `GS_ALLOC_REQ`, with both counts proven as `(field & mask) + 1` from one record word, may use those masks as the output limit. The multiply is `2^k` only when the entry `k` is the constant 1; an unknown `k` or any other `k` stays refused. A `v_bfe_u32` field, and a `v_mul_lo_u32` by `min(base + (1 << k), L) - base` with that `k` taken from a logical shift right by 29, use the same limit. An unproven multiplier, a mismatched base, or a shift other than 29 stays refused. The subtract can wrap when `L` is below the base; `SetMeshOutputCounts` still clamps each runtime count to the derived limit. A product above 256 vertices or 256 primitives stays refused. A color-target refusal logs the failing condition once per pipeline key. The group is the smallest multiple of 64 that covers that limit, from the direct mesh lane id (one thread writes one output). The translated shader passes the runtime counts to `SetMeshOutputCounts`. The immediate `m0` reader is unchanged. This switch does not invent a user-SGPR map for a heap-indexed root. With the switch on, the decoded depth and stencil state is copied into the derived mesh pipeline, the bound depth view's format is the pipeline depth format, and the dispatch sets the decoded stencil reference. Depth bounds, differing back-face masks, a multisampled depth buffer, and a stencil test without a stencil plane stay refused. See [Opt-in record bounds](experiments/native-fixed-mesh57.md#opt-in-record-bounds) | | `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 8e931e8749..60442870aa 100644 --- a/src/startup_stubs/mesh57_alloc.h +++ b/src/startup_stubs/mesh57_alloc.h @@ -270,11 +270,35 @@ inline std::size_t mesh57_record_bounds_line(const Mesh57RecordBounds& bounds, u } // m0 built by s_lshl_b32 sX, sP, 12 and s_or_b32 m0, sX, sV immediately before the only -// s_sendmsg GS_ALLOC_REQ. sV and sP must each be (field & mask) + 1 from one record word: -// the vertex field is the low mask and the primitive field is that word shifted by the -// mask width. The per-record maximum is mask + 1. It is multiplied by 2^k only when the -// entry k is the constant 1; otherwise the program is refused. A product above the D3D12 -// mesh output limit (256 vertices, 256 primitives) is refused. +// s_sendmsg GS_ALLOC_REQ. sV and sP must each be (field & mask) + 1 from one record word. +// The field is an and with a low mask, or v_bfe_u32 of that word with an immediate offset +// and width. Those are the same bits: a logical shift by the offset, then a mask of +// 2^width - 1. The vertex field is the low mask and the primitive field is shifted by +// that width. A v_readfirstlane of the sum, and an s_cselect_b32 of the count against +// immediate 0, still count as the same value. +// +// Between the + 1 and the readfirstlane the count may be v_mul_lo_u32 by one scalar. +// That scalar is accepted only when it is min(base + (1 << k), L) - base, with the same +// base register in the add and the sub: s_sub_i32 of the min and the base, s_min_u32 of +// the sum and L, s_add_u32 of that base and (1 << k), s_lshl_b32 of the immediate 1 by a +// register, and that register defined by s_lshr_b32 of some SGPR by 29. The shift result +// is 0..7. Registers are matched by this chain, not by fixed numbers. User data 13 is +// not read. The bound uses the caller-passed k, not the runtime field. Any other op, a +// multiply by a scalar that is not this chain, a min whose add uses a different base, or +// a shift other than 29 is refused with a reason that names that step. +// +// The per-record maximum is (mask + 1) * 2^k, and only when the entry k is the constant +// 1. A product above the D3D12 mesh output limit (256 vertices, 256 primitives) is refused. +// +// Unsigned wrap is possible. The add and the subtract are 32-bit SOP2 ops. The chain does +// not prove L >= base, and it does not prove that base + (1 << k) stays inside 32 bits. +// If L < base and the add does not wrap, min selects L and the subtract underflows, so +// the multiplier can exceed 2^k. If the add wraps, the result is also not bounded by 2^k. +// 1 << k itself fits, because k is a 32-bit value shifted right by 29 and is at most 7. +// The translated SetMeshOutputCounts path still clamps each runtime scalar count, the +// post-cselect readfirstlane of the multiplied value, with an unsigned ule select against +// min(the derived limit, the group size). A wrapped product is not passed above that +// declared maximum. // // Group size comes from gfx1013_direct_mesh.inl. That lowerer indexes every vertex and // primitive by flattenedThreadIdInGroup, and it splits a wave64 thread as @@ -291,11 +315,17 @@ inline Mesh57RecordBoundsRead mesh57_read_record_m0_bounds(std::string_view code return out; try { struct Def { - unsigned kind = 0; // 1 mask, 2 add 1, 3 logical shift right, 4 copy, 5 unknown write + // 1 mask, 2 add 1, 3 logical shift right, 4 copy, 5 unknown write, + // 7 multiply by a scalar, 8 bitfield extract, 9 sub, 10 unsigned min, + // 11 add of two registers, 12 shift of the immediate 1, 15 multiply + // whose operand is not one scalar. + unsigned kind = 0; unsigned src = 0; bool src_vector = false; unsigned imm = 0; unsigned width = 0; + unsigned src2 = 0; + bool src2_reg = false; }; // Each write is kept, in order. A copy is read at the copy's own pc, so a later // reuse of its source register does not erase the count that was moved. @@ -408,6 +438,25 @@ inline Mesh57RecordBoundsRead mesh57_read_record_m0_bounds(std::string_view code put(at, false, op.dst, Def{3u, op.src0, false, op.v1, 0u}); return; } + // min(base + (1 << k), L) - base. Each step is recorded on its own so a + // missing one can be named. An immediate in either register operand is not + // this chain. + if (op.name == "s_sub_i32" && reg0 && reg1) { + put(at, false, op.dst, Def{9u, op.src0, false, 0u, 0u, op.src1, true}); + return; + } + if (op.name == "s_min_u32" && reg0 && reg1) { + put(at, false, op.dst, Def{10u, op.src0, false, 0u, 0u, op.src1, true}); + return; + } + if (op.name == "s_add_u32" && reg0 && reg1) { + put(at, false, op.dst, Def{11u, op.src0, false, 0u, 0u, op.src1, true}); + return; + } + if (op.name == "s_lshl_b32" && op.imm0 && op.v0 == 1u && reg1) { + put(at, false, op.dst, Def{12u, op.src1, false, 1u, 0u}); + return; + } // Kind 5 is a write this reader does not understand. It is not a record word. const Def unknown{5u, 0u, false, 0u, 0u}; put(at, false, op.dst, unknown); @@ -559,6 +608,60 @@ inline Mesh57RecordBoundsRead mesh57_read_record_m0_bounds(std::string_view code } else { note_vector_binary(pc, op); } + } else if (inst.form == x2w::gfx1013::Form::vop3 && inst.name == "v_mul_lo_u32") { + const unsigned mul0 = word1 & 511u; + const unsigned mul1 = (word1 >> 9) & 511u; + const unsigned mul2 = (word1 >> 18) & 511u; + const unsigned mul_abs = (raw >> 8) & 7u; + const unsigned mul_neg = word1 >> 29; + const unsigned mul_scale = (word1 >> 27) & 3u; + const bool mul_clamp = (raw & 0x8000u) != 0; + const bool mul_tail = mul2 == 0u || mul2 == 128u; + unsigned mul_vec = 0; + unsigned mul_scalar = 0; + bool mul_vec_ok = false; + bool mul_scalar_ok = false; + auto take_mul = [&](unsigned src) noexcept { + if (src >= 256u && src < 512u) { + if (mul_vec_ok) + return false; + mul_vec = src - 256u; + mul_vec_ok = true; + return true; + } + if (src < 106u) { + if (mul_scalar_ok) + return false; + mul_scalar = src; + mul_scalar_ok = true; + return true; + } + return false; + }; + if (!mul_abs && !mul_neg && !mul_scale && !mul_clamp && mul_tail && op.dst < 256u && + take_mul(mul0) && take_mul(mul1) && mul_vec_ok && mul_scalar_ok) + put(pc, true, op.dst, Def{7u, mul_vec, true, 0u, 0u, mul_scalar, true}); + else if (op.dst < 256u) + put(pc, true, op.dst, Def{15u, 0u, false, 0u, 0u}); + } else if (inst.form == x2w::gfx1013::Form::vop3 && inst.name == "v_bfe_u32") { + const unsigned bfe0 = word1 & 511u; + const unsigned bfe1 = (word1 >> 9) & 511u; + const unsigned bfe2 = (word1 >> 18) & 511u; + const unsigned bfe_abs = (raw >> 8) & 7u; + const unsigned bfe_neg = word1 >> 29; + const unsigned bfe_scale = (word1 >> 27) & 3u; + const bool bfe_clamp = (raw & 0x8000u) != 0; + std::uint32_t bfe_offset = 0; + std::uint32_t bfe_width = 0; + const bool bfe_plain = !bfe_abs && !bfe_neg && !bfe_scale && !bfe_clamp && bfe0 >= 256u && + bfe0 < 512u && src_imm(bfe1, has_literal, literal, bfe_offset) && + src_imm(bfe2, has_literal, literal, bfe_width); + if (bfe_plain && op.dst < 256u && bfe_width >= 1u && bfe_width < 32u && bfe_offset < 32u && + bfe_offset + bfe_width <= 32u) + put(pc, true, op.dst, Def{8u, bfe0 - 256u, true, static_cast(bfe_offset), + static_cast(bfe_width)}); + else if (op.dst < 256u) + put(pc, true, op.dst, Def{5u, 0u, false, 0u, 0u}); } else if (inst.form == x2w::gfx1013::Form::vop3 && op.dst < 256u) { put(pc, true, op.dst, Def{5u, 0u, false, 0u, 0u}); } @@ -633,9 +736,85 @@ inline Mesh57RecordBoundsRead mesh57_read_record_m0_bounds(std::string_view code unsigned record = 0; bool record_vector = false; }; + auto scalar_written = [&](unsigned after_pc, unsigned before_pc, unsigned reg) noexcept { + for (const Event& event : events) { + if (!event.is_vector && event.reg == reg && event.pc > after_pc && event.pc < before_pc) + return true; + } + return false; + }; + // The scalar is min(base + (1 << k), L) - base. k is some SGPR >> 29, so the + // shift amount is at most 7. The caller-passed k, not this field, sizes the bound. + auto prove_multiplier = [&](unsigned reg, unsigned at_pc) noexcept -> const char* { + const Seen sub = follow(at_pc, false, reg); + if (!sub.ok || sub.def.kind != 9u || !sub.def.src2_reg || sub.def.src == sub.def.src2) + return "derived mesh record multiply scalar was not proven"; + const unsigned min_reg = sub.def.src; + const unsigned base_reg = sub.def.src2; + const Seen minv = follow(sub.pc, false, min_reg); + if (!minv.ok || minv.def.kind != 10u || !minv.def.src2_reg) + return "derived mesh record multiply min was not proven"; + auto step_rank = [](const char* why) noexcept { + if (!why) + return 0; + if (std::strcmp(why, "derived mesh record multiply shift is not 29") == 0) + return 5; + if (std::strcmp(why, "derived mesh record multiply base does not match") == 0) + return 4; + if (std::strcmp(why, "derived mesh record multiply is not a power of two") == 0) + return 3; + if (std::strcmp(why, "derived mesh record multiply add was not proven") == 0) + return 2; + return 1; + }; + auto arm = [&](unsigned sum_reg) noexcept -> const char* { + const Seen sum = follow(minv.pc, false, sum_reg); + if (!sum.ok || sum.def.kind != 11u || !sum.def.src2_reg) + return "derived mesh record multiply add was not proven"; + unsigned pow_reg = 0; + if (sum.def.src == base_reg) + pow_reg = sum.def.src2; + else if (sum.def.src2 == base_reg) + pow_reg = sum.def.src; + else + return "derived mesh record multiply base does not match"; + if (sum.reg == base_reg || minv.reg == base_reg || scalar_written(sum.pc, sub.pc, base_reg)) + return "derived mesh record multiply base does not match"; + const Seen pow = follow(sum.pc, false, pow_reg); + if (!pow.ok || pow.def.kind != 12u) + return "derived mesh record multiply is not a power of two"; + const Seen shifted = follow(pow.pc, false, pow.def.src); + if (!shifted.ok || shifted.def.kind != 3u || shifted.def.imm != 29u) + return "derived mesh record multiply shift is not 29"; + return nullptr; + }; + const char* left = arm(minv.def.src); + if (!left) + return nullptr; + const char* right = arm(minv.def.src2); + if (!right) + return nullptr; + return step_rank(left) >= step_rank(right) ? left : right; + }; auto as_mask = [&](unsigned at_pc, bool is_vector, unsigned reg, Extract& extracted) noexcept { const Seen mask = follow(at_pc, is_vector, reg); - if (!mask.ok || mask.def.kind != 1u) + if (!mask.ok) + return false; + if (mask.def.kind == 8u) { + if (mask.def.width == 0u || mask.def.width >= 32u || mask.def.imm >= 32u || + mask.def.imm + mask.def.width > 32u) + return false; + const Seen record = follow(mask.pc, mask.def.src_vector, mask.def.src); + if (!record.ok || record.def.kind != 0u) + return false; + extracted.ok = true; + extracted.width = mask.def.width; + extracted.shift = mask.def.imm; + extracted.record = record.reg; + extracted.record_vector = record.is_vector; + return true; + } + if (mask.def.kind != 1u) return false; const Seen inner = follow(mask.pc, mask.def.src_vector, mask.def.src); if (!inner.ok) @@ -658,18 +837,47 @@ inline Mesh57RecordBoundsRead mesh57_read_record_m0_bounds(std::string_view code extracted.record_vector = inner.is_vector; return true; }; + const char* count_why = nullptr; auto as_count = [&](unsigned reg, Extract& extracted) noexcept { // The +1 may sit in the scalar count register or in the VGPR that - // v_readfirstlane copied into it. Either is the record count. - const Seen count = follow(send_pc, false, reg); - if (!count.ok || count.def.kind != 2u) + // v_readfirstlane copied into it. A multiply, when present, sits between + // that +1 and the readfirstlane and must be the proven scalar. + Seen count = follow(send_pc, false, reg); + if (!count.ok) { + count_why = "derived mesh record mask was not proven"; + return false; + } + if (count.def.kind == 15u || (count.def.kind == 7u && !count.def.src2_reg)) { + count_why = "derived mesh record multiply operand is not a scalar"; return false; - return as_mask(count.pc, count.def.src_vector, count.def.src, extracted); + } + if (count.def.kind == 7u) { + count_why = prove_multiplier(count.def.src2, count.pc); + if (count_why) + return false; + count = follow(count.pc, count.def.src_vector, count.def.src); + if (!count.ok || count.def.kind != 2u) { + count_why = "derived mesh record multiply is not on the record count"; + return false; + } + } else if (count.def.kind != 2u) { + count_why = "derived mesh record mask was not proven"; + return false; + } + if (!as_mask(count.pc, count.def.src_vector, count.def.src, extracted)) { + count_why = "derived mesh record mask was not proven"; + return false; + } + return true; }; Extract vertices; Extract primitives; - if (!as_count(vertex_reg, vertices) || !as_count(primitive_reg, primitives)) { - out.reason = "derived mesh record mask was not proven"; + if (!as_count(vertex_reg, vertices)) { + out.reason = count_why ? count_why : "derived mesh record mask was not proven"; + return out; + } + if (!as_count(primitive_reg, primitives)) { + out.reason = count_why ? count_why : "derived mesh record mask was not proven"; return out; } if (!vertices.ok || !primitives.ok || vertices.shift != 0 || vertices.width == 0 || diff --git a/src/startup_stubs/mesh57_derived_depth.h b/src/startup_stubs/mesh57_derived_depth.h index 65e1266dd6..1f524c53f8 100644 --- a/src/startup_stubs/mesh57_derived_depth.h +++ b/src/startup_stubs/mesh57_derived_depth.h @@ -13,7 +13,10 @@ // stencil plane (D24_UNORM_S8_UINT, D32_FLOAT_S8X24_UINT, and the two typeless forms). #pragma once +#include #include +#include +#include namespace x2w_startup { @@ -199,6 +202,50 @@ inline const char* mesh57_color_target_reason() noexcept return "derived mesh needs one single-sample color target, a viewport and a scissor"; } +// The color-target, viewport, scissor and sample-count refusals. Depth-state refusals +// are not in this set: those are properties of the pipeline registers. +inline bool mesh57_target_attachment_reason(const char* reason) noexcept +{ + if (!reason) + return false; + return std::strcmp(reason, mesh57_color_target_reason()) == 0 || + std::strcmp(reason, "derived mesh sample count is unknown") == 0 || + std::strcmp(reason, "derived mesh depth buffer sample count is unknown") == 0 || + std::strcmp(reason, "derived mesh depth buffer is multisampled") == 0 || + std::strcmp(reason, "derived mesh color and depth sample counts differ") == 0 || + std::strcmp(reason, "derived mesh needs one single-sample color target") == 0; +} + +// One line naming which attachment condition failed. bounds_switch is the same opt-in +// switch. Off, or for any other reason, this writes nothing. The text is flags and +// counts: no pointer and no raw word. format is 1 when target 0's format is known. +// samples is the color sample count. depth_samples is the depth sample count. +inline std::size_t mesh57_target_gap_line(bool bounds_switch, const Mesh57DepthTargets& targets, + const char* reason, unsigned long long key, char* out, + std::size_t cap) noexcept +{ + if (!out || cap == 0) + return 0; + out[0] = 0; + if (!bounds_switch || !mesh57_target_attachment_reason(reason)) + return 0; + const int n = std::snprintf( + out, cap, + "x2w-render mesh57-derive targets key=%016llx bound=%u viewport=%u scissor=%u count=%u target0=%u format=%u samples=%u depth_samples=%u", + key, targets.targets_bound ? 1u : 0u, targets.viewport_set ? 1u : 0u, targets.scissor_set ? 1u : 0u, + targets.target_count, targets.has_target0 ? 1u : 0u, targets.target0_format != 0u ? 1u : 0u, + targets.color_samples, targets.depth_samples); + if (n < 0) { + out[0] = 0; + return 0; + } + if (static_cast(n) >= cap) { + out[cap - 1] = 0; + return cap - 1; + } + return static_cast(n); +} + // bounds_switch is X2W_MESH57_DERIVED_BOUNDS=1. Off, an enabled test is still // "derived mesh keeps depth and stencil disabled", and a bound depth view is still refused. // On, the decoded description is kept. A form this path cannot copy exactly is refused. diff --git a/src/startup_stubs/native_mesh57.inl b/src/startup_stubs/native_mesh57.inl index d5e8217b3b..da0b789197 100644 --- a/src/startup_stubs/native_mesh57.inl +++ b/src/startup_stubs/native_mesh57.inl @@ -734,6 +734,31 @@ void mesh57_log_record_bounds(const x2w_startup::Mesh57RecordBounds& bounds, uns log("%s", line); } +// One line per pipeline key when the color-target check refuses with the bounds switch +// on. The text is the flags from mesh57_target_gap_line. Eight keys, then further keys +// are dropped. A key of 0 is still one slot. +void mesh57_log_target_gap(unsigned long long key, const char* line) +{ + if (!line || !line[0]) + return; + static SRWLOCK seen_lock = SRWLOCK_INIT; + static unsigned long long seen[8]{}; + static unsigned seen_count = 0; + AcquireSRWLockExclusive(&seen_lock); + for (unsigned i = 0; i < seen_count; ++i) { + if (seen[i] == key) { + ReleaseSRWLockExclusive(&seen_lock); + return; + } + } + const bool emit = seen_count < 8u; + if (emit) + seen[seen_count++] = key; + ReleaseSRWLockExclusive(&seen_lock); + if (emit) + 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. @@ -907,8 +932,16 @@ const char* derive_slot57_mesh(Wrapper* pipeline, Pass& pass, const D3D12_BLEND_ depth_targets.depth_bound = true; } const auto depth_decision = x2w_startup::mesh57_derived_depth(derived_bounds, depth_facts, depth_targets); - if (depth_decision.reason) + if (depth_decision.reason) { + if (derived_bounds) { + char line[192]{}; + const auto key = static_cast(known_pipeline_key(pipeline)); + if (x2w_startup::mesh57_target_gap_line(true, depth_targets, depth_decision.reason, key, line, + sizeof(line))) + mesh57_log_target_gap(key, line); + } return depth_decision.remember ? remember(depth_decision.reason) : depth_decision.reason; + } auto* desktop = static_cast(root->own().real); ID3D12RootSignature* bound_root = pass.root_heap_flags ? pass.deferred_root : pass.graphics_root; if (!bound_root || bound_root != desktop || pass.root != root_info(root) || diff --git a/tests/mesh57_derived_depth_check.cpp b/tests/mesh57_derived_depth_check.cpp index 042ca1e813..411fbd2aa3 100644 --- a/tests/mesh57_derived_depth_check.cpp +++ b/tests/mesh57_derived_depth_check.cpp @@ -227,5 +227,56 @@ int main() const auto on_empty = x2w_startup::mesh57_derived_depth(true, empty, color_target()); if (!on_empty.reason || std::strcmp(on_empty.reason, "derived mesh depth state was refused") != 0 || !on_empty.remember) return fail("missing decode refused"); + + auto gap_line = [](bool bounds_switch, const x2w_startup::Mesh57DepthTargets& targets, const char* reason, + char* line, std::size_t cap) { + return x2w_startup::mesh57_target_gap_line(bounds_switch, targets, reason, 0x11ull, line, cap); + }; + auto gap_has = [&](const x2w_startup::Mesh57DepthTargets& targets, const char* needle) { + const auto decision = x2w_startup::mesh57_derived_depth(true, facts, targets); + char line[192]; + const auto written = gap_line(true, targets, decision.reason, line, sizeof(line)); + return written && decision.reason && std::strstr(line, needle) != nullptr && std::strstr(line, "0x") == nullptr && + std::strstr(line, "key=0000000000000011") != nullptr; + }; + auto unbound = depth_target(mesh57_fmt_d24_unorm_s8); + unbound.targets_bound = false; + if (!gap_has(unbound, "bound=0") || gap_has(unbound, "bound=1")) + return fail("targets not bound"); + auto no_view = depth_target(mesh57_fmt_d24_unorm_s8); + no_view.viewport_set = false; + if (!gap_has(no_view, "viewport=0")) + return fail("viewport not set"); + auto no_scissor = depth_target(mesh57_fmt_d24_unorm_s8); + no_scissor.scissor_set = false; + if (!gap_has(no_scissor, "scissor=0")) + return fail("scissor not set"); + auto no_count = depth_target(mesh57_fmt_d24_unorm_s8); + no_count.target_count = 0; + if (!gap_has(no_count, "count=0")) + return fail("color target count"); + auto no_rt = depth_target(mesh57_fmt_d24_unorm_s8); + no_rt.has_target0 = false; + if (!gap_has(no_rt, "target0=0")) + return fail("target 0 absent"); + auto no_format = depth_target(mesh57_fmt_d24_unorm_s8); + no_format.target0_format = 0; + if (!gap_has(no_format, "format=0")) + return fail("target 0 format unknown"); + auto no_samples = depth_target(mesh57_fmt_d24_unorm_s8); + no_samples.color_samples = 0; + if (!gap_has(no_samples, "samples=0")) + return fail("sample count"); + char silent[192]; + const auto off_gap = gap_line(false, no_view, "derived mesh needs one single-sample color target, a viewport and a scissor", + silent, sizeof(silent)); + if (off_gap != 0 || silent[0] != 0) + return fail("switch off logs no target gap"); + const auto kept = gap_line(true, depth_target(mesh57_fmt_d24_unorm_s8), on.reason, silent, sizeof(silent)); + if (kept != 0) + return fail("accepted depth logs no target gap"); + const auto other = gap_line(true, depth_target(mesh57_fmt_d32_float), on_bounds.reason, silent, sizeof(silent)); + if (other != 0) + return fail("depth-state refusal logs no target gap"); return 0; } diff --git a/tests/mesh57_record_bounds_check.cpp b/tests/mesh57_record_bounds_check.cpp index 61152b05b5..ac8e57a96f 100644 --- a/tests/mesh57_record_bounds_check.cpp +++ b/tests/mesh57_record_bounds_check.cpp @@ -112,6 +112,73 @@ std::vector record_program(unsigned mask, unsigned shift) return words; } +std::uint32_t vop3_word0(unsigned op, unsigned dst) +{ + return (0x35u << 26) | (op << 16) | (dst & 255u); +} + +std::uint32_t vop3_word1(unsigned src0, unsigned src1, unsigned src2) +{ + return (src0 & 511u) | ((src1 & 511u) << 9) | ((src2 & 511u) << 18); +} + +// Vertex field is v_and of the low mask. Primitive field is v_bfe_u32 of the same +// VGPR, offset = width, width = width. Each +1 is then v_mul_lo_u32 by s8. +// s8 is min(s1 + (1 << (s2 >> 29)), s3) - s1. The shift, the power of two, the min +// and the subtract all write s8. gap 1 replaces the subtract with an add. gap 2 +// adds s9 instead of s1. gap 3 shifts by 28. +std::vector multiplied_program(unsigned mask, unsigned width, int gap) +{ + const unsigned mask_src = mask <= 64u ? 128u + mask : 255u; + std::vector words; + auto append = [&](std::uint32_t word) { words.push_back(word); }; + append(vop2_word(27, 1, 8, mask_src)); + if (mask_src == 255u) + append(mask); + append(vop2_word(37, 2, 1, 129)); + append(vop3_word0(328, 3)); + append(vop3_word1(256u + 8u, 128u + width, 128u + width)); + append(vop2_word(37, 4, 3, 129)); + // One scalar register is reused for the shift, the power of two, the min and + // the subtract, which is the chain the reader has to follow by definition. + const unsigned shift = gap == 3 ? 28u : 29u; + append(sop2_word(32, 8, 2, 128u + shift)); + append(sop2_word(30, 8, 129, 8)); + const unsigned add_base = gap == 2 ? 9u : 1u; + append(sop2_word(0, 6, add_base, 8)); + append(sop2_word(7, 8, 6, 3)); + if (gap == 1) + append(sop2_word(0, 8, 1, 5)); + else + append(sop2_word(3, 8, 8, 1)); + append(vop3_word0(361, 2)); + append(vop3_word1(8, 256u + 2u, 0)); + append(vop3_word0(361, 4)); + append(vop3_word1(8, 256u + 4u, 0)); + append(vop1_word(2, 18, 256u + 2u)); + append(vop1_word(2, 21, 256u + 4u)); + append(vop1_word(1, 2, 256u + 7u)); + append(sop2_word(10, 18, 18, 128)); + append(sop2_word(10, 21, 21, 128)); + append(sop2_word(30, 22, 21, 140)); + append(sop2_word(16, 124, 22, 18)); + append(0xbf900009u); + append(sop1_word(4, 126, 126)); + append(0xf8000941u); + append(0x80808005u); + append(0xbf810000u); + return words; +} + +std::vector multiplied_names(int gap) +{ + return {"v_and_b32", "v_add_nc_u32", "v_bfe_u32", "v_add_nc_u32", "s_lshr_b32", "s_lshl_b32", + "s_add_u32", "s_min_u32", gap == 1 ? "s_add_u32" : "s_sub_i32", "v_mul_lo_u32", + "v_mul_lo_u32", "v_readfirstlane_b32", "v_readfirstlane_b32", "v_mov_b32", + "s_cselect_b32", "s_cselect_b32", "s_lshl_b32", "s_or_b32", "s_sendmsg", "s_mov_b64", + "exp", "s_endpgm"}; +} + const std::vector record_names = { "v_and_b32", "v_add_nc_u32", "v_lshrrev_b32", "v_and_b32", "v_add_nc_u32", "v_readfirstlane_b32", "v_readfirstlane_b32", "v_mov_b32", @@ -222,5 +289,44 @@ int main() x2w_startup::mesh57_record_bounds_line(*accepted.bounds, 100, 40, tiny, sizeof(tiny)); if (tiny[sizeof(tiny) - 1] != 0) return fail("bounds line cap"); + + const std::vector multiplied = multiplied_program(0x7fu, 7u, 0); + if (!names_match(multiplied, multiplied_names(0))) + return fail("multiplied encoding"); + const std::string multiplied_code = code_from(multiplied); + if (!bounds_are(x2w_startup::mesh57_read_record_m0_bounds(multiplied_code, known_k(1)), 256, 256, 256)) + return fail("multiplied bounds"); + const auto immediate_multiplied = x2w_startup::mesh57_read_layout(multiplied_code); + if (immediate_multiplied.layout || !immediate_multiplied.reason || + std::strcmp(immediate_multiplied.reason, "derived mesh needs one immediate allocation") != 0) + return fail("immediate reader refuses the multiplied program"); + + const std::vector unproven = multiplied_program(0x7fu, 7u, 1); + if (!names_match(unproven, multiplied_names(1))) + return fail("unproven encoding"); + if (!reason_is(x2w_startup::mesh57_read_record_m0_bounds(code_from(unproven), known_k(1)), + "derived mesh record multiply scalar was not proven")) + return fail("unproven scalar"); + + const std::vector mismatch = multiplied_program(0x7fu, 7u, 2); + if (!names_match(mismatch, multiplied_names(2))) + return fail("mismatched base encoding"); + if (!reason_is(x2w_startup::mesh57_read_record_m0_bounds(code_from(mismatch), known_k(1)), + "derived mesh record multiply base does not match")) + return fail("mismatched base"); + + const std::vector shift = multiplied_program(0x7fu, 7u, 3); + if (!names_match(shift, multiplied_names(3))) + return fail("shift encoding"); + if (!reason_is(x2w_startup::mesh57_read_record_m0_bounds(code_from(shift), known_k(1)), + "derived mesh record multiply shift is not 29")) + return fail("shift other than 29"); + + const std::vector over = multiplied_program(0xffu, 8u, 0); + if (!names_match(over, multiplied_names(0))) + return fail("multiplied wide encoding"); + if (!reason_is(x2w_startup::mesh57_read_record_m0_bounds(code_from(over), known_k(1)), + "derived mesh record bound exceeds the mesh output limit")) + return fail("multiplied bound over 256"); return 0; } From 452d9468be4cea8e2abd2c26ffc55654773afda4 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Mon, 30 Nov 2026 17:25:41 +0000 Subject: [PATCH 16/24] startup: record a raw buffer load as the derived mesh record word A buffer load was invisible to the record-m0 reader, so a mask of the loaded VGPR followed an older ALU write. Only the low VGPR of a raw dword, dwordx2, dwordx3, or dwordx4 load is the record word, and both fields have to name that same load. Other data VGPRs, a TFE status VGPR, and format, byte, short, and d16 loads are ordinary writes. An LDS load writes no VGPR. On an MTBUF load, word 0 bit 16 is an opcode bit, not LDS. The group-index exchange is still refused. With the derived-bounds layout the refusal names the first failed check, and one line per pipeline key is logged. The accepted sequence is unchanged. With the switch off the refusal sentence is unchanged. --- CMakeLists.txt | 5 + docs/experiments/native-fixed-mesh57.md | 12 +- .../experiments/native-mesh-frontend-rules.md | 2 + docs/startup-runtime.md | 2 +- src/gfx1013_compute_native.cpp | 1 + src/gfx1013_direct_mesh.inl | 20 +- src/startup_stubs/mesh57_alloc.h | 101 +++++++--- src/startup_stubs/mesh57_group_exchange.h | 134 +++++++++++++ src/startup_stubs/native_mesh57.inl | 35 +++- tests/mesh57_group_exchange_check.cpp | 150 +++++++++++++++ tests/mesh57_record_bounds_check.cpp | 180 +++++++++++++++++- 11 files changed, 607 insertions(+), 35 deletions(-) create mode 100644 src/startup_stubs/mesh57_group_exchange.h create mode 100644 tests/mesh57_group_exchange_check.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index e21029fadb..a4bb0d0e32 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1957,6 +1957,11 @@ target_include_directories(mesh57_record_bounds_check PRIVATE src src/startup_st target_compile_features(mesh57_record_bounds_check PRIVATE cxx_std_17) add_test(NAME mesh57_record_bounds COMMAND mesh57_record_bounds_check) +add_executable(mesh57_group_exchange_check tests/mesh57_group_exchange_check.cpp) +target_include_directories(mesh57_group_exchange_check PRIVATE src src/startup_stubs) +target_compile_features(mesh57_group_exchange_check PRIVATE cxx_std_17) +add_test(NAME mesh57_group_exchange COMMAND mesh57_group_exchange_check) + add_executable(mesh57_derived_depth_check tests/mesh57_derived_depth_check.cpp) target_include_directories(mesh57_derived_depth_check PRIVATE src) target_compile_features(mesh57_derived_depth_check PRIVATE cxx_std_17) diff --git a/docs/experiments/native-fixed-mesh57.md b/docs/experiments/native-fixed-mesh57.md index 7dc0efd744..906d13fceb 100644 --- a/docs/experiments/native-fixed-mesh57.md +++ b/docs/experiments/native-fixed-mesh57.md @@ -158,6 +158,8 @@ On the Windows test PC at `35b0d542`, the same switches, a 420 second run, forwa Set, `mesh57_read_record_m0_bounds` may supply the output limit for a program the immediate reader refuses. The program has one `s_sendmsg` `GS_ALLOC_REQ`. The two instructions immediately before it are `s_lshl_b32 sX, sP, 12` and `s_or_b32 m0, sX, sV` (either operand order of the `or`). `sV` and `sP` are each `(field & mask) + 1` from one record word: the vertex field is the low mask and the primitive field is that word shifted by the mask width. `v_bfe_u32` of that word with an immediate offset and width is the same extract as a logical shift by the offset and a mask of `2^width - 1`. A `v_readfirstlane` of that sum, and an `s_cselect_b32` of the count against immediate 0, still count as the same value. The per-record maximum is `mask + 1`. +The record word may be a VGPR written by a buffer load. Only the first data VGPR of `buffer_load_dword`, `buffer_load_dwordx2`, `buffer_load_dwordx3`, or `buffer_load_dwordx4` is that word, and both fields have to trace to that same load. The other data VGPRs are ordinary writes. A TFE status VGPR, the extra VGPR when the load's TFE bit is set, is an ordinary write too. An LDS load writes no VGPR: on a MUBUF load that is word 0 bit 16. That bit is an opcode bit on an MTBUF load, not LDS. A format, byte, short, or `d16` load writes its VGPRs and is not the packed record dword. `d16` of x or xy is one VGPR; `d16` of xyz or xyzw is two. Those loads are ordinary writes, so they cannot prove the mask, including when the fields read the loaded VGPR and an older ALU write of it would otherwise be the definition the reader follows. Two different loads of the same VGPR cannot prove it either. + Between the `+ 1` and the `v_readfirstlane`, the count may be `v_mul_lo_u32` by one scalar. That scalar is accepted only when it is `min(base + (1 << k), L) - base` and the add and the sub name the same base register. The chain is `s_sub_i32` of the min and the base, `s_min_u32` of the sum and `L`, `s_add_u32` of that base and `1 << k`, `s_lshl_b32` of the immediate 1 by a register, and `s_lshr_b32` of some SGPR by 29. That shift is at most 7. The reader matches registers, not fixed numbers. A scalar that is not this chain is `derived mesh record multiply scalar was not proven`. A min whose add uses a different base is `derived mesh record multiply base does not match`. A shift other than 29 is `derived mesh record multiply shift is not 29`. A multiply whose operand is not one scalar register is `derived mesh record multiply operand is not a scalar`. A missing min or add is named the same way. The subtract can wrap. The chain does not prove `L >= base`, and it does not prove that `base + (1 << k)` stays inside 32 bits. If `L < base` and the add does not wrap, `min` selects `L` and the subtract underflows, so the multiplier can exceed `2^k`. If the add wraps, the result is also not bounded by `2^k`. `1 << k` itself fits, because the shift amount is a 32-bit value shifted right by 29. The translated `SetMeshOutputCounts` still clamps each runtime count, the post-cselect `v_readfirstlane` of the multiplied value, with an unsigned `ule` select against the derived limit. A wrapped product is not passed above that maximum. @@ -166,14 +168,18 @@ The entry multiply `k` is accepted only when the caller passes the constant 1. T The group size comes from `gfx1013_direct_mesh.inl`. That lowerer indexes each vertex and each primitive with `flattenedThreadIdInGroup`, splits a wave64 id into `lane = id & 63` and `wave = id >> 6`, and skips the write when the id is at or past the runtime count. One thread emits one output. The group is the smallest multiple of 64 that covers the larger derived limit: 256 for the 7-bit, `k` 1 case, and 128 for a 6-bit mask. A program with no wave64 proof is refused rather than given a guessed wave width. The direct mesh path allows that group only when this layout sets `record_output_counts`. Every other mesh keeps the 128-thread check. A desktop compiler can still refuse `numthreads` of 256; this path does not lower the group to 128 to hide that. +That lowerer still accepts only one group-index exchange. It opens with `s_mov_b64 exec, 1`, optionally saves `exec`, masks s3 with the wave-id literal, and then matches a fixed 13-word tail: the scc branch, `v_lshrrev_b32 v5, 7, v5`, `v_mov_b32 v0, 0`, a `ds_write`, a wait, a barrier, a branch, a barrier, another `v_mov_b32 v0, 0`, and a `ds_read`. The entry state has to be a closed scalar branch, no open EXEC skip, EXEC the full wave, not wave32, a non-zero group stride, s3 and v5 not yet written, the mask destination an SGPR, and, when exec was saved, a free even SGPR pair that does not overlap that destination. The stride is what turns `groupId` into the value the exchange broadcasts (`v5 >> 7`). This derivation sets the stride to 0 and does not define that entry VGPR. The per-thread id, wave times 64 plus the lane, with the wave taken from s3 bits 27:24, is the lane index the lowerer already uses. It is not the value this exchange writes to LDS. This path does not invent a stride and does not treat the broadcast as the thread id. + +When `record_output_counts` is set and that opener is refused, the reason keeps `mesh group-index exchange shape or entry state is not covered` and names the first failed check. The checks, in order, are: the sequence is shorter than the accepted form (60 bytes, or 64 when exec is saved), the wave-bit mask is not an AND of s3 with a literal, one of the 13 tail steps does not match, a scalar branch is open, an EXEC skip is open, EXEC is not the full wave, the stage is wave32, the group stride is zero, s3 was already written, v5 was already written, the mask destination is not an SGPR, and the saved EXEC pair is not a free even SGPR. With the flag clear, the reason stays the sentence with no check name. One `x2w-render mesh57-derive exchange` line is logged per pipeline key, at most eight keys. The line is the key and the check. It has no pointer and no instruction word. + `SetMeshOutputCounts` receives the runtime vertex and primitive registers, each limited to the derived maximum, and both become 0 when either is 0. Outputs past the runtime count are not written. The static bound sizes the output arrays. It is not substituted when the registers are unproven. The first time a distinct pair is derived this way, stderr gets one `x2w-render mesh57-derive bounds` line: mesh and pixel byte counts, `v`, `p`, `threads`, `pattern=record-m0`, and `k`. The line has no pointer. At most eight distinct lines are kept. The global on-chip budget in the pipeline register block is not a per-shader size and is not read here. -`mesh57_record_bounds` checks the assembled pattern: the 7-bit limit, the 6-bit limit, an unknown `k`, a `k` other than 1, a mask whose product exceeds 256, the immediate triangle (3 vertices, 1 primitive, 64 threads), and that the immediate reader still refuses the record program. It also checks the `v_bfe_u32` plus proven `v_mul_lo_u32` chain at the same 256 limit, and the refusals for an unproven scalar, a mismatched base, a shift other than 29, and a multiplied mask whose product exceeds 256. It does not need a device. +`mesh57_record_bounds` checks the assembled pattern: the 7-bit limit, the 6-bit limit, an unknown `k`, a `k` other than 1, a mask whose product exceeds 256, the immediate triangle (3 vertices, 1 primitive, 64 threads), and that the immediate reader still refuses the record program. It also checks the `v_bfe_u32` plus proven `v_mul_lo_u32` chain at the same 256 limit, and the refusals for an unproven scalar, a mismatched base, a shift other than 29, and a multiplied mask whose product exceeds 256. It checks a raw dword load that hides an older ALU write of the same VGPR, an LDS load that does not, a field that reads the second dword of a dwordx2 load, two loads of the same VGPR, a `d16` xyzw load, and the TFE status VGPR. `mesh57_group_exchange` checks each failed check of the group-index exchange on the assembled sequence, including a zero group stride, and the log line. Neither needs a device. The Windows `native_direct_mesh` fixture still expects the exchange refusal with no check name, because that fixture does not set `record_output_counts`. ```powershell -ctest --preset dev --no-tests=error -R 'mesh57_record_bounds|mesh57_derive_alloc' +ctest --preset dev --no-tests=error -R 'mesh57_record_bounds|mesh57_group_exchange|mesh57_derive_alloc' ``` 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. @@ -189,5 +195,5 @@ When the switch is on and this color-target check refuses, one `x2w-render mesh5 `mesh57_derived_depth` checks the register-word mapping, the switch-off refusals, each of those reasons, and the target-gap line for a missing bind, viewport, scissor, count, target, format, or sample count. It does not need a device. ```powershell -ctest --preset dev --no-tests=error -R 'mesh57_derived_depth|mesh57_record_bounds|mesh57_derive_alloc' +ctest --preset dev --no-tests=error -R 'mesh57_derived_depth|mesh57_record_bounds|mesh57_group_exchange|mesh57_derive_alloc' ``` diff --git a/docs/experiments/native-mesh-frontend-rules.md b/docs/experiments/native-mesh-frontend-rules.md index bea6668bf6..c7f3307251 100644 --- a/docs/experiments/native-mesh-frontend-rules.md +++ b/docs/experiments/native-mesh-frontend-rules.md @@ -16,6 +16,8 @@ distinguishes these cases (lines 1121-1132). - A group-index opener `s_mov_b64 exec, 1` (word `0xbefe0481`) that reaches the fallback gets `mesh group-index exchange shape or entry state is not covered` (line 1123). See `mismatched-barriers` and `missing-exec-save` (fixture lines 283 and 286). + When the mesh layout sets `record_output_counts`, that same refusal names the first failed check. + The fixture does not set the flag, so its expected string is unchanged. - A raw word `0xbf8a0000` (`s_barrier`) that reaches the fallback and is followed by a word matching `(word & 0xffffff80) == 0xbf008000` (a comparison with zero whose source field can contain any scalar operand diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index befbb1fe79..bac17a97cc 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -1804,7 +1804,7 @@ ctest --preset dev --no-tests=error -R '^startup_hook_(window|overlap)$' -V | `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 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 and stencil unless `X2W_MESH57_DERIVED_BOUNDS=1`, 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_MESH57_DERIVED_BOUNDS=1` | experimental, with `X2W_MESH57_DERIVE_STATE=1`. Off by default, and unset it leaves the slot 57 derivation unchanged. Set, a mesh whose `m0` is `s_lshl_b32` by 12 then `s_or_b32` into `m0` immediately before the only `GS_ALLOC_REQ`, with both counts proven as `(field & mask) + 1` from one record word, may use those masks as the output limit. The multiply is `2^k` only when the entry `k` is the constant 1; an unknown `k` or any other `k` stays refused. A `v_bfe_u32` field, and a `v_mul_lo_u32` by `min(base + (1 << k), L) - base` with that `k` taken from a logical shift right by 29, use the same limit. An unproven multiplier, a mismatched base, or a shift other than 29 stays refused. The subtract can wrap when `L` is below the base; `SetMeshOutputCounts` still clamps each runtime count to the derived limit. A product above 256 vertices or 256 primitives stays refused. A color-target refusal logs the failing condition once per pipeline key. The group is the smallest multiple of 64 that covers that limit, from the direct mesh lane id (one thread writes one output). The translated shader passes the runtime counts to `SetMeshOutputCounts`. The immediate `m0` reader is unchanged. This switch does not invent a user-SGPR map for a heap-indexed root. With the switch on, the decoded depth and stencil state is copied into the derived mesh pipeline, the bound depth view's format is the pipeline depth format, and the dispatch sets the decoded stencil reference. Depth bounds, differing back-face masks, a multisampled depth buffer, and a stencil test without a stencil plane stay refused. See [Opt-in record bounds](experiments/native-fixed-mesh57.md#opt-in-record-bounds) | +| `X2W_MESH57_DERIVED_BOUNDS=1` | experimental, with `X2W_MESH57_DERIVE_STATE=1`. Off by default, and unset it leaves the slot 57 derivation unchanged. Set, a mesh whose `m0` is `s_lshl_b32` by 12 then `s_or_b32` into `m0` immediately before the only `GS_ALLOC_REQ`, with both counts proven as `(field & mask) + 1` from one record word, may use those masks as the output limit. The record word is the first data VGPR of one raw `buffer_load_dword`, `dwordx2`, `dwordx3`, or `dwordx4` when both fields trace to that same load. An LDS load, a format or `d16` load, a high dword, and a TFE status VGPR do not prove it. The multiply is `2^k` only when the entry `k` is the constant 1; an unknown `k` or any other `k` stays refused. A `v_bfe_u32` field, and a `v_mul_lo_u32` by `min(base + (1 << k), L) - base` with that `k` taken from a logical shift right by 29, use the same limit. An unproven multiplier, a mismatched base, or a shift other than 29 stays refused. The subtract can wrap when `L` is below the base; `SetMeshOutputCounts` still clamps each runtime count to the derived limit. A product above 256 vertices or 256 primitives stays refused. A color-target refusal logs the failing condition once per pipeline key. A group-index exchange the direct mesh lowerer does not cover stays refused. With this switch on, that refusal names the first failed check, and one line per pipeline key is logged. The group is the smallest multiple of 64 that covers that limit, from the direct mesh lane id (one thread writes one output). The translated shader passes the runtime counts to `SetMeshOutputCounts`. The immediate `m0` reader is unchanged. This switch does not invent a user-SGPR map for a heap-indexed root. With the switch on, the decoded depth and stencil state is copied into the derived mesh pipeline, the bound depth view's format is the pipeline depth format, and the dispatch sets the decoded stencil reference. Depth bounds, differing back-face masks, a multisampled depth buffer, and a stencil test without a stencil plane stay refused. See [Opt-in record bounds](experiments/native-fixed-mesh57.md#opt-in-record-bounds) | | `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/gfx1013_compute_native.cpp b/src/gfx1013_compute_native.cpp index 887f35cc5a..569fef51d0 100644 --- a/src/gfx1013_compute_native.cpp +++ b/src/gfx1013_compute_native.cpp @@ -3,6 +3,7 @@ #include "dxil_module.h" #include "guest_shader_container.h" #include "gfx1013_isa.h" +#include "startup_stubs/mesh57_group_exchange.h" #include #include #include diff --git a/src/gfx1013_direct_mesh.inl b/src/gfx1013_direct_mesh.inl index 501490fb24..fa2adb6b76 100644 --- a/src/gfx1013_direct_mesh.inl +++ b/src/gfx1013_direct_mesh.inl @@ -1268,8 +1268,24 @@ NativeComputeShader lower_mesh(const string &code, const MeshStageLayout &layout if (pair) partial_writes.insert(i.dst+1); } } else { - if (raw==0xbefe0481) - refuse(pc,"mesh group-index exchange shape or entry state is not covered"); + if (raw==0xbefe0481) { + // The accepted sequence is unchanged. record_output_counts only names + // the first check that missed, so the next derived-bounds run can tell + // a zero group stride from a tail that does not match. + if (layout.record_output_counts) { + x2w_startup::Mesh57GroupExchangeState exchange_state; + exchange_state.branch_open = branch.has_value(); + exchange_state.exec_skip = exec_skip.has_value(); + exchange_state.full_exec = full_exec; + exchange_state.wave32 = layout.wave32; + exchange_state.group_stride = layout.group_stride != 0; + exchange_state.s3_written = alu.graphics_registers.count(3) != 0; + exchange_state.v5_written = alu.graphics_registers.count(261) != 0; + const char* gap = x2w_startup::mesh57_group_exchange_gap(code, pc, exchange_state); + refuse(pc, string(x2w_startup::mesh57_group_exchange_refusal()) + ": " + gap); + } + refuse(pc, x2w_startup::mesh57_group_exchange_refusal()); + } // A barrier alone does not identify the count exchange. Its // next word compares the candidate wave SGPR against zero. if (raw==0xbf8a0000 && code.size()-pc>=8 && (word(code,pc+4)&0xffffff80u)==0xbf008000) diff --git a/src/startup_stubs/mesh57_alloc.h b/src/startup_stubs/mesh57_alloc.h index 60442870aa..e799b8c926 100644 --- a/src/startup_stubs/mesh57_alloc.h +++ b/src/startup_stubs/mesh57_alloc.h @@ -269,6 +269,34 @@ inline std::size_t mesh57_record_bounds_line(const Mesh57RecordBounds& bounds, u return static_cast(n); } +// How many data VGPRs a buffer load writes. d16 packs two channels per VGPR: +// x and xy are one VGPR, xyz and xyzw are two. A raw dword load is one VGPR per +// dword. The name comes from the same decoder the reader uses. +inline unsigned mesh57_buffer_load_vgprs(std::string_view name) noexcept +{ + const bool packed = name.find("d16") != std::string_view::npos; + if (packed) { + if (name.find("xyzw") != std::string_view::npos || name.find("xyz") != std::string_view::npos) + return 2u; + return 1u; + } + if (name.find("dwordx4") != std::string_view::npos || name.find("xyzw") != std::string_view::npos) + return 4u; + if (name.find("dwordx3") != std::string_view::npos || name.find("xyz") != std::string_view::npos) + return 3u; + if (name.find("dwordx2") != std::string_view::npos || name.find("xy") != std::string_view::npos) + return 2u; + return 1u; +} + +// The packed record dword is the low VGPR of a raw dword load. Format, byte, +// short and d16 loads are converted values, not that word. +inline bool mesh57_raw_dword_load(std::string_view name) noexcept +{ + return name == "buffer_load_dword" || name == "buffer_load_dwordx2" || + name == "buffer_load_dwordx3" || name == "buffer_load_dwordx4"; +} + // m0 built by s_lshl_b32 sX, sP, 12 and s_or_b32 m0, sX, sV immediately before the only // s_sendmsg GS_ALLOC_REQ. sV and sP must each be (field & mask) + 1 from one record word. // The field is an and with a low mask, or v_bfe_u32 of that word with an immediate offset @@ -277,6 +305,13 @@ inline std::size_t mesh57_record_bounds_line(const Mesh57RecordBounds& bounds, u // that width. A v_readfirstlane of the sum, and an s_cselect_b32 of the count against // immediate 0, still count as the same value. // +// The record word may be the low data VGPR of one raw buffer_load_dword, dwordx2, +// dwordx3 or dwordx4. Both fields have to trace to that same load. The other data +// VGPRs, and a TFE status VGPR, are ordinary writes. An LDS load (MUBUF word 0 bit +// 16) writes no VGPR; that bit is an opcode bit on MTBUF, not LDS. A format, byte, +// short or d16 load writes its VGPRs and is not the packed dword, so it cannot +// prove the mask. d16 of x or xy is one VGPR; d16 of xyz or xyzw is two. +// // Between the + 1 and the readfirstlane the count may be v_mul_lo_u32 by one scalar. // That scalar is accepted only when it is min(base + (1 << k), L) - base, with the same // base register in the add and the sub: s_sub_i32 of the min and the base, s_min_u32 of @@ -318,7 +353,9 @@ inline Mesh57RecordBoundsRead mesh57_read_record_m0_bounds(std::string_view code // 1 mask, 2 add 1, 3 logical shift right, 4 copy, 5 unknown write, // 7 multiply by a scalar, 8 bitfield extract, 9 sub, 10 unsigned min, // 11 add of two registers, 12 shift of the immediate 1, 15 multiply - // whose operand is not one scalar. + // whose operand is not one scalar, 16 the low VGPR of one raw dword + // load. Kind 0 is no writer. A load that is not the packed record + // dword is kind 5, so it cannot look like kind 0. unsigned kind = 0; unsigned src = 0; bool src_vector = false; @@ -664,6 +701,23 @@ inline Mesh57RecordBoundsRead mesh57_read_record_m0_bounds(std::string_view code put(pc, true, op.dst, Def{5u, 0u, false, 0u, 0u}); } else if (inst.form == x2w::gfx1013::Form::vop3 && op.dst < 256u) { put(pc, true, op.dst, Def{5u, 0u, false, 0u, 0u}); + } else if ((inst.form == x2w::gfx1013::Form::mubuf || + inst.form == x2w::gfx1013::Form::mtbuf) && + inst.name.find("load") != std::string_view::npos && inst.size >= 8u) { + // MUBUF word0 bit 16 sends the result to LDS. MTBUF uses that bit + // as the low opcode bit, so it is not an LDS flag there. + const bool to_lds = inst.form == x2w::gfx1013::Form::mubuf && (raw & 0x10000u) != 0; + if (!to_lds) { + unsigned vgprs = mesh57_buffer_load_vgprs(inst.name); + if ((word1 & 0x800000u) != 0) + vgprs += 1u; // TFE status VGPR, word1 bit 23. Not the record. + const unsigned vdata = (word1 >> 8) & 255u; + const bool record = mesh57_raw_dword_load(inst.name); + for (unsigned i = 0; i < vgprs && vdata + i < 256u; ++i) { + const bool low = record && i == 0u; + put(pc, true, vdata + i, Def{low ? 16u : 5u, 0u, false, 0u, 0u}); + } + } } if (raw == 0xbf900009u) { @@ -735,6 +789,22 @@ inline Mesh57RecordBoundsRead mesh57_read_record_m0_bounds(std::string_view code unsigned shift = 0; unsigned record = 0; bool record_vector = false; + // Kind 16 names one load. Kind 0 is no writer and is matched by register. + bool from_load = false; + unsigned load_pc = 0; + }; + auto note_record = [&](const Seen& record, Extract& extracted, unsigned shift, + unsigned width) noexcept { + if (!record.ok || (record.def.kind != 0u && record.def.kind != 16u)) + return false; + extracted.ok = true; + extracted.width = width; + extracted.shift = shift; + extracted.record = record.reg; + extracted.record_vector = record.is_vector; + extracted.from_load = record.def.kind == 16u; + extracted.load_pc = record.def.kind == 16u ? record.pc : 0u; + return true; }; auto scalar_written = [&](unsigned after_pc, unsigned before_pc, unsigned reg) noexcept { for (const Event& event : events) { @@ -805,37 +875,18 @@ inline Mesh57RecordBoundsRead mesh57_read_record_m0_bounds(std::string_view code mask.def.imm + mask.def.width > 32u) return false; const Seen record = follow(mask.pc, mask.def.src_vector, mask.def.src); - if (!record.ok || record.def.kind != 0u) - return false; - extracted.ok = true; - extracted.width = mask.def.width; - extracted.shift = mask.def.imm; - extracted.record = record.reg; - extracted.record_vector = record.is_vector; - return true; + return note_record(record, extracted, mask.def.imm, mask.def.width); } if (mask.def.kind != 1u) return false; const Seen inner = follow(mask.pc, mask.def.src_vector, mask.def.src); if (!inner.ok) return false; - extracted.ok = true; - extracted.width = mask.def.width; if (inner.def.kind == 3u) { const Seen record = follow(inner.pc, inner.def.src_vector, inner.def.src); - if (!record.ok || record.def.kind != 0u) - return false; - extracted.shift = inner.def.imm; - extracted.record = record.reg; - extracted.record_vector = record.is_vector; - return true; + return note_record(record, extracted, inner.def.imm, mask.def.width); } - if (inner.def.kind != 0u) - return false; - extracted.shift = 0; - extracted.record = inner.reg; - extracted.record_vector = inner.is_vector; - return true; + return note_record(inner, extracted, 0u, mask.def.width); }; const char* count_why = nullptr; auto as_count = [&](unsigned reg, Extract& extracted) noexcept { @@ -882,7 +933,9 @@ inline Mesh57RecordBoundsRead mesh57_read_record_m0_bounds(std::string_view code } if (!vertices.ok || !primitives.ok || vertices.shift != 0 || vertices.width == 0 || vertices.width != primitives.width || primitives.shift != vertices.width || - vertices.record != primitives.record || vertices.record_vector != primitives.record_vector) { + vertices.record != primitives.record || vertices.record_vector != primitives.record_vector || + vertices.from_load != primitives.from_load || + (vertices.from_load && vertices.load_pc != primitives.load_pc)) { out.reason = "derived mesh record mask was not proven"; return out; } diff --git a/src/startup_stubs/mesh57_group_exchange.h b/src/startup_stubs/mesh57_group_exchange.h new file mode 100644 index 0000000000..587215fefa --- /dev/null +++ b/src/startup_stubs/mesh57_group_exchange.h @@ -0,0 +1,134 @@ +#pragma once + +// The group-index exchange the direct mesh lowerer accepts, and which check failed. +// The lowerer still accepts only that one sequence. This names the first miss so a +// derived-bounds run can tell a short program from a zero group stride. It does not +// print instruction words. + +#include +#include +#include +#include +#include + +namespace x2w_startup { + +inline const char* mesh57_group_exchange_refusal() noexcept +{ + return "mesh group-index exchange shape or entry state is not covered"; +} + +// Flags the lowerer already has when the opener reaches the fallback. +struct Mesh57GroupExchangeState { + bool branch_open = false; + bool exec_skip = false; + bool full_exec = false; + bool wave32 = false; + bool group_stride = false; + bool s3_written = false; + bool v5_written = false; +}; + +// First failed check of the accepted sequence, in the order the lowerer tests them. +// A null is not returned. "the exchange matched the accepted checks" means the +// bytes and these flags would take the accept path. +inline const char* mesh57_group_exchange_gap(std::string_view code, unsigned pc, + const Mesh57GroupExchangeState& state) noexcept +{ + auto word_at = [&](unsigned at, std::uint32_t& out) noexcept { + if (at > code.size() || code.size() - at < 4u) + return false; + std::memcpy(&out, code.data() + at, 4); + return true; + }; + // Opener, optional exec save, the s3 mask, and 13 fixed words. Without the + // save that is 60 bytes. With the save it is 64. + if (pc > code.size() || code.size() - pc < 60u) + return "the exchange is shorter than the accepted sequence"; + std::uint32_t save = 0; + if (!word_at(pc + 4u, save)) + return "the exchange is shorter than the accepted sequence"; + const bool has_save = (save & 0xff80ffffu) == 0xbe80047eu; + const unsigned mask_offset = has_save ? 8u : 4u; + constexpr std::uint32_t tail[] = { + 0x0f000000u, 0xbf850007u, 0x2c0a0a87u, 0x7e000280u, 0xd8340008u, 0x500u, + 0xbfa3ffe3u, 0xbf8a0000u, 0xbf820004u, 0xbf8a0000u, 0x7e000280u, 0xd8d80008u, + 0x05000000u}; + constexpr unsigned tail_count = static_cast(sizeof(tail) / sizeof(tail[0])); + const unsigned exchange_size = mask_offset + 4u + 4u * tail_count; + if (code.size() - pc < exchange_size) + return "the exchange is shorter than the accepted sequence"; + std::uint32_t mask = 0; + if (!word_at(pc + mask_offset, mask) || (mask & 0xff80ffffu) != 0x8700ff03u) + return "the wave-bit mask is not an AND of s3 with a literal"; + static const char* const steps[tail_count] = { + "exchange step 0 does not match", "exchange step 1 does not match", + "exchange step 2 does not match", "exchange step 3 does not match", + "exchange step 4 does not match", "exchange step 5 does not match", + "exchange step 6 does not match", "exchange step 7 does not match", + "exchange step 8 does not match", "exchange step 9 does not match", + "exchange step 10 does not match", "exchange step 11 does not match", + "exchange step 12 does not match"}; + for (unsigned k = 0; k < tail_count; ++k) { + std::uint32_t got = 0; + if (!word_at(pc + mask_offset + 4u + 4u * k, got)) + return "the exchange is shorter than the accepted sequence"; + if (got != tail[k]) + return steps[k]; + } + if (state.branch_open) + return "a scalar branch is open"; + if (state.exec_skip) + return "an EXEC skip is open"; + if (!state.full_exec) + return "EXEC is not the full wave"; + if (state.wave32) + return "the stage is wave32"; + if (!state.group_stride) + return "group stride is zero"; + if (state.s3_written) + return "s3 was already written"; + if (state.v5_written) + return "v5 was already written"; + const unsigned temp = (mask >> 16) & 127u; + if (temp >= 106u) + return "the mask destination is not an SGPR"; + if (has_save) { + const unsigned saved = (save >> 16) & 127u; + if (saved > 104u || (saved & 1u) != 0 || temp == saved || temp == saved + 1u) + return "the saved EXEC pair is not a free even SGPR"; + } + return "the exchange matched the accepted checks"; +} + +// One log line for this refusal. text is the exception. The line is the pipeline +// key and the failed check. It does not copy the program counter or an instruction +// word. Any other exception writes nothing. +inline std::size_t mesh57_exchange_gap_line(const char* text, unsigned long long key, char* out, + std::size_t cap) noexcept +{ + if (!out || cap == 0) + return 0; + out[0] = 0; + if (!text) + return 0; + const char* const mark = std::strstr(text, mesh57_group_exchange_refusal()); + if (!mark) + return 0; + const char* detail = std::strstr(mark, ": "); + detail = detail ? detail + 2 : "the exchange condition was not named"; + if (!detail[0]) + detail = "the exchange condition was not named"; + const int n = std::snprintf(out, cap, "x2w-render mesh57-derive exchange key=%016llx %s", key, detail); + 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 da0b789197..f9280135c5 100644 --- a/src/startup_stubs/native_mesh57.inl +++ b/src/startup_stubs/native_mesh57.inl @@ -1,3 +1,5 @@ +#include "startup_stubs/mesh57_group_exchange.h" + // Included after both the native graphics compiler and the desktop stream validator. // Resolve every SRV before recording barriers or a descriptor table. A guest root address // has no descriptor length; use the remaining proven GPU allocation, including for indexed reads. @@ -759,6 +761,32 @@ void mesh57_log_target_gap(unsigned long long key, const char* line) log("%s", line); } +// One line per pipeline key when the derived-bounds path refuses the group-index +// exchange. Eight keys, then further keys are dropped. A key of 0 is still one slot. +// The line is the key and the failed check. It has no pointer and no instruction word. +void mesh57_log_exchange_gap(unsigned long long key, const char* text) +{ + char line[192]{}; + if (!x2w_startup::mesh57_exchange_gap_line(text, key, line, sizeof(line))) + return; + static SRWLOCK seen_lock = SRWLOCK_INIT; + static unsigned long long seen[8]{}; + static unsigned seen_count = 0; + AcquireSRWLockExclusive(&seen_lock); + for (unsigned i = 0; i < seen_count; ++i) { + if (seen[i] == key) { + ReleaseSRWLockExclusive(&seen_lock); + return; + } + } + const bool emit = seen_count < 8u; + if (emit) + seen[seen_count++] = key; + ReleaseSRWLockExclusive(&seen_lock); + if (emit) + 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. @@ -1106,10 +1134,13 @@ const char* derive_slot57_mesh(Wrapper* pipeline, Pass& pass, const D3D12_BLEND_ log("x2w-render derived slot57 mesh ready"); return nullptr; } catch (const std::exception& e) { - log("x2w-render derived slot57 mesh refused: %s", e.what()); + const std::string text = e.what(); + if (runtime_counts) + mesh57_log_exchange_gap(static_cast(known_pipeline_key(pipeline)), + text.c_str()); + log("x2w-render derived slot57 mesh refused: %s", text.c_str()); 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_group_exchange_check.cpp b/tests/mesh57_group_exchange_check.cpp new file mode 100644 index 0000000000..365d796111 --- /dev/null +++ b/tests/mesh57_group_exchange_check.cpp @@ -0,0 +1,150 @@ +// Host check for the group-index exchange diagnostic. Words are the accepted +// sequence from the direct mesh fixture. The lowerer is not run here. +#include "mesh57_group_exchange.h" + +#include +#include +#include +#include +#include + +namespace { +int fail(const char* name) +{ + std::fprintf(stderr, "mesh57 group exchange: %s\n", name); + return 1; +} + +std::string code_from(const std::vector& words) +{ + std::string out(words.size() * sizeof(std::uint32_t), '\0'); + if (!words.empty()) + std::memcpy(out.data(), words.data(), out.size()); + return out; +} + +const std::vector saved_exchange = { + 0xbefe0481u, 0xbe88047eu, 0x870aff03u, 0x0f000000u, 0xbf850007u, 0x2c0a0a87u, + 0x7e000280u, 0xd8340008u, 0x500u, 0xbfa3ffe3u, 0xbf8a0000u, 0xbf820004u, + 0xbf8a0000u, 0x7e000280u, 0xd8d80008u, 0x05000000u}; + +x2w_startup::Mesh57GroupExchangeState ready_state() +{ + x2w_startup::Mesh57GroupExchangeState state; + state.full_exec = true; + state.group_stride = true; + return state; +} + +bool gap_is(const std::string& code, const x2w_startup::Mesh57GroupExchangeState& state, const char* expect) +{ + const char* got = x2w_startup::mesh57_group_exchange_gap(code, 0, state); + if (!got || std::strcmp(got, expect) != 0 || std::strstr(got, "0x") != nullptr) { + std::fprintf(stderr, "mesh57 group exchange: got %s\n", got ? got : "(null)"); + return false; + } + return true; +} +} // namespace + +int main() +{ + if (std::strcmp(x2w_startup::mesh57_group_exchange_refusal(), + "mesh group-index exchange shape or entry state is not covered") != 0) + return fail("refusal text"); + + const std::string saved = code_from(saved_exchange); + const auto ready = ready_state(); + if (!gap_is(saved, ready, "the exchange matched the accepted checks")) + return fail("saved sequence matches"); + + std::vector no_save = saved_exchange; + no_save.erase(no_save.begin() + 1); + if (!gap_is(code_from(no_save), ready, "the exchange matched the accepted checks")) + return fail("sequence without a save matches"); + + if (!gap_is(code_from({0xbefe0481u, 0xbe88047eu}), ready_state(), + "the exchange is shorter than the accepted sequence")) + return fail("short sequence"); + + // A save makes the accepted sequence 64 bytes. 60 bytes is not enough. + if (!gap_is(code_from(std::vector(saved_exchange.begin(), saved_exchange.end() - 1)), + ready, "the exchange is shorter than the accepted sequence")) + return fail("save form does not fit"); + + auto mask = saved_exchange; + mask[2] ^= 1u; + if (!gap_is(code_from(mask), ready, "the wave-bit mask is not an AND of s3 with a literal")) + return fail("mask"); + + auto step = saved_exchange; + step[5] ^= 1u; + if (!gap_is(code_from(step), ready, "exchange step 2 does not match")) + return fail("tail step"); + + auto branched = ready; + branched.branch_open = true; + if (!gap_is(saved, branched, "a scalar branch is open")) + return fail("branch"); + + auto skipped = ready; + skipped.exec_skip = true; + if (!gap_is(saved, skipped, "an EXEC skip is open")) + return fail("exec skip"); + + auto partial = ready; + partial.full_exec = false; + if (!gap_is(saved, partial, "EXEC is not the full wave")) + return fail("exec"); + + auto wave32 = ready; + wave32.wave32 = true; + if (!gap_is(saved, wave32, "the stage is wave32")) + return fail("wave32"); + + auto stride = ready; + stride.group_stride = false; + if (!gap_is(saved, stride, "group stride is zero")) + return fail("group stride"); + if (!gap_is(code_from(no_save), stride, "group stride is zero")) + return fail("group stride without a save"); + + auto s3 = ready; + s3.s3_written = true; + if (!gap_is(saved, s3, "s3 was already written")) + return fail("s3"); + + auto v5 = ready; + v5.v5_written = true; + if (!gap_is(saved, v5, "v5 was already written")) + return fail("v5"); + + auto high_dest = saved_exchange; + high_dest[2] = (high_dest[2] & 0xff80ffffu) | (106u << 16); + if (!gap_is(code_from(high_dest), ready, "the mask destination is not an SGPR")) + return fail("mask destination"); + + auto odd_save = saved_exchange; + odd_save[1] = (odd_save[1] & 0xff80ffffu) | (105u << 16); + if (!gap_is(code_from(odd_save), ready, "the saved EXEC pair is not a free even SGPR")) + return fail("saved exec pair"); + + char line[192]; + const char* text = + "native compute +0x28: mesh group-index exchange shape or entry state is not covered: group stride is zero"; + if (!x2w_startup::mesh57_exchange_gap_line(text, 0, line, sizeof(line)) || + std::strstr(line, "key=0000000000000000") == nullptr || + std::strstr(line, "group stride is zero") == nullptr || std::strstr(line, "0x") != nullptr || + std::strstr(line, "befe") != nullptr) + return fail("gap line"); + char other[64]; + if (x2w_startup::mesh57_exchange_gap_line("derived mesh translation was refused", 1, other, sizeof(other)) || + other[0] != 0) + return fail("other exception"); + char tiny[8]; + std::memset(tiny, 0x5a, sizeof(tiny)); + x2w_startup::mesh57_exchange_gap_line(text, 1, tiny, sizeof(tiny)); + if (tiny[sizeof(tiny) - 1] != 0) + return fail("gap line cap"); + return 0; +} diff --git a/tests/mesh57_record_bounds_check.cpp b/tests/mesh57_record_bounds_check.cpp index ac8e57a96f..0c942bd1fc 100644 --- a/tests/mesh57_record_bounds_check.cpp +++ b/tests/mesh57_record_bounds_check.cpp @@ -127,17 +127,17 @@ std::uint32_t vop3_word1(unsigned src0, unsigned src1, unsigned src2) // s8 is min(s1 + (1 << (s2 >> 29)), s3) - s1. The shift, the power of two, the min // and the subtract all write s8. gap 1 replaces the subtract with an add. gap 2 // adds s9 instead of s1. gap 3 shifts by 28. -std::vector multiplied_program(unsigned mask, unsigned width, int gap) +std::vector multiplied_program(unsigned mask, unsigned width, int gap, unsigned field = 8u) { const unsigned mask_src = mask <= 64u ? 128u + mask : 255u; std::vector words; auto append = [&](std::uint32_t word) { words.push_back(word); }; - append(vop2_word(27, 1, 8, mask_src)); + append(vop2_word(27, 1, field, mask_src)); if (mask_src == 255u) append(mask); append(vop2_word(37, 2, 1, 129)); append(vop3_word0(328, 3)); - append(vop3_word1(256u + 8u, 128u + width, 128u + width)); + append(vop3_word1(256u + field, 128u + width, 128u + width)); append(vop2_word(37, 4, 3, 129)); // One scalar register is reused for the shift, the power of two, the min and // the subtract, which is the chain the reader has to follow by definition. @@ -179,6 +179,77 @@ std::vector multiplied_names(int gap) "exp", "s_endpgm"}; } +// MUBUF. soffset is the inline 0 (128). vdata is word1 bits 15:8. LDS is word0 bit 16. +// TFE is word1 bit 23. Opcode 12/13/14/15 are dword, dwordx2, dwordx4, dwordx3. +// Opcode 131 is buffer_load_format_d16_xyzw, two VGPRs, not a raw record dword. +void append_mubuf(std::vector& words, unsigned op, unsigned vdata, bool lds, bool tfe) +{ + unsigned word0 = 0xE0000000u | ((op & 255u) << 18); + if (lds) + word0 |= 0x10000u; + unsigned word1 = 0x80000000u | ((vdata & 255u) << 8); + if (tfe) + word1 |= 0x800000u; + words.push_back(word0); + words.push_back(word1); +} + +// MTBUF. The low opcode bits sit in word0 bits 18:16, so opcode 1 sets bit 16. +// That bit is LDS on MUBUF and is not LDS here. Opcode bit 3 is word1 bit 18. +void append_mtbuf(std::vector& words, unsigned op, unsigned vdata) +{ + const unsigned word0 = 0xE8000000u | ((op & 7u) << 16); + unsigned word1 = 0x80000000u | ((vdata & 255u) << 8); + if ((op & 8u) != 0) + word1 |= 1u << 18; + words.push_back(word0); + words.push_back(word1); +} + +// The multiplied chain, with a buffer load of the record VGPR in front of the masks. +// older writes that VGPR first. second inserts another load of it between the and +// and the bitfield extract. field is the VGPR the masks read. +struct LoadSpec { + unsigned op = 13u; + unsigned vdata = 8u; + unsigned field = 8u; + bool lds = false; + bool tfe = false; + bool older = false; + bool second = false; +}; + +std::vector loaded_program(const LoadSpec& spec) +{ + std::vector words = multiplied_program(0x7fu, 7u, 0, spec.field); + if (spec.second) { + // 0x7f does not fit an inline immediate, so the and is the opcode plus a literal. + std::vector extra; + append_mubuf(extra, spec.op, spec.vdata, spec.lds, spec.tfe); + words.insert(words.begin() + 2, extra.begin(), extra.end()); + } + std::vector head; + if (spec.older) + head.push_back(vop1_word(1, spec.vdata, 256u + 9u)); + append_mubuf(head, spec.op, spec.vdata, spec.lds, spec.tfe); + words.insert(words.begin(), head.begin(), head.end()); + return words; +} + +std::vector loaded_names(const char* load, bool older, bool second) +{ + std::vector names; + if (older) + names.push_back("v_mov_b32"); + names.push_back(load); + names.push_back("v_and_b32"); + if (second) + names.push_back(load); + const auto rest = multiplied_names(0); + names.insert(names.end(), rest.begin() + 1, rest.end()); + return names; +} + const std::vector record_names = { "v_and_b32", "v_add_nc_u32", "v_lshrrev_b32", "v_and_b32", "v_add_nc_u32", "v_readfirstlane_b32", "v_readfirstlane_b32", "v_mov_b32", @@ -328,5 +399,108 @@ int main() if (!reason_is(x2w_startup::mesh57_read_record_m0_bounds(code_from(over), known_k(1)), "derived mesh record bound exceeds the mesh output limit")) return fail("multiplied bound over 256"); + + // An older ALU write of the record VGPR, then a raw dwordx2 load (with the TFE + // status VGPR), then the mask. The load is the record word, so the older write + // is not what the mask reads. + const LoadSpec hidden{13u, 8u, 8u, false, true, true, false}; + const auto hidden_words = loaded_program(hidden); + if (!names_match(hidden_words, loaded_names("buffer_load_dwordx2", true, false))) + return fail("loaded encoding"); + const std::string hidden_code = code_from(hidden_words); + if (!bounds_are(x2w_startup::mesh57_read_record_m0_bounds(hidden_code, known_k(1)), 256, 256, 256)) + return fail("load hides the older write"); + const auto immediate_loaded = x2w_startup::mesh57_read_layout(hidden_code); + if (immediate_loaded.layout || !immediate_loaded.reason || + std::strcmp(immediate_loaded.reason, "derived mesh needs one immediate allocation") != 0) + return fail("immediate reader refuses the loaded program"); + + // The same load with the LDS bit set writes no VGPR, so the older write remains. + const LoadSpec lds{13u, 8u, 8u, true, false, true, false}; + const auto lds_words = loaded_program(lds); + if (!names_match(lds_words, loaded_names("buffer_load_dwordx2", true, false))) + return fail("lds encoding"); + if (!reason_is(x2w_startup::mesh57_read_record_m0_bounds(code_from(lds_words), known_k(1)), + "derived mesh record mask was not proven")) + return fail("lds load does not define the VGPR"); + + // dwordx2 writes two VGPRs. The second is not the record word. + const LoadSpec high{13u, 8u, 9u, false, false, false, false}; + const auto high_words = loaded_program(high); + if (!names_match(high_words, loaded_names("buffer_load_dwordx2", false, false))) + return fail("second dword encoding"); + if (!reason_is(x2w_startup::mesh57_read_record_m0_bounds(code_from(high_words), known_k(1)), + "derived mesh record mask was not proven")) + return fail("second dword is not the record"); + + // Two raw loads of the same VGPR. Each field has to come from the same load. + const LoadSpec split{12u, 8u, 8u, false, false, false, true}; + const auto split_words = loaded_program(split); + if (!names_match(split_words, loaded_names("buffer_load_dword", false, true))) + return fail("two load encoding"); + if (!reason_is(x2w_startup::mesh57_read_record_m0_bounds(code_from(split_words), known_k(1)), + "derived mesh record mask was not proven")) + return fail("fields come from two loads"); + + // d16 xyzw is two VGPRs of converted data, not four raw dwords and not the record. + const LoadSpec packed{131u, 8u, 8u, false, false, false, false}; + const auto packed_words = loaded_program(packed); + if (!names_match(packed_words, loaded_names("buffer_load_format_d16_xyzw", false, false))) + return fail("d16 encoding"); + if (!reason_is(x2w_startup::mesh57_read_record_m0_bounds(code_from(packed_words), known_k(1)), + "derived mesh record mask was not proven")) + return fail("d16 load is not the record"); + + // The TFE status VGPR follows the data VGPR. It is not the record word. + const LoadSpec status{12u, 8u, 9u, false, true, false, false}; + const auto status_words = loaded_program(status); + if (!names_match(status_words, loaded_names("buffer_load_dword", false, false))) + return fail("tfe encoding"); + if (!reason_is(x2w_startup::mesh57_read_record_m0_bounds(code_from(status_words), known_k(1)), + "derived mesh record mask was not proven")) + return fail("tfe status is not the record"); + + // d16 xyzw writes two VGPRs. A raw dword in the third VGPR stays the record. + auto packed_width = loaded_program(LoadSpec{131u, 8u, 10u, false, false, false, false}); + std::vector prior_dword; + append_mubuf(prior_dword, 12u, 10u, false, false); + packed_width.insert(packed_width.begin(), prior_dword.begin(), prior_dword.end()); + const auto packed_width_names = [&] { + auto names = loaded_names("buffer_load_format_d16_xyzw", false, false); + names.insert(names.begin(), "buffer_load_dword"); + return names; + }(); + if (!names_match(packed_width, packed_width_names)) + return fail("d16 width encoding"); + if (!bounds_are(x2w_startup::mesh57_read_record_m0_bounds(code_from(packed_width), known_k(1)), 256, 256, 256)) + return fail("d16 xyzw is two VGPRs"); + + // d16 xy is one VGPR. The next VGPR can still be a raw record dword. + auto packed_xy = loaded_program(LoadSpec{129u, 8u, 9u, false, false, false, false}); + std::vector prior_xy; + append_mubuf(prior_xy, 12u, 9u, false, false); + packed_xy.insert(packed_xy.begin(), prior_xy.begin(), prior_xy.end()); + const auto packed_xy_names = [&] { + auto names = loaded_names("buffer_load_format_d16_xy", false, false); + names.insert(names.begin(), "buffer_load_dword"); + return names; + }(); + if (!names_match(packed_xy, packed_xy_names)) + return fail("d16 xy encoding"); + if (!bounds_are(x2w_startup::mesh57_read_record_m0_bounds(code_from(packed_xy), known_k(1)), 256, 256, 256)) + return fail("d16 xy is one VGPR"); + + // MTBUF opcode 1 sets word0 bit 16. That is not an LDS load, and a typed + // load is not the packed record dword. + auto typed = loaded_program(LoadSpec{13u, 8u, 8u, false, false, false, false}); + typed.erase(typed.begin(), typed.begin() + 2); + std::vector typed_head; + append_mtbuf(typed_head, 1u, 8u); + typed.insert(typed.begin(), typed_head.begin(), typed_head.end()); + if (!names_match(typed, loaded_names("tbuffer_load_format_xy", false, false))) + return fail("mtbuf encoding"); + if (!reason_is(x2w_startup::mesh57_read_record_m0_bounds(code_from(typed), known_k(1)), + "derived mesh record mask was not proven")) + return fail("mtbuf bit 16 is not an lds load"); return 0; } From efc11e8dfb2d18e4f6cc3f586f2dff76042379d9 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Mon, 30 Nov 2026 17:41:07 +0000 Subject: [PATCH 17/24] startup: include the mesh exchange header at file scope native_mesh57.inl is included inside the anonymous namespace of the device translation unit. A header included from there nested x2w_startup inside that namespace. The header is included at file scope with the other mesh headers. The record layout still leaves the group stride at 0: the hardware entry value of v5 is not modelled. --- docs/experiments/native-fixed-mesh57.md | 2 ++ docs/startup-runtime.md | 2 +- src/startup_stubs/d3d12_xs_device.cpp | 3 +++ src/startup_stubs/native_mesh57.inl | 2 -- 4 files changed, 6 insertions(+), 3 deletions(-) diff --git a/docs/experiments/native-fixed-mesh57.md b/docs/experiments/native-fixed-mesh57.md index 906d13fceb..af1a62c897 100644 --- a/docs/experiments/native-fixed-mesh57.md +++ b/docs/experiments/native-fixed-mesh57.md @@ -170,6 +170,8 @@ The group size comes from `gfx1013_direct_mesh.inl`. That lowerer indexes each v That lowerer still accepts only one group-index exchange. It opens with `s_mov_b64 exec, 1`, optionally saves `exec`, masks s3 with the wave-id literal, and then matches a fixed 13-word tail: the scc branch, `v_lshrrev_b32 v5, 7, v5`, `v_mov_b32 v0, 0`, a `ds_write`, a wait, a barrier, a branch, a barrier, another `v_mov_b32 v0, 0`, and a `ds_read`. The entry state has to be a closed scalar branch, no open EXEC skip, EXEC the full wave, not wave32, a non-zero group stride, s3 and v5 not yet written, the mask destination an SGPR, and, when exec was saved, a free even SGPR pair that does not overlap that destination. The stride is what turns `groupId` into the value the exchange broadcasts (`v5 >> 7`). This derivation sets the stride to 0 and does not define that entry VGPR. The per-thread id, wave times 64 plus the lane, with the wave taken from s3 bits 27:24, is the lane index the lowerer already uses. It is not the value this exchange writes to LDS. This path does not invent a stride and does not treat the broadcast as the thread id. +The stride is still an open input. On the path this repository already translates, `group_stride` comes from a reviewed `.mesh57-state` profile or from a `mesh1` layout line. The lowerer sets the entry value of v5 to `groupId.x * group_stride` and the exchange keeps that value shifted right by 7. The immediate reader stores 0 as well: its programs are one wave of 64 and do not broadcast a group id. The record reader stores 0, and the derive check refuses a non-zero value from that reader. `DispatchMesh` passes group counts, not the word the hardware places in v5. The root constants this derivation binds are not that word. The offline translator records the same gap: the broadcast is entry v5 shifted right by 7 from wave 0, lane 0, and what v5 holds at entry is not verified. The thread count, a PSV0 thread count, and the register block do not define it. The missing model is that hardware entry value. + When `record_output_counts` is set and that opener is refused, the reason keeps `mesh group-index exchange shape or entry state is not covered` and names the first failed check. The checks, in order, are: the sequence is shorter than the accepted form (60 bytes, or 64 when exec is saved), the wave-bit mask is not an AND of s3 with a literal, one of the 13 tail steps does not match, a scalar branch is open, an EXEC skip is open, EXEC is not the full wave, the stage is wave32, the group stride is zero, s3 was already written, v5 was already written, the mask destination is not an SGPR, and the saved EXEC pair is not a free even SGPR. With the flag clear, the reason stays the sentence with no check name. One `x2w-render mesh57-derive exchange` line is logged per pipeline key, at most eight keys. The line is the key and the check. It has no pointer and no instruction word. `SetMeshOutputCounts` receives the runtime vertex and primitive registers, each limited to the derived maximum, and both become 0 when either is 0. Outputs past the runtime count are not written. The static bound sizes the output arrays. It is not substituted when the registers are unproven. diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index bac17a97cc..e9a9aecdfb 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -1804,7 +1804,7 @@ ctest --preset dev --no-tests=error -R '^startup_hook_(window|overlap)$' -V | `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 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 and stencil unless `X2W_MESH57_DERIVED_BOUNDS=1`, 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_MESH57_DERIVED_BOUNDS=1` | experimental, with `X2W_MESH57_DERIVE_STATE=1`. Off by default, and unset it leaves the slot 57 derivation unchanged. Set, a mesh whose `m0` is `s_lshl_b32` by 12 then `s_or_b32` into `m0` immediately before the only `GS_ALLOC_REQ`, with both counts proven as `(field & mask) + 1` from one record word, may use those masks as the output limit. The record word is the first data VGPR of one raw `buffer_load_dword`, `dwordx2`, `dwordx3`, or `dwordx4` when both fields trace to that same load. An LDS load, a format or `d16` load, a high dword, and a TFE status VGPR do not prove it. The multiply is `2^k` only when the entry `k` is the constant 1; an unknown `k` or any other `k` stays refused. A `v_bfe_u32` field, and a `v_mul_lo_u32` by `min(base + (1 << k), L) - base` with that `k` taken from a logical shift right by 29, use the same limit. An unproven multiplier, a mismatched base, or a shift other than 29 stays refused. The subtract can wrap when `L` is below the base; `SetMeshOutputCounts` still clamps each runtime count to the derived limit. A product above 256 vertices or 256 primitives stays refused. A color-target refusal logs the failing condition once per pipeline key. A group-index exchange the direct mesh lowerer does not cover stays refused. With this switch on, that refusal names the first failed check, and one line per pipeline key is logged. The group is the smallest multiple of 64 that covers that limit, from the direct mesh lane id (one thread writes one output). The translated shader passes the runtime counts to `SetMeshOutputCounts`. The immediate `m0` reader is unchanged. This switch does not invent a user-SGPR map for a heap-indexed root. With the switch on, the decoded depth and stencil state is copied into the derived mesh pipeline, the bound depth view's format is the pipeline depth format, and the dispatch sets the decoded stencil reference. Depth bounds, differing back-face masks, a multisampled depth buffer, and a stencil test without a stencil plane stay refused. See [Opt-in record bounds](experiments/native-fixed-mesh57.md#opt-in-record-bounds) | +| `X2W_MESH57_DERIVED_BOUNDS=1` | experimental, with `X2W_MESH57_DERIVE_STATE=1`. Off by default, and unset it leaves the slot 57 derivation unchanged. Set, a mesh whose `m0` is `s_lshl_b32` by 12 then `s_or_b32` into `m0` immediately before the only `GS_ALLOC_REQ`, with both counts proven as `(field & mask) + 1` from one record word, may use those masks as the output limit. The record word is the first data VGPR of one raw `buffer_load_dword`, `dwordx2`, `dwordx3`, or `dwordx4` when both fields trace to that same load. An LDS load, a format or `d16` load, a high dword, and a TFE status VGPR do not prove it. The multiply is `2^k` only when the entry `k` is the constant 1; an unknown `k` or any other `k` stays refused. A `v_bfe_u32` field, and a `v_mul_lo_u32` by `min(base + (1 << k), L) - base` with that `k` taken from a logical shift right by 29, use the same limit. An unproven multiplier, a mismatched base, or a shift other than 29 stays refused. The subtract can wrap when `L` is below the base; `SetMeshOutputCounts` still clamps each runtime count to the derived limit. A product above 256 vertices or 256 primitives stays refused. A color-target refusal logs the failing condition once per pipeline key. A group-index exchange the direct mesh lowerer does not cover stays refused. With this switch on, that refusal names the first failed check, and one line per pipeline key is logged. The record layout leaves the group stride at 0. The hardware entry value of v5, which a reviewed profile's stride stands in for, is not modelled. The group is the smallest multiple of 64 that covers that limit, from the direct mesh lane id (one thread writes one output). The translated shader passes the runtime counts to `SetMeshOutputCounts`. The immediate `m0` reader is unchanged. This switch does not invent a user-SGPR map for a heap-indexed root. With the switch on, the decoded depth and stencil state is copied into the derived mesh pipeline, the bound depth view's format is the pipeline depth format, and the dispatch sets the decoded stencil reference. Depth bounds, differing back-face masks, a multisampled depth buffer, and a stencil test without a stencil plane stay refused. See [Opt-in record bounds](experiments/native-fixed-mesh57.md#opt-in-record-bounds) | | `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 b54624e953..c5b8b9ee87 100644 --- a/src/startup_stubs/d3d12_xs_device.cpp +++ b/src/startup_stubs/d3d12_xs_device.cpp @@ -34,6 +34,9 @@ #include "startup_stubs/pso_recipe.h" #include "startup_stubs/depth_state_apply.h" #include "startup_stubs/mesh57_derived_depth.h" +// File scope. native_mesh57.inl is included inside the anonymous namespace below, +// and a header included from there would nest namespace x2w_startup inside it. +#include "startup_stubs/mesh57_group_exchange.h" #include "startup_stubs/d16_image_format.h" #include "startup_stubs/formatted_buffer.h" #include "startup_stubs/view_content_token.h" diff --git a/src/startup_stubs/native_mesh57.inl b/src/startup_stubs/native_mesh57.inl index f9280135c5..02131a02a3 100644 --- a/src/startup_stubs/native_mesh57.inl +++ b/src/startup_stubs/native_mesh57.inl @@ -1,5 +1,3 @@ -#include "startup_stubs/mesh57_group_exchange.h" - // Included after both the native graphics compiler and the desktop stream validator. // Resolve every SRV before recording barriers or a descriptor table. A guest root address // has no descriptor length; use the remaining proven GPU allocation, including for indexed reads. From e8d65c1826eed8fbbf31f8a811672e4a81af089b Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Mon, 30 Nov 2026 19:34:13 +0000 Subject: [PATCH 18/24] startup: accept one to eight color targets on a derived mesh AI-assisted (Cursor) Co-authored-by: SimSalabimse --- docs/experiments/native-fixed-mesh57.md | 10 +- src/startup_stubs/mesh57_derived_depth.h | 106 ++++++++++++++++--- src/startup_stubs/native_mesh57.inl | 33 ++++-- tests/mesh57_derived_depth_check.cpp | 127 ++++++++++++++++++++++- 4 files changed, 249 insertions(+), 27 deletions(-) diff --git a/docs/experiments/native-fixed-mesh57.md b/docs/experiments/native-fixed-mesh57.md index af1a62c897..e4873f989b 100644 --- a/docs/experiments/native-fixed-mesh57.md +++ b/docs/experiments/native-fixed-mesh57.md @@ -132,9 +132,9 @@ An empty guest root is unchanged. One 32-bit constant parameter of 1..8 dwords a 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 unless `X2W_MESH57_DERIVED_BOUNDS=1`; 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. A bound depth view stays refused unless that second switch is on. 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. +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 unless `X2W_MESH57_DERIVED_BOUNDS=1`; an enabled test is refused rather than given a guessed depth format. The color targets are the single-sample targets bound on that direct list, one to eight in slot order, with a viewport and a scissor and no depth view. A gap or a null slot, an unknown format, and more than eight targets are refused. A bound depth view stays refused unless that second switch is on. 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. +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 formats of that call. From the x64 Windows build environment, with DXC available to the native shader stand-in: @@ -188,13 +188,13 @@ Heap 1024 is the view-heap flag (`0x400`). Heap 3072 is that flag plus the sampl ## Derived depth and stencil -`X2W_MESH57_DERIVED_BOUNDS=1` also lifts the depth refusal in this derivation. With the switch off, an enabled depth or stencil test is still `derived mesh keeps depth and stencil disabled`, and a bound depth view is still refused. The description is the one `decode_depth_stencil` already produces from state block A. It is copied into the mesh pipeline's depth-stencil state. The pipeline depth format is the depth view already bound on that list by `OMSetRenderTargets`, the same bind a translated draw uses. The dispatch sets `OMSetStencilRef` from the decoded reference for that command and then restores the list's reference. One single-sample color target, a viewport and a scissor are still required. +`X2W_MESH57_DERIVED_BOUNDS=1` also lifts the depth refusal in this derivation. With the switch off, an enabled depth or stencil test is still `derived mesh keeps depth and stencil disabled`, and a bound depth view is still refused. The description is the one `decode_depth_stencil` already produces from state block A. It is copied into the mesh pipeline's depth-stencil state. The pipeline depth format is the depth view already bound on that list by `OMSetRenderTargets`, the same bind a translated draw uses. The dispatch sets `OMSetStencilRef` from the decoded reference for that command and then restores the list's reference. One to eight single-sample color targets, a viewport and a scissor are still required. Each target needs a known format, the slots are contiguous from slot 0, and every target is single-sample with the same sample count as the depth buffer when one is bound. The mesh pipeline takes that count and those formats in slot order. Blend and write mask stay the per-target state decoded from the eight colour-blend registers. Dual-source blending stays render target 0 only. -A form that cannot be copied exactly stays refused, and the reason names it. Depth bounds are not a desktop depth-stencil field. Back-face stencil masks or a reference that differ from the front are not one desktop reference and one pair of masks. A stencil op or compare with no desktop form stays refused. A depth or stencil test with no depth view, a multisampled depth buffer, color and depth sample counts that differ, a zero sample count, and a stencil test whose depth format has no stencil plane stay refused. The format is the bound view's format. This path does not choose one. Those attachment refusals are not remembered: a later list can bind a depth view. A refusal that comes from the pipeline's own registers is remembered. +A form that cannot be copied exactly stays refused, and the reason names it. Depth bounds are not a desktop depth-stencil field. Back-face stencil masks or a reference that differ from the front are not one desktop reference and one pair of masks. A stencil op or compare with no desktop form stays refused. A depth or stencil test with no depth view, a multisampled depth buffer, color and depth sample counts that differ, color targets whose sample counts differ, a zero sample count, and a stencil test whose depth format has no stencil plane stay refused. A gap or a null slot, an unknown color format, and more than eight color targets stay refused. The format is the bound view's format. This path does not choose one. Those attachment refusals are not remembered: a later list can bind a depth view. A refusal that comes from the pipeline's own registers is remembered. When the switch is on and this color-target check refuses, one `x2w-render mesh57-derive targets` line is logged per pipeline key, and at most eight keys are kept. The line names whether targets are bound, whether the viewport and scissor are set, the color-target count, whether target 0 is present, whether its format is known, and the color and depth sample counts. It has no pointer and no raw word. The census still receives the same refusal string. The switch off does not log the line. -`mesh57_derived_depth` checks the register-word mapping, the switch-off refusals, each of those reasons, and the target-gap line for a missing bind, viewport, scissor, count, target, format, or sample count. It does not need a device. +`mesh57_derived_depth` checks the register-word mapping, the switch-off refusals, each of those reasons, one, three and six color targets, a gap or null slot, an unknown format, differing color sample counts, more than eight targets, the formats kept for the pipeline, and the target-gap line for a missing bind, viewport, scissor, count, target, format, or sample count. It does not need a device. ```powershell ctest --preset dev --no-tests=error -R 'mesh57_derived_depth|mesh57_record_bounds|mesh57_group_exchange|mesh57_derive_alloc' diff --git a/src/startup_stubs/mesh57_derived_depth.h b/src/startup_stubs/mesh57_derived_depth.h index 1f524c53f8..debe1bf006 100644 --- a/src/startup_stubs/mesh57_derived_depth.h +++ b/src/startup_stubs/mesh57_derived_depth.h @@ -42,10 +42,24 @@ struct Mesh57DepthFacts { bool masks_differ = false; }; +// D3D12_SIMULTANEOUS_RENDER_TARGET_COUNT. The Windows caller static_asserts they match. +constexpr unsigned mesh57_color_target_limit = 8; + +// One color-target slot. format 0 is unknown. samples and quality are the desktop sample +// description. They are filled from the bound resource only when the bounds switch is on. +struct Mesh57BoundColor { + bool bound = false; + unsigned format = 0; + unsigned samples = 1; + unsigned quality = 0; +}; + // targets_single_sample is the list flag the switch-off check already uses: every color // target and the depth target, when one is bound, are one sample with quality 0. // color_samples and depth_samples are read from the bound resources only when the switch -// is on. depth_bound is false when the format is known but the resource is not. +// is on. color_samples is target 0, which is what the diagnostic line prints. colors[] is +// every slot in order, and target_count may be above the limit. depth_bound is false when +// the format is known but the resource is not. struct Mesh57DepthTargets { bool targets_bound = false; bool viewport_set = false; @@ -54,6 +68,7 @@ struct Mesh57DepthTargets { unsigned target_count = 0; bool has_target0 = false; unsigned target0_format = 0; + Mesh57BoundColor colors[mesh57_color_target_limit]{}; unsigned dsv_format = 0; bool depth_bound = false; unsigned color_samples = 1; @@ -68,6 +83,9 @@ struct Mesh57DerivedDepth { unsigned dsv_format = 0; bool set_stencil_ref = false; unsigned stencil_ref = 0; + // NumRenderTargets and RTVFormats for the mesh pipeline, in slot order. Left at 0 when refused. + unsigned render_target_count = 0; + unsigned rtv_formats[mesh57_color_target_limit]{}; }; constexpr unsigned mesh57_cmp_never = 1; @@ -202,6 +220,52 @@ inline const char* mesh57_color_target_reason() noexcept return "derived mesh needs one single-sample color target, a viewport and a scissor"; } +inline const char* mesh57_color_gap_reason() noexcept +{ + return "derived mesh color target list has a gap or a null slot"; +} + +inline const char* mesh57_color_format_reason() noexcept +{ + return "derived mesh color target format is unknown"; +} + +inline const char* mesh57_color_sample_mismatch_reason() noexcept +{ + return "derived mesh color target sample counts differ"; +} + +inline const char* mesh57_color_limit_reason() noexcept +{ + return "derived mesh has more than 8 color targets"; +} + +// Bound, viewport, scissor and a count of 0 stay on the original reason. One to eight +// slots must be contiguous from slot 0, each with a known format. +inline const char* mesh57_color_list_reason(const Mesh57DepthTargets& targets) noexcept +{ + if (!targets.targets_bound || !targets.viewport_set || !targets.scissor_set || targets.target_count == 0) + return mesh57_color_target_reason(); + if (targets.target_count > mesh57_color_target_limit) + return mesh57_color_limit_reason(); + for (unsigned i = 0; i < targets.target_count; ++i) { + if (!targets.colors[i].bound) + return mesh57_color_gap_reason(); + } + for (unsigned i = 0; i < targets.target_count; ++i) { + if (targets.colors[i].format == 0) + return mesh57_color_format_reason(); + } + return nullptr; +} + +inline void mesh57_publish_rtv_formats(Mesh57DerivedDepth& out, const Mesh57DepthTargets& targets) noexcept +{ + out.render_target_count = targets.target_count; + for (unsigned i = 0; i < targets.target_count && i < mesh57_color_target_limit; ++i) + out.rtv_formats[i] = targets.colors[i].format; +} + // The color-target, viewport, scissor and sample-count refusals. Depth-state refusals // are not in this set: those are properties of the pipeline registers. inline bool mesh57_target_attachment_reason(const char* reason) noexcept @@ -209,6 +273,10 @@ inline bool mesh57_target_attachment_reason(const char* reason) noexcept if (!reason) return false; return std::strcmp(reason, mesh57_color_target_reason()) == 0 || + std::strcmp(reason, mesh57_color_gap_reason()) == 0 || + std::strcmp(reason, mesh57_color_format_reason()) == 0 || + std::strcmp(reason, mesh57_color_sample_mismatch_reason()) == 0 || + std::strcmp(reason, mesh57_color_limit_reason()) == 0 || std::strcmp(reason, "derived mesh sample count is unknown") == 0 || std::strcmp(reason, "derived mesh depth buffer sample count is unknown") == 0 || std::strcmp(reason, "derived mesh depth buffer is multisampled") == 0 || @@ -259,12 +327,15 @@ inline Mesh57DerivedDepth mesh57_derived_depth(bool bounds_switch, const Mesh57D out.remember = true; return out; } - if (!targets.targets_bound || !targets.viewport_set || !targets.scissor_set || - !targets.targets_single_sample || targets.target_count != 1 || !targets.has_target0 || - targets.dsv_format != 0 || targets.target0_format == 0) { + if (const char* color = mesh57_color_list_reason(targets)) { + out.reason = color; + return out; + } + if (!targets.targets_single_sample || targets.dsv_format != 0) { out.reason = mesh57_color_target_reason(); return out; } + mesh57_publish_rtv_formats(out, targets); return out; } if (!depth.ok) { @@ -292,13 +363,16 @@ inline Mesh57DerivedDepth mesh57_derived_depth(bool bounds_switch, const Mesh57D out.remember = true; return out; } - if (!targets.targets_bound || !targets.viewport_set || !targets.scissor_set || - targets.target_count != 1 || !targets.has_target0 || targets.target0_format == 0) { - out.reason = mesh57_color_target_reason(); + if (const char* color = mesh57_color_list_reason(targets)) { + out.reason = color; return out; } - if ((targets.has_target0 && targets.color_samples == 0) || - (targets.depth_bound && targets.depth_samples == 0)) { + bool color_samples_unknown = false; + for (unsigned i = 0; i < targets.target_count; ++i) { + if (targets.colors[i].samples == 0) + color_samples_unknown = true; + } + if (color_samples_unknown || (targets.depth_bound && targets.depth_samples == 0)) { out.reason = "derived mesh sample count is unknown"; return out; } @@ -306,10 +380,17 @@ inline Mesh57DerivedDepth mesh57_derived_depth(bool bounds_switch, const Mesh57D out.reason = "derived mesh depth buffer sample count is unknown"; return out; } - const bool color_single = targets.color_samples == 1 && targets.color_quality == 0; + const unsigned color_samples = targets.colors[0].samples; + const unsigned color_quality = targets.colors[0].quality; + for (unsigned i = 1; i < targets.target_count; ++i) { + if (targets.colors[i].samples != color_samples || targets.colors[i].quality != color_quality) { + out.reason = mesh57_color_sample_mismatch_reason(); + return out; + } + } + const bool color_single = color_samples == 1 && color_quality == 0; const bool depth_msaa = targets.depth_samples != 1 || targets.depth_quality != 0; - const bool samples_differ = targets.depth_samples != targets.color_samples || - targets.depth_quality != targets.color_quality; + const bool samples_differ = targets.depth_samples != color_samples || targets.depth_quality != color_quality; if (targets.depth_bound && color_single && depth_msaa) { out.reason = "derived mesh depth buffer is multisampled"; return out; @@ -335,6 +416,7 @@ inline Mesh57DerivedDepth mesh57_derived_depth(bool bounds_switch, const Mesh57D out.set_stencil_ref = true; out.stencil_ref = depth.stencil_ref & 0xffu; } + mesh57_publish_rtv_formats(out, targets); return out; } diff --git a/src/startup_stubs/native_mesh57.inl b/src/startup_stubs/native_mesh57.inl index 02131a02a3..309c81892f 100644 --- a/src/startup_stubs/native_mesh57.inl +++ b/src/startup_stubs/native_mesh57.inl @@ -943,13 +943,28 @@ const char* derive_slot57_mesh(Wrapper* pipeline, Pass& pass, const D3D12_BLEND_ depth_targets.scissor_set = pass.scissor_set; depth_targets.targets_single_sample = pass.targets_single_sample; depth_targets.target_count = pass.target_count; - depth_targets.has_target0 = pass.target0 != nullptr; - depth_targets.target0_format = static_cast(pass.target_formats[0]); depth_targets.dsv_format = static_cast(pass.dsv_format); - if (derived_bounds && pass.target0) { - const auto color_samples = pass.target0->GetDesc().SampleDesc; - depth_targets.color_samples = color_samples.Count; - depth_targets.color_quality = color_samples.Quality; + UINT listed = pass.target_count; + if (listed > x2w_startup::mesh57_color_target_limit) + listed = x2w_startup::mesh57_color_target_limit; + for (UINT i = 0; i < listed; ++i) { + ID3D12Resource* resource = pass.bound_targets[i]; + auto& slot = depth_targets.colors[i]; + slot.bound = resource != nullptr; + slot.format = static_cast(pass.target_formats[i]); + if (!derived_bounds || !resource) + continue; + const auto samples = resource->GetDesc().SampleDesc; + slot.samples = samples.Count; + slot.quality = samples.Quality; + } + if (listed > 0) { + depth_targets.has_target0 = depth_targets.colors[0].bound; + depth_targets.target0_format = depth_targets.colors[0].format; + if (derived_bounds && depth_targets.colors[0].bound) { + depth_targets.color_samples = depth_targets.colors[0].samples; + depth_targets.color_quality = depth_targets.colors[0].quality; + } } if (derived_bounds && pass.bound_depth) { const auto depth_samples = pass.bound_depth->GetDesc().SampleDesc; @@ -1062,9 +1077,11 @@ const char* derive_slot57_mesh(Wrapper* pipeline, Pass& pass, const D3D12_BLEND_ return remember("derived mesh rasterizer does not match the bound state"); stream.rasterizer.value = bound_raster; stream.depth_stencil.value = depth.desc; + static_assert(x2w_startup::mesh57_color_target_limit == D3D12_SIMULTANEOUS_RENDER_TARGET_COUNT); D3D12_RT_FORMAT_ARRAY targets{}; - targets.NumRenderTargets = 1; - targets.RTFormats[0] = pass.target_formats[0]; + targets.NumRenderTargets = depth_decision.render_target_count; + for (UINT i = 0; i < depth_decision.render_target_count && i < D3D12_SIMULTANEOUS_RENDER_TARGET_COUNT; ++i) + targets.RTFormats[i] = static_cast(depth_decision.rtv_formats[i]); stream.rtv_formats.value = targets; stream.dsv_format.value = static_cast(depth_decision.dsv_format); DXGI_SAMPLE_DESC samples; diff --git a/tests/mesh57_derived_depth_check.cpp b/tests/mesh57_derived_depth_check.cpp index 411fbd2aa3..d22b3e14da 100644 --- a/tests/mesh57_derived_depth_check.cpp +++ b/tests/mesh57_derived_depth_check.cpp @@ -42,6 +42,10 @@ x2w_startup::Mesh57DepthTargets color_target() targets.target_count = 1; targets.has_target0 = true; targets.target0_format = 28; + targets.colors[0].bound = true; + targets.colors[0].format = 28; + targets.colors[0].samples = 1; + targets.colors[0].quality = 0; return targets; } @@ -53,16 +57,58 @@ x2w_startup::Mesh57DepthTargets depth_target(unsigned format, unsigned color_sam targets.depth_bound = true; targets.color_samples = color_samples; targets.color_quality = color_quality; + targets.colors[0].samples = color_samples; + targets.colors[0].quality = color_quality; targets.depth_samples = depth_samples; targets.depth_quality = depth_quality; targets.targets_single_sample = color_samples == 1 && color_quality == 0 && depth_samples == 1 && depth_quality == 0; return targets; } +x2w_startup::Mesh57DepthTargets listed_targets(unsigned count, const unsigned* formats, const unsigned* samples = nullptr) +{ + auto targets = color_target(); + targets.target_count = count; + for (unsigned i = 0; i < x2w_startup::mesh57_color_target_limit; ++i) { + targets.colors[i].bound = false; + targets.colors[i].format = 0; + targets.colors[i].samples = 1; + targets.colors[i].quality = 0; + } + const unsigned filled = count < x2w_startup::mesh57_color_target_limit ? count : x2w_startup::mesh57_color_target_limit; + for (unsigned i = 0; i < filled; ++i) { + targets.colors[i].bound = true; + targets.colors[i].format = formats[i]; + targets.colors[i].samples = samples ? samples[i] : 1u; + targets.colors[i].quality = 0; + } + targets.has_target0 = filled > 0 && targets.colors[0].bound; + targets.target0_format = targets.has_target0 ? targets.colors[0].format : 0u; + targets.color_samples = targets.has_target0 ? targets.colors[0].samples : 1u; + targets.color_quality = 0; + return targets; +} + +bool formats_are(const x2w_startup::Mesh57DerivedDepth& decision, const unsigned* formats, unsigned count) +{ + if (decision.reason || decision.render_target_count != count) + return false; + for (unsigned i = 0; i < count; ++i) { + if (decision.rtv_formats[i] != formats[i]) + return false; + } + for (unsigned i = count; i < x2w_startup::mesh57_color_target_limit; ++i) { + if (decision.rtv_formats[i] != 0) + return false; + } + return true; +} + bool reason_is(const x2w_startup::Mesh57DerivedDepth& decision, const char* reason, bool remember) { return decision.reason && std::strcmp(decision.reason, reason) == 0 && decision.remember == remember && - !decision.set_stencil_ref && decision.dsv_format == 0; + !decision.set_stencil_ref && decision.dsv_format == 0 && decision.render_target_count == 0 && + decision.rtv_formats[0] == 0; } using x2w_startup::mesh57_cmp_always; @@ -158,7 +204,8 @@ int main() if (!reason_is(off_bounds, "derived mesh keeps depth and stencil disabled", true)) return fail("switch off does not name depth bounds"); const auto off_clear = x2w_startup::mesh57_derived_depth(false, disabled, color_target()); - if (off_clear.reason || off_clear.dsv_format || off_clear.set_stencil_ref) + if (off_clear.reason || off_clear.dsv_format || off_clear.set_stencil_ref || off_clear.render_target_count != 1 || + off_clear.rtv_formats[0] != 28 || off_clear.rtv_formats[1] != 0) return fail("switch off accepts a disabled test"); const auto on = x2w_startup::mesh57_derived_depth(true, facts, depth_target(mesh57_fmt_d24_unorm_s8)); @@ -257,14 +304,17 @@ int main() return fail("color target count"); auto no_rt = depth_target(mesh57_fmt_d24_unorm_s8); no_rt.has_target0 = false; + no_rt.colors[0].bound = false; if (!gap_has(no_rt, "target0=0")) return fail("target 0 absent"); auto no_format = depth_target(mesh57_fmt_d24_unorm_s8); no_format.target0_format = 0; + no_format.colors[0].format = 0; if (!gap_has(no_format, "format=0")) return fail("target 0 format unknown"); auto no_samples = depth_target(mesh57_fmt_d24_unorm_s8); no_samples.color_samples = 0; + no_samples.colors[0].samples = 0; if (!gap_has(no_samples, "samples=0")) return fail("sample count"); char silent[192]; @@ -278,5 +328,78 @@ int main() const auto other = gap_line(true, depth_target(mesh57_fmt_d32_float), on_bounds.reason, silent, sizeof(silent)); if (other != 0) return fail("depth-state refusal logs no target gap"); + + const unsigned one[] = {28}; + const unsigned three[] = {28, 10, 2}; + const unsigned six[] = {28, 10, 2, 24, 41, 29}; + const auto one_on = x2w_startup::mesh57_derived_depth(true, disabled, listed_targets(1, one)); + if (!formats_are(one_on, one, 1) || one_on.dsv_format || one_on.set_stencil_ref) + return fail("one color target"); + auto three_depth = listed_targets(3, three); + three_depth.dsv_format = mesh57_fmt_d32_float; + three_depth.depth_bound = true; + const auto three_on = x2w_startup::mesh57_derived_depth(true, depth_only, three_depth); + if (!formats_are(three_on, three, 3) || three_on.dsv_format != mesh57_fmt_d32_float || three_on.set_stencil_ref) + return fail("three color targets"); + const auto six_on = x2w_startup::mesh57_derived_depth(true, disabled, listed_targets(6, six)); + if (!formats_are(six_on, six, 6) || six_on.dsv_format || six_on.set_stencil_ref) + return fail("six color targets"); + const auto off_three = x2w_startup::mesh57_derived_depth(false, disabled, listed_targets(3, three)); + if (!formats_are(off_three, three, 3) || off_three.dsv_format) + return fail("switch off accepts three color targets"); + + auto middle = listed_targets(3, three); + middle.colors[1].bound = false; + const auto null_slot = x2w_startup::mesh57_derived_depth(true, disabled, middle); + char gap_text[192]; + const auto gap_wrote = x2w_startup::mesh57_target_gap_line(true, middle, null_slot.reason, 0x11ull, gap_text, sizeof(gap_text)); + if (!reason_is(null_slot, x2w_startup::mesh57_color_gap_reason(), false) || !gap_wrote || !std::strstr(gap_text, "count=3")) + return fail("null slot in the color target list"); + auto leading = listed_targets(3, three); + leading.colors[0].bound = false; + leading.has_target0 = false; + leading.target0_format = 0; + const auto slot_order = x2w_startup::mesh57_derived_depth(true, disabled, leading); + if (!reason_is(slot_order, x2w_startup::mesh57_color_gap_reason(), false)) + return fail("color target slots are not contiguous from slot 0"); + auto unknown_slot = listed_targets(3, three); + unknown_slot.colors[2].format = 0; + const auto unknown_format = x2w_startup::mesh57_derived_depth(true, disabled, unknown_slot); + if (!reason_is(unknown_format, x2w_startup::mesh57_color_format_reason(), false) || unknown_slot.target0_format == 0) + return fail("later color target format unknown"); + const unsigned mixed_samples[] = {1u, 4u, 1u}; + auto mixed = listed_targets(3, three, mixed_samples); + mixed.dsv_format = mesh57_fmt_d32_float; + mixed.depth_bound = true; + mixed.depth_samples = 1; + const auto mixed_counts = x2w_startup::mesh57_derived_depth(true, depth_only, mixed); + if (!reason_is(mixed_counts, x2w_startup::mesh57_color_sample_mismatch_reason(), false)) + return fail("color target sample counts differ"); + const unsigned wide_samples[] = {4u, 4u, 4u}; + auto wide = listed_targets(3, three, wide_samples); + wide.dsv_format = mesh57_fmt_d32_float; + wide.depth_bound = true; + wide.depth_samples = 4; + const auto wide_color = x2w_startup::mesh57_derived_depth(true, depth_only, wide); + if (!reason_is(wide_color, "derived mesh needs one single-sample color target", false)) + return fail("several multisampled color targets refused"); + auto wide_depth = listed_targets(3, three); + wide_depth.dsv_format = mesh57_fmt_d32_float; + wide_depth.depth_bound = true; + wide_depth.depth_samples = 4; + const auto wide_depth_decision = x2w_startup::mesh57_derived_depth(true, depth_only, wide_depth); + if (!reason_is(wide_depth_decision, "derived mesh depth buffer is multisampled", false)) + return fail("several color targets against a multisampled depth buffer"); + auto too_many = listed_targets(1, one); + too_many.target_count = 9; + const auto over_limit = x2w_startup::mesh57_derived_depth(true, disabled, too_many); + if (!reason_is(over_limit, x2w_startup::mesh57_color_limit_reason(), false)) + return fail("more than 8 color targets"); + auto off_depth_many = listed_targets(3, three); + off_depth_many.dsv_format = mesh57_fmt_d32_float; + off_depth_many.depth_bound = true; + const auto off_many = x2w_startup::mesh57_derived_depth(false, disabled, off_depth_many); + if (!reason_is(off_many, "derived mesh needs one single-sample color target, a viewport and a scissor", false)) + return fail("switch off refuses depth with several color targets"); return 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 19/24] 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)) From ec5d89ba210e5307964f6bd8698984641b2d42ed Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Mon, 30 Nov 2026 20:24:17 +0000 Subject: [PATCH 20/24] startup: accept a depth-only derived mesh when depth or stencil is used Zero color targets stay refused unless a single-sample depth buffer is bound and the decoded state tests or writes depth or stencil. A pixel color export to an unbound target is refused. AI-assisted (Cursor) Co-authored-by: SimSalabimse --- CMakeLists.txt | 2 +- docs/experiments/native-fixed-mesh57.md | 6 +- src/startup_stubs/mesh57_derived_depth.h | 116 ++++++++++++++++++++++- src/startup_stubs/native_mesh57.inl | 11 ++- tests/mesh57_derived_depth_check.cpp | 73 +++++++++++++- 5 files changed, 198 insertions(+), 10 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index a4bb0d0e32..9d27a05eb5 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1962,7 +1962,7 @@ target_include_directories(mesh57_group_exchange_check PRIVATE src src/startup_s target_compile_features(mesh57_group_exchange_check PRIVATE cxx_std_17) add_test(NAME mesh57_group_exchange COMMAND mesh57_group_exchange_check) -add_executable(mesh57_derived_depth_check tests/mesh57_derived_depth_check.cpp) +add_executable(mesh57_derived_depth_check tests/mesh57_derived_depth_check.cpp src/gfx1013_isa.cpp) target_include_directories(mesh57_derived_depth_check PRIVATE src) target_compile_features(mesh57_derived_depth_check PRIVATE cxx_std_17) add_test(NAME mesh57_derived_depth COMMAND mesh57_derived_depth_check) diff --git a/docs/experiments/native-fixed-mesh57.md b/docs/experiments/native-fixed-mesh57.md index e4873f989b..06e38d1d16 100644 --- a/docs/experiments/native-fixed-mesh57.md +++ b/docs/experiments/native-fixed-mesh57.md @@ -188,13 +188,13 @@ Heap 1024 is the view-heap flag (`0x400`). Heap 3072 is that flag plus the sampl ## Derived depth and stencil -`X2W_MESH57_DERIVED_BOUNDS=1` also lifts the depth refusal in this derivation. With the switch off, an enabled depth or stencil test is still `derived mesh keeps depth and stencil disabled`, and a bound depth view is still refused. The description is the one `decode_depth_stencil` already produces from state block A. It is copied into the mesh pipeline's depth-stencil state. The pipeline depth format is the depth view already bound on that list by `OMSetRenderTargets`, the same bind a translated draw uses. The dispatch sets `OMSetStencilRef` from the decoded reference for that command and then restores the list's reference. One to eight single-sample color targets, a viewport and a scissor are still required. Each target needs a known format, the slots are contiguous from slot 0, and every target is single-sample with the same sample count as the depth buffer when one is bound. The mesh pipeline takes that count and those formats in slot order. Blend and write mask stay the per-target state decoded from the eight colour-blend registers. Dual-source blending stays render target 0 only. +`X2W_MESH57_DERIVED_BOUNDS=1` also lifts the depth refusal in this derivation. With the switch off, an enabled depth or stencil test is still `derived mesh keeps depth and stencil disabled`, and a bound depth view is still refused. The description is the one `decode_depth_stencil` already produces from state block A. It is copied into the mesh pipeline's depth-stencil state. The pipeline depth format is the depth view already bound on that list by `OMSetRenderTargets`, the same bind a translated draw uses. The dispatch sets `OMSetStencilRef` from the decoded reference for that command and then restores the list's reference. One to eight single-sample color targets, a viewport and a scissor are still required. Each target needs a known format, the slots are contiguous from slot 0, and every target is single-sample with the same sample count as the depth buffer when one is bound. The mesh pipeline takes that count and those formats in slot order. Zero color targets are accepted only when a depth buffer is bound and the decoded state tests or writes depth or stencil. The pipeline then has no render targets, every color format stays unknown, and the sample count is the depth buffer's, which has to be one sample. Blend and write mask stay the per-target state decoded from the eight colour-blend registers. Dual-source blending stays render target 0 only. -A form that cannot be copied exactly stays refused, and the reason names it. Depth bounds are not a desktop depth-stencil field. Back-face stencil masks or a reference that differ from the front are not one desktop reference and one pair of masks. A stencil op or compare with no desktop form stays refused. A depth or stencil test with no depth view, a multisampled depth buffer, color and depth sample counts that differ, color targets whose sample counts differ, a zero sample count, and a stencil test whose depth format has no stencil plane stay refused. A gap or a null slot, an unknown color format, and more than eight color targets stay refused. The format is the bound view's format. This path does not choose one. Those attachment refusals are not remembered: a later list can bind a depth view. A refusal that comes from the pipeline's own registers is remembered. +A form that cannot be copied exactly stays refused, and the reason names it. Depth bounds are not a desktop depth-stencil field. Back-face stencil masks or a reference that differ from the front are not one desktop reference and one pair of masks. A stencil op or compare with no desktop form stays refused. A depth or stencil test with no depth view, a multisampled depth buffer, color and depth sample counts that differ, color targets whose sample counts differ, a zero sample count, and a stencil test whose depth format has no stencil plane stay refused. A gap or a null slot, an unknown color format, and more than eight color targets stay refused. Zero color targets with no depth buffer stay refused. A bound depth buffer that does not test or write depth or stencil stays refused. A pixel color export, an `exp` target below 8 with a non-empty mask, whose target index is not bound stays refused. A depth, stencil, coverage, or null export is not a color target. The constant pixel translator is unchanged. The format is the bound view's format. This path does not choose one. Those attachment refusals are not remembered: a later list can bind a depth view. A refusal that comes from the pipeline's own registers is remembered. When the switch is on and this color-target check refuses, one `x2w-render mesh57-derive targets` line is logged per pipeline key, and at most eight keys are kept. The line names whether targets are bound, whether the viewport and scissor are set, the color-target count, whether target 0 is present, whether its format is known, and the color and depth sample counts. It has no pointer and no raw word. The census still receives the same refusal string. The switch off does not log the line. -`mesh57_derived_depth` checks the register-word mapping, the switch-off refusals, each of those reasons, one, three and six color targets, a gap or null slot, an unknown format, differing color sample counts, more than eight targets, the formats kept for the pipeline, and the target-gap line for a missing bind, viewport, scissor, count, target, format, or sample count. It does not need a device. +`mesh57_derived_depth` checks the register-word mapping, the switch-off refusals, each of those reasons, one, three and six color targets, a depth-only pass, zero targets with no depth buffer, a multisampled depth buffer and no color target, a pixel color export to a missing target, a gap or null slot, an unknown format, differing color sample counts, more than eight targets, the formats kept for the pipeline, and the target-gap line for a missing bind, viewport, scissor, count, target, format, or sample count. It does not need a device. ```powershell ctest --preset dev --no-tests=error -R 'mesh57_derived_depth|mesh57_record_bounds|mesh57_group_exchange|mesh57_derive_alloc' diff --git a/src/startup_stubs/mesh57_derived_depth.h b/src/startup_stubs/mesh57_derived_depth.h index debe1bf006..cf86f65d73 100644 --- a/src/startup_stubs/mesh57_derived_depth.h +++ b/src/startup_stubs/mesh57_derived_depth.h @@ -13,10 +13,14 @@ // stencil plane (D24_UNORM_S8_UINT, D32_FLOAT_S8X24_UINT, and the two typeless forms). #pragma once +#include "gfx1013_isa.h" + #include #include #include #include +#include +#include namespace x2w_startup { @@ -240,8 +244,24 @@ inline const char* mesh57_color_limit_reason() noexcept return "derived mesh has more than 8 color targets"; } -// Bound, viewport, scissor and a count of 0 stay on the original reason. One to eight -// slots must be contiguous from slot 0, each with a known format. +inline const char* mesh57_no_attachment_reason() noexcept +{ + return "derived mesh binds no color target and no depth buffer"; +} + +inline const char* mesh57_depth_unused_reason() noexcept +{ + return "derived mesh depth buffer does not test or write depth or stencil"; +} + +inline const char* mesh57_color_export_reason() noexcept +{ + return "derived mesh pixel exports color to a target that does not exist"; +} + +// Bound, viewport or scissor still use the original reason. A count of 0 is a depth-only +// pass and is decided before this. One to eight slots must be contiguous from slot 0, +// each with a known format. inline const char* mesh57_color_list_reason(const Mesh57DepthTargets& targets) noexcept { if (!targets.targets_bound || !targets.viewport_set || !targets.scissor_set || targets.target_count == 0) @@ -281,7 +301,62 @@ inline bool mesh57_target_attachment_reason(const char* reason) noexcept std::strcmp(reason, "derived mesh depth buffer sample count is unknown") == 0 || std::strcmp(reason, "derived mesh depth buffer is multisampled") == 0 || std::strcmp(reason, "derived mesh color and depth sample counts differ") == 0 || - std::strcmp(reason, "derived mesh needs one single-sample color target") == 0; + std::strcmp(reason, "derived mesh needs one single-sample color target") == 0 || + std::strcmp(reason, mesh57_no_attachment_reason()) == 0 || + std::strcmp(reason, mesh57_depth_unused_reason()) == 0 || + std::strcmp(reason, mesh57_color_export_reason()) == 0; +} + +// Color exports are EXP targets 0..7. The graphics translator records those as pixel +// writes and lowers them to SV_Target. Target 8 is depth, stencil or coverage. Target 9 +// is the null export. A target index at or past the bound count has no render target. +// A program this decoder cannot walk is left to the translator. +inline const char* mesh57_pixel_color_export_reason(std::string_view code, unsigned render_target_count) noexcept +{ + if (code.empty() || (code.size() & 3u) != 0) + return nullptr; + try { + for (unsigned pc = 0; pc < code.size();) { + const auto inst = x2w::gfx1013::instruction(code, pc); + if (inst.size == 0 || pc + inst.size > code.size()) + return nullptr; + if (inst.form == x2w::gfx1013::Form::exp) { + std::uint32_t raw = 0; + std::memcpy(&raw, code.data() + pc, sizeof(raw)); + const unsigned target = (raw >> 4) & 63u; + const unsigned mask = raw & 15u; + if (target < 8u && mask != 0u && target >= render_target_count) + return mesh57_color_export_reason(); + } + pc += inst.size; + } + } catch (const std::exception&) { + return nullptr; + } + return nullptr; +} + +// Zero color targets. The caller has already required a bound list, a viewport and a +// scissor. Null means the depth buffer may be used: it is bound, single-sample, and the +// decoded state tests or writes depth or stencil. +inline const char* mesh57_depth_only_attachment_reason(const Mesh57DepthFacts& depth, + const Mesh57DepthTargets& targets) noexcept +{ + if (targets.dsv_format == 0 && !targets.depth_bound) + return mesh57_no_attachment_reason(); + if (targets.dsv_format != 0 && !targets.depth_bound) + return "derived mesh depth buffer sample count is unknown"; + if (targets.depth_samples == 0) + return "derived mesh sample count is unknown"; + if (targets.depth_samples != 1 || targets.depth_quality != 0) + return "derived mesh depth buffer is multisampled"; + if (!depth.depth_enable && depth.depth_write == 0 && !depth.stencil_enable) + return mesh57_depth_unused_reason(); + if (targets.dsv_format == 0) + return "derived mesh depth or stencil test needs a bound depth buffer"; + if (depth.stencil_enable && !mesh57_format_has_stencil(targets.dsv_format)) + return "derived mesh stencil test needs a stencil plane in the depth format"; + return nullptr; } // One line naming which attachment condition failed. bounds_switch is the same opt-in @@ -317,16 +392,25 @@ inline std::size_t mesh57_target_gap_line(bool bounds_switch, const Mesh57DepthT // bounds_switch is X2W_MESH57_DERIVED_BOUNDS=1. Off, an enabled test is still // "derived mesh keeps depth and stencil disabled", and a bound depth view is still refused. // On, the decoded description is kept. A form this path cannot copy exactly is refused. +// pixel is the pixel stage. Empty skips the export check. A color export whose target +// index is not bound is refused. The translator is not changed. inline Mesh57DerivedDepth mesh57_derived_depth(bool bounds_switch, const Mesh57DepthFacts& depth, - const Mesh57DepthTargets& targets) noexcept + const Mesh57DepthTargets& targets, + std::string_view pixel = {}) noexcept { Mesh57DerivedDepth out; + const bool listed = targets.targets_bound && targets.viewport_set && targets.scissor_set; if (!bounds_switch) { if (depth.depth_enable || depth.stencil_enable) { out.reason = "derived mesh keeps depth and stencil disabled"; out.remember = true; return out; } + if (targets.target_count == 0 && listed) { + out.reason = targets.dsv_format == 0 && !targets.depth_bound ? mesh57_no_attachment_reason() + : mesh57_color_target_reason(); + return out; + } if (const char* color = mesh57_color_list_reason(targets)) { out.reason = color; return out; @@ -335,6 +419,10 @@ inline Mesh57DerivedDepth mesh57_derived_depth(bool bounds_switch, const Mesh57D out.reason = mesh57_color_target_reason(); return out; } + if (const char* exported = mesh57_pixel_color_export_reason(pixel, targets.target_count)) { + out.reason = exported; + return out; + } mesh57_publish_rtv_formats(out, targets); return out; } @@ -363,6 +451,22 @@ inline Mesh57DerivedDepth mesh57_derived_depth(bool bounds_switch, const Mesh57D out.remember = true; return out; } + if (targets.target_count == 0 && listed) { + if (const char* why = mesh57_depth_only_attachment_reason(depth, targets)) { + out.reason = why; + return out; + } + if (const char* exported = mesh57_pixel_color_export_reason(pixel, 0)) { + out.reason = exported; + return out; + } + out.dsv_format = targets.dsv_format; + if (depth.stencil_enable) { + out.set_stencil_ref = true; + out.stencil_ref = depth.stencil_ref & 0xffu; + } + return out; + } if (const char* color = mesh57_color_list_reason(targets)) { out.reason = color; return out; @@ -411,6 +515,10 @@ inline Mesh57DerivedDepth mesh57_derived_depth(bool bounds_switch, const Mesh57D out.reason = "derived mesh stencil test needs a stencil plane in the depth format"; return out; } + if (const char* exported = mesh57_pixel_color_export_reason(pixel, targets.target_count)) { + out.reason = exported; + return out; + } out.dsv_format = targets.dsv_format; if (depth.stencil_enable) { out.set_stencil_ref = true; diff --git a/src/startup_stubs/native_mesh57.inl b/src/startup_stubs/native_mesh57.inl index 309c81892f..db9db11612 100644 --- a/src/startup_stubs/native_mesh57.inl +++ b/src/startup_stubs/native_mesh57.inl @@ -972,7 +972,10 @@ const char* derive_slot57_mesh(Wrapper* pipeline, Pass& pass, const D3D12_BLEND_ depth_targets.depth_quality = depth_samples.Quality; depth_targets.depth_bound = true; } - const auto depth_decision = x2w_startup::mesh57_derived_depth(derived_bounds, depth_facts, depth_targets); + std::string_view pixel_code; + if (info->fixed_ps && !info->fixed_ps->empty()) + pixel_code = std::string_view(reinterpret_cast(info->fixed_ps->data()), info->fixed_ps->size()); + const auto depth_decision = x2w_startup::mesh57_derived_depth(derived_bounds, depth_facts, depth_targets, pixel_code); if (depth_decision.reason) { if (derived_bounds) { char line[192]{}; @@ -1087,6 +1090,12 @@ const char* derive_slot57_mesh(Wrapper* pipeline, Pass& pass, const D3D12_BLEND_ DXGI_SAMPLE_DESC samples; samples.Count = 1; samples.Quality = 0; + // A depth-only pass has no color sample count. The decision already required the + // depth buffer to be single-sample, and the pipeline takes that count. + if (depth_decision.render_target_count == 0) { + samples.Count = depth_targets.depth_samples; + samples.Quality = depth_targets.depth_quality; + } stream.sample_desc.value = samples; stream.topology.value = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE; D3D12_PIPELINE_STATE_STREAM_DESC desc; diff --git a/tests/mesh57_derived_depth_check.cpp b/tests/mesh57_derived_depth_check.cpp index d22b3e14da..f06d82de4f 100644 --- a/tests/mesh57_derived_depth_check.cpp +++ b/tests/mesh57_derived_depth_check.cpp @@ -5,6 +5,7 @@ #include #include #include +#include namespace { int fail(const char* name) @@ -89,6 +90,25 @@ x2w_startup::Mesh57DepthTargets listed_targets(unsigned count, const unsigned* f return targets; } +x2w_startup::Mesh57DepthTargets no_color(unsigned format = 0, bool depth_bound = false, unsigned depth_samples = 1) +{ + x2w_startup::Mesh57DepthTargets targets; + targets.targets_bound = true; + targets.viewport_set = true; + targets.scissor_set = true; + targets.targets_single_sample = depth_samples == 1; + targets.target_count = 0; + targets.dsv_format = format; + targets.depth_bound = depth_bound; + targets.depth_samples = depth_samples; + return targets; +} + +std::string_view pixel_words(const std::uint32_t* words, unsigned count) +{ + return std::string_view(reinterpret_cast(words), static_cast(count) * sizeof(std::uint32_t)); +} + bool formats_are(const x2w_startup::Mesh57DerivedDepth& decision, const unsigned* formats, unsigned count) { if (decision.reason || decision.render_target_count != count) @@ -298,8 +318,12 @@ int main() no_scissor.scissor_set = false; if (!gap_has(no_scissor, "scissor=0")) return fail("scissor not set"); - auto no_count = depth_target(mesh57_fmt_d24_unorm_s8); + auto no_count = color_target(); no_count.target_count = 0; + no_count.has_target0 = false; + no_count.target0_format = 0; + no_count.colors[0].bound = false; + no_count.colors[0].format = 0; if (!gap_has(no_count, "count=0")) return fail("color target count"); auto no_rt = depth_target(mesh57_fmt_d24_unorm_s8); @@ -401,5 +425,52 @@ int main() const auto off_many = x2w_startup::mesh57_derived_depth(false, disabled, off_depth_many); if (!reason_is(off_many, "derived mesh needs one single-sample color target, a viewport and a scissor", false)) return fail("switch off refuses depth with several color targets"); + + const auto depth_pass = x2w_startup::mesh57_derived_depth(true, depth_only, no_color(mesh57_fmt_d32_float, true)); + if (depth_pass.reason || !formats_are(depth_pass, nullptr, 0) || depth_pass.dsv_format != mesh57_fmt_d32_float || + depth_pass.set_stencil_ref) + return fail("depth-only accepted"); + auto tested = x2w_startup::mesh57_depth_facts(depth_control(false, true, false, false, 6, false, 7, 7), 0, 0, 0); + const auto test_pass = x2w_startup::mesh57_derived_depth(true, tested, no_color(mesh57_fmt_d32_float, true)); + if (test_pass.reason || test_pass.render_target_count != 0 || test_pass.dsv_format != mesh57_fmt_d32_float) + return fail("depth test without a write accepted"); + auto stencil_only = x2w_startup::mesh57_depth_facts(depth_control(true, false, false, false, 7, false, 7, 7), keep, masks, + masks); + const auto stencil_pass = + x2w_startup::mesh57_derived_depth(true, stencil_only, no_color(mesh57_fmt_d24_unorm_s8, true)); + if (stencil_pass.reason || stencil_pass.render_target_count != 0 || stencil_pass.dsv_format != mesh57_fmt_d24_unorm_s8 || + !stencil_pass.set_stencil_ref || stencil_pass.stencil_ref != 0x5c || stencil_pass.rtv_formats[0] != 0) + return fail("stencil-only accepted"); + const auto unused = x2w_startup::mesh57_derived_depth(true, disabled, no_color(mesh57_fmt_d32_float, true)); + if (!reason_is(unused, x2w_startup::mesh57_depth_unused_reason(), false)) + return fail("bound depth that does not test or write refused"); + + const auto none = x2w_startup::mesh57_derived_depth(true, depth_only, no_color()); + if (!reason_is(none, x2w_startup::mesh57_no_attachment_reason(), false)) + return fail("zero targets with no depth refused"); + const auto none_off = x2w_startup::mesh57_derived_depth(false, disabled, no_color()); + if (!reason_is(none_off, x2w_startup::mesh57_no_attachment_reason(), false)) + return fail("switch off refuses zero targets with no depth"); + const auto off_depth_only = x2w_startup::mesh57_derived_depth(false, disabled, no_color(mesh57_fmt_d32_float, true)); + if (!reason_is(off_depth_only, "derived mesh needs one single-sample color target, a viewport and a scissor", false)) + return fail("switch off refuses a depth-only pass"); + + const auto msaa_depth = x2w_startup::mesh57_derived_depth(true, depth_only, no_color(mesh57_fmt_d32_float, true, 4)); + if (!reason_is(msaa_depth, "derived mesh depth buffer is multisampled", false)) + return fail("zero targets with a multisampled depth buffer refused"); + + const std::uint32_t mrt0[] = {0xf800180fu, 0u, 0xbf810000u}; + const auto exported = x2w_startup::mesh57_derived_depth(true, depth_only, no_color(mesh57_fmt_d32_float, true), + pixel_words(mrt0, 3)); + if (!reason_is(exported, x2w_startup::mesh57_color_export_reason(), false)) + return fail("pixel color export with no color target refused"); + const auto export_kept = x2w_startup::mesh57_derived_depth(true, disabled, listed_targets(1, one), pixel_words(mrt0, 3)); + if (!formats_are(export_kept, one, 1)) + return fail("pixel color export to a bound target accepted"); + const std::uint32_t depth_export[] = {0xf8001881u, 0u, 0xbf810000u}; + const auto depth_pixel = x2w_startup::mesh57_derived_depth(true, depth_only, no_color(mesh57_fmt_d32_float, true), + pixel_words(depth_export, 3)); + if (depth_pixel.reason || depth_pixel.render_target_count != 0 || depth_pixel.dsv_format != mesh57_fmt_d32_float) + return fail("depth export is not a color target"); return 0; } From 6aeeff0da9c386440642b6d4236e6d45f3843500 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Mon, 30 Nov 2026 21:24:47 +0000 Subject: [PATCH 21/24] startup: add an opt-in unproven stride for the derived record group X2W_MESH57_EXPERIMENT_STRIDE, off by default, may set the record layout stride to a positive integer after the reader has stored 0. Unset and invalid values keep stride 0. AI-assisted (Cursor) Co-authored-by: SimSalabimse --- CMakeLists.txt | 5 + docs/experiments/native-fixed-mesh57.md | 4 +- src/startup_stubs/d3d12_xs_device.cpp | 1 + src/startup_stubs/mesh57_experiment_stride.h | 94 ++++++++++++++ src/startup_stubs/native_mesh57.inl | 19 +++ tests/mesh57_experiment_stride_check.cpp | 124 +++++++++++++++++++ 6 files changed, 246 insertions(+), 1 deletion(-) create mode 100644 src/startup_stubs/mesh57_experiment_stride.h create mode 100644 tests/mesh57_experiment_stride_check.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 9d27a05eb5..a91ba31944 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1962,6 +1962,11 @@ target_include_directories(mesh57_group_exchange_check PRIVATE src src/startup_s target_compile_features(mesh57_group_exchange_check PRIVATE cxx_std_17) add_test(NAME mesh57_group_exchange COMMAND mesh57_group_exchange_check) +add_executable(mesh57_experiment_stride_check tests/mesh57_experiment_stride_check.cpp) +target_include_directories(mesh57_experiment_stride_check PRIVATE src) +target_compile_features(mesh57_experiment_stride_check PRIVATE cxx_std_17) +add_test(NAME mesh57_experiment_stride COMMAND mesh57_experiment_stride_check) + add_executable(mesh57_derived_depth_check tests/mesh57_derived_depth_check.cpp src/gfx1013_isa.cpp) target_include_directories(mesh57_derived_depth_check PRIVATE src) target_compile_features(mesh57_derived_depth_check PRIVATE cxx_std_17) diff --git a/docs/experiments/native-fixed-mesh57.md b/docs/experiments/native-fixed-mesh57.md index 06e38d1d16..54f9b9dd94 100644 --- a/docs/experiments/native-fixed-mesh57.md +++ b/docs/experiments/native-fixed-mesh57.md @@ -172,6 +172,8 @@ That lowerer still accepts only one group-index exchange. It opens with `s_mov_b The stride is still an open input. On the path this repository already translates, `group_stride` comes from a reviewed `.mesh57-state` profile or from a `mesh1` layout line. The lowerer sets the entry value of v5 to `groupId.x * group_stride` and the exchange keeps that value shifted right by 7. The immediate reader stores 0 as well: its programs are one wave of 64 and do not broadcast a group id. The record reader stores 0, and the derive check refuses a non-zero value from that reader. `DispatchMesh` passes group counts, not the word the hardware places in v5. The root constants this derivation binds are not that word. The offline translator records the same gap: the broadcast is entry v5 shifted right by 7 from wave 0, lane 0, and what v5 holds at entry is not verified. The thread count, a PSV0 thread count, and the register block do not define it. The missing model is that hardware entry value. +`X2W_MESH57_EXPERIMENT_STRIDE` is an unverified experiment, off by default. Unset, the record layout stride stays 0 and the exchange stays refused. Set to a positive integer `N`, and only then, the derived record layout's `group_stride` becomes `N` after that reader has stored 0 and the wave64 check has passed. The intended test value is 128. The lowerer models the entry as `groupId.x * group_stride` and the matched exchange shifts that product right by 7, so 128 is the value for which the guest receives `groupId`. For this record pair `max(threads, vertices, primitives)` is 256, and 256 doubles every group index. Zero, a negative value, and text that is not a positive integer are refused and the stride stays 0. Each time the experiment supplies a stride, stderr gets one line containing `experimental stride, unproven` and that stride. Nothing in this repository shows that this value matches the hardware entry. It needs a reference capture or maintainer confirmation. The reviewed `.mesh57-state` profile path is not read, and `mesh57_read_layout` is unchanged. + When `record_output_counts` is set and that opener is refused, the reason keeps `mesh group-index exchange shape or entry state is not covered` and names the first failed check. The checks, in order, are: the sequence is shorter than the accepted form (60 bytes, or 64 when exec is saved), the wave-bit mask is not an AND of s3 with a literal, one of the 13 tail steps does not match, a scalar branch is open, an EXEC skip is open, EXEC is not the full wave, the stage is wave32, the group stride is zero, s3 was already written, v5 was already written, the mask destination is not an SGPR, and the saved EXEC pair is not a free even SGPR. With the flag clear, the reason stays the sentence with no check name. One `x2w-render mesh57-derive exchange` line is logged per pipeline key, at most eight keys. The line is the key and the check. It has no pointer and no instruction word. `SetMeshOutputCounts` receives the runtime vertex and primitive registers, each limited to the derived maximum, and both become 0 when either is 0. Outputs past the runtime count are not written. The static bound sizes the output arrays. It is not substituted when the registers are unproven. @@ -181,7 +183,7 @@ The first time a distinct pair is derived this way, stderr gets one `x2w-render `mesh57_record_bounds` checks the assembled pattern: the 7-bit limit, the 6-bit limit, an unknown `k`, a `k` other than 1, a mask whose product exceeds 256, the immediate triangle (3 vertices, 1 primitive, 64 threads), and that the immediate reader still refuses the record program. It also checks the `v_bfe_u32` plus proven `v_mul_lo_u32` chain at the same 256 limit, and the refusals for an unproven scalar, a mismatched base, a shift other than 29, and a multiplied mask whose product exceeds 256. It checks a raw dword load that hides an older ALU write of the same VGPR, an LDS load that does not, a field that reads the second dword of a dwordx2 load, two loads of the same VGPR, a `d16` xyzw load, and the TFE status VGPR. `mesh57_group_exchange` checks each failed check of the group-index exchange on the assembled sequence, including a zero group stride, and the log line. Neither needs a device. The Windows `native_direct_mesh` fixture still expects the exchange refusal with no check name, because that fixture does not set `record_output_counts`. ```powershell -ctest --preset dev --no-tests=error -R 'mesh57_record_bounds|mesh57_group_exchange|mesh57_derive_alloc' +ctest --preset dev --no-tests=error -R 'mesh57_record_bounds|mesh57_group_exchange|mesh57_experiment_stride|mesh57_derive_alloc' ``` 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/src/startup_stubs/d3d12_xs_device.cpp b/src/startup_stubs/d3d12_xs_device.cpp index c5b8b9ee87..5c03438e5d 100644 --- a/src/startup_stubs/d3d12_xs_device.cpp +++ b/src/startup_stubs/d3d12_xs_device.cpp @@ -37,6 +37,7 @@ // File scope. native_mesh57.inl is included inside the anonymous namespace below, // and a header included from there would nest namespace x2w_startup inside it. #include "startup_stubs/mesh57_group_exchange.h" +#include "startup_stubs/mesh57_experiment_stride.h" #include "startup_stubs/d16_image_format.h" #include "startup_stubs/formatted_buffer.h" #include "startup_stubs/view_content_token.h" diff --git a/src/startup_stubs/mesh57_experiment_stride.h b/src/startup_stubs/mesh57_experiment_stride.h new file mode 100644 index 0000000000..2e185da69c --- /dev/null +++ b/src/startup_stubs/mesh57_experiment_stride.h @@ -0,0 +1,94 @@ +// Opt-in, off by default. X2W_MESH57_EXPERIMENT_STRIDE may replace the record +// layout's group stride after the record reader has stored 0. Nothing here is a +// measurement of the hardware entry value. 128 is the value for which +// (groupId * stride) >> 7 is groupId. 256, from max(threads, vertices, primitives) +// on the 256 record pair, doubles that index. A reviewed profile is not read. +#pragma once + +#include +#include +#include +#include +#include + +namespace x2w_startup { + +struct Mesh57ExperimentStride { + unsigned stride = 0; + bool refused = false; +}; + +// text null is unset: stride 0, not refused. Any other text that is not a +// positive integer is refused and the stride stays 0. The whole string has to +// be digits, and the value has to fit in 32 bits. +inline Mesh57ExperimentStride mesh57_experiment_stride(const char* text) noexcept +{ + Mesh57ExperimentStride out; + if (!text) + return out; + if (text[0] == 0) { + out.refused = true; + return out; + } + unsigned long long value = 0; + for (const char* p = text; *p; ++p) { + if (*p < '0' || *p > '9') { + out.refused = true; + return out; + } + value = value * 10ull + static_cast(*p - '0'); + if (value > 0xffffffffull) { + out.refused = true; + return out; + } + } + if (value == 0) { + out.refused = true; + return out; + } + out.stride = static_cast(value); + return out; +} + +inline Mesh57ExperimentStride mesh57_experiment_stride_env() noexcept +{ + return mesh57_experiment_stride(std::getenv("X2W_MESH57_EXPERIMENT_STRIDE")); +} + +// reader_stride is the value the record reader stored. A non-zero reader stride +// is left alone. A positive experiment replaces only a zero. +inline unsigned mesh57_apply_experiment_stride(unsigned reader_stride, unsigned experiment) noexcept +{ + if (reader_stride != 0 || experiment == 0) + return reader_stride; + return experiment; +} + +// Same arithmetic as the direct mesh lowerer: entry is groupId.x * group_stride, +// and the matched exchange shifts that value right by 7. +inline unsigned mesh57_experiment_group_index(unsigned group_id, unsigned stride) noexcept +{ + return static_cast((static_cast(group_id) * stride) >> 7); +} + +// One line each time a positive experiment stride is used. The words name it as unproven. +inline std::size_t mesh57_experiment_stride_line(unsigned stride, char* out, std::size_t cap) noexcept +{ + if (!out || cap == 0) + return 0; + out[0] = 0; + if (stride == 0) + return 0; + const int n = std::snprintf(out, cap, "x2w-render mesh57-derive experimental stride, unproven stride=%u", stride); + 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 db9db11612..87fcb2f8c8 100644 --- a/src/startup_stubs/native_mesh57.inl +++ b/src/startup_stubs/native_mesh57.inl @@ -1018,6 +1018,25 @@ const char* derive_slot57_mesh(Wrapper* pipeline, Pass& pass, const D3D12_BLEND_ if (layout.wave_size != 64 || layout.topology != 2 || layout.group_stride != 0 || !layout.threads || (layout.threads % 64u) != 0 || layout.threads > 256) return remember("derived mesh record group is not wave64"); + // Opt-in and unproven. The reader still stored 0. A positive integer replaces + // only that zero. Unset, zero, negative, and other text leave the stride at 0. + char stride_text[16]{}; + const DWORD stride_error = GetLastError(); + const DWORD stride_length = GetEnvironmentVariableA("X2W_MESH57_EXPERIMENT_STRIDE", stride_text, + sizeof(stride_text)); + SetLastError(stride_error); + const char* stride_value = nullptr; + if (stride_length > 0 && stride_length < sizeof(stride_text)) + stride_value = stride_text; + else if (stride_length >= sizeof(stride_text)) + stride_value = ""; + const auto experiment = x2w_startup::mesh57_experiment_stride(stride_value); + layout.group_stride = x2w_startup::mesh57_apply_experiment_stride(layout.group_stride, experiment.stride); + if (layout.group_stride != 0) { + char line[160]{}; + if (x2w_startup::mesh57_experiment_stride_line(layout.group_stride, line, sizeof(line))) + log("%s", line); + } } else { layout = *read.layout; if (layout.threads != 64 || layout.wave_size != 64 || layout.topology != 2 || layout.group_stride != 0) diff --git a/tests/mesh57_experiment_stride_check.cpp b/tests/mesh57_experiment_stride_check.cpp new file mode 100644 index 0000000000..794003534d --- /dev/null +++ b/tests/mesh57_experiment_stride_check.cpp @@ -0,0 +1,124 @@ +// Host check for the opt-in record stride. The lowerer is not run here. +// The exchange words are the accepted sequence, and the matcher is unchanged. +#include "startup_stubs/mesh57_experiment_stride.h" +#include "startup_stubs/mesh57_group_exchange.h" + +#include +#include +#include +#include +#include +#include + +namespace { +int fail(const char* name) +{ + std::fprintf(stderr, "mesh57 experiment stride: %s\n", name); + return 1; +} + +bool set_stride(const char* value) +{ +#if defined(_WIN32) + if (!value) + return _putenv_s("X2W_MESH57_EXPERIMENT_STRIDE", "") == 0; + return _putenv_s("X2W_MESH57_EXPERIMENT_STRIDE", value) == 0; +#else + if (!value || value[0] == 0) + return unsetenv("X2W_MESH57_EXPERIMENT_STRIDE") == 0; + return setenv("X2W_MESH57_EXPERIMENT_STRIDE", value, 1) == 0; +#endif +} + +std::string code_from(const std::vector& words) +{ + std::string out(words.size() * sizeof(std::uint32_t), '\0'); + if (!words.empty()) + std::memcpy(out.data(), words.data(), out.size()); + return out; +} + +const std::vector saved_exchange = { + 0xbefe0481u, 0xbe88047eu, 0x870aff03u, 0x0f000000u, 0xbf850007u, 0x2c0a0a87u, + 0x7e000280u, 0xd8340008u, 0x500u, 0xbfa3ffe3u, 0xbf8a0000u, 0xbf820004u, + 0xbf8a0000u, 0x7e000280u, 0xd8d80008u, 0x05000000u}; + +bool parsed(const char* text, unsigned stride, bool refused) +{ + const auto got = x2w_startup::mesh57_experiment_stride(text); + return got.stride == stride && got.refused == refused; +} + +const char* exchange_for(unsigned experiment) +{ + x2w_startup::Mesh57GroupExchangeState state; + state.full_exec = true; + state.group_stride = x2w_startup::mesh57_apply_experiment_stride(0, experiment) != 0; + return x2w_startup::mesh57_group_exchange_gap(code_from(saved_exchange), 0, state); +} +} // namespace + +int main() +{ + if (!set_stride(nullptr)) + return fail("clear stride env"); + const auto unset = x2w_startup::mesh57_experiment_stride_env(); + if (unset.stride != 0 || unset.refused || x2w_startup::mesh57_apply_experiment_stride(0, unset.stride) != 0) + return fail("env unset gives stride 0"); + const char* unset_gap = exchange_for(unset.stride); + if (!unset_gap || std::strcmp(unset_gap, "group stride is zero") != 0) + return fail("env unset keeps the exchange refusal"); + + if (!parsed(nullptr, 0, false) || !parsed("128", 128, false)) + return fail("positive integer"); + if (!parsed("0", 0, true) || !parsed("-1", 0, true) || !parsed("text", 0, true) || !parsed("128abc", 0, true) || + !parsed("", 0, true)) + return fail("invalid stride text"); + + if (!set_stride("128")) + return fail("set stride 128"); + const auto on = x2w_startup::mesh57_experiment_stride_env(); + const unsigned applied = x2w_startup::mesh57_apply_experiment_stride(0, on.stride); + if (on.refused || applied != 128) + return fail("env 128 gives stride 128"); + const char* accepted = exchange_for(applied); + if (!accepted || std::strcmp(accepted, "the exchange matched the accepted checks") != 0) + return fail("env 128 accepts the exchange"); + if (x2w_startup::mesh57_experiment_group_index(1, applied) != 1) + return fail("group 1 maps to index 1"); + if (x2w_startup::mesh57_experiment_group_index(1, 256) != 2) + return fail("stride 256 doubles the group index"); + char line[160]; + if (!x2w_startup::mesh57_experiment_stride_line(applied, line, sizeof(line)) || + std::strstr(line, "experimental stride, unproven") == nullptr || std::strstr(line, "128") == nullptr) + return fail("unproven stride line"); + if (x2w_startup::mesh57_experiment_stride_line(0, line, sizeof(line)) != 0) + return fail("zero stride logs nothing"); + if (x2w_startup::mesh57_apply_experiment_stride(7, 128) != 7) + return fail("reader stride is not replaced"); + + if (!set_stride("0")) + return fail("set stride 0"); + const auto zero = x2w_startup::mesh57_experiment_stride_env(); + if (!zero.refused || zero.stride != 0 || x2w_startup::mesh57_apply_experiment_stride(0, zero.stride) != 0) + return fail("env 0 falls back to 0"); + const char* zero_gap = exchange_for(zero.stride); + if (!zero_gap || std::strcmp(zero_gap, "group stride is zero") != 0) + return fail("env 0 keeps the exchange refusal"); + + if (!set_stride("-4")) + return fail("set negative stride"); + const auto negative = x2w_startup::mesh57_experiment_stride_env(); + if (!negative.refused || negative.stride != 0) + return fail("env negative falls back to 0"); + + if (!set_stride("text")) + return fail("set text stride"); + const auto text = x2w_startup::mesh57_experiment_stride_env(); + if (!text.refused || text.stride != 0 || std::strcmp(exchange_for(text.stride), "group stride is zero") != 0) + return fail("env text falls back to 0"); + + if (!set_stride(nullptr)) + return fail("restore stride env"); + return 0; +} From 291adf07b3d40edf08d325bcf4397d78a76eb2e6 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Mon, 30 Nov 2026 21:57:05 +0000 Subject: [PATCH 22/24] mesh: lower v_sub_nc_u32 and sibling integer ALU ops The native mesh path now accepts the no-carry subtract forms, the carry-out subtract forms, and v_and_or_b32 by calling the existing ALU. AI-assisted (Cursor) Co-authored-by: SimSalabimse --- CMakeLists.txt | 5 + src/gfx1013_direct_mesh.inl | 5 +- tests/mesh57_integer_alu_check.cpp | 349 +++++++++++++++++++++++++++++ 3 files changed, 358 insertions(+), 1 deletion(-) create mode 100644 tests/mesh57_integer_alu_check.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index a91ba31944..6c28792429 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1972,6 +1972,11 @@ target_include_directories(mesh57_derived_depth_check PRIVATE src) target_compile_features(mesh57_derived_depth_check PRIVATE cxx_std_17) add_test(NAME mesh57_derived_depth COMMAND mesh57_derived_depth_check) +add_executable(mesh57_integer_alu_check tests/mesh57_integer_alu_check.cpp src/gfx1013_isa.cpp) +target_include_directories(mesh57_integer_alu_check PRIVATE src) +target_compile_features(mesh57_integer_alu_check PRIVATE cxx_std_17) +add_test(NAME mesh57_integer_alu COMMAND mesh57_integer_alu_check "${CMAKE_SOURCE_DIR}") + add_executable(mesh57_span_dump_check tests/mesh57_span_dump_check.cpp) target_include_directories(mesh57_span_dump_check PRIVATE src) target_compile_features(mesh57_span_dump_check PRIVATE cxx_std_17) diff --git a/src/gfx1013_direct_mesh.inl b/src/gfx1013_direct_mesh.inl index fa2adb6b76..45f588d240 100644 --- a/src/gfx1013_direct_mesh.inl +++ b/src/gfx1013_direct_mesh.inl @@ -1221,7 +1221,10 @@ NativeComputeShader lower_mesh(const string &code, const MeshStageLayout &layout i.name=="v_subrev_f32" || i.name=="v_fmac_f32" || i.name=="v_fmaak_f32" || i.name=="v_rsq_f32" || i.name=="v_rcp_f32" || i.name=="v_sin_f32" || i.name=="v_cos_f32" || i.name.substr(0,15)=="v_cvt_f32_ubyte" || i.name=="v_min_u32" || i.name=="v_max_f32" || - i.name=="v_mad_u32_u24" || i.name=="v_add3_u32" || i.name=="v_bfe_u32" || i.name=="v_mov_b32" || i.name=="v_add_nc_u32" || i.name=="v_lshlrev_b32" || + i.name=="v_mad_u32_u24" || i.name=="v_add3_u32" || i.name=="v_bfe_u32" || i.name=="v_mov_b32" || + i.name=="v_add_nc_u32" || i.name=="v_sub_nc_u32" || i.name=="v_subrev_nc_u32" || + i.name=="v_sub_co_u32" || i.name=="v_subrev_co_u32" || i.name=="v_and_or_b32" || + i.name=="v_lshlrev_b32" || i.name=="v_lshrrev_b32" || i.name=="v_or_b32" || i.name=="v_and_b32" || i.name=="v_xor_b32" || i.name=="v_lshl_add_u32" || i.name=="v_cvt_f32_u32" || i.name=="v_cvt_f32_i32" || i.name=="v_mul_f32" || i.name=="v_add_f32" || i.name=="v_fma_f32")) { diff --git a/tests/mesh57_integer_alu_check.cpp b/tests/mesh57_integer_alu_check.cpp new file mode 100644 index 0000000000..13f06a6dd6 --- /dev/null +++ b/tests/mesh57_integer_alu_check.cpp @@ -0,0 +1,349 @@ +// Synthetic gfx1013 words for the mesh integer ops the native mesh path now +// accepts. The mesh translator calls the existing ALU: a wrapping sub, the +// unsigned clamp select, (a & b) | c, or a sub plus a borrow bit. These checks +// decode the words and evaluate that result, including 0 - 1 == 0xFFFFFFFF. +#include "gfx1013_isa.h" + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +enum class Kind { sub, subrev, sub_clamp, subrev_clamp, and_or, sub_co, subrev_co }; + +struct Lowered { + std::uint32_t bits = 0; + bool borrow = false; +}; + +int g_failures = 0; + +void fail(const char* label, const std::string& detail) +{ + std::cerr << label << ": " << detail << '\n'; + ++g_failures; +} + +constexpr std::uint32_t vop2(std::uint32_t op, std::uint32_t dst, std::uint32_t src0, std::uint32_t vsrc1) +{ + return (op << 25) | (dst << 17) | (vsrc1 << 9) | (src0 & 511u); +} + +constexpr std::uint32_t vop3_word0(std::uint32_t op, std::uint32_t dst, bool clamp, std::uint32_t sdst = 0) +{ + return 0xd4000000u | (op << 16) | (clamp ? 0x8000u : 0u) | ((sdst & 127u) << 8) | (dst & 255u); +} + +constexpr std::uint32_t vop3_word1(std::uint32_t src0, std::uint32_t src1, std::uint32_t src2 = 0) +{ + return (src0 & 511u) | ((src1 & 511u) << 9) | ((src2 & 511u) << 18); +} + +constexpr std::uint32_t sdwa_ext(std::uint32_t src0, std::uint32_t dst_sel, std::uint32_t src0_sel, std::uint32_t src1_sel) +{ + return (src0 & 255u) | (dst_sel << 8) | (src0_sel << 16) | (src1_sel << 24); +} + +constexpr std::uint32_t dpp_ext(std::uint32_t src0, std::uint32_t ctrl) +{ + return (src0 & 255u) | (ctrl << 8) | (1u << 18) | (0xfu << 24) | (0xfu << 28); +} + +std::optional source_bits(unsigned r, const std::uint32_t vgpr[8]) +{ + if (r >= 256 && r < 264) + return vgpr[r - 256]; + if (r >= 128 && r <= 192) + return r - 128u; + if (r >= 193 && r <= 208) + return static_cast(192u - r); + return std::nullopt; +} + +Lowered lower(Kind kind, std::uint32_t a, std::uint32_t b, std::uint32_t c) +{ + const bool rev = kind == Kind::subrev || kind == Kind::subrev_clamp || kind == Kind::subrev_co; + const std::uint32_t left = rev ? b : a; + const std::uint32_t right = rev ? a : b; + const std::uint32_t difference = left - right; + const bool borrow = left < right; + if (kind == Kind::sub_clamp || kind == Kind::subrev_clamp) + return {borrow ? 0u : difference, false}; + if (kind == Kind::and_or) + return {(a & b) | c, false}; + if (kind == Kind::sub_co || kind == Kind::subrev_co) + return {difference, borrow}; + return {difference, false}; +} + +bool decode_name(const char* label, const std::uint32_t* words, unsigned count, const char* expect) +{ + std::string code(count * 4u, '\0'); + std::memcpy(code.data(), words, code.size()); + const auto inst = x2w::gfx1013::instruction(code, 0); + if (inst.name != expect || inst.size != count * 4u) { + std::ostringstream out; + out << "decoded '" << std::string(inst.name) << "' size " << inst.size + << ", expected " << expect << " size " << (count * 4u); + fail(label, out.str()); + return false; + } + return true; +} + +bool run_case(const char* label, const char* expect, Kind kind, const std::uint32_t* words, unsigned count, + const std::uint32_t vgpr[8]) +{ + if (!decode_name(label, words, count, expect)) + return false; + const std::uint32_t w0 = words[0]; + unsigned src[3] = {0, 0, 0}; + unsigned arity = 2; + bool clamp = false; + if ((w0 >> 31) == 0) { + const unsigned src0 = w0 & 511u; + const unsigned vsrc1 = (w0 >> 9) & 255u; + if (src0 == 249) { + if (count != 2) { + fail(label, "SDWA word count"); + return false; + } + const std::uint32_t ext = words[1]; + const unsigned dst_sel = (ext >> 8) & 7u; + const unsigned src0_sel = (ext >> 16) & 7u; + const unsigned src1_sel = (ext >> 24) & 7u; + if (dst_sel != 6 || src0_sel != 6 || src1_sel != 6 || (ext & 0x0800f800u) != 0) { + fail(label, "SDWA select is not a full dword"); + return false; + } + src[0] = (ext & 255u) + 256u; + src[1] = vsrc1 + 256u; + } else if (src0 == 250) { + if (count != 2) { + fail(label, "DPP word count"); + return false; + } + src[0] = (words[1] & 255u) + 256u; + src[1] = vsrc1 + 256u; + } else { + if (count != 1) { + fail(label, "VOP2 word count"); + return false; + } + src[0] = src0; + src[1] = vsrc1 + 256u; + } + } else if ((w0 & 0xfc000000u) == 0xd4000000u) { + if (count != 2) { + fail(label, "VOP3 word count"); + return false; + } + clamp = (w0 & 0x8000u) != 0; + src[0] = words[1] & 511u; + src[1] = (words[1] >> 9) & 511u; + src[2] = (words[1] >> 18) & 511u; + if (kind == Kind::and_or) + arity = 3; + } else { + fail(label, "encoding"); + return false; + } + const bool wants_clamp = kind == Kind::sub_clamp || kind == Kind::subrev_clamp; + if (clamp != wants_clamp) { + fail(label, clamp ? "unexpected clamp" : "missing clamp"); + return false; + } + std::uint32_t value[3] = {}; + for (unsigned i = 0; i < arity; ++i) { + const auto bits = source_bits(src[i], vgpr); + if (!bits) { + fail(label, "source is not an inline constant or a test VGPR"); + return false; + } + value[i] = *bits; + } + const Lowered result = lower(kind, value[0], value[1], value[2]); + const bool rev = kind == Kind::subrev || kind == Kind::subrev_clamp || kind == Kind::subrev_co; + const std::uint32_t left = rev ? value[1] : value[0]; + const std::uint32_t right = rev ? value[0] : value[1]; + if (kind == Kind::and_or) { + if (result.bits != 0xffffffffu) { + fail(label, "and-or result is not 0xFFFFFFFF"); + return false; + } + } else if (left != 0 || right != 1) { + fail(label, "operands are not 0 - 1"); + return false; + } else if (wants_clamp) { + if (result.bits != 0u) { + fail(label, "clamped 0 - 1 is not 0"); + return false; + } + } else if (result.bits != 0xffffffffu) { + fail(label, "0 - 1 is not 0xFFFFFFFF"); + return false; + } + if ((kind == Kind::sub_co || kind == Kind::subrev_co) && !result.borrow) { + fail(label, "0 - 1 did not borrow"); + return false; + } + const Lowered plain = lower(Kind::sub, 5u, 3u, 0u); + const Lowered wrapped = lower(Kind::sub, 0u, 1u, 0u); + const Lowered saturated = lower(Kind::sub_clamp, 0u, 1u, 0u); + if (plain.bits != 2u || wrapped.bits != 0xffffffffu || saturated.bits != 0u) { + fail(label, "formula self-check"); + return false; + } + return true; +} + +bool sub_nc_vop2() +{ + const std::uint32_t words[] = {vop2(0x26u, 1u, 128u, 2u)}; + const std::uint32_t vgpr[8] = {0, 0, 1u}; + return run_case("v_sub_nc_u32 VOP2", "v_sub_nc_u32", Kind::sub, words, 1, vgpr); +} + +bool sub_nc_vop3() +{ + const std::uint32_t words[] = {vop3_word0(0x126u, 1u, false), vop3_word1(128u, 129u)}; + const std::uint32_t vgpr[8] = {}; + return run_case("v_sub_nc_u32 VOP3", "v_sub_nc_u32", Kind::sub, words, 2, vgpr); +} + +bool sub_nc_vop3_clamp() +{ + const std::uint32_t words[] = {vop3_word0(0x126u, 1u, true), vop3_word1(128u, 129u)}; + const std::uint32_t vgpr[8] = {}; + return run_case("v_sub_nc_u32 VOP3 clamp", "v_sub_nc_u32", Kind::sub_clamp, words, 2, vgpr); +} + +bool sub_nc_sdwa() +{ + const std::uint32_t words[] = {vop2(0x26u, 1u, 249u, 3u), sdwa_ext(2u, 6u, 6u, 6u)}; + const std::uint32_t vgpr[8] = {0, 0, 0u, 1u}; + return run_case("v_sub_nc_u32 SDWA", "v_sub_nc_u32", Kind::sub, words, 2, vgpr); +} + +bool sub_nc_dpp() +{ + const std::uint32_t words[] = {vop2(0x26u, 1u, 250u, 3u), dpp_ext(2u, 0xe4u)}; + const std::uint32_t vgpr[8] = {0, 0, 0u, 1u}; + return run_case("v_sub_nc_u32 DPP", "v_sub_nc_u32", Kind::sub, words, 2, vgpr); +} + +bool subrev_nc_vop2() +{ + const std::uint32_t words[] = {vop2(0x27u, 1u, 129u, 2u)}; + const std::uint32_t vgpr[8] = {0, 0, 0u}; + return run_case("v_subrev_nc_u32 VOP2", "v_subrev_nc_u32", Kind::subrev, words, 1, vgpr); +} + +bool subrev_nc_vop3() +{ + const std::uint32_t words[] = {vop3_word0(0x127u, 1u, false), vop3_word1(129u, 128u)}; + const std::uint32_t vgpr[8] = {}; + return run_case("v_subrev_nc_u32 VOP3", "v_subrev_nc_u32", Kind::subrev, words, 2, vgpr); +} + +bool subrev_nc_vop3_clamp() +{ + const std::uint32_t words[] = {vop3_word0(0x127u, 1u, true), vop3_word1(129u, 128u)}; + const std::uint32_t vgpr[8] = {}; + return run_case("v_subrev_nc_u32 VOP3 clamp", "v_subrev_nc_u32", Kind::subrev_clamp, words, 2, vgpr); +} + +bool subrev_nc_sdwa() +{ + const std::uint32_t words[] = {vop2(0x27u, 1u, 249u, 3u), sdwa_ext(2u, 6u, 6u, 6u)}; + const std::uint32_t vgpr[8] = {0, 0, 1u, 0u}; + return run_case("v_subrev_nc_u32 SDWA", "v_subrev_nc_u32", Kind::subrev, words, 2, vgpr); +} + +bool subrev_nc_dpp() +{ + const std::uint32_t words[] = {vop2(0x27u, 1u, 250u, 3u), dpp_ext(2u, 0xe4u)}; + const std::uint32_t vgpr[8] = {0, 0, 1u, 0u}; + return run_case("v_subrev_nc_u32 DPP", "v_subrev_nc_u32", Kind::subrev, words, 2, vgpr); +} + +bool and_or_vop3() +{ + const std::uint32_t words[] = {vop3_word0(0x371u, 1u, false), vop3_word1(128u, 129u, 193u)}; + const std::uint32_t vgpr[8] = {}; + return run_case("v_and_or_b32 VOP3", "v_and_or_b32", Kind::and_or, words, 2, vgpr); +} + +bool sub_co_vop3() +{ + const std::uint32_t words[] = {vop3_word0(0x310u, 1u, false, 106u), vop3_word1(128u, 129u)}; + const std::uint32_t vgpr[8] = {}; + return run_case("v_sub_co_u32 VOP3", "v_sub_co_u32", Kind::sub_co, words, 2, vgpr); +} + +bool subrev_co_vop3() +{ + const std::uint32_t words[] = {vop3_word0(0x319u, 1u, false, 106u), vop3_word1(129u, 128u)}; + const std::uint32_t vgpr[8] = {}; + return run_case("v_subrev_co_u32 VOP3", "v_subrev_co_u32", Kind::subrev_co, words, 2, vgpr); +} + +bool mesh_whitelist(const char* root) +{ + if (!root) { + fail("mesh whitelist", "missing repository root"); + return false; + } + const std::string path = std::string(root) + "/src/gfx1013_direct_mesh.inl"; + std::ifstream in(path); + std::ostringstream text; + text << in.rdbuf(); + if (!in) { + fail("mesh whitelist", "could not read " + path); + return false; + } + const std::string source = text.str(); + const char* names[] = { + "v_sub_nc_u32", "v_subrev_nc_u32", "v_sub_co_u32", "v_subrev_co_u32", "v_and_or_b32", + }; + for (const char* name : names) { + const std::string needle = std::string("i.name==\"") + name + "\""; + if (source.find(needle) == std::string::npos) { + fail("mesh whitelist", std::string(name) + " is not accepted"); + return false; + } + } + return true; +} + +} // namespace + +int main(int argc, char** argv) +{ + const char* root = argc > 1 ? argv[1] : nullptr; + sub_nc_vop2(); + sub_nc_vop3(); + sub_nc_vop3_clamp(); + sub_nc_sdwa(); + sub_nc_dpp(); + subrev_nc_vop2(); + subrev_nc_vop3(); + subrev_nc_vop3_clamp(); + subrev_nc_sdwa(); + subrev_nc_dpp(); + and_or_vop3(); + sub_co_vop3(); + subrev_co_vop3(); + mesh_whitelist(root); + if (g_failures) { + std::cerr << g_failures << " mesh integer ALU check(s) failed\n"; + return 1; + } + return 0; +} From 949add33b4558cfdf6d0eeea0ee46ec2201d7a56 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Mon, 30 Nov 2026 23:47:20 +0000 Subject: [PATCH 23/24] mesh: refuse an out-of-range derived root parameter DispatchMesh indexed the bound root by the guest constant parameter before checking that the vector contains it. A missing or shorter root aborted in the debug CRT, which does not throw, so the derive log stayed empty. The mesh mapping and the lowerer now refuse a parameter index past the root before they read it. AI-assisted (Cursor) Co-authored-by: SimSalabimse --- CMakeLists.txt | 14 ++ CMakePresets.json | 2 +- docs/experiments/native-fixed-mesh57.md | 2 + src/gfx1013_compute_native.cpp | 40 ++++- src/gfx1013_direct_compute.inl | 8 +- src/gfx1013_direct_mesh.inl | 23 ++- src/startup_stubs/d3d12_xs_device.cpp | 9 ++ src/startup_stubs/mesh57_root_bounds.h | 163 ++++++++++++++++++++ tests/mesh57_root_bounds_check.cpp | 189 ++++++++++++++++++++++++ 9 files changed, 437 insertions(+), 13 deletions(-) create mode 100644 src/startup_stubs/mesh57_root_bounds.h create mode 100644 tests/mesh57_root_bounds_check.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index f3ed79a572..bd13bd01b6 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -2035,6 +2035,20 @@ target_include_directories(mesh57_block_a_check PRIVATE src/startup_stubs) target_compile_features(mesh57_block_a_check PRIVATE cxx_std_17) add_test(NAME mesh57_block_a COMMAND mesh57_block_a_check "${CMAKE_SOURCE_DIR}") +add_executable(mesh57_root_bounds_check tests/mesh57_root_bounds_check.cpp) +target_include_directories(mesh57_root_bounds_check PRIVATE src src/startup_stubs) +target_compile_features(mesh57_root_bounds_check PRIVATE cxx_std_17) +if(CMAKE_CXX_COMPILER_ID MATCHES "GNU|Clang") + target_compile_options(mesh57_root_bounds_check PRIVATE -D_GLIBCXX_ASSERTIONS) +endif() +# Clang's ASan runtime is not installed in every Linux image. GCC's is. +if(CMAKE_CXX_COMPILER_ID STREQUAL "GNU") + target_compile_options(mesh57_root_bounds_check PRIVATE + -fsanitize=address,undefined -fno-omit-frame-pointer) + target_link_options(mesh57_root_bounds_check PRIVATE -fsanitize=address,undefined) +endif() +add_test(NAME mesh57_root_bounds COMMAND mesh57_root_bounds_check "${CMAKE_SOURCE_DIR}") + add_executable(mesh57_span_dump_check tests/mesh57_span_dump_check.cpp) target_include_directories(mesh57_span_dump_check PRIVATE src) target_compile_features(mesh57_span_dump_check PRIVATE cxx_std_17) diff --git a/CMakePresets.json b/CMakePresets.json index b4fc7aef2a..3ca9f7b1cd 100644 --- a/CMakePresets.json +++ b/CMakePresets.json @@ -49,7 +49,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_mesh57_real_shape|mesh57_derive_alloc|mesh57_block_a|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_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_indirect_mesh_cache_heap(_wide)?_warp|runtime_mesh86_cache_cli_check|startup_shader_cache_key|startup_present_readback|startup_present_planes(_control)?|startup_present_composite_(warp|overlay_removed_control_warp)|startup_mesh_title_snapshot_warp|startup_list_copy_(warp|title_snapshot_warp|validation(_[a-z_]+_control)?)|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_mesh57_real_shape|mesh57_derive_alloc|mesh57_block_a|mesh57_root_bounds|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_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_indirect_mesh_cache_heap(_wide)?_warp|runtime_mesh86_cache_cli_check|startup_shader_cache_key|startup_present_readback|startup_present_planes(_control)?|startup_present_composite_(warp|overlay_removed_control_warp)|startup_mesh_title_snapshot_warp|startup_list_copy_(warp|title_snapshot_warp|validation(_[a-z_]+_control)?)|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 a6c1015c8f..4c12fb80e4 100644 --- a/docs/experiments/native-fixed-mesh57.md +++ b/docs/experiments/native-fixed-mesh57.md @@ -138,6 +138,8 @@ 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 forwarded `DispatchMesh` reads that constant parameter from the bound root only when the root vector contains it and the index is one of the sixteen stored constant slots. A missing root, or a parameter index past the vector, is refused as `derived mesh root constant parameter is missing` before the subscript. A block longer than eight words is refused as `derived mesh root constant count exceeds 8 words`. The mesh mapping and the lowerer use the same rule for a parameter number taken from the mapping or the shader: an index past the root is `missing mesh root parameter`, and the parameter is not read. A five-parameter root accepts parameter 4 and refuses parameter 5. + 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. The derived path passes that whole block to the blend reader, which applies the mesh shift from the tag: blend words are at `+0x124` (`+0xD0` plus `+0x54`). A tag other than 4 or 6 is `unknown state block A layout`. Depth and stencil must decode as disabled unless `X2W_MESH57_DERIVED_BOUNDS=1`; an enabled test is refused rather than given a guessed depth format. The color targets are the single-sample targets bound on that direct list, one to eight in slot order, with a viewport and a scissor and no depth view. A gap or a null slot, an unknown format, and more than eight targets are refused. A bound depth view stays refused unless that second switch is on. 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. diff --git a/src/gfx1013_compute_native.cpp b/src/gfx1013_compute_native.cpp index c233e0bb2d..fbfdfe172e 100644 --- a/src/gfx1013_compute_native.cpp +++ b/src/gfx1013_compute_native.cpp @@ -4,6 +4,7 @@ #include "guest_shader_container.h" #include "gfx1013_isa.h" #include "startup_stubs/mesh57_group_exchange.h" +#include "startup_stubs/mesh57_root_bounds.h" #include #include #include @@ -2290,8 +2291,12 @@ template static void walk_raw_graphics_root(const D3D12_ROOT_SIGNATURE_DESC1 &layout, D3D12_SHADER_VISIBILITY visibility, AddInput add_input) { const bool mesh = visibility == D3D12_SHADER_VISIBILITY_MESH; + if (layout.NumParameters && !layout.pParameters) + refuse(0, mesh ? "missing mesh root parameter" : "graphics root parameter inaccessible"); unsigned sgpr = mesh ? 16 : 8; for (unsigned j=0; j parameters; + parameters.reserve(root.NumParameters); + for (unsigned j = 0; j < root.NumParameters; ++j) { + if (const char* why = x2w_startup::mesh57_root_input_parameter_reason(root.NumParameters, j)) + throw UnsupportedComputeShader(why); + const auto &p = root.pParameters[j]; + x2w_startup::Mesh57Parameter parameter; + parameter.mesh_visible = p.ShaderVisibility == D3D12_SHADER_VISIBILITY_ALL || + p.ShaderVisibility == D3D12_SHADER_VISIBILITY_MESH; + if (p.ParameterType == D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE) + parameter.kind = x2w_startup::Mesh57ParameterClass::table; + else if (p.ParameterType == D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS) { + parameter.kind = x2w_startup::Mesh57ParameterClass::constants; + parameter.constant_count = p.Constants.Num32BitValues; + } else if (p.ParameterType == D3D12_ROOT_PARAMETER_TYPE_SRV) + parameter.kind = x2w_startup::Mesh57ParameterClass::srv; + else + parameter.kind = x2w_startup::Mesh57ParameterClass::other; + parameters.push_back(parameter); + } + x2w_startup::Mesh57MappedRoot mapped; + const bool resource_heap = (root.Flags & D3D12_ROOT_SIGNATURE_FLAG_CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED) != 0; + if (const char* why = x2w_startup::mesh57_map_mesh_root(parameters, resource_heap, mapped)) + throw UnsupportedComputeShader(why); MeshRootMapping mapping; - walk_raw_graphics_root(root, D3D12_SHADER_VISIBILITY_MESH, - [&](unsigned type, unsigned count, unsigned sgpr, unsigned root_parameter) { - if (type == 5) mapping.resource_heap_sgpr = sgpr; - else mapping.inputs.push_back({sgpr, root_parameter, type == 0 ? count : 0, type == 1}); - }); + for (const auto &input : mapped.inputs) + mapping.inputs.push_back({input.sgpr, input.root_parameter, input.constant_count, input.root_address}); + if (mapped.resource_heap) + mapping.resource_heap_sgpr = mapped.resource_heap_sgpr; return mapping; } diff --git a/src/gfx1013_direct_compute.inl b/src/gfx1013_direct_compute.inl index 0c1a03e96d..031c765d43 100644 --- a/src/gfx1013_direct_compute.inl +++ b/src/gfx1013_direct_compute.inl @@ -3552,7 +3552,13 @@ struct DirectCompute { } } } - return scc_live[program.at.at(definition.next)]; + // program.code is empty on the mesh lowerer, so scc_live is empty too. + // A recorded index of 0 is then a vector subscript, and that check does + // not throw. Refuse the use instead of reading past the vector. + const auto index = program.at.at(definition.next); + if (index >= scc_live.size()) + refuse(definition.pc, "numeric SCC from a symbolic descriptor field"); + return scc_live[index]; } void prepare_descriptor_strides() { const auto &p = analysis.program; diff --git a/src/gfx1013_direct_mesh.inl b/src/gfx1013_direct_mesh.inl index 1919a1b0b1..4cc57a7a23 100644 --- a/src/gfx1013_direct_mesh.inl +++ b/src/gfx1013_direct_mesh.inl @@ -64,13 +64,24 @@ NativeComputeShader lower_mesh(const string &code, const MeshStageLayout &layout if (at<8 || at>=106 || count>106-at || param>=16) refuse(0,"mesh root input outside user SGPR range"); if (!reflected || root.NumParameters) { - if (param>=root.NumParameters) refuse(0,"missing mesh root parameter"); + // The parameter number comes from the mapping or the shader. Refuse + // before pParameters[param]: a debug vector subscript does not throw. + if (const char* why = x2w_startup::mesh57_root_input_parameter_reason(root.NumParameters, param)) + refuse(0, why); + if (!root.pParameters) + refuse(0, "missing mesh root parameter"); const auto &binding=root.pParameters[param]; - if (input.root_address ? binding.ParameterType!=D3D12_ROOT_PARAMETER_TYPE_SRV : - count ? (binding.ParameterType!=D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS || - binding.Constants.Num32BitValues!=count) : - binding.ParameterType!=D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE) - refuse(0,"mesh root parameter kind or size disagrees with entry"); + x2w_startup::Mesh57ParameterClass kind = x2w_startup::Mesh57ParameterClass::other; + unsigned declared = 0; + if (binding.ParameterType == D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE) + kind = x2w_startup::Mesh57ParameterClass::table; + else if (binding.ParameterType == D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS) { + kind = x2w_startup::Mesh57ParameterClass::constants; + declared = binding.Constants.Num32BitValues; + } else if (binding.ParameterType == D3D12_ROOT_PARAMETER_TYPE_SRV) + kind = x2w_startup::Mesh57ParameterClass::srv; + if (const char* why = x2w_startup::mesh57_root_input_kind_reason(kind, declared, input.root_address, count)) + refuse(0, why); } if (input.root_address) { if (count || at+1>=106 || state[at].type!=Symbol::Type::unbound || state[at+1].type!=Symbol::Type::unbound) diff --git a/src/startup_stubs/d3d12_xs_device.cpp b/src/startup_stubs/d3d12_xs_device.cpp index c11a9dd43b..8ca596956e 100644 --- a/src/startup_stubs/d3d12_xs_device.cpp +++ b/src/startup_stubs/d3d12_xs_device.cpp @@ -104,6 +104,7 @@ // 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" +#include "mesh57_root_bounds.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" @@ -4682,8 +4683,16 @@ void __stdcall list_execute_indirect(Wrapper* self, void* signature, UINT count, list->SetGraphicsRootSignature(pass.graphics_root); if (pso.constant_guest != UINT_MAX) { const UINT guest = pso.constant_guest; + // constant_guest is a root parameter (4 on a five-parameter walk root). + // The debug CRT's vector subscript aborts instead of throwing, so a + // missing or shorter root never reaches the derive log. + if (const char* why = x2w_startup::mesh57_root_constant_parameter_reason( + pass.root != nullptr, pass.root ? pass.root->size() : 0, guest)) + return refuse(why, indirect_graphics_pipeline, indirect_pipeline_refusal_code::mesh_bind); UINT words[8]{}; const auto count = (*pass.root)[guest].constants_count; + if (const char* why = x2w_startup::mesh57_root_constant_count_reason(count)) + return refuse(why, indirect_graphics_pipeline, indirect_pipeline_refusal_code::mesh_bind); std::copy_n(pass.constants[guest], count, words); if (const char* why = bind_mesh57_buffers(self, pass, list, resource)) return refuse(why, indirect_graphics_pipeline, indirect_pipeline_refusal_code::mesh_bind); diff --git a/src/startup_stubs/mesh57_root_bounds.h b/src/startup_stubs/mesh57_root_bounds.h new file mode 100644 index 0000000000..a1c24673ae --- /dev/null +++ b/src/startup_stubs/mesh57_root_bounds.h @@ -0,0 +1,163 @@ +// Bounds for a derived mesh root before any vector subscript. +// DispatchMesh indexes the bound root by the guest constant parameter. +// The mesh mapping and the lowerer index a root by a parameter number taken +// from that mapping or from the shader. Both refuse instead of reading past +// the vector. No desktop types: the Windows callers apply the same decision +// to the root signature they already hold. +#pragma once + +#include +#include +#include + +namespace x2w_startup { + +inline constexpr const char* mesh57_root_constant_missing() noexcept +{ + return "derived mesh root constant parameter is missing"; +} + +inline constexpr const char* mesh57_root_parameter_missing() noexcept +{ + return "missing mesh root parameter"; +} + +inline constexpr const char* mesh57_root_input_range() noexcept +{ + return "mesh root input outside user SGPR range"; +} + +inline constexpr const char* mesh57_root_kind_mismatch() noexcept +{ + return "mesh root parameter kind or size disagrees with entry"; +} + +inline constexpr const char* mesh57_root_constant_count_limit() noexcept +{ + return "derived mesh root constant count exceeds 8 words"; +} + +// The pass stores sixteen constant parameters. A guest index past the bound +// root, or past that table, is missing. +inline const char* mesh57_root_constant_parameter_reason(bool has_root, std::size_t root_count, + unsigned guest) noexcept +{ + constexpr std::size_t stored = 16; + if (!has_root || static_cast(guest) >= root_count || static_cast(guest) >= stored) + return mesh57_root_constant_missing(); + return nullptr; +} + +// The draw copies the block into eight words. A longer block is refused +// before that copy. +inline const char* mesh57_root_constant_count_reason(unsigned count) noexcept +{ + if (count > 8) + return mesh57_root_constant_count_limit(); + return nullptr; +} + +inline const char* mesh57_root_input_parameter_reason(std::size_t parameter_count, unsigned root_parameter) noexcept +{ + if (static_cast(root_parameter) >= parameter_count) + return mesh57_root_parameter_missing(); + return nullptr; +} + +// Index `root` only after the parameter is in range. An out-of-range index +// returns the reason and does not subscript the vector. +template +const char* mesh57_root_parameter_at(const std::vector& root, unsigned index, + const Parameter*& out) noexcept +{ + out = nullptr; + if (const char* why = mesh57_root_input_parameter_reason(root.size(), index)) + return why; + out = &root[index]; + return nullptr; +} + +enum class Mesh57ParameterClass : unsigned { table = 0, constants = 1, srv = 2, other = 3 }; + +struct Mesh57Parameter { + Mesh57ParameterClass kind = Mesh57ParameterClass::other; + unsigned constant_count = 0; + bool mesh_visible = true; +}; + +struct Mesh57MappedInput { + unsigned sgpr = 0; + unsigned root_parameter = 0; + unsigned constant_count = 0; + bool root_address = false; +}; + +struct Mesh57MappedRoot { + std::vector inputs; + bool resource_heap = false; + unsigned resource_heap_sgpr = 0; +}; + +// Mesh-stage user-SGPR walk. Every parameter index is taken from `parameters` +// after the range check. A table uses one SGPR, a constant block uses its +// dword count, and any other parameter uses two. Invisible parameters still +// occupy registers. Only a visible table, constant block, or root SRV becomes +// an input. A resource heap, when requested, takes the next SGPR. +inline const char* mesh57_map_mesh_root(const std::vector& parameters, bool resource_heap, + Mesh57MappedRoot& out) +{ + out = {}; + unsigned sgpr = 16; + for (unsigned j = 0; j < parameters.size(); ++j) { + const Mesh57Parameter* parameter = nullptr; + if (const char* why = mesh57_root_parameter_at(parameters, j, parameter)) + return why; + const bool table = parameter->kind == Mesh57ParameterClass::table; + const bool constants = parameter->kind == Mesh57ParameterClass::constants; + const unsigned count = table ? 1u : constants ? parameter->constant_count : 2u; + if (!count || count > 106u - sgpr || j >= 16) + return "raw graphics user data exceeds register range"; + if (parameter->mesh_visible && (table || constants || parameter->kind == Mesh57ParameterClass::srv)) { + Mesh57MappedInput input; + input.sgpr = sgpr; + input.root_parameter = j; + input.constant_count = constants ? count : 0; + input.root_address = parameter->kind == Mesh57ParameterClass::srv; + out.inputs.push_back(input); + } + sgpr += count; + } + if (resource_heap) { + if (sgpr >= 106) + return "resource heap outside graphics user data"; + out.resource_heap = true; + out.resource_heap_sgpr = sgpr; + } + return nullptr; +} + +inline const char* mesh57_root_input_kind_reason(Mesh57ParameterClass kind, unsigned declared_count, + bool root_address, unsigned input_count) noexcept +{ + if (root_address ? kind != Mesh57ParameterClass::srv + : input_count ? (kind != Mesh57ParameterClass::constants || declared_count != input_count) + : kind != Mesh57ParameterClass::table) + return mesh57_root_kind_mismatch(); + return nullptr; +} + +// `sgpr` is the physical user SGPR. `root_parameter` is the index taken from +// the shader or the mapping. The parameter vector is indexed only when that +// index is in range. +inline const char* mesh57_check_mesh_root_input(const std::vector& parameters, unsigned sgpr, + unsigned root_parameter, unsigned count, bool root_address) +{ + if (sgpr < 8 || sgpr >= 106 || count > 106u - sgpr || root_parameter >= 16) + return mesh57_root_input_range(); + const Mesh57Parameter* parameter = nullptr; + if (const char* why = mesh57_root_parameter_at(parameters, root_parameter, parameter)) + return why; + return mesh57_root_input_kind_reason(parameter->kind, parameter->constant_count, root_address, count); +} + +} // namespace x2w_startup diff --git a/tests/mesh57_root_bounds_check.cpp b/tests/mesh57_root_bounds_check.cpp new file mode 100644 index 0000000000..a08480bf58 --- /dev/null +++ b/tests/mesh57_root_bounds_check.cpp @@ -0,0 +1,189 @@ +// A five-parameter mesh root, and indexes past it. +// Parameter 4 is the constant on a root of three tables, one root SRV and one +// constant. The draw and the lowerer must refuse a larger index before they +// subscript the root vector. Tag-4 and tag-6 blocks of 388 and 396 bytes still +// have room for the blend words and the depth words. +#include "mesh57_derived_depth.h" +#include "mesh57_root_bounds.h" +#include "state_block_a_layout.h" + +#include +#include +#include +#include +#include +#include + +namespace { +int fail(const char* name, const char* detail) +{ + std::cerr << "mesh57 root bounds: " << name; + if (detail) std::cerr << ": " << detail; + std::cerr << '\n'; + return 1; +} + +bool same(const char* got, const char* want) +{ + if (want == nullptr) return got == nullptr; + return got && std::strcmp(got, want) == 0; +} + +std::vector walk_root() +{ + using x2w_startup::Mesh57Parameter; + using x2w_startup::Mesh57ParameterClass; + std::vector root(5); + root[0].kind = Mesh57ParameterClass::table; + root[1].kind = Mesh57ParameterClass::table; + root[2].kind = Mesh57ParameterClass::table; + root[3].kind = Mesh57ParameterClass::srv; + root[4].kind = Mesh57ParameterClass::constants; + root[4].constant_count = 1; + return root; +} + +bool constant_guest() +{ + const char* missing = x2w_startup::mesh57_root_constant_missing(); + if (x2w_startup::mesh57_root_constant_parameter_reason(true, 5, 4) != nullptr) + return fail("five-parameter constant", "parameter 4 is in range"); + if (!same(x2w_startup::mesh57_root_constant_parameter_reason(true, 5, 5), missing)) + return fail("parameter 5", "a five-parameter root has no parameter 5"); + if (!same(x2w_startup::mesh57_root_constant_parameter_reason(true, 1, 4), missing)) + return fail("shorter root", "parameter 4 is past a one-parameter root"); + if (!same(x2w_startup::mesh57_root_constant_parameter_reason(false, 5, 4), missing)) + return fail("null root", "a missing root is not indexed"); + if (!same(x2w_startup::mesh57_root_constant_parameter_reason(true, 20, 16), missing)) + return fail("stored constants", "parameter 16 is past the sixteen stored slots"); + if (x2w_startup::mesh57_root_constant_count_reason(8) != nullptr) + return fail("eight words", "eight words fit the draw copy"); + if (!same(x2w_startup::mesh57_root_constant_count_reason(9), x2w_startup::mesh57_root_constant_count_limit())) + return fail("nine words", "a longer block is refused"); + return false; +} + +bool mapping() +{ + const auto root = walk_root(); + x2w_startup::Mesh57MappedRoot mapped; + if (const char* why = x2w_startup::mesh57_map_mesh_root(root, true, mapped)) + return fail("map five", why); + if (mapped.inputs.size() != 5 || !mapped.resource_heap || mapped.resource_heap_sgpr != 22) + return fail("map five", "expected five inputs and a heap SGPR"); + const unsigned expect_sgpr[] = {16, 17, 18, 19, 21}; + for (unsigned i = 0; i < 5; ++i) { + if (mapped.inputs[i].root_parameter != i || mapped.inputs[i].sgpr != expect_sgpr[i]) + return fail("map five", "input parameter or SGPR differs"); + const x2w_startup::Mesh57Parameter* parameter = nullptr; + if (const char* why = x2w_startup::mesh57_root_parameter_at(root, i, parameter)) + return fail("map five", why); + if (parameter != &root[i]) + return fail("map five", "in-range lookup did not return the parameter"); + if (const char* why = x2w_startup::mesh57_check_mesh_root_input( + root, mapped.inputs[i].sgpr, mapped.inputs[i].root_parameter, + mapped.inputs[i].constant_count, mapped.inputs[i].root_address)) + return fail("check input", why); + } + if (!mapped.inputs[3].root_address || mapped.inputs[4].constant_count != 1 || mapped.inputs[4].root_address) + return fail("map five", "the SRV and the constant were not classified"); + const x2w_startup::Mesh57Parameter* past = nullptr; + if (!same(x2w_startup::mesh57_root_parameter_at(root, 5, past), x2w_startup::mesh57_root_parameter_missing()) || past) + return fail("parameter 5", "the lookup subscripted past the root"); + if (!same(x2w_startup::mesh57_check_mesh_root_input(root, 16, 5, 0, false), + x2w_startup::mesh57_root_parameter_missing())) + return fail("table parameter 5", "a descriptor-table parameter past the root was accepted"); + if (!same(x2w_startup::mesh57_check_mesh_root_input(root, 200, 0, 0, false), + x2w_startup::mesh57_root_input_range())) + return fail("user SGPR", "an SGPR past the window was accepted"); + if (!same(x2w_startup::mesh57_check_mesh_root_input(root, 21, 4, 2, false), + x2w_startup::mesh57_root_kind_mismatch())) + return fail("constant size", "a two-word read of a one-word constant was accepted"); + return false; +} + +std::vector block(std::uint32_t tag, std::size_t bytes) +{ + std::vector out(bytes, 0); + if (bytes >= x2w_pipeline_state::a_layout + sizeof(tag)) + std::memcpy(out.data() + x2w_pipeline_state::a_layout, &tag, sizeof(tag)); + return out; +} + +bool blend_block(const char* name, std::uint32_t tag, std::size_t bytes, bool ok, std::size_t offset, const char* reason) +{ + const auto data = block(tag, bytes); + const auto span = x2w_pipeline_state::state_block_a_blend_span(data.data(), data.size()); + if (span.ok != ok || span.offset != offset) + return fail(name, "blend offset differs"); + if (!same(span.reason, reason)) + return fail(name, span.reason ? span.reason : "missing reason"); + constexpr std::size_t depth_last = 0x0c4 + 4; + const std::size_t shift = tag == x2w_pipeline_state::a_layout_mesh ? x2w_pipeline_state::a_mesh_shift : 0; + if (ok && (offset + 32 > bytes || depth_last + shift > bytes)) + return fail(name, "accepted block does not hold the blend or depth words"); + return false; +} + +bool blocks() +{ + const std::size_t vertex_blend = x2w_pipeline_state::a_blend; + const std::size_t mesh_blend = x2w_pipeline_state::a_blend + x2w_pipeline_state::a_mesh_shift; + for (std::size_t bytes : {std::size_t{388}, std::size_t{396}}) { + if (blend_block("tag 4", x2w_pipeline_state::a_layout_vertex, bytes, true, vertex_blend, nullptr)) + return true; + if (blend_block("tag 6", x2w_pipeline_state::a_layout_mesh, bytes, true, mesh_blend, nullptr)) + return true; + } + if (blend_block("short tag 4", x2w_pipeline_state::a_layout_vertex, vertex_blend + 32 - 1, false, vertex_blend, + "state block A shorter than the blend words")) + return true; + if (blend_block("short tag 6", x2w_pipeline_state::a_layout_mesh, mesh_blend + 32 - 1, false, mesh_blend, + "state block A shorter than the blend words")) + return true; + if (blend_block("tag 5", 5, 396, false, vertex_blend, "unknown state block A layout")) + return true; + x2w_startup::Mesh57DepthTargets targets; + targets.targets_bound = true; + targets.viewport_set = true; + targets.scissor_set = true; + targets.target_count = 9; + if (!same(x2w_startup::mesh57_color_list_reason(targets), x2w_startup::mesh57_color_limit_reason())) + return fail("nine color targets", "a count past 8 was accepted"); + return false; +} + +bool sources_guard_the_index(const char* root) +{ + const auto read = [](const std::string& path, std::string& text) { + std::ifstream in(path); + if (!in) return false; + text.assign(std::istreambuf_iterator(in), std::istreambuf_iterator()); + return true; + }; + std::string device, mesh, native; + if (!read(std::string(root) + "/src/startup_stubs/d3d12_xs_device.cpp", device) || + !read(std::string(root) + "/src/gfx1013_direct_mesh.inl", mesh) || + !read(std::string(root) + "/src/gfx1013_compute_native.cpp", native)) + return fail("sources", "could not read the root callers"); + const auto guest = device.find("(*pass.root)[guest]"); + const auto guard = device.find("mesh57_root_constant_parameter_reason"); + if (guard == std::string::npos || guest == std::string::npos || guard > guest) + return fail("dispatch", "the constant parameter is indexed before the root size is checked"); + const auto parameter = mesh.find("root.pParameters[param]"); + const auto input = mesh.find("mesh57_root_input_parameter_reason"); + if (input == std::string::npos || parameter == std::string::npos || input > parameter) + return fail("lowerer", "the root parameter is indexed before its range is checked"); + if (native.find("mesh57_map_mesh_root") == std::string::npos) + return fail("mapping", "derive_mesh_root_mapping does not use the checked walk"); + return false; +} +} // namespace + +int main(int argc, char** argv) +{ + if (argc < 2) return fail("usage", "pass the repository root"); + if (constant_guest() || mapping() || blocks() || sources_guard_the_index(argv[1])) + return 1; + return 0; +} From 83684cf99e121685cd825f9fcc10087387b53cb9 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Tue, 1 Dec 2026 00:23:36 +0000 Subject: [PATCH 24/24] mesh: lower a scalar readfirstlane on a whole wave A v_readfirstlane_b32 whose source is an SGPR, a constant, or a value already tracked as wave-uniform is a copy. A VGPR that is not uniform becomes WaveReadLaneFirst when the instruction runs for the whole wave. Unknown EXEC, a per-lane mask, a vector destination, and modifiers stay refused and name the condition that failed. AI-assisted (Cursor) Co-authored-by: SimSalabimse --- CMakeLists.txt | 13 +++ CMakePresets.json | 2 +- docs/experiments.md | 2 +- docs/experiments/native-fixed-mesh57.md | 2 + src/gfx1013_compute_native.cpp | 1 + src/gfx1013_direct_mesh.inl | 46 +++++++- src/startup_stubs/mesh57_readfirstlane.h | 47 +++++++++ tests/mesh57_readfirstlane_check.cpp | 129 +++++++++++++++++++++++ tests/native_direct_mesh_check.py | 28 ++--- 9 files changed, 251 insertions(+), 19 deletions(-) create mode 100644 src/startup_stubs/mesh57_readfirstlane.h create mode 100644 tests/mesh57_readfirstlane_check.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index bd13bd01b6..f1cbbbe574 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -2049,6 +2049,19 @@ if(CMAKE_CXX_COMPILER_ID STREQUAL "GNU") endif() add_test(NAME mesh57_root_bounds COMMAND mesh57_root_bounds_check "${CMAKE_SOURCE_DIR}") +add_executable(mesh57_readfirstlane_check tests/mesh57_readfirstlane_check.cpp) +target_include_directories(mesh57_readfirstlane_check PRIVATE src src/startup_stubs) +target_compile_features(mesh57_readfirstlane_check PRIVATE cxx_std_17) +if(CMAKE_CXX_COMPILER_ID MATCHES "GNU|Clang") + target_compile_options(mesh57_readfirstlane_check PRIVATE -D_GLIBCXX_ASSERTIONS) +endif() +if(CMAKE_CXX_COMPILER_ID STREQUAL "GNU") + target_compile_options(mesh57_readfirstlane_check PRIVATE + -fsanitize=address,undefined -fno-omit-frame-pointer) + target_link_options(mesh57_readfirstlane_check PRIVATE -fsanitize=address,undefined) +endif() +add_test(NAME mesh57_readfirstlane COMMAND mesh57_readfirstlane_check "${CMAKE_SOURCE_DIR}") + add_executable(mesh57_span_dump_check tests/mesh57_span_dump_check.cpp) target_include_directories(mesh57_span_dump_check PRIVATE src) target_compile_features(mesh57_span_dump_check PRIVATE cxx_std_17) diff --git a/CMakePresets.json b/CMakePresets.json index 3ca9f7b1cd..5e0752e73e 100644 --- a/CMakePresets.json +++ b/CMakePresets.json @@ -49,7 +49,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_mesh57_real_shape|mesh57_derive_alloc|mesh57_block_a|mesh57_root_bounds|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_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_indirect_mesh_cache_heap(_wide)?_warp|runtime_mesh86_cache_cli_check|startup_shader_cache_key|startup_present_readback|startup_present_planes(_control)?|startup_present_composite_(warp|overlay_removed_control_warp)|startup_mesh_title_snapshot_warp|startup_list_copy_(warp|title_snapshot_warp|validation(_[a-z_]+_control)?)|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_mesh57_real_shape|mesh57_derive_alloc|mesh57_block_a|mesh57_root_bounds|mesh57_readfirstlane|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_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_indirect_mesh_cache_heap(_wide)?_warp|runtime_mesh86_cache_cli_check|startup_shader_cache_key|startup_present_readback|startup_present_planes(_control)?|startup_present_composite_(warp|overlay_removed_control_warp)|startup_mesh_title_snapshot_warp|startup_list_copy_(warp|title_snapshot_warp|validation(_[a-z_]+_control)?)|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.md b/docs/experiments.md index ddd7c1b4f1..7046382934 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -10315,7 +10315,7 @@ The direct C++ mesh frontend lowers `v_or3_b32` and sign-extends the immediate in `s_movk_i32`. OR and XOR with `-1` retain uniformity information for a following CNDMASK and READFIRSTLANE when the input masks are proven uniform over the current EXEC mask. The -`native_direct_mesh` fixture checks these forms and rejects a varying input mask. +`native_direct_mesh` fixture checks these forms. A varying input mask becomes `WaveReadLaneFirst` when that read runs for the whole wave, and a per-lane EXEC still refuses it. For an LDS-free mesh stage with a proven flat-thread-zero allocation arm, the C++ frontend shares that lane's counts, synchronizes the group, then diff --git a/docs/experiments/native-fixed-mesh57.md b/docs/experiments/native-fixed-mesh57.md index 4c12fb80e4..1204b381ea 100644 --- a/docs/experiments/native-fixed-mesh57.md +++ b/docs/experiments/native-fixed-mesh57.md @@ -270,6 +270,8 @@ subset. The same mesh subset also accepts `v_sub_co_u32`, `v_subrev_co_u32` and `v_and_or_b32`, using the existing carry-out and bitwise lowerings. `v_sub_co_ci_u32` stays outside it. +`v_readfirstlane_b32` copies a source that is an SGPR, a constant, or a value this lowerer already tracks as wave-uniform. A VGPR that is not uniform becomes `WaveReadLaneFirst` when the instruction runs for the whole wave, so the desktop wave's first active lane is the guest first lane. The shared compute lowering reads EXEC as a register and is unchanged. Operand modifiers are `mesh readfirstlane has operand modifiers`. A destination that is not one SGPR is `mesh readfirstlane result is not a scalar`. An undefined SGPR is `mesh readfirstlane source is undefined`. Any other source is `mesh readfirstlane source is not an SGPR, a constant, or a VGPR`. A non-uniform VGPR whose EXEC is not known non-empty is `mesh readfirstlane EXEC is not known non-empty`. A non-uniform VGPR under a per-lane mask is `mesh readfirstlane EXEC is not the whole wave`. `mesh57_readfirstlane` checks that decision on the synthetic words `v_readfirstlane_b32 s18, v6` (`0x7e240506`) and `v_readfirstlane_b32 s2, v0` (`0x7e040500`). + The raw root-buffer V# path accepts `root_stride_one_high` with the `0x31016fac` byte-count format, and OFFEN may carry a nonzero immediate offset. This moves the live request `314407020a96f733` from diff --git a/src/gfx1013_compute_native.cpp b/src/gfx1013_compute_native.cpp index fbfdfe172e..c6d9215554 100644 --- a/src/gfx1013_compute_native.cpp +++ b/src/gfx1013_compute_native.cpp @@ -4,6 +4,7 @@ #include "guest_shader_container.h" #include "gfx1013_isa.h" #include "startup_stubs/mesh57_group_exchange.h" +#include "startup_stubs/mesh57_readfirstlane.h" #include "startup_stubs/mesh57_root_bounds.h" #include #include diff --git a/src/gfx1013_direct_mesh.inl b/src/gfx1013_direct_mesh.inl index 4cc57a7a23..61ac731efe 100644 --- a/src/gfx1013_direct_mesh.inl +++ b/src/gfx1013_direct_mesh.inl @@ -1592,9 +1592,49 @@ NativeComputeShader lower_mesh(const string &code, const MeshStageLayout &layout alu.arithmetic(i,state); } else if (i.name=="v_readfirstlane_b32" && i.dst<106 && i.src[0]==261 && !exchanged_group.empty() && full_exec) { alu.write(i.dst,exchanged_group); - } else if (i.name=="v_readfirstlane_b32" && i.dst<106 && (full_exec || exec_skip) && - !uniform(alu.read(i.src[0])).empty()) { - alu.write(i.dst,uniform(alu.read(i.src[0]))); + } else if (i.name=="v_readfirstlane_b32") { + // Modifiers and a non-scalar destination are refused before the source is read. + // An SGPR or a constant is already one value for the wave. A VGPR uses the + // same uniform() proof as the other mesh ALU results. Anything else is + // WaveReadLaneFirst only when the whole wave executes this instruction. + const bool modifiers = i.dpp_control || i.dpp8_selectors || i.subword || i.abs || i.neg || + i.clamp || i.scale || (i.wide && (i.a & 0x7800u)); + const bool scalar = i.dst < 106; + auto source = x2w_startup::Mesh57ReadFirstLaneSource::not_a_lane_value; + string lane_value; + if (!modifiers && scalar) { + if (const auto constant = constant32(i, i.src[0])) { + source = x2w_startup::Mesh57ReadFirstLaneSource::uniform; + lane_value = to_string(*constant); + } else if (i.src[0] < 106) { + const auto defined = alu.graphics_registers.find(i.src[0]); + if (defined == alu.graphics_registers.end() || defined->second.empty()) + source = x2w_startup::Mesh57ReadFirstLaneSource::undefined; + else { + source = x2w_startup::Mesh57ReadFirstLaneSource::uniform; + lane_value = defined->second; + } + } else if (i.src[0] >= 256 && i.src[0] < 512) { + lane_value = alu.read(i.src[0]); + const auto proven = uniform(lane_value); + if (!proven.empty()) { + source = x2w_startup::Mesh57ReadFirstLaneSource::uniform; + lane_value = proven; + } else if (lane_value.empty()) + source = x2w_startup::Mesh57ReadFirstLaneSource::undefined; + else + source = x2w_startup::Mesh57ReadFirstLaneSource::varying_vgpr; + } + } + bool wave_read = false; + if (const char* reason = x2w_startup::mesh57_readfirstlane_reason( + modifiers, scalar, source, whole_wave_execution(), exec_nonempty_known(), wave_read)) + refuse(pc, reason); + if (wave_read) + lane_value = ir.invoke("i32", "waveReadLaneFirst.i32", 110, {{"i32", lane_value}}, "nounwind"); + alu.write(i.dst, lane_value); + if (full_exec) uniform_values.insert(lane_value); + else if (!lane_active.empty()) active_uniform[lane_value] = {lane_active, lane_value}; } else if (i.name=="s_pack_ll_b32_b16" || i.name=="s_pack_hh_b32_b16") { if (i.dst==126 || i.dst==127) refuse(pc,"mesh scalar write to EXEC"); if (i.dst==106 || i.dst==107) refuse(pc,"mesh scalar write to VCC"); diff --git a/src/startup_stubs/mesh57_readfirstlane.h b/src/startup_stubs/mesh57_readfirstlane.h new file mode 100644 index 0000000000..5f7919eb98 --- /dev/null +++ b/src/startup_stubs/mesh57_readfirstlane.h @@ -0,0 +1,47 @@ +#pragma once + +// v_readfirstlane_b32 in the native mesh lowerer. +// A source that is an SGPR, a constant, or a value the lowerer already tracks +// as wave-uniform is a plain copy. A VGPR that is not uniform becomes +// WaveReadLaneFirst only when this instruction executes for the whole wave: +// that is when the desktop wave's first active lane is the guest first lane. +// A per-lane guest EXEC mask is not that wave, and an unknown EXEC is not a +// non-empty wave. The shared compute lowering reads EXEC as a register and is +// not used here. + +namespace x2w_startup { + +enum class Mesh57ReadFirstLaneSource { + uniform, + varying_vgpr, + undefined, + not_a_lane_value, +}; + +// Returns nullptr when the instruction is accepted. wave_read is then false +// for a copy and true for WaveReadLaneFirst. +inline const char* mesh57_readfirstlane_reason(bool modifiers, bool scalar_destination, + Mesh57ReadFirstLaneSource source, bool whole_wave, + bool exec_nonempty, bool& wave_read) +{ + wave_read = false; + if (modifiers) + return "mesh readfirstlane has operand modifiers"; + if (!scalar_destination) + return "mesh readfirstlane result is not a scalar"; + if (source == Mesh57ReadFirstLaneSource::undefined) + return "mesh readfirstlane source is undefined"; + if (source == Mesh57ReadFirstLaneSource::not_a_lane_value) + return "mesh readfirstlane source is not an SGPR, a constant, or a VGPR"; + if (source == Mesh57ReadFirstLaneSource::uniform) + return nullptr; + if (whole_wave) { + wave_read = true; + return nullptr; + } + if (!exec_nonempty) + return "mesh readfirstlane EXEC is not known non-empty"; + return "mesh readfirstlane EXEC is not the whole wave"; +} + +} diff --git a/tests/mesh57_readfirstlane_check.cpp b/tests/mesh57_readfirstlane_check.cpp new file mode 100644 index 0000000000..7bde00d971 --- /dev/null +++ b/tests/mesh57_readfirstlane_check.cpp @@ -0,0 +1,129 @@ +// Synthetic VOP1 words for v_readfirstlane_b32. +// 0x7e240506 is s18, v6. 0x7e040500 is s2, v0. A vdst field above 105 is not +// a scalar destination. Uniformity and EXEC are not in the word; the lowerer +// supplies those proofs and this check applies the same decision. +#include "mesh57_readfirstlane.h" + +#include +#include +#include +#include +#include +#include + +namespace { +int fail(const char* name, const char* detail) +{ + std::cerr << "mesh57 readfirstlane: " << name; + if (detail) std::cerr << ": " << detail; + std::cerr << '\n'; + return 1; +} + +struct Vop1 { + unsigned src = 0; + unsigned op = 0; + unsigned vdst = 0; +}; + +bool decode_vop1(std::uint32_t word, Vop1& out) +{ + if ((word >> 25) != 0x3f) return false; + out.src = word & 0x1ff; + out.op = (word >> 9) & 0xff; + out.vdst = (word >> 17) & 0xff; + return true; +} + +bool same(const char* got, const char* want) +{ + if (want == nullptr) return got == nullptr; + return got && std::strcmp(got, want) == 0; +} + +bool decide(const char* name, std::uint32_t word, x2w_startup::Mesh57ReadFirstLaneSource source, + bool whole_wave, bool exec_nonempty, bool modifiers, const char* want, bool want_wave) +{ + Vop1 fields; + if (!decode_vop1(word, fields) || fields.op != 2) + return fail(name, "word is not v_readfirstlane_b32"); + bool wave = true; + const char* reason = x2w_startup::mesh57_readfirstlane_reason( + modifiers, fields.vdst <= 105, source, whole_wave, exec_nonempty, wave); + if (!same(reason, want) || wave != want_wave) + return fail(name, reason ? reason : "accepted"); + return false; +} + +bool words() +{ + using x2w_startup::Mesh57ReadFirstLaneSource; + // VOP1: [31:25] = 0b0111111, [24:17] = vdst, [16:9] = op, [8:0] = src0. + // v_readfirstlane_b32 is opcode 2. A VGPR source is 256 plus its number. + const std::uint32_t s18_v6 = 0x7e000000u | (18u << 17) | (2u << 9) | (256u + 6u); + const std::uint32_t s2_v0 = 0x7e000000u | (2u << 17) | (2u << 9) | 256u; + const std::uint32_t vector_dst = 0x7e000000u | (200u << 17) | (2u << 9) | (256u + 6u); + std::vector encoded{s18_v6, s2_v0, vector_dst}; + if (encoded.size() != 3 || encoded[0] != 0x7e240506u || encoded[1] != 0x7e040500u) + return fail("encoding", "synthetic words do not match the documented VOP1 fields"); + Vop1 lane; + if (!decode_vop1(encoded[0], lane) || lane.vdst != 18 || lane.src != 262) + return fail("s18, v6", "decoded fields"); + if (!decode_vop1(encoded[1], lane) || lane.vdst != 2 || lane.src != 256) + return fail("s2, v0", "decoded fields"); + + if (decide("uniform copy", encoded[0], Mesh57ReadFirstLaneSource::uniform, true, true, false, nullptr, false)) + return true; + if (decide("uniform copy under unknown EXEC", encoded[1], Mesh57ReadFirstLaneSource::uniform, false, false, + false, nullptr, false)) + return true; + if (decide("wave read", encoded[0], Mesh57ReadFirstLaneSource::varying_vgpr, true, true, false, nullptr, true)) + return true; + if (decide("unknown EXEC", encoded[0], Mesh57ReadFirstLaneSource::varying_vgpr, false, false, false, + "mesh readfirstlane EXEC is not known non-empty", false)) + return true; + if (decide("partial EXEC", encoded[0], Mesh57ReadFirstLaneSource::varying_vgpr, false, true, false, + "mesh readfirstlane EXEC is not the whole wave", false)) + return true; + if (decide("vector result", encoded[2], Mesh57ReadFirstLaneSource::varying_vgpr, true, true, false, + "mesh readfirstlane result is not a scalar", false)) + return true; + if (decide("modifiers", encoded[0], Mesh57ReadFirstLaneSource::uniform, true, true, true, + "mesh readfirstlane has operand modifiers", false)) + return true; + if (decide("undefined source", encoded[0], Mesh57ReadFirstLaneSource::undefined, true, true, false, + "mesh readfirstlane source is undefined", false)) + return true; + if (decide("other source", encoded[0], Mesh57ReadFirstLaneSource::not_a_lane_value, true, true, false, + "mesh readfirstlane source is not an SGPR, a constant, or a VGPR", false)) + return true; + return false; +} + +bool lowerer_uses_the_decision(const char* root) +{ + std::ifstream in(std::string(root) + "/src/gfx1013_direct_mesh.inl"); + if (!in) return fail("sources", "could not read the mesh lowerer"); + const std::string mesh((std::istreambuf_iterator(in)), std::istreambuf_iterator()); + const auto decision = mesh.find("mesh57_readfirstlane_reason"); + const auto wave = mesh.find("waveReadLaneFirst.i32"); + const auto generic = mesh.find("unsupported mesh instruction or EXEC state: "); + if (decision == std::string::npos || wave == std::string::npos || decision > wave) + return fail("lowerer", "WaveReadLaneFirst is emitted before the readfirstlane decision"); + if (generic == std::string::npos) + return fail("lowerer", "other unsupported instructions no longer name themselves"); + std::ifstream native(std::string(root) + "/src/gfx1013_compute_native.cpp"); + if (!native) return fail("sources", "could not read the native translation unit"); + const std::string cpp((std::istreambuf_iterator(native)), std::istreambuf_iterator()); + if (cpp.find("mesh57_readfirstlane.h") == std::string::npos) + return fail("include", "the native translation unit does not include the decision"); + return false; +} +} + +int main(int argc, char** argv) +{ + if (argc < 2) return fail("usage", "pass the repository root"); + if (words() || lowerer_uses_the_decision(argv[1])) return 1; + return 0; +} diff --git a/tests/native_direct_mesh_check.py b/tests/native_direct_mesh_check.py index 4d2d2b8921..59cd3035f7 100644 --- a/tests/native_direct_mesh_check.py +++ b/tests/native_direct_mesh_check.py @@ -203,8 +203,8 @@ def run(name, words, expected=None): assert re.search(r'xor i1 %\w+, true', text), text assert_position_x(text, r'select i1 %\w+, i32 1, i32 0') varying = [0xd4c2001e, 0x20080] # v_cmp_eq_u32 s[30:31], 0, v0 - run('or-varying-exec-mask', prefix + varying + second + select + program[8:], - 'unsupported mesh instruction or EXEC state: v_readfirstlane_b32') + text = run('or-varying-exec-mask', prefix + varying + second + select + program[8:]) + assert 'waveReadLaneFirst' in text flat = [ *wave, 0xd7650000, 0x100c1, # mbcnt_lo v0, -1, 0 0xd7660000, 0x200c1, # mbcnt_hi v0, -1, v0 @@ -858,12 +858,15 @@ def movv(v,s): return 0x7e000200|(v<<17)|s tail[2] = 0x7e020c13 # v_cvt_f32_u32 v1, s19 feeds POS0.x text = run('uniform-udiv',program[:5]+reciprocal+refine+tail) assert 'storeVertexOutput.f32' in text + assert 'waveReadLaneFirst' not in text varying_reciprocal = reciprocal.copy() varying_reciprocal[0] = 0x7e0c0d00 # v_cvt_f32_u32 v6, v0 (lane index saturated at 32) - readfirstlane_error = 'unsupported mesh instruction or EXEC state: v_readfirstlane_b32' - run('varying-udiv',program[:5]+varying_reciprocal+refine+tail,readfirstlane_error) + def accept_first_lane(name, words): + dumped = run(name, words) + assert 'waveReadLaneFirst' in dumped, dumped + accept_first_lane('varying-udiv', program[:5]+varying_reciprocal+refine+tail) overwrite = [0x7e0c0300] # v_mov_b32 v6, v0 - run('overwritten-udiv',program[:5]+reciprocal+overwrite+refine+tail,readfirstlane_error) + accept_first_lane('overwritten-udiv', program[:5]+reciprocal+overwrite+refine+tail) guard_tail = refine[:1] + reads_group[5:] # Read v6 into s18 and export it. varying_accumulator = [ @@ -871,28 +874,25 @@ def movv(v,s): return 0x7e000200|(v<<17)|s movv(7,242), # v_mov_b32 v7, 1.0 0x560c0ef2, # v_fmac_f32 v6, 1.0, v7 (also reads old v6) ] - run('varying-accumulator', program[:5]+varying_accumulator+guard_tail, - 'native compute +0x20: '+readfirstlane_error) + accept_first_lane('varying-accumulator', program[:5]+varying_accumulator+guard_tail) varying_pair_high = [ movv(8,128), # v_mov_b32 v8, 0 (uniform low word) movv(9,256), # v_mov_b32 v9, v0 (lane-varying high word) 0xd7000006, 0x000210a0, # v_lshrrev_b64 v[6:7], 32, v[8:9] ] - run('varying-pair-high', program[:5]+varying_pair_high+guard_tail, - 'native compute +0x24: '+readfirstlane_error) + accept_first_lane('varying-pair-high', program[:5]+varying_pair_high+guard_tail) sdwa_source = [ movv(7,21), # v_mov_b32 v7, s21 (uniform root constant) 0x360c0ef9, 0x06000607, # v_and_b32 v6, v7, v7 SDWA (src0 BYTE_0, src1 and dst DWORD) ] - run('sdwa-uniform-source', program[:5]+sdwa_source+guard_tail, - 'native compute +0x20: '+readfirstlane_error) + # SDWA and DPP keep the result out of the uniform set, so the read is the wave op. + accept_first_lane('sdwa-uniform-source', program[:5]+sdwa_source+guard_tail) # DPP cannot prove a uniform result even when both inputs are uniform. dpp_source = [movv(7,21), 0x360c0efa, 0xff00e407] - run('dpp-uniform-source', program[:5]+dpp_source+guard_tail, - 'native compute +0x20: '+readfirstlane_error) + accept_first_lane('dpp-uniform-source', program[:5]+dpp_source+guard_tail) partial_write = [ 0xbe96047e, # s_mov_b64 s[22:23], exec (save EXEC) @@ -904,7 +904,7 @@ def movv(v,s): return 0x7e000200|(v<<17)|s 0xbefe04c1, # s_mov_b64 exec, -1 (enable all lanes) ] run('partial-exec-write', program[:5]+partial_write+reads_group[5:], - 'native compute +0x24: '+readfirstlane_error) + 'native compute +0x24: mesh readfirstlane EXEC is not the whole wave') print('mesh allocation, indexed outputs, group exchange and negative controls passed')