From 9886eb8e61fab589e743b83e6367b43dce404423 Mon Sep 17 00:00:00 2001 From: Luuk Motz Date: Tue, 1 Dec 2026 08:55:23 +0100 Subject: [PATCH 01/32] shader: lower s_not_b32, s_brev_b32 and s_bfe_i32 in the mesh frontend The shared scalar ALU already lowers all three, SCC included. The mesh frontend refused them with "unsupported mesh instruction or EXEC state". They now join s_bfe_u32 and s_min_u32 on the shared path, with the same EXEC and VCC destination refusals. On a native Mesh86 capture (1,569 distinct slot 86 programs), these were the first refusal for 555 of them, and 122 more now translate fully. Co-Authored-By: Claude Opus 5.5 --- src/gfx1013_direct_mesh.inl | 4 +++- tests/native_direct_mesh_check.py | 20 ++++++++++++++++++++ 2 files changed, 23 insertions(+), 1 deletion(-) diff --git a/src/gfx1013_direct_mesh.inl b/src/gfx1013_direct_mesh.inl index ee48a603b7..1f16a69a02 100644 --- a/src/gfx1013_direct_mesh.inl +++ b/src/gfx1013_direct_mesh.inl @@ -1827,7 +1827,9 @@ NativeComputeShader lower_mesh(const string &code, const MeshStageLayout &layout const auto sum=ir.binary("add",lo,hi); alu.write(i.dst,sum); alu.write(128,ir.value("zext i1 "+alu.cmp("ne",sum,"0")+" to i32")); - } else if (i.name=="s_bfe_u32" || i.name=="s_min_u32") { + } else if (i.name=="s_bfe_u32" || i.name=="s_min_u32" || i.name=="s_bfe_i32" || + i.name=="s_not_b32" || i.name=="s_brev_b32") { + // The shared scalar ALU lowers each one, SCC included (s_brev_b32 leaves it unchanged). 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"); alu.arithmetic(i,state); diff --git a/tests/native_direct_mesh_check.py b/tests/native_direct_mesh_check.py index 03b310a893..c5e46a2e88 100644 --- a/tests/native_direct_mesh_check.py +++ b/tests/native_direct_mesh_check.py @@ -398,7 +398,27 @@ def run(name, words, expected=None): xor = re.search(r'(%[\w.]+) = xor i32 -2, -1\n', text) assert xor, text assert_position_x(text, r'and i32 ' + re.escape(xor[1]) + ',') + # s_not_b32, s_brev_b32 and s_bfe_i32 on the same s20 = -2 go through the shared scalar ALU. + movk = 0xb014fffe # s_movk_i32 s20, 0xfffe + use = 0x36020015 # v_and_b32 v1, s21, v0 + text = run('scalar-not', program[:5] + [movk, 0xbe950714, use] + program[6:]) # s_not_b32 s21, s20 + inverted = re.search(r'(%[\w.]+) = xor i32 -2, -1\n', text) + assert inverted, text + assert_position_x(text, r'and i32 ' + re.escape(inverted[1]) + ',') + text = run('scalar-brev', program[:5] + [movk, 0xbe950b14, use] + program[6:]) # s_brev_b32 s21, s20 + reversed_bits = re.search(r'(%[\w.]+) = call i32 @dx\.op\.unary\.i32\(i32 30, i32 -2\)', text) + assert reversed_bits, text + assert_position_x(text, r'and i32 ' + re.escape(reversed_bits[1]) + ',') + # s_bfe_i32 s21, s20, 0x80004: 8 bits from bit 4, sign-extended (an arithmetic shift, not a logical one). + text = run('scalar-bfe-i32', program[:5] + [movk, 0x9415ff14, 0x00080004, use] + program[6:]) + signed = re.search(r'(?P%[\w.]+) = ashr i32 -2, %[\w.]+\n.*?' + r'(?P%[\w.]+) = shl i32 (?P=shifted), (?P%[\w.]+)\n' + r'\s*%[\w.]+ = ashr i32 (?P=up), (?P=pad)\n', text, re.S) + assert signed and not re.search(r'= lshr i32 -2,', text), text for scalar_k_case, scalar_k_word, scalar_k_reason in ( + ('scalar-not-exec', 0xbefe0714, 'mesh scalar write to EXEC'), # s_not_b32 exec_lo, s20 + ('scalar-brev-vcc', 0xbeea0b14, 'mesh scalar write to VCC'), # s_brev_b32 vcc_lo, s20 + ('scalar-not-vcc-hi', 0xbeeb0714, 'mesh scalar write to VCC'), # s_not_b32 vcc_hi, s20 ('scalar-movk-vcc', 0xb06afffe, 'unsupported mesh instruction or EXEC state: s_movk_i32'), ('scalar-movk-exec', 0xb07efffe, 'unsupported mesh instruction or EXEC state: s_movk_i32'), ('scalar-movk-m0', 0xb07cfffe, 'unsupported mesh instruction or EXEC state: s_movk_i32'), From a6602c755b1274cf24f14500491fbbb9a1f223d8 Mon Sep 17 00:00:00 2001 From: Luuk Motz Date: Tue, 1 Dec 2026 09:33:01 +0100 Subject: [PATCH 02/32] tests: pin SCC for s_brev_b32 and s_not_b32 in the mesh frontend Review follow-up on #3708. After s_cmp_eq_u32 s20, 0, an s_cselect_b32 behind s_brev_b32 still selects on the compare's SCC, and behind s_not_b32 on (result != 0). Both selects reach the exported X. Co-Authored-By: Claude Opus 5.5 --- tests/native_direct_mesh_check.py | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/tests/native_direct_mesh_check.py b/tests/native_direct_mesh_check.py index c5e46a2e88..68b4bb360a 100644 --- a/tests/native_direct_mesh_check.py +++ b/tests/native_direct_mesh_check.py @@ -415,6 +415,24 @@ def run(name, words, expected=None): r'(?P%[\w.]+) = shl i32 (?P=shifted), (?P%[\w.]+)\n' r'\s*%[\w.]+ = ashr i32 (?P=up), (?P=pad)\n', text, re.S) assert signed and not re.search(r'= lshr i32 -2,', text), text + # SCC: s_cmp_eq_u32 s20, 0 sets it, then s_cselect_b32 s21, 1, 0 reads it after the op. + # s_brev_b32 leaves the compare's SCC; s_not_b32 replaces it with (result != 0). + compare, cselect = 0xbf068014, 0x85158081 + text = run('scalar-brev-keeps-scc', program[:5] + [movk, compare, 0xbe960b14, # s_brev_b32 s22, s20 + cselect, use] + program[6:]) + kept_scc = re.search(r'(?P%[\w.]+) = icmp eq i32 -2, 0\n\s*(?P%[\w.]+) = zext i1 (?P=cmp) to i32\n.*?' + r'(?P%[\w.]+) = icmp ne i32 (?P=scc), 0\n\s*' + r'(?P%[\w.]+) = select i1 (?P=test), i32 1, i32 0\n', text, re.S) + assert kept_scc, text + assert_position_x(text, r'and i32 ' + re.escape(kept_scc['pick']) + ',') + text = run('scalar-not-sets-scc', program[:5] + [movk, compare, 0xbe960714, # s_not_b32 s22, s20 + cselect, use] + program[6:]) + not_scc = re.search(r'(?P%[\w.]+) = xor i32 -2, -1\n.*?' + r'(?P%[\w.]+) = icmp ne i32 (?P=not), 0\n\s*(?P%[\w.]+) = zext i1 (?P=nz) to i32\n.*?' + r'(?P%[\w.]+) = icmp ne i32 (?P=scc), 0\n\s*' + r'(?P%[\w.]+) = select i1 (?P=test), i32 1, i32 0\n', text, re.S) + assert not_scc, text + assert_position_x(text, r'and i32 ' + re.escape(not_scc['pick']) + ',') for scalar_k_case, scalar_k_word, scalar_k_reason in ( ('scalar-not-exec', 0xbefe0714, 'mesh scalar write to EXEC'), # s_not_b32 exec_lo, s20 ('scalar-brev-vcc', 0xbeea0b14, 'mesh scalar write to VCC'), # s_brev_b32 vcc_lo, s20 From 31cc179390e805ea90fef85f787fb594d1144fa0 Mon Sep 17 00:00:00 2001 From: Roland Edi Date: Tue, 1 Dec 2026 11:12:10 +0000 Subject: [PATCH 03/32] runtime: refresh large placed Mesh86 material SRVs Adopt the existing committed desktop backing for a placed material view, refresh it from title memory at submit, and copy only changed runs. Keep the existing backing and its fences; a submitted GPU write stops refreshes. Add a source-built two-SRV fixture with range, token, stale, budget and mutant controls. Refs #3640, #3638, #3545. --- CMakePresets.json | 4 +- docs/experiments.md | 9 + docs/experiments/mesh86-pixel-execz.md | 45 +- src/startup_stubs/d3d12_compute_dispatch.inl | 1 + src/startup_stubs/d3d12_draw.inl | 18 +- src/startup_stubs/d3d12_xs_device.cpp | 64 +- src/startup_stubs/linear_buffer_backing.h | 158 ++++- src/startup_stubs/linear_buffer_report.h | 4 +- src/startup_stubs/list_copy.inl | 28 +- .../startup_mesh86_material_backing.cmake | 17 + tests/startup_mesh86_material_backing.cpp | 549 ++++++++++++++++++ 11 files changed, 861 insertions(+), 36 deletions(-) create mode 100644 tests/cmake/startup_mesh86_material_backing.cmake create mode 100644 tests/startup_mesh86_material_backing.cpp diff --git a/CMakePresets.json b/CMakePresets.json index 6bd4804f08..ec63263762 100644 --- a/CMakePresets.json +++ b/CMakePresets.json @@ -34,7 +34,7 @@ "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", - "xmem_page_runs_device_check", "linear_buffer_backing_check", + "xmem_page_runs_device_check", "linear_buffer_backing_check", "startup_mesh86_material_backing", "bcpack_formats_check", "startup_stub_consumer", "startup_inline_retire", "startup_resource_retire_title", "startup_table_lock", "native_compute_ir_dump", "native_pixel_ir_dump", "native_store_replay", "native_raw_buffer_view_check" ] @@ -50,7 +50,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|startup_mesh57_runtime(_[a-z]+)?_warp|native_fixed_mesh57_published_pair(_refusal)?_warp|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_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|native_.*_(ir|dxil|controls)|native_direct_mesh|startup_triage_run)$" + "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|startup_mesh57_runtime(_[a-z]+)?_warp|native_fixed_mesh57_published_pair(_refusal)?_warp|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_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_mesh86_material_backing(_mutant)?_warp|startup_stage_package|startup_compute_packed_d16_x_uav_reference|native_.*_(ir|dxil|controls)|native_direct_mesh|startup_triage_run)$" } } }, diff --git a/docs/experiments.md b/docs/experiments.md index 1b446afa25..fc5d3bb935 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -11162,6 +11162,15 @@ Run `python -B tests/startup_mesh86_srv_proof_check.py` to check the load count without DXC. The synthetic DXIL dump passes with one DWORD load and is rejected when a second identical load uses the same SRV handle. +The placed material-buffer backing has its own source-built fixture: one 64 KiB +placed buffer at an unaligned title address, two raw SRVs at different offsets, +a submitted GPU readback, a stale token, a UAV token and out-of-range records. +Run `ctest --preset release --no-tests=error -R +'^startup_mesh86_material_backing_(warp|hardware)$' --output-on-failure`; the +mutant entries keep the bytes visible at adoption and must fail. The fixture +reports refresh bytes (65,536 first, 4 per changed word) and the reused backing; +see [the mesh86 note](experiments/mesh86-pixel-execz.md#material-placed-buffer-backing). + On the Release worktree at `76aeef7f` plus these changes, the combined lease, SRV proof, export and mapped-page selection passed eight tests. The two mesh cases returned 77 on the adapters listed above. `dumpbin /exports` showed diff --git a/docs/experiments/mesh86-pixel-execz.md b/docs/experiments/mesh86-pixel-execz.md index d6a8711a6d..6d3c579b00 100644 --- a/docs/experiments/mesh86-pixel-execz.md +++ b/docs/experiments/mesh86-pixel-execz.md @@ -92,8 +92,47 @@ resource. Verified GPU-backed views can span more than 16 MiB up to the desktop raw SRV limit. A local runtime sample created and selected four desktop Mesh PSOs and -observed their direct dispatch calls. All sampled scene dispatches stopped at -resource binding. One needed a 128-byte root SRV with no mapped backing. The -other three needed a large placed buffer view whose desktop backing did not +observed their direct dispatch calls. At the time of that sample, all scene +dispatches stopped at resource binding. One needed a 128-byte root SRV with no +mapped backing. The other three needed a large placed buffer view whose desktop +backing did not alias the guest memory or have a verified GPU producer. Visible scene output remains unverified. + +## Material placed-buffer backing + +A native Mesh86 material SRV on a placed buffer whose desktop backing does not +alias title memory no longer stops the bind. The material path adopts the +existing committed desktop resource through the linear-buffer refresh path +(`linear_buffer_backing.h`): the first submission before a consumer copies the +title range, later submissions compare 4 KiB blocks and copy contiguous changed +runs (runs separated by at most one block are merged; more than 1024 runs fall +back to one span). The consumer queue waits for the refresh fence, and a refresh +waits for earlier tracked submissions. The placed backing is reused, so adoption +adds no default-heap VRAM. A submitted copy or bound UAV makes the +desktop bytes authoritative and stops the refreshes. + +The source-built fixture places a 64 KiB buffer at an unaligned title address, +so slot 133 keeps a committed default backing. Two raw SRVs at offsets 0 and +`0x8000` are read by one compute dispatch; the readback distinguishes the two +values. Changing one title word changes only that SRV's value, and the refresh +copies four bytes; two disjoint changed words copy two four-byte runs. Sentinels +outside the placed range stay unchanged. The controls refuse an out-of-range +record, a record over the raw-SRV limit, a UAV view token and a released +resource. The fixture reports one adopted backing and no linear placement. + +```powershell +ctest --preset release --no-tests=error -R '^startup_mesh86_material_backing_(warp|hardware)$' --output-on-failure +ctest --preset release --no-tests=error -R '^startup_mesh86_material_backing_mutant_(warp|hardware)$' --output-on-failure +``` + +The mutant keeps the bytes visible at adoption; both normal tests must pass and +both mutant tests must fail (the CTest entries use `WILL_FAIL`). + +Limits. Adoption does not see a GPU write submitted before the first material +bind; only writes recorded on the current recording or tracked through a +submitted copy stop a refresh. The changed-run comparison runs at each submit +over the whole resource and the first refresh copies it whole, so a 174 MiB +resource still costs a 174 MiB compare per submission even when few bytes +changed. The fixture measures refresh bytes and the reused backing; it does not +measure frame time or peak VRAM against the DXGI budget on a title scene. diff --git a/src/startup_stubs/d3d12_compute_dispatch.inl b/src/startup_stubs/d3d12_compute_dispatch.inl index e32e1246d8..a58d6ddbe7 100644 --- a/src/startup_stubs/d3d12_compute_dispatch.inl +++ b/src/startup_stubs/d3d12_compute_dispatch.inl @@ -1630,6 +1630,7 @@ const char* record_translated_dispatch(Wrapper* self, const TranslatedDispatch& buffer_view(dest, view.resource, view.offset, static_cast(view.bytes)); continue; } + note_linear_gpu_write_resource(self, view.resource); require_state(self, view.resource, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); if (view.texture || view.described) { device_of(the_device)->CreateUnorderedAccessView(view.resource, nullptr, diff --git a/src/startup_stubs/d3d12_draw.inl b/src/startup_stubs/d3d12_draw.inl index 2b79836af2..d290abc259 100644 --- a/src/startup_stubs/d3d12_draw.inl +++ b/src/startup_stubs/d3d12_draw.inl @@ -2684,7 +2684,7 @@ struct IndirectBufferView { u64 offset = 0, bytes = 0; UINT stride = 0; bool upload = false; - int source = 0; // 0 aliased or any other backing, 1 a GPU copy this list made (X2W_TRANSLATED_INDIRECT_COPY_RANGES), 2 a snapshot of title memory, 3 zeros for a null descriptor + int source = 0; // 0 aliased or any other backing, 1 a GPU copy this list made (X2W_TRANSLATED_INDIRECT_COPY_RANGES) or a GPU-written backing, 2 a snapshot of title memory, 3 zeros for a null descriptor, 4 a placed material backing refreshed from title memory at submit u64 snapshot_address = 0; // title address for a pending snapshot (source 2 with no resource) }; @@ -2891,6 +2891,21 @@ IndirectBufferView indirect_table_buffer(Wrapper* self, const std::uint32_t* wor if (!placed.alias) { if (native && indirect_table_copied_gpu_range(self, native, offset, bytes)) { input_source = 1; // a GPU copy of this list filled the range: the GPU buffer is the truth + } else if (use == InputBufferUse::mesh86_material && native && linear_buffers().written_by_gpu(native)) { + input_source = 1; // a submitted GPU write filled the backing: the desktop bytes are the truth + } else if (use == InputBufferUse::mesh86_material && native) { + // The placed backing exists but does not alias title memory. Adopt that same resource: the + // linear-buffer path refreshes it from the title bytes before the recording executes, copies + // only the changed span after the first refresh, and orders the consumer behind its fence. No + // second default-heap buffer is allocated. + X2wLinearBufferInfo info{}; + if (SUCCEEDED(linear_buffers().adopt(device_of(device), native, owner->own().title_memory, + native->GetDesc().Width, &info))) + input_source = 4; + else { + diag_placed_refusal(self, native, offset, bytes, placed_context); + return refuse("a placed material buffer has no coherent desktop backing"); + } } else if (allow_title_snapshot && title_input_snapshot_enabled() && bytes <= (u64{16} << 20)) { // The desktop buffer does not alias title memory. Resolve the title range here and let the // dispatch copy it after its outputs have been validated. @@ -4050,6 +4065,7 @@ bool draw_translated(Wrapper* self, bool indexed, UINT count, UINT instances, UI } for (UINT j = 0; j < tr->uavs.size(); ++j) { const D3D12_CPU_DESCRIPTOR_HANDLE dest{draw_heap->GetCPUDescriptorHandleForHeapStart().ptr + SIZE_T{first + n + j} * draw_heap_increment}; + note_linear_gpu_write_resource(self, uav_bindings[j].resource); require_state(self, uav_bindings[j].resource, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); if (tr->uavs[j].raw) { D3D12_RESOURCE_BARRIER barrier{}; diff --git a/src/startup_stubs/d3d12_xs_device.cpp b/src/startup_stubs/d3d12_xs_device.cpp index 6a852b1847..96fa7772fe 100644 --- a/src/startup_stubs/d3d12_xs_device.cpp +++ b/src/startup_stubs/d3d12_xs_device.cpp @@ -1468,6 +1468,13 @@ x2w_startup::LinearBuffers& linear_buffers() static x2w_startup::LinearBuffers buffers; return buffers; } + +// Linear-buffer refresh and queue ordering run when the opt-in placements are on, or once a placed +// material backing has adopted its existing desktop resource (which happens without the switch). +bool linear_tracking() +{ + return linear_buffers().ever_active(); +} // The wrappers and their desktop objects stay alive for the process (experiment scope). The one exception is // X2W_D3D12_RELEASE_RETIRED=1: the desktop object of a resource of the retire class is freed once nothing refers to it. // The wrapper stays. @@ -1509,8 +1516,8 @@ ULONG __stdcall release(Wrapper* self) drop_mesh_lease_owner(self); retire_placement(self); if (self->own().retire_when_idle) retire_note_title_release(self); - if (x2w_startup::linear_buffer_mode() != x2w_startup::LinearBufferMode::off) - linear_buffers().retire(static_cast(self->own().real)); + // Idempotent: an adopted placed material backing also has to stop reading title memory. + linear_buffers().retire(static_cast(self->own().real)); } if (self->own().kind == list_kind && self->own().real) { if (indirect_cross_list_copy()) indirect_copy_tracker().reset(self); @@ -1829,6 +1836,7 @@ void end_open_queries(Wrapper* self, ID3D12GraphicsCommandList* list); void reset_list_dynamic_state(Wrapper* self); void discard_list_gpu_writes(Wrapper* self); void commit_list_gpu_writes(Wrapper* self); +void note_linear_gpu_write_resource(Wrapper* self, ID3D12Resource* resource); void discard_address_uploads(ID3D12CommandList* list); void use_as_target(Wrapper* self, ID3D12Resource* resource); bool is_container(const void* p); @@ -2331,8 +2339,7 @@ extern "C" __declspec(dllexport) void x2w_d3d12_render_target_stats(unsigned* bi extern "C" __declspec(dllexport) bool x2w_d3d12_linear_buffer_info(void* resource, X2wLinearBufferInfo* info) { Wrapper* w = as_wrapper(resource); - if (!info || !w || w->own().kind != resource_kind || !w->own().real || - x2w_startup::linear_buffer_mode() == x2w_startup::LinearBufferMode::off) + if (!info || !w || w->own().kind != resource_kind || !w->own().real) return false; return linear_buffers().info(static_cast(w->own().real), info); } @@ -2340,7 +2347,7 @@ extern "C" __declspec(dllexport) void x2w_d3d12_linear_buffer_totals(X2wLinearBu { if (!totals) return; *totals = X2wLinearBufferTotals{}; - if (x2w_startup::linear_buffer_mode() != x2w_startup::LinearBufferMode::off) linear_buffers().totals(totals); + linear_buffers().totals(totals); } // Fixtures: the next refresh that reaches `point` (0 before staging, 1 after the title bytes are staged, // 2 after its copy was executed, before it is published), or for point 3 the next title Wait (queue slot 17) @@ -5667,8 +5674,9 @@ void __stdcall list_dispatch_mesh(Wrapper* self, UINT x, UINT y, UINT z) } #endif -// X2W_D3D12_LINEAR_BUFFERS: the copied linear buffers are refreshed from title memory on the internal -// refresh queue, and queue waits for those refreshes, just before the title's lists. A refresh that +// X2W_D3D12_LINEAR_BUFFERS, or an adopted placed material backing: the copied buffers are refreshed +// from title memory on the internal refresh queue, and queue waits for those refreshes, just before +// the title's lists. A refresh that // fails leaves that buffer stale (logged, counted); the lists run either way. False: a refresh had no // safe completion order and the submission is refused (logged, counted): nothing was enqueued, and the // caller drops the title's lists without executing them or committing their bookkeeping. The title's @@ -5676,20 +5684,21 @@ void __stdcall list_dispatch_mesh(Wrapper* self, UINT x, UINT y, UINT z) // waits on it. bool linear_refresh(ID3D12CommandQueue* queue) { - return x2w_startup::linear_buffer_mode() == x2w_startup::LinearBufferMode::off || linear_buffers().before_submit(queue); + return !linear_tracking() || linear_buffers().before_submit(queue); } // After the title's lists on queue: a later refresh's copy waits for this submission (the producer wait). void linear_submitted(ID3D12CommandQueue* queue) { - if (x2w_startup::linear_buffer_mode() != x2w_startup::LinearBufferMode::off) linear_buffers().after_submit(queue); + if (linear_tracking()) linear_buffers().after_submit(queue); } // The queue's order lock (linear_buffer_backing.h), so its title waits and user fence values are recorded in // the order the desktop queue receives them: held by a submission from its ExecuteCommandLists through // linear_submitted, and by queue slot 17 from the desktop Wait through note_title_wait. Taken before -// draw_lock and allocator_lock and with no other lock held; nothing while the switch is off. +// draw_lock and allocator_lock and with no other lock held; nothing until the switch or an adoption +// enables tracking. x2w_startup::LinearBuffers::QueueOrder linear_queue_order(ID3D12CommandQueue* queue, bool title_wait) { - if (x2w_startup::linear_buffer_mode() == x2w_startup::LinearBufferMode::off) return {}; + if (!linear_tracking()) return {}; return linear_buffers().queue_order(queue, title_wait); } @@ -5928,8 +5937,7 @@ u64 __stdcall queue_wait(Wrapper* self, u64 rdx, u64 r8, u64 r9) { const auto order = linear_queue_order(queue, true); hr = queue->Wait(static_cast(fence->own().real), r8); - if (SUCCEEDED(hr) && x2w_startup::linear_buffer_mode() != x2w_startup::LinearBufferMode::off) - linear_buffers().note_title_wait(queue, static_cast(fence->own().real), r8); + if (SUCCEEDED(hr)) linear_buffers().note_title_wait(queue, static_cast(fence->own().real), r8); } static LONG calls; if (first_calls(calls, 2)) @@ -9436,3 +9444,33 @@ HRESULT x2w_d3d12_permissive_create_device(IUnknown* adapter, const void* parame if (debug) device->QueryInterface(IID_PPV_ARGS(&info_queue)); return S_OK; } + +// Fixture-only entry point: resolve one eight-word material table record through the production +// Mesh86 material path (indirect_table_buffer with InputBufferUse::mesh86_material), on an open +// recording. The fixture can then submit a read of the returned backing through the queue wrapper, +// which exercises the refresh and its fences without needing a captured guest shader. +extern "C" __declspec(dllexport) HRESULT x2w_d3d12_mesh86_material_resolve( + void* guest_list, const UINT* words, ID3D12Resource** out_resource, UINT64* out_offset, UINT64* out_bytes, + int* out_source, const char** out_reason) +{ + if (!out_resource || !out_offset || !out_bytes || !out_source || !out_reason) return E_POINTER; + *out_resource = nullptr; + *out_offset = *out_bytes = 0; + *out_source = 0; + *out_reason = nullptr; + Wrapper* self = as_wrapper(guest_list); + if (!self || self->own().kind != list_kind || !self->own().list_open || !render_mode()) return E_UNEXPECTED; + const char* why = nullptr; + const auto view = indirect_table_buffer(self, words, false, &why, u64{4} << D3D12_REQ_BUFFER_RESOURCE_TEXEL_COUNT_2_TO_EXP, + D3D12_RAW_UAV_SRV_BYTE_ALIGNMENT, true, false, nullptr, nullptr, nullptr, + InputBufferUse::mesh86_material); + *out_resource = view.resource; + *out_offset = view.offset; + *out_bytes = view.bytes; + *out_source = view.source; + if (!view.resource) { + *out_reason = why ? why : "a material buffer has no desktop resource"; + return E_FAIL; + } + return S_OK; +} diff --git a/src/startup_stubs/linear_buffer_backing.h b/src/startup_stubs/linear_buffer_backing.h index 18c9a9278e..8c6f234952 100644 --- a/src/startup_stubs/linear_buffer_backing.h +++ b/src/startup_stubs/linear_buffer_backing.h @@ -35,6 +35,17 @@ // record. Only the bytes that differ from the last upload are copied, through an upload staging // buffer. // +// Adoption. A placed buffer that already has a committed default backing (slot 133's placement when +// the title memory cannot be aliased) can be adopted for a read-only material view instead of being +// refused. The existing backing is reused, so adoption adds no default-heap VRAM; its first refresh +// copies the title range because nothing is known about the backing's bytes yet, and later +// submissions copy only the changed runs. Adoption is only for a range validated against the +// resource, whose backing has no recorded GPU write, and which the caller binds as an SRV. A recorded +// GPU write (copy or bound UAV) makes the desktop backing authoritative: refreshes stop, as +// they do for a copied placement. The caller still owns placement, retention and range validation; +// this file owns the refresh and its fences. A GPU write already submitted before the first adoption +// is not seen; the caller may only adopt a range whose earlier GPU use was read-only. +// // Every refresh runs on one internal COPY queue per device, which never waits on a title fence. A // refresh's copy (staging -> backing) is executed there and signals an internal fence value; the // buffer remembers the value of its last refresh. Every submission through a queue wrapper, on any @@ -423,6 +434,99 @@ class LinearBuffers { } } + // A placed material view resolved a buffer whose desktop backing does not alias title memory and + // whose range has no recorded GPU producer. Adopt that existing backing for refresh at submit: + // no new default-heap resource is created, and the first refresh establishes the authoritative + // copy from the title bytes. S_FALSE: this resource is shared/aliased, so no refresh is needed. + // Failure: the caller refuses the material view. + HRESULT adopt(ID3D12Device* device, ID3D12Resource* resource, const void* title, UINT64 bytes, + X2wLinearBufferInfo* report) + { + if (report) *report = X2wLinearBufferInfo{}; + if (!device || !resource || !title || !bytes) return E_INVALIDARG; + const auto desc = resource->GetDesc(); + if (desc.Dimension != D3D12_RESOURCE_DIMENSION_BUFFER || bytes > desc.Width) return E_INVALIDARG; + std::lock_guard lock(mutex_); + if (const auto found = records_.find(resource); found != records_.end()) { + if (found->second.info.path == shared_path) { + if (report) *report = found->second.info; + return S_FALSE; + } + if (const Copied* copy = found->second.copy.get()) { + if (copy->gpu_written) return E_INVALIDARG; + if (!found->second.info.adopted) { + found->second.info.adopted = 1; + ++totals_.adopted; + } + adopted_.store(true); + if (report) *report = found->second.info; + return S_OK; + } + } + if (x2w_local::probe_readable(reinterpret_cast(title), static_cast(bytes)) < bytes) + return E_INVALIDARG; // a partial title range cannot establish a coherent whole backing + const HRESULT internal = linear_detail::submit_fence_forced_off() ? E_NOT_VALID_STATE : internal_ready(device); + if (FAILED(internal)) { + if (report) { + report->path = kept_default_path; + report->refusal_hr = internal; + report->backing = resource; + } + return internal; + } + Record record{}; + record.info.use = gpu_read; + record.info.path = copied_path; + record.info.refusal_hr = S_OK; + record.info.feature_hr = S_FALSE; + record.info.share_hr = S_FALSE; + record.info.backing = resource; + record.info.adopted = 1; + try { + record.copy = std::make_shared(); + record.copy->title = static_cast(title); + record.copy->bytes = bytes; + if (linear_detail::mutant("skip-refresh")) { + // Negative control: the bytes at adoption are all every submission gets. + record.copy->bound.resize(static_cast(bytes)); + if (!x2w_local::guarded_memcpy(record.copy->bound.data(), title, static_cast(bytes), false)) + return E_INVALIDARG; + } + records_.insert_or_assign(resource, std::move(record)); + } catch (const std::bad_alloc&) { + return E_OUTOFMEMORY; + } + ++totals_.adopted; + adopted_.store(true); + if (x2w_local::first_calls(adopt_logged_, 8)) + x2w_local::logf("x2w-d3d12 linear buffer %p: adopted its existing placed backing for material refresh, " + "%llu bytes", static_cast(resource), static_cast(bytes)); + if (report) *report = records_.at(resource).info; + return S_OK; + } + + // A queue submission (or a title wait) can name an adopted or copied backing. Once true, queue + // submissions and slot 17 waits take the per-queue order lock for the process lifetime, so a + // wait recorded after the first adoption is still ordered with submissions. + bool ever_active() const { return adopted_.load() || linear_buffer_mode() != LinearBufferMode::off; } + + // This resource has an adopted or copied backing that a later GPU write must stop refreshing. + bool watching(ID3D12Resource* resource) + { + std::lock_guard lock(mutex_); + const auto found = records_.find(resource); + return found != records_.end() && found->second.copy && found->second.copy->live && + !found->second.copy->gpu_written; + } + + // The desktop backing holds bytes a submitted GPU command wrote; title memory is stale from then on. + bool written_by_gpu(ID3D12Resource* resource) + { + std::lock_guard lock(mutex_); + const auto found = records_.find(resource); + return found != records_.end() && found->second.copy && found->second.copy->gpu_written; + } + // A submitted recording writes the backing of `resource` (list_copy.inl, after its ExecuteCommandLists): // if it is a copied buffer, it keeps the GPU's bytes from now on and is no longer refreshed from the // title memory. @@ -501,20 +605,42 @@ class LinearBuffers { ++totals_.unreadable; continue; } - std::size_t first = 0, last = bytes; - if (copy->uploaded.size() == bytes) { - if (std::memcmp(copy->uploaded.data(), source, bytes) == 0) { - copy->stale = false; - continue; - } - while (first < bytes && copy->uploaded[first] == source[first]) ++first; - while (last > first && copy->uploaded[last - 1] == source[last - 1]) --last; - first &= ~std::size_t{3}; - last = (std::min)(bytes, (last + 3) & ~std::size_t{3}); - } + // The first refresh copies the whole range: the backing's bytes are not known. After that, + // compare 4 KiB blocks and copy contiguous changed runs. Runs with a gap of at most one + // block are merged, so a scattered set of changed pages costs one copy per region rather + // than one copy from the first to the last changed byte. More than 1024 runs fall back to + // one span; every work item has its own staging buffer, so this bounds the pool. + const std::size_t work_before = work.size(); try { - work.push_back({resource, copy, source, first, last - first}); + std::vector> runs; + if (copy->uploaded.size() == bytes) { + constexpr UINT64 block = 4096; + for (UINT64 at = 0; at < bytes; at += block) { + const UINT64 size = (std::min)(block, bytes - at); + const unsigned char* old_bytes = copy->uploaded.data() + at; + const unsigned char* new_bytes = source + at; + if (std::memcmp(old_bytes, new_bytes, static_cast(size)) == 0) continue; + UINT64 first = 0, last = size; + while (first < size && old_bytes[first] == new_bytes[first]) ++first; + while (last > first && old_bytes[last - 1] == new_bytes[last - 1]) --last; + first = at + (first & ~UINT64{3}); + last = (std::min)(bytes, at + ((last + 3) & ~UINT64{3})); + if (!runs.empty() && first - runs.back().second <= block) runs.back().second = last; + else runs.push_back({first, last}); + } + if (runs.empty()) { + copy->stale = false; + continue; + } + if (runs.size() > 1024) runs = {{runs.front().first, runs.back().second}}; + } else { + runs.push_back({0, bytes}); + } + for (const auto& [offset, end] : runs) { + work.push_back({resource, copy, source, offset, end - offset}); + } } catch (const std::bad_alloc&) { + work.resize(work_before); refresh_failed(resource, *copy, E_OUTOFMEMORY); } } @@ -680,6 +806,7 @@ class LinearBuffers { out->gpu_written = copy->gpu_written ? 1 : 0; out->refresh_failures = copy->refresh_failures; out->last_refresh_hr = copy->last_refresh_hr; + out->adopted = found->second.info.adopted; } return true; } @@ -744,7 +871,8 @@ class LinearBuffers { UINT64 generation, bytes; x2w_budget::Ticket* budget; // the heap's budget ticket (X2W_D3D12_BUDGET), counted while a buffer uses it }; - // 256 staging buffers; X2W_TEST_LINEAR_STAGING_LIMIT= (fixtures) lowers it, to make the pool fill. + // 2048 staging buffers (one per changed run); X2W_TEST_LINEAR_STAGING_LIMIT= (fixtures) lowers it, + // to make the pool fill. static std::size_t staging_limit() { static const std::size_t limit = [] { @@ -753,7 +881,7 @@ class LinearBuffers { const DWORD n = GetEnvironmentVariableA("X2W_TEST_LINEAR_STAGING_LIMIT", value, sizeof(value)); SetLastError(saved); const unsigned long parsed = n && n < sizeof(value) ? std::strtoul(value, nullptr, 10) : 0; - return parsed ? static_cast(parsed) : std::size_t{256}; + return parsed ? static_cast(parsed) : std::size_t{2048}; }(); return limit; } @@ -1255,10 +1383,12 @@ class LinearBuffers { std::atomic pauses_armed_{false}; ID3D12Device* feature_device_ = nullptr; HRESULT feature_hr_ = S_FALSE; + std::atomic adopted_{false}; // a placed material backing adopted its existing desktop resource UINT64 generation_ = 0, staging_ids_ = 0, staging_requests_ = 0; std::size_t creating_ = 0; // staging buffers being created outside the lock X2wLinearBufferTotals totals_{}; volatile LONG unreadable_logged_ = 0, wait_logged_ = 0, refresh_logged_ = 0, gpu_write_logged_ = 0, unsafe_logged_ = 0; + volatile LONG adopt_logged_ = 0; }; } // namespace x2w_startup diff --git a/src/startup_stubs/linear_buffer_report.h b/src/startup_stubs/linear_buffer_report.h index 107ca76e28..2ec2d27efd 100644 --- a/src/startup_stubs/linear_buffer_report.h +++ b/src/startup_stubs/linear_buffer_report.h @@ -15,17 +15,19 @@ struct X2wLinearBufferInfo { std::uint32_t stale; // copied: 1 while the backing holds an older upload than the title's bytes std::uint64_t heap_generation; // shared: generation of the opened heap void* backing; // the desktop ID3D12Resource - std::uint64_t refreshes; // copied: submissions that copied bytes into the backing + std::uint64_t refreshes; // copied: changed spans copied into the backing (a submission may have several) std::uint64_t bytes_copied; // copied: bytes copied from title memory into the backing std::uint64_t last_staging; // copied: id of the staging buffer of the last refresh (0: none) std::uint64_t last_fence; // copied: internal fence value of the last refresh (0: none) std::uint64_t refresh_failures; // copied: submissions that ran without this buffer's refresh std::int32_t last_refresh_hr; // copied: HRESULT of the last failed refresh; S_OK if none std::uint32_t gpu_written; // copied: 1 once a submitted copy wrote it; it is no longer refreshed + std::uint32_t adopted; // copied: 1 when a placed material view adopted this existing backing }; struct X2wLinearBufferTotals { std::uint64_t placements, shared, copied, kept_default; + std::uint64_t adopted; // existing placed backings refreshed for material views std::uint64_t feature_queries, heap_opens, heap_open_failures, heap_cache_hits, place_failures; std::uint64_t submissions, refreshes, bytes_copied, staging_created, staging_reused, unreadable; std::uint64_t refresh_failures; diff --git a/src/startup_stubs/list_copy.inl b/src/startup_stubs/list_copy.inl index 6d3ac77b6e..69f90cbfd3 100644 --- a/src/startup_stubs/list_copy.inl +++ b/src/startup_stubs/list_copy.inl @@ -170,8 +170,7 @@ void mark_gpu_written(Wrapper* self, const CopyEndpoint& destination) // Until then the write is pending on the recording: Reset or a failed Close drops it with the texture writes. void note_linear_gpu_write(Wrapper* self, const CopyEndpoint& destination) { - if (!destination.wrapper || !destination.wrapper->own().title_memory || - x2w_startup::linear_buffer_mode() == x2w_startup::LinearBufferMode::off) + if (!destination.wrapper || !destination.wrapper->own().title_memory) return; if (x2w_startup::linear_detail::mutant("gpuw-at-record")) { // Mutant: the backing changes at recording, so a discarded recording still stops its refreshes. @@ -184,6 +183,31 @@ void note_linear_gpu_write(Wrapper* self, const CopyEndpoint& destination) ReleaseSRWLockExclusive(&pending_writes_lock); } +// A translated draw or dispatch binds `resource` as a UAV. Keep the write pending on the recording, +// like a recorded copy: only a submitted recording makes the desktop bytes authoritative, and a +// discarded recording leaves the adopted backing refreshed from title memory. +void note_linear_gpu_write_resource(Wrapper* self, ID3D12Resource* resource) +{ + if (!resource) return; + if (x2w_startup::linear_detail::mutant("gpuw-at-record")) { + linear_buffers().note_gpu_write(resource); + return; + } + AcquireSRWLockExclusive(&pending_writes_lock); + auto& writes = pending_linear_writes()[self]; + if (std::find(writes.begin(), writes.end(), resource) == writes.end()) { + try { + writes.push_back(resource); + } catch (const std::bad_alloc&) { + // The refresh cannot know about this write: stop refreshing the resource now. + ReleaseSRWLockExclusive(&pending_writes_lock); + linear_buffers().note_gpu_write(resource); + return; + } + } + ReleaseSRWLockExclusive(&pending_writes_lock); +} + // Refusal shared by the three handlers once the descriptions passed, or none. x2w_startup::CopyRefusal check_roles_and_sync(Wrapper* self, const CopyEndpoint& to, const CopyEndpoint& from, bool sync) { diff --git a/tests/cmake/startup_mesh86_material_backing.cmake b/tests/cmake/startup_mesh86_material_backing.cmake new file mode 100644 index 0000000000..d7adf9ade5 --- /dev/null +++ b/tests/cmake/startup_mesh86_material_backing.cmake @@ -0,0 +1,17 @@ +# A placed buffer whose desktop backing does not alias title memory: the Mesh86 material path adopts +# the existing backing, refreshes it at submit, and two GPU SRVs read distinct offsets. The mutant +# test keeps the bytes visible at adoption, so a stale second read must fail. +add_executable(startup_mesh86_material_backing tests/startup_mesh86_material_backing.cpp) +target_compile_features(startup_mesh86_material_backing PRIVATE cxx_std_17) +target_include_directories(startup_mesh86_material_backing PRIVATE src) +target_link_libraries(startup_mesh86_material_backing PRIVATE d3d12_xs_shim d3d12 dxgi d3dcompiler) + +foreach(backend IN ITEMS warp hardware) + add_test(NAME startup_mesh86_material_backing_${backend} COMMAND startup_mesh86_material_backing ${backend}) + set_tests_properties(startup_mesh86_material_backing_${backend} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77 + ENVIRONMENT "X2W_D3D12_PERMISSIVE=1;X2W_D3D12_LIST_NOOP=1;X2W_D3D12_RENDER=1") + add_test(NAME startup_mesh86_material_backing_mutant_${backend} COMMAND startup_mesh86_material_backing ${backend}) + set_tests_properties(startup_mesh86_material_backing_mutant_${backend} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77 + WILL_FAIL TRUE + ENVIRONMENT "X2W_D3D12_PERMISSIVE=1;X2W_D3D12_LIST_NOOP=1;X2W_D3D12_RENDER=1;X2W_TEST_LINEAR_BUFFER_MUTANT=skip-refresh") +endforeach() diff --git a/tests/startup_mesh86_material_backing.cpp b/tests/startup_mesh86_material_backing.cpp new file mode 100644 index 0000000000..132b265fbd --- /dev/null +++ b/tests/startup_mesh86_material_backing.cpp @@ -0,0 +1,549 @@ +// A placed buffer whose desktop backing does not alias title memory, read through the Mesh86 +// material path. The test adopts the existing backing, records two raw SRVs at distinct offsets, +// and reads both through a compute dispatch submitted through the queue wrapper. The first +// submission copies the title range; later submissions copy only the changed span. Controls cover +// an out-of-range record, an oversized record, a UAV view token (wrong type) and a released +// resource. Sentinels outside the placed buffer catch reads of unrelated title memory. +// +// startup_mesh86_material_backing +// +// X2W_TEST_LINEAR_BUFFER_MUTANT=skip-refresh makes adoption keep the bytes visible at adoption, so +// the second and third readbacks are stale; the registered mutant test expects that failure. + +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +#include "../src/startup_stubs/linear_buffer_report.h" +#include "../src/startup_stubs/resource_budget.h" + +extern "C" __declspec(dllimport) HRESULT WINAPI D3D12XboxCreateDevice(IUnknown*, const void*, REFIID, void**); +extern "C" __declspec(dllimport) bool x2w_d3d12_linear_buffer_info(void*, X2wLinearBufferInfo*); +extern "C" __declspec(dllimport) void x2w_d3d12_linear_buffer_totals(X2wLinearBufferTotals*); +extern "C" __declspec(dllimport) BOOL x2w_d3d12_budget_snapshot(x2w_budget::Snapshot*, SIZE_T); +extern "C" __declspec(dllimport) HRESULT x2w_d3d12_mesh86_material_resolve( + void*, const UINT*, ID3D12Resource**, UINT64*, UINT64*, int*, const char**); + +using Microsoft::WRL::ComPtr; + +namespace { +constexpr UINT64 page = 64 * 1024; +constexpr UINT64 buffer_bytes = page; +constexpr UINT64 buffer_offset = 0x1000; // private allocation, not 64 KiB aligned: the default copied placement +constexpr UINT64 second_srv_offset = 0x8000; +constexpr UINT64 allocation_bytes = 3 * page; +constexpr std::uint32_t sentinel = 0xa5a5a5a5u; +constexpr std::uint32_t a0 = 0x11112222u, b0 = 0x33334444u, c0 = 0x55556666u, d0 = 0x77778888u; +constexpr std::uint32_t e0 = 0x9999aaaau, f0 = 0xbbbbccccu; + +unsigned failures = 0; + +void check(bool pass, const char* what) +{ + std::printf("%s: %s\n", pass ? "PASS" : "FAIL", what); + if (!pass) ++failures; +} + +std::string hex(HRESULT hr) +{ + char text[16]; + std::snprintf(text, sizeof(text), "0x%08lx", static_cast(hr)); + return text; +} + +template +Method slot(IUnknown* object, unsigned index) +{ + return reinterpret_cast((*reinterpret_cast(object))[index]); +} + +using Word = std::uint64_t; +Word invoke(void* object, unsigned index, Word a = 0, Word b = 0, Word c = 0, Word d = 0, Word e = 0) +{ + using Slot = Word(WINAPI*)(void*, Word, Word, Word, Word, Word); + return reinterpret_cast((*static_cast(object))[index])(object, a, b, c, d, e); +} +template Word arg(T* value) { return reinterpret_cast(value); } + +// The desktop object behind a wrapper: SetPrivateDataInterface unwraps its argument before the +// call reaches the shared desktop device. +template +ComPtr underlying(ID3D12Device* desktop, ID3D12Device* guest, IUnknown* object) +{ + constexpr GUID key{0x6c1f0a3e, 0x2b51, 0x4d0e, {0x9b, 0x31, 0x5e, 0x0c, 0x72, 0x14, 0x88, 0x19}}; + ComPtr result; + if (FAILED(guest->SetPrivateDataInterface(key, object))) return result; + ComPtr stored; + UINT bytes = sizeof(IUnknown*); + const HRESULT read = desktop->GetPrivateData(key, &bytes, stored.GetAddressOf()); + guest->SetPrivateDataInterface(key, nullptr); + if (SUCCEEDED(read)) stored.As(&result); + return result; +} + +D3D12_RESOURCE_DESC buffer_desc(UINT64 bytes, D3D12_RESOURCE_FLAGS flags) +{ + D3D12_RESOURCE_DESC desc{}; + desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + desc.Width = bytes; + desc.Height = 1; + desc.DepthOrArraySize = 1; + desc.MipLevels = 1; + desc.Format = DXGI_FORMAT_UNKNOWN; + desc.SampleDesc.Count = 1; + desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + desc.Flags = flags; + return desc; +} + +struct Device { + ComPtr desktop, guest; + ComPtr guest_queue, native_queue; + ComPtr completed; + UINT64 completed_value = 0; +}; + +bool init_device(bool warp, Device& device) +{ + ComPtr factory; + if (FAILED(CreateDXGIFactory1(IID_PPV_ARGS(&factory)))) return false; + ComPtr adapter; + if (warp) { + if (FAILED(factory->EnumWarpAdapter(IID_PPV_ARGS(&adapter)))) return false; + } else { + for (UINT i = 0; factory->EnumAdapters1(i, adapter.ReleaseAndGetAddressOf()) == S_OK; ++i) { + DXGI_ADAPTER_DESC1 desc{}; + if (SUCCEEDED(adapter->GetDesc1(&desc)) && !(desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE)) break; + } + if (!adapter) return false; + } + DXGI_ADAPTER_DESC1 adapter_desc{}; + if (SUCCEEDED(adapter->GetDesc1(&adapter_desc))) + std::printf("adapter %ls vendor=%04x device=%04x\n", adapter_desc.Description, adapter_desc.VendorId, + adapter_desc.DeviceId); + if (FAILED(D3D12XboxCreateDevice(adapter.Get(), nullptr, IID_PPV_ARGS(&device.desktop)))) return false; + unsigned char parameters[64]{}; + if (FAILED(D3D12XboxCreateDevice(adapter.Get(), parameters, IID_PPV_ARGS(&device.guest)))) return false; + const D3D12_COMMAND_QUEUE_DESC queue_desc{D3D12_COMMAND_LIST_TYPE_DIRECT}; + if (FAILED(device.guest->CreateCommandQueue(&queue_desc, IID_PPV_ARGS(&device.guest_queue)))) return false; + device.native_queue = underlying(device.desktop.Get(), device.guest.Get(), device.guest_queue.Get()); + return device.native_queue && + SUCCEEDED(device.desktop->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&device.completed))); +} + +bool wait_fence(ID3D12Fence* fence, UINT64 value) +{ + if (fence->GetCompletedValue() >= value) return true; + HANDLE event = CreateEventW(nullptr, FALSE, FALSE, nullptr); + if (!event) return false; + const bool ok = SUCCEEDED(fence->SetEventOnCompletion(value, event)) && + WaitForSingleObject(event, 20000) == WAIT_OBJECT_0; + CloseHandle(event); + return ok; +} + +struct TitleList { + Device* device = nullptr; + ComPtr allocator; + ComPtr list; + ComPtr native; + + bool begin(Device& d) + { + device = &d; + if (FAILED(d.guest->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator)))) + return false; + using CreateList = HRESULT(WINAPI*)(IUnknown*, const void*, IUnknown*, IUnknown*, REFIID, void**); + const UINT list_desc[]{static_cast(D3D12_COMMAND_LIST_TYPE_DIRECT), 2, 1, 0}; + auto* create = reinterpret_cast((*reinterpret_cast(d.guest.Get()))[73]); + if (FAILED(create(d.guest.Get(), list_desc, allocator.Get(), nullptr, __uuidof(ID3D12GraphicsCommandList), + reinterpret_cast(list.GetAddressOf())))) + return false; + if (FAILED(static_cast(invoke(list.Get(), 139, arg(allocator.Get()))))) return false; + native = underlying(d.desktop.Get(), d.guest.Get(), list.Get()); + return native != nullptr; + } + + void barrier(ID3D12Resource* resource, D3D12_RESOURCE_STATES before, D3D12_RESOURCE_STATES after) + { + D3D12_RESOURCE_BARRIER barrier{}; + barrier.Transition = {resource, D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, before, after}; + native->ResourceBarrier(1, &barrier); + } + + bool close() { return SUCCEEDED(static_cast(invoke(list.Get(), 9))); } + + bool submit() + { + void* lists[] = {list.Get()}; + invoke(device->guest_queue.Get(), 10, 1, arg(lists)); + if (FAILED(device->native_queue->Signal(device->completed.Get(), ++device->completed_value))) return false; + return wait_fence(device->completed.Get(), device->completed_value); + } +}; + +struct ComputeRead { + ComPtr root; + ComPtr pipeline; + ComPtr srv_heap; + ComPtr output, readback; +}; + +// Compile the two-SRV read program and create its descriptor heap over the adopted backing. +bool init_read(Device& device, ID3D12Resource* backing, ComputeRead& read) +{ + constexpr char shader[] = R"( +ByteAddressBuffer first : register(t0); +ByteAddressBuffer second : register(t1); +RWByteAddressBuffer result : register(u0); +[numthreads(1, 1, 1)] +void main() { result.Store2(0, uint2(first.Load(0), second.Load(0))); } +)"; + D3D12_DESCRIPTOR_RANGE range{}; + range.RangeType = D3D12_DESCRIPTOR_RANGE_TYPE_SRV; + range.NumDescriptors = 2; + range.BaseShaderRegister = 0; + D3D12_ROOT_PARAMETER params[2]{}; + params[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; + params[0].DescriptorTable = {1, &range}; + params[1].ParameterType = D3D12_ROOT_PARAMETER_TYPE_UAV; + params[1].Descriptor.ShaderRegister = 0; + const D3D12_ROOT_SIGNATURE_DESC root_desc{2, params, 0, nullptr, D3D12_ROOT_SIGNATURE_FLAG_NONE}; + ComPtr blob, code, errors; + if (FAILED(D3D12SerializeRootSignature(&root_desc, D3D_ROOT_SIGNATURE_VERSION_1, &blob, nullptr)) || + FAILED(device.desktop->CreateRootSignature(0, blob->GetBufferPointer(), blob->GetBufferSize(), + IID_PPV_ARGS(&read.root))) || + FAILED(D3DCompile(shader, sizeof(shader) - 1, nullptr, nullptr, nullptr, "main", "cs_5_0", 0, 0, + &code, &errors))) + return false; + D3D12_COMPUTE_PIPELINE_STATE_DESC pso{}; + pso.pRootSignature = read.root.Get(); + pso.CS = {code->GetBufferPointer(), code->GetBufferSize()}; + if (FAILED(device.desktop->CreateComputePipelineState(&pso, IID_PPV_ARGS(&read.pipeline)))) return false; + const D3D12_DESCRIPTOR_HEAP_DESC heap_desc{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 2, + D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE}; + if (FAILED(device.desktop->CreateDescriptorHeap(&heap_desc, IID_PPV_ARGS(&read.srv_heap)))) return false; + auto at = read.srv_heap->GetCPUDescriptorHandleForHeapStart(); + const UINT increment = device.desktop->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); + for (UINT i = 0; i < 2; ++i) { + D3D12_SHADER_RESOURCE_VIEW_DESC view{DXGI_FORMAT_R32_TYPELESS, D3D12_SRV_DIMENSION_BUFFER, + D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING}; + view.Buffer.FirstElement = static_cast((i ? second_srv_offset : 0) / 4); + view.Buffer.NumElements = 4; + view.Buffer.Flags = D3D12_BUFFER_SRV_FLAG_RAW; + device.desktop->CreateShaderResourceView(backing, &view, at); + at.ptr += increment; + } + const D3D12_HEAP_PROPERTIES default_heap{D3D12_HEAP_TYPE_DEFAULT}; + const auto output_desc = buffer_desc(16, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS); + if (FAILED(device.desktop->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &output_desc, + D3D12_RESOURCE_STATE_COMMON, nullptr, IID_PPV_ARGS(&read.output)))) + return false; + const D3D12_HEAP_PROPERTIES readback_heap{D3D12_HEAP_TYPE_READBACK}; + const auto readback_desc = buffer_desc(16, D3D12_RESOURCE_FLAG_NONE); + return SUCCEEDED(device.desktop->CreateCommittedResource(&readback_heap, D3D12_HEAP_FLAG_NONE, &readback_desc, + D3D12_RESOURCE_STATE_COPY_DEST, nullptr, + IID_PPV_ARGS(&read.readback))); +} + +bool record_read(TitleList& list, ComputeRead& read, ID3D12Resource* backing, std::array& values) +{ + list.barrier(backing, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE); + list.barrier(read.output.Get(), D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); + ID3D12DescriptorHeap* heap = read.srv_heap.Get(); + list.native->SetDescriptorHeaps(1, &heap); + list.native->SetComputeRootSignature(read.root.Get()); + list.native->SetPipelineState(read.pipeline.Get()); + list.native->SetComputeRootDescriptorTable(0, read.srv_heap->GetGPUDescriptorHandleForHeapStart()); + list.native->SetComputeRootUnorderedAccessView(1, read.output->GetGPUVirtualAddress()); + list.native->Dispatch(1, 1, 1); + list.barrier(backing, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE, D3D12_RESOURCE_STATE_COMMON); + list.barrier(read.output.Get(), D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE); + list.native->CopyBufferRegion(read.readback.Get(), 0, read.output.Get(), 0, 8); + list.barrier(read.output.Get(), D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_COMMON); + if (!list.close() || !list.submit()) return false; + + void* mapped = nullptr; + const D3D12_RANGE range{0, 8}; + if (FAILED(read.readback->Map(0, &range, &mapped))) return false; + std::memcpy(values.data(), mapped, 8); + const D3D12_RANGE none{0, 0}; + read.readback->Unmap(0, &none); + return true; +} + +void write_word(std::uint8_t* base, UINT64 offset, std::uint32_t value) +{ + std::memcpy(base + offset, &value, sizeof(value)); +} + +bool resolve_words(Device& device, TitleList& list, const UINT* words, ID3D12Resource** resource, UINT64* offset, + UINT64* bytes, int* source, std::string& reason) +{ + (void)device; + const char* why = nullptr; + const HRESULT hr = x2w_d3d12_mesh86_material_resolve(list.list.Get(), words, resource, offset, bytes, source, &why); + reason = why ? why : ""; + return SUCCEEDED(hr) && *resource; +} + +std::array raw_record(const std::uint8_t* address, UINT64 bytes) +{ + const auto value = reinterpret_cast(address); + return {static_cast(value), static_cast(value >> 32) | (4u << 16), + static_cast(bytes / 4), 0x31016facu, 0, 0, 0, 0}; +} + +} // namespace + +int main(int argc, char** argv) +{ + if (argc != 2) { + std::puts("usage: startup_mesh86_material_backing "); + return 2; + } + const bool warp = std::strcmp(argv[1], "warp") == 0; + if (!warp && std::strcmp(argv[1], "hardware") != 0) return 2; + SetEnvironmentVariableW(L"X2W_D3D12_PERMISSIVE", L"1"); + SetEnvironmentVariableW(L"X2W_D3D12_LIST_NOOP", L"1"); + SetEnvironmentVariableW(L"X2W_D3D12_RENDER", L"1"); + SetEnvironmentVariableW(L"X2W_D3D12_LINEAR_BUFFERS", nullptr); + SetEnvironmentVariableW(L"X2W_D3D12_BUDGET", L"1"); + + Device device; + if (!init_device(warp, device)) { + std::puts(warp ? "WARP device not created" : "no D3D12 hardware adapter"); + return warp ? 1 : 77; + } + + auto* allocation = static_cast(VirtualAlloc(nullptr, allocation_bytes, MEM_RESERVE | MEM_COMMIT, + PAGE_READWRITE)); + if (!allocation) { + std::puts("FAIL: title allocation"); + return 1; + } + std::memset(allocation, 0xa5, allocation_bytes); + std::uint8_t* title = allocation + buffer_offset; + std::memset(title, 0, buffer_bytes); + write_word(title, 0, a0); + write_word(title, second_srv_offset, b0); + + const D3D12_RESOURCE_DESC placed_desc = buffer_desc(buffer_bytes, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS); + ComPtr placed; + using Place = HRESULT(WINAPI*)(IUnknown*, void*, const D3D12_RESOURCE_DESC*, UINT, const void*, REFIID, void**); + const HRESULT placed_hr = slot(device.guest.Get(), 133)( + device.guest.Get(), title, &placed_desc, D3D12_RESOURCE_STATE_COMMON, nullptr, + __uuidof(ID3D12Resource), reinterpret_cast(placed.GetAddressOf())); + check(SUCCEEDED(placed_hr), "slot 133 places the 64 KiB title buffer"); + if (FAILED(placed_hr)) return 1; + ComPtr backing = underlying(device.desktop.Get(), device.guest.Get(), placed.Get()); + check(backing != nullptr, "the placed wrapper has a desktop resource"); + if (!backing) return 1; + x2w_budget::Snapshot placed_budget{}, adopted_budget{}; + check(x2w_d3d12_budget_snapshot(&placed_budget, sizeof(placed_budget)), "budget snapshot before adoption"); + + ComputeRead read; + check(init_read(device, backing.Get(), read), "compute read program and readback"); + if (failures) return 1; + + std::array first_record = raw_record(title, 16); + std::array second_record = raw_record(title + second_srv_offset, 16); + TitleList list; + check(list.begin(device), "open fixture recording"); + if (failures) return 1; + ID3D12Resource* first_resource = nullptr; + ID3D12Resource* second_resource = nullptr; + UINT64 first_offset = 0, first_bytes = 0, second_offset = 0, second_bytes = 0; + int first_source = 0, second_source = 0; + std::string reason; + const bool first_ok = resolve_words(device, list, first_record.data(), &first_resource, &first_offset, &first_bytes, + &first_source, reason); + check(first_ok && first_resource == backing.Get() && first_offset == 0 && first_bytes == 16 && first_source == 4, + "first raw SRV is adopted on the placed backing"); + const bool second_ok = resolve_words(device, list, second_record.data(), &second_resource, &second_offset, + &second_bytes, &second_source, reason); + check(second_ok && second_resource == backing.Get() && second_offset == second_srv_offset && second_bytes == 16 && + second_source == 4, + "second raw SRV names a distinct offset of the same backing"); + if (failures) return 1; + + X2wLinearBufferInfo info{}; + check(x2w_d3d12_linear_buffer_info(placed.Get(), &info) && info.path == 2 && info.adopted == 1 && + info.backing == backing.Get() && info.refusal_hr == S_OK, + "the existing desktop backing is adopted, without a linear placement"); + check(x2w_d3d12_budget_snapshot(&adopted_budget, sizeof(adopted_budget)) && + adopted_budget.live[x2w_budget::buffer].objects == placed_budget.live[x2w_budget::buffer].objects && + adopted_budget.live[x2w_budget::buffer].bytes == placed_budget.live[x2w_budget::buffer].bytes, + "adoption grows no default-heap buffer in the budget"); + std::printf("budget buffer: %llu objects / %llu bytes before and after adoption\n", + static_cast(adopted_budget.live[x2w_budget::buffer].objects), + static_cast(adopted_budget.live[x2w_budget::buffer].bytes)); + X2wLinearBufferTotals before_totals{}; + x2w_d3d12_linear_buffer_totals(&before_totals); + + std::array values{}; + check(record_read(list, read, backing.Get(), values), "first GPU read submits and completes"); + check(values[0] == a0 && values[1] == b0, "two GPU-selected SRVs read distinct first-upload values"); + check(x2w_d3d12_linear_buffer_info(placed.Get(), &info) && info.bytes_copied == buffer_bytes && + info.refreshes >= 1 && info.last_fence != 0, + "first refresh copies the full title range and signals its fence"); + const UINT64 first_copied = info.bytes_copied; + const UINT64 first_staging = info.last_staging; + + write_word(title, 0, c0); + TitleList second_list; + check(second_list.begin(device), "open second recording"); + if (failures) return 1; + ID3D12Resource* again = nullptr; + UINT64 again_offset = 0, again_bytes = 0; + int again_source = 0; + check(resolve_words(device, second_list, first_record.data(), &again, &again_offset, &again_bytes, &again_source, reason) && + again == backing.Get() && again_offset == 0 && again_source == 4, + "second recording reuses the adopted backing"); + check(record_read(second_list, read, backing.Get(), values), "second GPU read submits and completes"); + check(values[0] == c0 && values[1] == b0, "the changed SRV reads its new value and the other keeps its own"); + check(x2w_d3d12_linear_buffer_info(placed.Get(), &info) && info.bytes_copied - first_copied == 4 && + info.last_staging == first_staging, + "the second refresh copies only the four changed bytes and reuses the staging buffer"); + const UINT64 second_copied = info.bytes_copied; + + write_word(title, second_srv_offset, d0); + TitleList third_list; + check(third_list.begin(device), "open third recording"); + if (failures) return 1; + check(resolve_words(device, third_list, second_record.data(), &again, &again_offset, &again_bytes, &again_source, reason), + "third recording resolves the second SRV"); + check(record_read(third_list, read, backing.Get(), values), "third GPU read submits and completes"); + check(values[0] == c0 && values[1] == d0, "the second SRV reads its new value independently"); + check(x2w_d3d12_linear_buffer_info(placed.Get(), &info), "third refresh reports its bytes"); + const UINT64 third_copied = info.bytes_copied; + X2wLinearBufferTotals after_totals{}; + x2w_d3d12_linear_buffer_totals(&after_totals); + check(after_totals.copied == 0 && after_totals.adopted == 1 && + after_totals.bytes_copied == first_copied + 8 && after_totals.consumer_waits >= 1, + "totals report one adopted backing, no second default buffer and fenced consumers"); + check(after_totals.staging_reused >= 2, "staging buffers are reused across submissions"); + + // Two changed words more than one compare block apart: each contiguous run is copied, not the + // span between them. The read sees both the changed first SRV and the unchanged second one. + { + write_word(title, 0, e0); + write_word(title, 0x4000, f0); + X2wLinearBufferInfo before_runs{}; + x2w_d3d12_linear_buffer_info(placed.Get(), &before_runs); + TitleList fourth; + check(fourth.begin(device), "open multi-run recording"); + ID3D12Resource* resource = nullptr; + UINT64 offset = 0, bytes = 0; + int source = 0; + check(resolve_words(device, fourth, first_record.data(), &resource, &offset, &bytes, &source, reason), + "multi-run recording resolves the first SRV"); + check(record_read(fourth, read, backing.Get(), values), "multi-run read submits"); + check(values[0] == e0 && values[1] == d0, "the multi-run read sees both SRV values"); + X2wLinearBufferInfo after_runs{}; + check(x2w_d3d12_linear_buffer_info(placed.Get(), &after_runs) && + after_runs.bytes_copied - before_runs.bytes_copied == 8, + "two disjoint changed words copy two four-byte runs"); + std::printf("material backing: first %llu bytes, one-word change %llu bytes, second one-word change %llu bytes, " + "two disjoint words %llu bytes; adopted %llu, linear placements %llu\n", + static_cast(first_copied), + static_cast(second_copied - first_copied), + static_cast(third_copied - second_copied), + static_cast(after_runs.bytes_copied - before_runs.bytes_copied), + static_cast(after_totals.adopted), + static_cast(after_totals.copied)); + } + + const auto untouched = [&](const std::uint8_t* begin, const std::uint8_t* end) { + for (const std::uint8_t* at = begin; at < end; ++at) + if (*at != 0xa5) return false; + return true; + }; + check(untouched(allocation, title) && untouched(title + buffer_bytes, allocation + allocation_bytes), + "bytes outside the placed range are never read or copied"); + check(std::memcmp(title, &e0, sizeof(e0)) == 0, + "the title bytes used by the GPU views keep their sentinels"); + + TitleList control_list; + check(control_list.begin(device), "open control recording"); + if (failures) return 1; + { + std::array outside = raw_record(title + buffer_bytes - 8, 16); + ID3D12Resource* resource = nullptr; + UINT64 offset = 0, bytes = 0; + int source = 0; + const bool refused = !resolve_words(device, control_list, outside.data(), &resource, &offset, &bytes, &source, reason); + check(refused && reason.find("crosses the end") != std::string::npos, + ("out-of-range record is refused: " + reason).c_str()); + } + { + std::array oversized = raw_record(title, 16); + oversized[2] = 0xffffffffu; + ID3D12Resource* resource = nullptr; + UINT64 offset = 0, bytes = 0; + int source = 0; + const bool refused = !resolve_words(device, control_list, oversized.data(), &resource, &offset, &bytes, &source, reason); + check(refused && reason.find("raw SRV limit") != std::string::npos, + ("oversized record is refused: " + reason).c_str()); + } + { + alignas(64) static UINT table[4096 / 4]{}; + struct { D3D12_DESCRIPTOR_HEAP_DESC desc; UINT64 address, bytes; } heap_desc{ + {D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 128, D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE}, + reinterpret_cast(table), sizeof(table)}; + ComPtr heap; + const HRESULT heap_hr = device.guest->CreateDescriptorHeap(&heap_desc.desc, IID_PPV_ARGS(&heap)); + check(SUCCEEDED(heap_hr), "create a guest view heap for the wrong-type control"); + if (SUCCEEDED(heap_hr)) { + using Handle = UINT64(WINAPI*)(IUnknown*); + const UINT64 title_cpu = slot(heap.Get(), 9)(heap.Get()); + auto* token_words = reinterpret_cast(title_cpu); + D3D12_UNORDERED_ACCESS_VIEW_DESC uav{DXGI_FORMAT_R32_TYPELESS, D3D12_UAV_DIMENSION_BUFFER}; + uav.Buffer.NumElements = 4; + uav.Buffer.Flags = D3D12_BUFFER_UAV_FLAG_RAW; + using Uav = void(WINAPI*)(IUnknown*, IUnknown*, IUnknown*, const D3D12_UNORDERED_ACCESS_VIEW_DESC*, UINT64); + slot(device.guest.Get(), 19)(device.guest.Get(), placed.Get(), nullptr, &uav, title_cpu); + ID3D12Resource* resource = nullptr; + UINT64 offset = 0, bytes = 0; + int source = 0; + const bool refused = !resolve_words(device, control_list, token_words, &resource, &offset, &bytes, &source, reason); + check(refused && reason.find("unordered access view") != std::string::npos, + ("wrong-type (UAV) descriptor is refused: " + reason).c_str()); + } + } + { + alignas(64) static UINT table[4096 / 4]{}; + struct { D3D12_DESCRIPTOR_HEAP_DESC desc; UINT64 address, bytes; } heap_desc{ + {D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 128, D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE}, + reinterpret_cast(table), sizeof(table)}; + ComPtr heap; + if (SUCCEEDED(device.guest->CreateDescriptorHeap(&heap_desc.desc, IID_PPV_ARGS(&heap)))) { + using Handle = UINT64(WINAPI*)(IUnknown*); + const UINT64 title_cpu = slot(heap.Get(), 9)(heap.Get()); + auto* token_words = reinterpret_cast(title_cpu); + D3D12_SHADER_RESOURCE_VIEW_DESC srv{DXGI_FORMAT_R32_TYPELESS, D3D12_SRV_DIMENSION_BUFFER, + D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING}; + srv.Buffer.NumElements = 4; + srv.Buffer.Flags = D3D12_BUFFER_SRV_FLAG_RAW; + using View = void(WINAPI*)(IUnknown*, IUnknown*, const D3D12_SHADER_RESOURCE_VIEW_DESC*, UINT64); + slot(device.guest.Get(), 18)(device.guest.Get(), placed.Get(), &srv, title_cpu); + placed.Reset(); // the title's final Release retires the placement and the wrapper + ID3D12Resource* resource = nullptr; + UINT64 offset = 0, bytes = 0; + int source = 0; + const bool refused = !resolve_words(device, control_list, token_words, &resource, &offset, &bytes, &source, reason); + check(refused && !reason.empty(), ("released-resource descriptor is refused: " + reason).c_str()); + } + } + + std::printf("startup_mesh86_material_backing %s: %s (%u failed)\n", argv[1], failures ? "FAIL" : "PASS", failures); + return failures ? 1 : 0; +} From f71199638d5da5be9c57effda30f4275f92587fa Mon Sep 17 00:00:00 2001 From: Roland Edi Date: Tue, 1 Dec 2026 11:21:02 +0000 Subject: [PATCH 04/32] tooling: allow-list the placed material backing reason --- tools/startup/triage_run.py | 1 + 1 file changed, 1 insertion(+) diff --git a/tools/startup/triage_run.py b/tools/startup/triage_run.py index 055cb037c4..6f30d735a9 100644 --- a/tools/startup/triage_run.py +++ b/tools/startup/triage_run.py @@ -91,6 +91,7 @@ 'a heap index word is outside its table buffer', "a heap record is outside the list's view heap", 'a null input could not get its zero bytes', + 'a placed material buffer has no coherent desktop backing', 'a raw buffer writer was bound to a non-buffer UAV', 'a raw buffer writer was bound to a non-buffer backing', 'a resource heap range outside the supported layout', From fd9c6e8acff66055d4d647d3ffca21ed60ae7a3e Mon Sep 17 00:00:00 2001 From: Luuk Motz Date: Tue, 1 Dec 2026 09:06:24 +0100 Subject: [PATCH 05/32] shader: lower v_rcp_iflag_f32 and v_ashrrev_i32 in the mesh frontend Both are already lowered by the shared ALU (the reciprocal as v_rcp_f32, the shift as an arithmetic right shift by src0 & 31). The mesh lane ALU list now admits them, so the full_exec || exec_skip rule and the partial-write merge apply unchanged. Co-Authored-By: Claude Opus 5.5 --- src/gfx1013_direct_mesh.inl | 4 ++-- tests/native_direct_mesh_check.py | 9 +++++++++ 2 files changed, 11 insertions(+), 2 deletions(-) diff --git a/src/gfx1013_direct_mesh.inl b/src/gfx1013_direct_mesh.inl index abc97056b8..ed9c7c6853 100644 --- a/src/gfx1013_direct_mesh.inl +++ b/src/gfx1013_direct_mesh.inl @@ -2100,8 +2100,8 @@ NativeComputeShader lower_mesh(const string &code, const MeshStageLayout &layout i.name=="v_mad_f32" || i.name=="v_mul_lo_u32" || i.name=="v_mul_hi_u32" || i.name=="v_mac_f32" || i.name=="v_mul_legacy_f32" || i.name=="v_sub_f32" || 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_sqrt_f32" || - i.name=="v_fma_mixlo_f16" || i.name=="v_fma_mixhi_f16" || i.name=="v_fma_mix_f32" || i.name=="v_pack_b32_f16" || + i.name=="v_rsq_f32" || i.name=="v_rcp_f32" || i.name=="v_rcp_iflag_f32" || i.name=="v_sqrt_f32" || + i.name=="v_ashrrev_i32" || i.name=="v_fma_mixlo_f16" || i.name=="v_fma_mixhi_f16" || i.name=="v_fma_mix_f32" || i.name=="v_pack_b32_f16" || 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_sub_nc_u32" || i.name=="v_subrev_nc_u32" || i.name=="v_add_co_ci_u32" || i.name=="v_lshlrev_b32" || diff --git a/tests/native_direct_mesh_check.py b/tests/native_direct_mesh_check.py index 0816a19356..a8a74e0878 100644 --- a/tests/native_direct_mesh_check.py +++ b/tests/native_direct_mesh_check.py @@ -299,6 +299,15 @@ def run(name, words, expected=None): text = run('v-mad-f32', program[:5] + program[6:7] + mad + program[7:]) assert re.search(r'fmul float', text) and re.search(r'fadd float', text), text assert '@dx.op.tertiary.f32' not in text, text + # VOP2 0x18: v_ashrrev_i32 v1, 2, v0 shifts v0 right by 2, keeping the sign (ashr, not lshr). + text = run('v-ashrrev-i32', program[:5] + program[6:7] + [0x30020082] + program[7:]) + shifted = re.search(rf'(?P{value}) = and i32 2, 31\n\s*(?P{value}) = ashr i32 {value}, (?P=amount)\n', text) + assert shifted, text + assert_position_x(text, rf'ashr i32 {value}, {re.escape(shifted["amount"])}') + # VOP1 0x2b: v_rcp_iflag_f32 v1, v0 is the same reciprocal as v_rcp_f32; the flag only + # changes IEEE exception reporting, which DXIL does not expose. + text = run('v-rcp-iflag-f32', program[:5] + program[6:7] + [0x7e025700] + program[7:]) + assert re.search(rf'{value} = fdiv float 1\.000000e\+00, {value}\n', text), text # Pack the thread ID, the inline constant 2 and the sign-extended immediate in s7. pack_position = [0xb0078000, 0xd7720001, 256 | (130 << 9) | (7 << 18)] text = run('v-or3-b32', program[:5] + program[6:7] + pack_position + program[7:]) From 95e4d369cf1bef6366c05605d50852bd557c6e56 Mon Sep 17 00:00:00 2001 From: Luuk Motz Date: Tue, 1 Dec 2026 09:34:21 +0100 Subject: [PATCH 06/32] tests: follow v_rcp_iflag_f32 to the exported position Review follow-up on #3709: v-rcp-iflag-f32 now checks that the reciprocal's bits reach the exported X, as v-ashrrev-i32 already does. Co-Authored-By: Claude Opus 5.5 --- tests/native_direct_mesh_check.py | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/tests/native_direct_mesh_check.py b/tests/native_direct_mesh_check.py index a8a74e0878..9e5f88046f 100644 --- a/tests/native_direct_mesh_check.py +++ b/tests/native_direct_mesh_check.py @@ -307,7 +307,10 @@ def run(name, words, expected=None): # VOP1 0x2b: v_rcp_iflag_f32 v1, v0 is the same reciprocal as v_rcp_f32; the flag only # changes IEEE exception reporting, which DXIL does not expose. text = run('v-rcp-iflag-f32', program[:5] + program[6:7] + [0x7e025700] + program[7:]) - assert re.search(rf'{value} = fdiv float 1\.000000e\+00, {value}\n', text), text + reciprocal = re.search(rf'(?P{value}) = fdiv float 1\.000000e\+00, {value}\n', text) + assert reciprocal, text + # The reciprocal's bits are v1, which the fixture converts and exports as X. + assert_position_x(text, rf'bitcast float {re.escape(reciprocal["rcp"])} to i32') # Pack the thread ID, the inline constant 2 and the sign-extended immediate in s7. pack_position = [0xb0078000, 0xd7720001, 256 | (130 << 9) | (7 << 18)] text = run('v-or3-b32', program[:5] + program[6:7] + pack_position + program[7:]) From c3c3552c4260f8acfc45dc27e99bc2d3fbb04d3c Mon Sep 17 00:00:00 2001 From: Roland Edi Date: Tue, 1 Dec 2026 11:29:07 +0000 Subject: [PATCH 07/32] runtime: correlate slot 86 mesh drawings across record, close and submit --- src/startup_stubs/d3d12_xs_device.cpp | 51 +++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) diff --git a/src/startup_stubs/d3d12_xs_device.cpp b/src/startup_stubs/d3d12_xs_device.cpp index 6a852b1847..4f415727b8 100644 --- a/src/startup_stubs/d3d12_xs_device.cpp +++ b/src/startup_stubs/d3d12_xs_device.cpp @@ -264,6 +264,8 @@ struct alignas(16) WrapperOwn { volatile LONG64 output_trace_recording; u64 direct_mesh_trace_recording; bool direct_mesh_trace_submitted; + u64 mesh86_trace_recording; // X2W_MESH86_PRESENT_TRACE: one id per recording that recorded a slot 86 mesh draw + bool mesh86_trace_submitted; // whether that recording reached a queue submission bool list_ready; // CommandList (render mode): closed with recorded work, not yet submitted bool compute_pipeline; // PipelineState: a desktop compute pipeline bool builder_pipeline; // PipelineState: slot 62 created it for XboxBvhBuilder.dll (X2W_COMPUTE_BUILDER_GATE) @@ -2461,6 +2463,10 @@ HRESULT __stdcall list_reset(Wrapper* self, void* allocator) self, state.direct_mesh_trace_recording); state.direct_mesh_trace_recording = 0; state.direct_mesh_trace_submitted = false; + if (state.mesh86_trace_recording && !state.mesh86_trace_submitted) + log("x2w-mesh86-present reset list=%p recording=%llu submitted=0", self, state.mesh86_trace_recording); + state.mesh86_trace_recording = 0; + state.mesh86_trace_submitted = false; state.list_ready = false; state.list_open = true; } @@ -2520,6 +2526,9 @@ HRESULT __stdcall list_close(Wrapper* self) if (state.direct_mesh_trace_recording) log("x2w-mesh-direct close list=%p recording=%llu hr=0x%08lx", self, state.direct_mesh_trace_recording, static_cast(hr)); + if (state.mesh86_trace_recording) + log("x2w-mesh86-present close list=%p recording=%llu hr=0x%08lx", + self, state.mesh86_trace_recording, static_cast(hr)); ReleaseSRWLockExclusive(&allocator_lock); InterlockedIncrement(&render_closes); if (FAILED(hr)) { @@ -4521,6 +4530,26 @@ bool root_srv_at_draw() } LONG root_srv_copies_skipped, root_srv_copies_made; +// X2W_MESH86_PRESENT_TRACE=1 or X2W_D3D12_TRACE_DIRECT_MESH=1: bounded (48 rows per stage) correlation of a +// recording that holds a slot 86 DrawMesh, reported at record, Close, reset and queue submission so one draw's +// PSO, group counts and recording ID can be matched across the four. Off by default: no allocation, readback, +// list bookkeeping or GPU wait is added to the normal path. +bool mesh86_present_trace() +{ + static const bool on = x2w_local::env_on("X2W_MESH86_PRESENT_TRACE") || x2w_local::env_on("X2W_D3D12_TRACE_DIRECT_MESH"); + return on; +} +LONG64 mesh86_trace_recordings; + +// The correlation id of this recording. Call under allocator_lock. +u64 mesh86_trace_id(Wrapper* list) +{ + auto& state = list->own(); + if (!state.mesh86_trace_recording) + state.mesh86_trace_recording = static_cast(InterlockedIncrement64(&mesh86_trace_recordings)); + return state.mesh86_trace_recording; +} + void __stdcall list_execute_indirect(Wrapper* self, void* signature, UINT count, void* argument, u64 offset, void* count_buffer, u64 count_offset) { @@ -4955,6 +4984,23 @@ void __stdcall list_execute_indirect(Wrapper* self, void* signature, UINT count, dred_marker(list, mesh ? "mesh" : indexed ? "ei-drawidx" : graphics ? "ei-draw" : "ei-cs", dred_pipeline_key(pass.pipeline)); list->ExecuteIndirect(static_cast(sig->own().real), count, draw_arguments, draw_offset, counts, counts ? count_offset : 0); + // X2W_MESH86_PRESENT_TRACE: the record half of the slot 86 mesh correlation. The argument record is read + // only under the opt-in and only when its title bytes are readable; a refused read reports groups_known=0. + if (mesh && pass.pipeline && pass.pipeline->own().mesh86_key && mesh86_present_trace()) { + UINT groups[3]{}; + const void* record = reinterpret_cast(base + offset); + const bool known = x2w_local::readable(record, sizeof(groups)) && + copy_title_bytes(groups, record, sizeof(groups)); + static LONG rows; + if (first_calls(rows, 48)) { + x2w_startup::ExclusiveNoteLock note(allocator_lock); + log("x2w-mesh86-present record list=%p recording=%llu guest_pso=%p pso=%p mesh86=%016llx " + "groups=%u,%u,%u groups_known=%d root=%p targets=%u format=%u", + self, mesh86_trace_id(self), pass.pipeline, pass.pipeline->own().real, pass.pipeline->own().mesh86_key, + groups[0], groups[1], groups[2], known ? 1 : 0, pass.graphics_root, pass.target_count, + pass.target_count ? pass.target_formats[0] : 0); + } + } if (trace_compute_outputs()) trace_compute_output_use(self, OutputUse::indirect_recorded, "indirect-recorded", argument, 0, offset, span, known_pipeline_key(refusal_pipeline)); @@ -5749,6 +5795,11 @@ void __stdcall queue_execute(Wrapper* self, UINT count, void* const* lists) w, state.direct_mesh_trace_recording, self); state.direct_mesh_trace_submitted = true; } + if (state.mesh86_trace_recording && !state.mesh86_trace_submitted) { + log("x2w-mesh86-present submit list=%p recording=%llu queue=%p", + w, state.mesh86_trace_recording, self); + state.mesh86_trace_submitted = true; + } } if (trace_compute_outputs()) { for (auto* recorded : wrappers) { From a59f4a57b74d6a4b1245e7659721fa76266b490d Mon Sep 17 00:00:00 2001 From: Roland Edi Date: Tue, 1 Dec 2026 11:29:08 +0000 Subject: [PATCH 08/32] tests: prove a Mesh86 draw through the target and the presented frame --- CMakePresets.json | 2 +- docs/experiments/mesh86-pixel-execz.md | 34 ++++ tests/cmake/startup_mesh86_present.cmake | 14 ++ tests/startup_indirect_draw_indexed.cpp | 235 ++++++++++++++++++++++- tests/startup_mesh86_present_check.py | 191 ++++++++++++++++++ 5 files changed, 474 insertions(+), 2 deletions(-) create mode 100644 tests/cmake/startup_mesh86_present.cmake create mode 100644 tests/startup_mesh86_present_check.py diff --git a/CMakePresets.json b/CMakePresets.json index 6bd4804f08..92e3476f56 100644 --- a/CMakePresets.json +++ b/CMakePresets.json @@ -50,7 +50,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|startup_mesh57_runtime(_[a-z]+)?_warp|native_fixed_mesh57_published_pair(_refusal)?_warp|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_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|native_.*_(ir|dxil|controls)|native_direct_mesh|startup_triage_run)$" + "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|startup_mesh57_runtime(_[a-z]+)?_warp|native_fixed_mesh57_published_pair(_refusal)?_warp|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_indirect_mesh_cache_heap(_wide)?_warp|startup_mesh86_present_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|native_.*_(ir|dxil|controls)|native_direct_mesh|startup_triage_run)$" } } }, diff --git a/docs/experiments/mesh86-pixel-execz.md b/docs/experiments/mesh86-pixel-execz.md index d6a8711a6d..ef89592f23 100644 --- a/docs/experiments/mesh86-pixel-execz.md +++ b/docs/experiments/mesh86-pixel-execz.md @@ -97,3 +97,37 @@ resource binding. One needed a 128-byte root SRV with no mapped backing. The other three needed a large placed buffer view whose desktop backing did not alias the guest memory or have a verified GPU producer. Visible scene output remains unverified. ++ +## Presented-frame proof (#3641) + +`tests/startup_mesh86_present_check.py` publishes the constants-only pair of +`tests/startup_indirect_mesh.hlsl`, then records one slot 86 DispatchMesh with +groups (1,1,1) into a 4x2 RGBA8 target with three attachments. It reads the +target back before composition, composites the target as plane 0 with the +window's selection (`composite_steps`) and compositor (`PlaneCompositor`), and +reads the presented plane back. The same frame without its ExecuteIndirect +call must leave both frames at the clear colour. + +The fixture also records the sampled draw's root SRV shape (a 128-byte window +with no mapped backing). The published constants-only profile refuses that +root before any record or submission, so the first refusal is reported apart +from the colour evidence. The target and presented readbacks live in the +fixture; the runtime adds no readback, allocation or CPU wait to the normal +rendering path. + +`X2W_MESH86_PRESENT_TRACE=1` (also `X2W_D3D12_TRACE_DIRECT_MESH=1`) adds at +most 48 rows per stage and prints the record, close and submit stages of one +recording: + +```text +x2w-mesh86-present record list=... recording=... guest_pso=... pso=... mesh86=... groups=1,1,1 groups_known=1 root=... targets=3 format=28 +``` + +The close and submit rows repeat the list pointer and recording ID. The record +row reads the group counts from the title's argument record. Without the +switch the runtime takes one cached environment check per recorded mesh draw +and prints nothing. + +```powershell +ctest --preset release --no-tests=error -j1 -R '^startup_mesh86_present_(warp|hardware)$' --output-on-failure +``` diff --git a/tests/cmake/startup_mesh86_present.cmake b/tests/cmake/startup_mesh86_present.cmake new file mode 100644 index 0000000000..1b010c3147 --- /dev/null +++ b/tests/cmake/startup_mesh86_present.cmake @@ -0,0 +1,14 @@ +# Issue #3641: one source-built slot 86 DrawMesh through the target and the presented frame. +# The fixture publishes the constants-only request of tests/startup_indirect_mesh.hlsl, records one +# DispatchMesh with groups (1,1,1), reads the target back before composition, composites the target as +# plane 0 with the window's plane selection and compositor, and reads the presented frame back. The +# skipped-draw control and the sampled root SRV shape's first refusal must leave both frames clear. With +# X2W_MESH86_PRESENT_TRACE=1, the record, close and submit rows must name one list pointer and recording. +if(EXISTS "${INTAKE_PYTHON}" AND TARGET startup_indirect_draw_indexed AND EXISTS "${DXC_EXECUTABLE}") + foreach(backend IN ITEMS warp hardware) + add_test(NAME startup_mesh86_present_${backend} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_mesh86_present_check.py" + "${DXC_EXECUTABLE}" "$" ${backend}) + set_tests_properties(startup_mesh86_present_${backend} PROPERTIES TIMEOUT 180 SKIP_RETURN_CODE 77) + endforeach() +endif() diff --git a/tests/startup_indirect_draw_indexed.cpp b/tests/startup_indirect_draw_indexed.cpp index a6bfc97275..d8cdaf8e04 100644 --- a/tests/startup_indirect_draw_indexed.cpp +++ b/tests/startup_indirect_draw_indexed.cpp @@ -8,6 +8,7 @@ #include "xmem_section_lease.h" #include "startup_stubs/rect_indirect_args.h" #include "startup_stubs/mesh57_profile.h" +#include "startup_stubs/plane_compositor.h" #include "startup_indirect_mesh_mesh.h" #include "startup_indirect_mesh_amplify.h" #include "startup_indirect_mesh_amplified_mesh.h" @@ -3063,6 +3064,230 @@ static int native_fixed_mesh_fixture(ID3D12Device* device, ID3D12Device* guest, return 0; } +// Issue #3641: one selected slot 86 DrawMesh through the target and the presented frame. +// +// Fixed profile: 4 x 2 R8G8B8A8_UNORM with the three attachments the cached slot 86 pipeline declares, one +// DispatchMesh record with groups (1,1,1), and the pipeline published for X2W_MESH86_FIXTURE_DIR. Mesh group 0 +// reports side 0, so the pixel stage paints the left half red and discards the right half. Each case records +// one guest list, closes it, submits it on a wrapped direct queue and reads the target back (the frame before +// composition); it then composites the target as plane 0 with the window's plane selection and compositor +// (present_planes.h, plane_compositor.h) and reads that frame back. +// X2W_TEST_MESH86_PRESENT=draw the draw is recorded +// X2W_TEST_MESH86_PRESENT=skip the same frame without its ExecuteIndirect call (skipped-draw control) +// X2W_TEST_MESH86_PRESENT=refused the sampled draw's root SRV shape, which the published profile refuses +// Without X2W_MESH86_FIXTURE_READY the fixture only creates the PSO, which publishes req_.m86 for the +// driver to compile. X2W_TEST_MESH86_PRESENT_KEY names that key in the printed rows. +static int mesh86_present_fixture(ID3D12Device* device, ID3D12Device* guest, const wchar_t* directory) +{ + char mode[16]{}; + const DWORD mode_length = GetEnvironmentVariableA("X2W_TEST_MESH86_PRESENT", mode, sizeof(mode)); + if (!mode_length || mode_length >= sizeof(mode)) return 2; + const bool skip = std::strcmp(mode, "skip") == 0; + const bool refused = std::strcmp(mode, "refused") == 0; + if (!skip && !refused && std::strcmp(mode, "draw") != 0) return 2; + const bool ready = GetEnvironmentVariableA("X2W_MESH86_FIXTURE_READY", nullptr, 0) != 0; + char key_text[32]{}; + UINT64 key = 0; + if (GetEnvironmentVariableA("X2W_TEST_MESH86_PRESENT_KEY", key_text, sizeof(key_text)) == 16) + key = std::strtoull(key_text, nullptr, 16); + + const std::filesystem::path input{directory}; + const auto read_stage = [&](const char* name) { + std::ifstream file(input / name, std::ios::binary); + check(file ? S_OK : E_FAIL, name); + return std::vector(std::istreambuf_iterator(file), {}); + }; + const auto ms_bytes = read_stage("source.ms.dxbc"); + const auto ps_bytes = read_stage("source.ps.dxbc"); + + D3D12_ROOT_PARAMETER parameters[2]{}; + parameters[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS; + parameters[0].ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL; + parameters[0].Constants = {0, 0, 2}; + if (refused) { + // The sampled draw's shape: a root SRV over a 128-byte window without a mapped desktop backing. + parameters[1].ParameterType = D3D12_ROOT_PARAMETER_TYPE_SRV; + parameters[1].ShaderVisibility = D3D12_SHADER_VISIBILITY_MESH; + parameters[1].Descriptor = {0, 0}; + } + const auto root = create_root(guest, {refused ? 2u : 1u, parameters, 0, nullptr, D3D12_ROOT_SIGNATURE_FLAG_NONE}); + D3D12_INDIRECT_ARGUMENT_DESC argument{}; + argument.Type = D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH_MESH; + const D3D12_COMMAND_SIGNATURE_DESC signature_desc{sizeof(D3D12_DISPATCH_MESH_ARGUMENTS), 1, &argument, 0}; + ComPtr signature; + check(guest->CreateCommandSignature(&signature_desc, nullptr, IID_PPV_ARGS(&signature)), "create present mesh signature"); + const D3D12_SHADER_BYTECODE ms_code{ms_bytes.data(), static_cast(ms_bytes.size())}; + const D3D12_SHADER_BYTECODE ps_code{ps_bytes.data(), static_cast(ps_bytes.size())}; + const auto pso = guest_pipeline( + guest, root.Get(), ms_code, ps_code, {}, 3, StreamDepth::none); + const bool native = bool(native_object(device, guest, pso.Get(), true)); + // The refused profile's request carries the root SRV, so its key is not the published draw key. + if (refused) std::printf("mesh86 present profile=refused native_pso=%d ready=%d\n", native ? 1 : 0, ready ? 1 : 0); + else std::printf("mesh86 present profile=%s mesh86=%016llx native_pso=%d ready=%d\n", mode, key, native ? 1 : 0, + ready ? 1 : 0); + // The slot 86 create publishes the request that the driver compiles and publishes; nothing is drawn yet. + if (!ready) return refused || !native ? 0 : (std::puts("mesh86 present profile unexpectedly ready"), 1); + + const D3D12_RESOURCE_DESC target_desc{D3D12_RESOURCE_DIMENSION_TEXTURE2D, 0, width, height, 1, 1, format, {1, 0}, + D3D12_TEXTURE_LAYOUT_UNKNOWN, D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET}; + const D3D12_CLEAR_VALUE clear_value{format, {0, 0, 0, 1}}; + std::vector> targets; + const D3D12_DESCRIPTOR_HEAP_DESC target_heap_desc{D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 3, + D3D12_DESCRIPTOR_HEAP_FLAG_NONE, 0}; + ComPtr target_heap; + check(device->CreateDescriptorHeap(&target_heap_desc, IID_PPV_ARGS(&target_heap)), "create present target heap"); + std::vector rtvs; + auto rtv = target_heap->GetCPUDescriptorHandleForHeapStart(); + for (UINT i = 0; i < 3; ++i) { + targets.push_back(resource(device, target_desc, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_STATE_COMMON, &clear_value)); + guest->CreateRenderTargetView(targets.back().Get(), nullptr, rtv); + rtvs.push_back(rtv); + rtv.ptr += device->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_RTV); + } + + PlacedBuffer arguments(device, guest, sizeof(D3D12_DISPATCH_MESH_ARGUMENTS), D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS); + const D3D12_DISPATCH_MESH_ARGUMENTS record{1, 1, 1}; + const auto upload = make_buffer(device, sizeof(record), D3D12_HEAP_TYPE_UPLOAD, D3D12_RESOURCE_STATE_GENERIC_READ); + void* mapped = nullptr; + const D3D12_RANGE untouched{0, 0}; + check(upload->Map(0, &untouched, &mapped), "map present arguments"); + std::memcpy(mapped, &record, sizeof(record)); + upload->Unmap(0, nullptr); + // The title's copy of the record: the runtime executes the desktop stand-in the copy below fills, and the + // opt-in correlation row reads the group counts from here, as it does for a title-written argument buffer. + std::memcpy(arguments.address, &record, sizeof(record)); + + ComPtr allocator; + check(guest->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator)), "create present allocator"); + auto wrapped_list = begin_guest_list(guest, allocator.Get()); + auto* wrapped = wrapped_list.Get(); + const auto native_list = native_object(device, guest, wrapped); + auto* list = native_list.Get(); + transition(list, arguments.native.Get(), D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_COPY_DEST); + list->CopyBufferRegion(arguments.native.Get(), 0, upload.Get(), 0, sizeof(record)); + transition(list, arguments.native.Get(), D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_COMMON); + + using Bind = void (WINAPI*)(IUnknown*, IUnknown*); + using Clear = void (WINAPI*)(IUnknown*, SIZE_T, const float*, UINT, const D3D12_RECT*); + using Constants = void (WINAPI*)(IUnknown*, UINT, UINT, const UINT*, UINT); + using Execute = void (WINAPI*)(IUnknown*, IUnknown*, UINT, IUnknown*, UINT64, IUnknown*, UINT64); + using RootSrv = void (WINAPI*)(IUnknown*, UINT, UINT64); + using Scissor = void (WINAPI*)(IUnknown*, UINT, const D3D12_RECT*); + using Targets = void (WINAPI*)(IUnknown*, UINT, const D3D12_CPU_DESCRIPTOR_HANDLE*, BOOL, const D3D12_CPU_DESCRIPTOR_HANDLE*); + using Viewport = void (WINAPI*)(IUnknown*, UINT, const D3D12_VIEWPORT*); + constexpr float clear[]{0, 0, 0, 1}; + for (const auto view : rtvs) slot(wrapped, 52)(wrapped, view.ptr, clear, 0, nullptr); + slot(wrapped, 50)(wrapped, 3, rtvs.data(), FALSE, nullptr); + slot(wrapped, 25)(wrapped, pso.Get()); + slot(wrapped, 34)(wrapped, root.Get()); + const UINT constants[2]{0, 0}; + slot(wrapped, 40)(wrapped, 0, 2, constants, 0); + const D3D12_VIEWPORT viewport{0, 0, static_cast(width), static_cast(height), 0, 1}; + const D3D12_RECT scissor{0, 0, width, height}; + slot(wrapped, 21)(wrapped, 1, &viewport); + slot(wrapped, 22)(wrapped, 1, &scissor); + if (refused) { + // CPU memory that the runtime cannot turn into a desktop SRV range. + void* const unmapped = VirtualAlloc(nullptr, 128, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); + check(unmapped ? S_OK : E_FAIL, "reserve the unmapped root SRV window"); + slot(wrapped, 44)(wrapped, 1, reinterpret_cast(unmapped)); + } + if (!skip) slot(wrapped, 61)(wrapped, signature.Get(), 1, arguments.wrapped.Get(), 0, nullptr, 0); + check(slot(wrapped, 9)(wrapped), "close present list"); + + const D3D12_COMMAND_QUEUE_DESC queue_desc{D3D12_COMMAND_LIST_TYPE_DIRECT}; + ComPtr queue; + check(guest->CreateCommandQueue(&queue_desc, __uuidof(ID3D12CommandQueue), reinterpret_cast(queue.GetAddressOf())), + "create present queue"); + ComPtr completion; + check(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&completion)), "create present fence"); + submit_wrapped(queue.Get(), wrapped); + check(native_object(device, guest, queue.Get())->Signal(completion.Get(), 1), + "signal present completion"); + check(mesh_fence_reached(completion.Get(), 5000) ? S_OK : E_FAIL, "wait for present submission"); + check(device->GetDeviceRemovedReason(), "present GPU completion"); + + const auto read_target = [&](ID3D12Resource* texture) { + D3D12_PLACED_SUBRESOURCE_FOOTPRINT footprint{}; + UINT64 bytes = 0; + device->GetCopyableFootprints(&texture->GetDesc(), 0, 1, 0, &footprint, nullptr, nullptr, &bytes); + const auto readback = make_buffer(device, bytes, D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_STATE_COPY_DEST); + ComputeCommands copy(device, kept_direct_queue(device), nullptr); + transition(copy.list.Get(), texture, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_COPY_SOURCE); + const D3D12_TEXTURE_COPY_LOCATION source{texture, D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, {}}; + D3D12_TEXTURE_COPY_LOCATION destination{readback.Get(), D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, {}}; + destination.PlacedFootprint = footprint; + copy.list->CopyTextureRegion(&destination, 0, 0, 0, &source, nullptr); + copy.submit_and_wait(device); + std::vector pixels(width * height); + void* memory = nullptr; + const D3D12_RANGE range{0, static_cast(bytes)}; + check(readback->Map(0, &range, &memory), "map present readback"); + for (UINT y = 0; y < height; ++y) + for (UINT x = 0; x < width; ++x) + std::memcpy(&pixels[y * width + x], + static_cast(memory) + y * footprint.Footprint.RowPitch + x * sizeof(std::uint32_t), + sizeof(std::uint32_t)); + readback->Unmap(0, &untouched); + return pixels; + }; + const auto target_pixels = read_target(targets.front().Get()); + std::printf("x2w-mesh86-present target mode=%s mesh86=%016llx before-composition draw=%d pixel=%08x,%08x painted=%u\n", + mode, key, skip ? 0 : 1, target_pixels[0], target_pixels[2], + static_cast(std::count_if(target_pixels.begin(), target_pixels.end(), + [](std::uint32_t pixel) { return pixel != black; }))); + + const auto presented = resource(device, target_desc, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_STATE_COMMON, &clear_value); + const D3D12_DESCRIPTOR_HEAP_DESC presented_heap_desc{D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 1, + D3D12_DESCRIPTOR_HEAP_FLAG_NONE, 0}; + ComPtr presented_heap; + check(device->CreateDescriptorHeap(&presented_heap_desc, IID_PPV_ARGS(&presented_heap)), "create presented target heap"); + const auto presented_rtv = presented_heap->GetCPUDescriptorHandleForHeapStart(); + device->CreateRenderTargetView(presented.Get(), nullptr, presented_rtv); + x2w_startup::PlaneCompositor compositor; + check(compositor.create(device, format, 1), "create plane compositor"); + const std::uint64_t resources[]{reinterpret_cast(targets.front().Get())}; + x2w_startup::PlaneStep steps[1]{}; + const unsigned step_count = x2w_startup::composite_steps(resources, 1, steps, 1); + ID3D12Resource* const surfaces[]{targets.front().Get()}; + { + ComputeCommands composite(device, nullptr, D3D12_COMMAND_LIST_TYPE_DIRECT); + transition(composite.list.Get(), presented.Get(), D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_RENDER_TARGET); + const UINT drawn = compositor.record(device, composite.list.Get(), presented_rtv, width, height, steps, + step_count, surfaces); + transition(composite.list.Get(), presented.Get(), D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_COMMON); + composite.submit_and_wait(device); + check(drawn == 1 ? S_OK : E_FAIL, "composite the plane into the presented frame"); + } + const auto presented_pixels = read_target(presented.Get()); + std::printf("x2w-mesh86-present presented mode=%s mesh86=%016llx draw=%d pixel=%08x,%08x painted=%u\n", mode, key, + skip ? 0 : 1, presented_pixels[0], presented_pixels[2], + static_cast(std::count_if(presented_pixels.begin(), presented_pixels.end(), + [](std::uint32_t pixel) { return pixel != black; }))); + + // The selected draw paints the left half; the skipped-draw control and the refused profile leave the clear + // colour in both frames. The right half stays clear in every case. + const std::uint32_t left = skip || refused ? black : red; + const std::uint32_t right = black; + for (UINT y = 0; y < height; ++y) { + for (UINT x = 0; x < width; ++x) { + const auto wanted = x < width / 2 ? left : right; + if (target_pixels[y * width + x] != wanted) { + std::fprintf(stderr, "mesh86 present target (%u,%u): got %08x, expected %08x\n", x, y, + target_pixels[y * width + x], wanted); + return 1; + } + if (presented_pixels[y * width + x] != wanted) { + std::fprintf(stderr, "mesh86 present presented (%u,%u): got %08x, expected %08x\n", x, y, + presented_pixels[y * width + x], wanted); + return 1; + } + } + } + std::printf("mesh86 present %s: target %08x presented %08x\n", mode, target_pixels[0], presented_pixels[0]); + return 0; +} + int main(int argc, char** argv) try { DrawKind kind = DrawKind::indexed; @@ -3085,6 +3310,7 @@ int main(int argc, char** argv) try else if (lease_fixture && !lease_arguments) check(SetEnvironmentVariableA("X2W_MESH86_XMEM_SRV", "1") ? S_OK : E_FAIL, "enable mesh XMem handoff"); const bool console_mesh = argc == 3 && std::strcmp(argv[2], "mesh-console") == 0; + const bool present_mesh = argc == 3 && std::strcmp(argv[2], "mesh86-present") == 0; const bool runtime_mesh57 = argc == 3 && std::strcmp(argv[2], "mesh57-runtime") == 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; @@ -3125,7 +3351,8 @@ 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 || runtime_mesh57 || (argc == 3 && std::strcmp(argv[2], "mesh") == 0)) + else if (lease_arguments || console_mesh || present_mesh || desktop_as || runtime_mesh57 || + (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 && !bucket_case && !stream_key_case) @@ -3207,6 +3434,12 @@ int main(int argc, char** argv) try check_lease_debug(info.Get()); return 0; } + if (present_mesh) { + wchar_t directory[MAX_PATH]{}; + const DWORD size = GetEnvironmentVariableW(L"X2W_MESH86_FIXTURE_DIR", directory, MAX_PATH); + check(size && size < MAX_PATH ? S_OK : E_FAIL, "get mesh86 present fixture directory"); + return mesh86_present_fixture(device.Get(), guest.Get(), directory); + } const D3D12_ROOT_PARAMETER uav{D3D12_ROOT_PARAMETER_TYPE_UAV, {}, D3D12_SHADER_VISIBILITY_ALL}; const D3D12_ROOT_SIGNATURE_DESC writer_desc{1, &uav, 0, nullptr, D3D12_ROOT_SIGNATURE_FLAG_NONE}; const auto root_flags = mesh ? D3D12_ROOT_SIGNATURE_FLAG_NONE : D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT; diff --git a/tests/startup_mesh86_present_check.py b/tests/startup_mesh86_present_check.py new file mode 100644 index 0000000000..aab95ca7c6 --- /dev/null +++ b/tests/startup_mesh86_present_check.py @@ -0,0 +1,191 @@ +"""Issue #3641: one source-built Mesh86 draw through the target and the presented frame. + +Publishes the constants-only slot 86 request of tests/startup_indirect_mesh.hlsl, then runs +startup_indirect_draw_indexed mesh86-present in three cases: + + draw one DispatchMesh record with groups (1,1,1) paints the left half of the target red. + The target is read back before composition and again after the window's plane + composite; both rows must show the same pixels. With X2W_MESH86_PRESENT_TRACE=1 the + runtime's record, close and submit rows must name one list pointer, one recording id, + the published mesh key and groups 1,1,1. The same case with the switch off must print + no correlation row and keep the same readbacks. + skip the same frame without its ExecuteIndirect call: no row, both frames keep the clear + colour. This is the skipped-draw control. + refused the sampled draw's root SRV shape (a 128-byte window with no mapped backing). The + constants-only profile refuses the root before any record or submission; the exact + first refusal is printed and both frames stay clear. + +A passing run supports the behavior under test; it does not establish full-game startup. +""" + +import os +import re +import subprocess +import sys +import tempfile +from pathlib import Path + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE)) +sys.path.insert(0, str(HERE.parent / 'tools' / 'startup')) +import mesh86_cache +from startup_indirect_mesh_cache_check import source_envelope + +PREFIX = re.compile(r'x2w-mesh86-present (\w+) (.*)') + + +def rows(text): + """The correlation rows of one run, keyed by stage.""" + found = [] + for line in text.splitlines(): + match = PREFIX.fullmatch(line) + if match: + fields = dict(re.findall(r'([a-z0-9_]+)=([^ ]+)', match.group(2))) + found.append((match.group(1), fields)) + return found + + +def fields_of(text, prefix): + for line in text.splitlines(): + if line.startswith(prefix): + return line + raise AssertionError(f'missing line {prefix!r}') + + +def run_fixture(fixture, backend, work, base_environment, mode, ready, key=None, trace=False): + environment = dict(base_environment) + environment['X2W_MESH86_FIXTURE_DIR'] = str(work) + environment['X2W_SHADER_CACHE'] = str(work) + environment['X2W_TEST_MESH86_PRESENT'] = mode + environment.pop('X2W_MESH86_FIXTURE_READY', None) + environment.pop('X2W_TEST_MESH86_PRESENT_KEY', None) + environment.pop('X2W_MESH86_PRESENT_TRACE', None) + if ready: + environment['X2W_MESH86_FIXTURE_READY'] = '1' + if key is not None: + environment['X2W_TEST_MESH86_PRESENT_KEY'] = f'{key:016x}' + if trace: + environment['X2W_MESH86_PRESENT_TRACE'] = '1' + result = subprocess.run([fixture, backend, 'mesh86-present'], env=environment, + capture_output=True, text=True, encoding='utf-8', errors='replace', timeout=120) + if result.stdout: + sys.stdout.write(result.stdout) + if result.stderr: + sys.stderr.write(result.stderr) + return result + + +def publish_stages(dxc, work, key, constants_only): + source_ms, source_ps, root, stream = mesh86_cache.load_request(work, key) + assert source_ms == source_envelope(13), 'mesh stage request bytes changed' + assert source_ps == source_envelope(0), 'pixel stage request bytes changed' + assert root.startswith(b'DXBC') and stream[:16] == bytes(16), 'request enumerates title bytes' + source = HERE / 'startup_indirect_mesh.hlsl' + ms = work / 'desktop.ms.cso' + ps = work / 'desktop.ps.cso' + subprocess.run([dxc, '-T', 'ms_6_5', '-E', 'mesh', '-Fo', ms, source], check=True) + subprocess.run([dxc, '-T', 'ps_6_0', '-E', 'pixel', '-Fo', ps, source], check=True) + # The draw profile is proven to read only its root constants. The refused profile is published + # without a proof so the runtime, not the driver, reports the first binding refusal. + mesh86_cache.publish(work, key, ms, ps, constants_dxc=dxc if constants_only else None) + marker = work / f'{key:016x}.mesh86.txt' + manifest = marker.read_text(encoding='ascii') + assert manifest.startswith('x2w-mesh86 4 ' if constants_only else 'x2w-mesh86 1 '), manifest + return manifest + + +def check_draw(fixture, backend, work, environment, key): + for trace in (True, False): + label = 'trace on' if trace else 'trace off' + result = run_fixture(fixture, backend, work, environment, 'draw', True, key, trace) + assert result.returncode == 0, f'draw case ({label}) exited {result.returncode}' + fields_of(result.stdout, f'mesh86 present profile=draw mesh86={key:016x} native_pso=1 ready=1') + target = fields_of(result.stdout, f'x2w-mesh86-present target mode=draw mesh86={key:016x} before-composition draw=1') + assert 'pixel=ff0000ff,ff000000' in target, target + assert 'painted=4' in target, target + presented = fields_of(result.stdout, f'x2w-mesh86-present presented mode=draw mesh86={key:016x} draw=1') + assert 'pixel=ff0000ff,ff000000' in presented, presented + assert 'painted=4' in presented, presented + fields_of(result.stdout, 'mesh86 present draw: target ff0000ff presented ff0000ff') + correlation = rows(result.stderr) + if not trace: + assert not correlation, f'trace-off run printed correlation rows: {correlation!r}' + print(f'draw {label}: target and presented left halves are ff0000ff, no correlation row') + continue + stages = dict(correlation) + assert list(stages) == ['record', 'close', 'submit'], correlation + record = stages['record'] + assert record['mesh86'] == f'{key:016x}', record + assert record['groups'] == '1,1,1' and record['groups_known'] == '1', record + assert record['targets'] == '3' and record['format'] == '28', record + assert record['guest_pso'] != '0x0000000000000000' and record['pso'] != '0x0000000000000000', record + for stage in ('close', 'submit'): + assert stages[stage]['list'] == record['list'], (stage, stages[stage], record) + assert stages[stage]['recording'] == record['recording'], (stage, stages[stage], record) + assert stages['close']['hr'] == '0x00000000', stages['close'] + assert stages['submit']['queue'] != '0x0000000000000000', stages['submit'] + print(f'draw {label}: target and presented left halves are ff0000ff; record, close and submit ' + f'share list {record["list"]} recording {record["recording"]} mesh86 {record["mesh86"]} groups 1,1,1') + + +def check_skip(fixture, backend, work, environment, key): + result = run_fixture(fixture, backend, work, environment, 'skip', True, key, True) + assert result.returncode == 0, f'skip case exited {result.returncode}' + target = fields_of(result.stdout, f'x2w-mesh86-present target mode=skip mesh86={key:016x} before-composition draw=0') + assert 'pixel=ff000000,ff000000' in target and 'painted=0' in target, target + presented = fields_of(result.stdout, f'x2w-mesh86-present presented mode=skip mesh86={key:016x} draw=0') + assert 'pixel=ff000000,ff000000' in presented and 'painted=0' in presented, presented + fields_of(result.stdout, 'mesh86 present skip: target ff000000 presented ff000000') + correlation = rows(result.stderr) + assert not correlation, f'skipped-draw control printed correlation rows: {correlation!r}' + print('skip: both frames keep the clear colour, no correlation row') + + +def check_refused(fixture, backend, work, environment, dxc, key): + first = run_fixture(fixture, backend, work, environment, 'refused', False, None, False) + assert first.returncode == 0, f'refused request pass exited {first.returncode}' + markers = [marker for marker in work.glob('req_*.m86') if marker.stem != f'req_{key:016x}'] + assert len(markers) == 1, markers + refused_key = int(markers[0].stem.removeprefix('req_'), 16) + manifest = publish_stages(dxc, work, refused_key, constants_only=False) + print(f'refused profile {refused_key:016x} published without a proof: {manifest.strip()}') + result = run_fixture(fixture, backend, work, environment, 'refused', True, None, True) + assert result.returncode == 0, f'refused case exited {result.returncode}' + profile = fields_of(result.stdout, 'mesh86 present profile=refused') + assert 'native_pso=0' in profile, profile + target = fields_of(result.stdout, 'x2w-mesh86-present target mode=refused') + assert 'pixel=ff000000,ff000000' in target and 'painted=0' in target, target + presented = fields_of(result.stdout, 'x2w-mesh86-present presented mode=refused') + assert 'pixel=ff000000,ff000000' in presented and 'painted=0' in presented, presented + refusal = [line for line in result.stderr.splitlines() if 'root bindings outside supported profile' in line] + assert refusal, 'the refused root SRV shape printed no first refusal' + correlation = rows(result.stderr) + assert not correlation, f'refused draw printed correlation rows: {correlation!r}' + print(f'refused: {refusal[0].split("x2w-render ", 1)[-1]}') + + +def main(dxc, fixture, backend): + with tempfile.TemporaryDirectory(prefix='mesh86-present-') as directory: + work = Path(directory) + (work / 'source.ms.dxbc').write_bytes(source_envelope(13)) + (work / 'source.ps.dxbc').write_bytes(source_envelope(0)) + environment = dict(os.environ) + environment['X2W_NATIVE_SHADERS'] = str(Path(dxc).parent) + first = run_fixture(fixture, backend, work, environment, 'draw', False) + assert first.returncode == 0, f'request pass exited {first.returncode}' + markers = list(work.glob('req_*.m86')) + assert len(markers) == 1, markers + key = int(markers[0].stem.removeprefix('req_'), 16) + manifest = publish_stages(dxc, work, key, constants_only=True) + print(f'published {manifest.strip()}') + check_draw(fixture, backend, work, environment, key) + check_skip(fixture, backend, work, environment, key) + check_refused(fixture, backend, work, environment, dxc, key) + print('mesh86 present: draw, skipped-draw control and first refusal passed') + + +if __name__ == '__main__': + if len(sys.argv) != 4: + print('usage: startup_mesh86_present_check.py ', file=sys.stderr) + raise SystemExit(2) + sys.exit(main(sys.argv[1], sys.argv[2], sys.argv[3])) From e325352364980fb1c3116b18146682b56f8ea263 Mon Sep 17 00:00:00 2001 From: Luuk Motz Date: Tue, 1 Dec 2026 12:48:59 +0100 Subject: [PATCH 09/32] shader: lower v_cmpx_lg_f32, v_cmpx_gt_f32 and per-lane v_cmpx_gt_u32 in the mesh frontend The mesh frontend narrowed EXEC only for v_cmpx_eq_u32, ne_u32 and lt_u32, and for v_cmpx_gt_u32 only in the lane-linear count form. Mesh86 programs also use v_cmpx_lg_f32, v_cmpx_gt_f32 and a per-lane v_cmpx_gt_u32. They now get the same EXEC-only narrowing through the shared compare: lg is an ordered fcmp one and gt_f32 an ordered ogt, so a NaN lane leaves EXEC, and gt_u32 is icmp ugt. The count form of v_cmpx_gt_u32 is still matched first. Float abs/neg, SDWA, DPP, clamp and omod stay refused. Part of #3703. Co-Authored-By: Claude Opus 5.5 --- src/gfx1013_direct_mesh.inl | 11 ++++++++++ tests/native_direct_mesh_check.py | 36 +++++++++++++++++++++++++++++++ 2 files changed, 47 insertions(+) diff --git a/src/gfx1013_direct_mesh.inl b/src/gfx1013_direct_mesh.inl index abc97056b8..72792a9d8d 100644 --- a/src/gfx1013_direct_mesh.inl +++ b/src/gfx1013_direct_mesh.inl @@ -1355,6 +1355,17 @@ NativeComputeShader lower_mesh(const string &code, const MeshStageLayout &layout lane_active=full_exec ? pred : ir.value("and i1 "+before+", "+pred); mask_parent[lane_active]=before; full_exec=false; wave_active.clear(); exec_value[0].clear();exec_value[1].clear(); + } else if ((i.name=="v_cmpx_lg_f32" || i.name=="v_cmpx_gt_f32" || i.name=="v_cmpx_gt_u32") && + !branch && !i.dpp_control && !i.subword && !i.abs && !i.neg && + !i.scale && !i.clamp && (full_exec || !lane_active.empty())) { + // The same EXEC-only narrowing as v_cmpx_lt_u32. The shared compare gives + // lg as an ordered fcmp one and gt as ogt, so a NaN lane leaves EXEC. + // The lane-linear v_cmpx_gt_u32 count form above is matched first. + const auto before=lane_active; + auto pred=alu.comparison(i); + lane_active=full_exec ? pred : ir.value("and i1 "+before+", "+pred); + mask_parent[lane_active]=before; + full_exec=false; wave_active.clear(); exec_value[0].clear();exec_value[1].clear(); } else if (i.name=="s_cbranch_execz" && !full_exec && !lane_active.empty() && !branch && i.target()>i.next && i.target(){value}) = {predicate}\n', text) @@ -345,6 +358,29 @@ def run(name, words, expected=None): signed = v_cmpx_lt_u32_words(program, 256, 2, (_v_mov_b32(2, _inline_u32(2)),)) signed[9] = _vopc(0x91, 256, 2) # v_cmpx_lt_i32 v0, v2 stays refused run('v-cmpx-lt-i32-refused', signed, 'unsupported mesh instruction or EXEC state: v_cmpx_lt_i32') + # v_cmpx_gt_u32 outside the lane-linear count form narrows EXEC per lane with icmp ugt. + assert_cmpx_ne(run('v-cmpx-gt-u32-lanes', v_cmpx_words( + program, [_vopc(0xD4, 256, 2)], (_v_mov_b32(2, _inline_u32(2)),))), rf'icmp ugt i32 {lane}, 2') + assert_cmpx_ne(run('v-cmpx-gt-u32-unsigned', v_cmpx_words( + program, [_vopc(0xD4, _inline_u32(0xFFFFFFFF), 2)], (_v_mov_b32(2, _inline_u32(0)),))), + rf'icmp ugt i32 {_ir_u32(0xFFFFFFFF)}, 0') + assert_cmpx_ne(run('v-cmpx-gt-u32-empty', v_cmpx_words(program, [_vopc(0xD4, 256, 0)])), + rf'icmp ugt i32 (?P{lane}), (?P=same)') + run('v-cmpx-gt-i32-refused', v_cmpx_words(program, [_vopc(0x94, 256, 0)]), + 'unsupported mesh instruction or EXEC state: v_cmpx_gt_i32') + # v_cmpx_gt_f32 1.0, v2 (VOPC 0x14) and v_cmpx_lg_f32 1.0, v2 (0x15) are ordered: + # a NaN in v2 fails both, so that lane leaves EXEC. + half = (_v_mov_b32(2, 240),) # v_mov_b32 v2, 0.5 + nan = (_v_mov_b32(2, 255), 0x7FC00000) # v_mov_b32 v2, quiet NaN + for name, opcode, predicate in (('gt', 0x14, 'ogt'), ('lg', 0x15, 'one')): + for case, prepare in (('half', half), ('nan', nan)): + text = run(f'v-cmpx-{name}-f32-{case}', v_cmpx_words(program, [_vopc(opcode, 242, 2)], prepare)) + assert_cmpx_ne(text, rf'fcmp {predicate} float {lane}, {lane}') + assert not re.search(r'fcmp u\w+ float', text), text + # |v2| on the VOP3 form stays refused: the shared compare ignores float modifiers. + abs_lg = [0xD415026A, 242 | (258 << 9)] # v_cmpx_lg_f32 vcc, 1.0, |v2| + run('v-cmpx-lg-f32-abs', v_cmpx_words(program, abs_lg, half), + 'unsupported mesh instruction or EXEC state: v_cmpx_lg_f32') # Two scalar tests select either EXEC or zero. Their OR still gives # every active lane the same bit for CNDMASK and READFIRSTLANE. wave = [0x9396ff03, 0x40018] # s_bfe_u32 s22, s3, 0x40018 From 715b84f07685d8a969c3b2ac158ea405af67a4cc Mon Sep 17 00:00:00 2001 From: Roland Edi Date: Tue, 1 Dec 2026 11:49:43 +0000 Subject: [PATCH 10/32] runtime: fail closed when a material backing was GPU-written before adoption --- docs/experiments/mesh86-pixel-execz.md | 11 ++- src/startup_stubs/linear_buffer_backing.h | 32 +++++++- .../startup_mesh86_material_backing.cmake | 3 + tests/startup_mesh86_material_backing.cpp | 77 ++++++++++++++++++- 4 files changed, 118 insertions(+), 5 deletions(-) diff --git a/docs/experiments/mesh86-pixel-execz.md b/docs/experiments/mesh86-pixel-execz.md index 6d3c579b00..43a1238e89 100644 --- a/docs/experiments/mesh86-pixel-execz.md +++ b/docs/experiments/mesh86-pixel-execz.md @@ -124,14 +124,19 @@ resource. The fixture reports one adopted backing and no linear placement. ```powershell ctest --preset release --no-tests=error -R '^startup_mesh86_material_backing_(warp|hardware)$' --output-on-failure ctest --preset release --no-tests=error -R '^startup_mesh86_material_backing_mutant_(warp|hardware)$' --output-on-failure +ctest --preset release --no-tests=error -R '^startup_mesh86_material_backing_provenance_(warp|hardware)$' --output-on-failure ``` The mutant keeps the bytes visible at adoption; both normal tests must pass and both mutant tests must fail (the CTest entries use `WILL_FAIL`). -Limits. Adoption does not see a GPU write submitted before the first material -bind; only writes recorded on the current recording or tracked through a -submitted copy stop a refresh. The changed-run comparison runs at each submit +A GPU write submitted before the first material bind is remembered by +`note_gpu_write` even when linear-buffer tracking is off; adoption then fails +closed with the named refusal instead of refreshing the GPU bytes from stale +title memory. The provenance control seeds a GPU copy while tracking is off, +resolves the first material view (refused) and verifies the GPU bytes survive. +A write performed outside the shim, for example through a desktop list that +bypasses the copy slots, is still not visible. The changed-run comparison runs at each submit over the whole resource and the first refresh copies it whole, so a 174 MiB resource still costs a 174 MiB compare per submission even when few bytes changed. The fixture measures refresh bytes and the reused backing; it does not diff --git a/src/startup_stubs/linear_buffer_backing.h b/src/startup_stubs/linear_buffer_backing.h index 8c6f234952..5882e5db56 100644 --- a/src/startup_stubs/linear_buffer_backing.h +++ b/src/startup_stubs/linear_buffer_backing.h @@ -190,6 +190,7 @@ #include #include #include +#include #include #include "startup_stubs/linear_buffer_report.h" @@ -447,6 +448,16 @@ class LinearBuffers { const auto desc = resource->GetDesc(); if (desc.Dimension != D3D12_RESOURCE_DIMENSION_BUFFER || bytes > desc.Width) return E_INVALIDARG; std::lock_guard lock(mutex_); + // A submitted GPU write on a backing that was not tracked yet makes its desktop bytes + // authoritative; refreshing it from title memory would overwrite them. Fail closed. + if (untracked_gpu_write_overflow_ || untracked_gpu_writes_.count(resource)) { + if (report) { + report->path = kept_default_path; + report->refusal_hr = E_INVALIDARG; + report->backing = resource; + } + return E_INVALIDARG; + } if (const auto found = records_.find(resource); found != records_.end()) { if (found->second.info.path == shared_path) { if (report) *report = found->second.info; @@ -535,7 +546,21 @@ class LinearBuffers { if (linear_detail::mutant("refresh-gpu-written")) return; std::lock_guard lock(mutex_); const auto found = records_.find(resource); - if (found == records_.end() || !found->second.copy || found->second.copy->gpu_written) return; + if (found == records_.end() || !found->second.copy) { + // The backing is not tracked yet. Remember the submitted write so a later adoption + // refuses instead of refreshing the GPU's bytes from stale title memory. + if (untracked_gpu_writes_.size() >= (1u << 16)) { + untracked_gpu_write_overflow_ = true; + } else { + try { + untracked_gpu_writes_.insert(resource); + } catch (const std::bad_alloc&) { + untracked_gpu_write_overflow_ = true; + } + } + return; + } + if (found->second.copy->gpu_written) return; found->second.copy->gpu_written = true; ++totals_.gpu_written; if (x2w_local::first_calls(gpu_write_logged_, 8)) @@ -548,6 +573,7 @@ class LinearBuffers { { std::lock_guard lock(mutex_); records_.erase(resource); + untracked_gpu_writes_.erase(resource); } // The title released the resource: its memory is not read again. The desktop backing stays (as @@ -555,6 +581,7 @@ class LinearBuffers { void retire(ID3D12Resource* resource) { std::lock_guard lock(mutex_); + untracked_gpu_writes_.erase(resource); const auto found = records_.find(resource); if (found == records_.end() || !found->second.copy) return; found->second.copy->live = false; @@ -1363,6 +1390,9 @@ class LinearBuffers { std::mutex mutex_; std::unordered_map records_; + // Submitted GPU writes on a resource without a tracked backing: a later adoption must fail closed. + std::unordered_set untracked_gpu_writes_; + bool untracked_gpu_write_overflow_ = false; std::mutex internal_mutex_; // the internal queue's ExecuteCommandLists and Signal, in value order ID3D12Device* internal_device_ = nullptr; ID3D12CommandQueue* internal_queue_ = nullptr; diff --git a/tests/cmake/startup_mesh86_material_backing.cmake b/tests/cmake/startup_mesh86_material_backing.cmake index d7adf9ade5..9d1776fae7 100644 --- a/tests/cmake/startup_mesh86_material_backing.cmake +++ b/tests/cmake/startup_mesh86_material_backing.cmake @@ -14,4 +14,7 @@ foreach(backend IN ITEMS warp hardware) set_tests_properties(startup_mesh86_material_backing_mutant_${backend} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77 WILL_FAIL TRUE ENVIRONMENT "X2W_D3D12_PERMISSIVE=1;X2W_D3D12_LIST_NOOP=1;X2W_D3D12_RENDER=1;X2W_TEST_LINEAR_BUFFER_MUTANT=skip-refresh") + add_test(NAME startup_mesh86_material_backing_provenance_${backend} COMMAND startup_mesh86_material_backing ${backend}) + set_tests_properties(startup_mesh86_material_backing_provenance_${backend} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77 + ENVIRONMENT "X2W_D3D12_PERMISSIVE=1;X2W_D3D12_LIST_NOOP=1;X2W_D3D12_RENDER=1;X2W_TEST_LINEAR_BUFFER_PROVENANCE=1") endforeach() diff --git a/tests/startup_mesh86_material_backing.cpp b/tests/startup_mesh86_material_backing.cpp index 132b265fbd..9b2d894b99 100644 --- a/tests/startup_mesh86_material_backing.cpp +++ b/tests/startup_mesh86_material_backing.cpp @@ -179,6 +179,14 @@ struct TitleList { native->ResourceBarrier(1, &barrier); } + void guest_barrier(ID3D12Resource* resource, D3D12_RESOURCE_STATES before, D3D12_RESOURCE_STATES after) + { + D3D12_RESOURCE_BARRIER barrier{}; + barrier.Transition = {resource, D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, before, after}; + using Barrier = void (WINAPI*)(IUnknown*, UINT, const D3D12_RESOURCE_BARRIER*); + slot(list.Get(), 26)(list.Get(), 1, &barrier); + } + bool close() { return SUCCEEDED(static_cast(invoke(list.Get(), 9))); } bool submit() @@ -336,11 +344,13 @@ int main(int argc, char** argv) write_word(title, 0, a0); write_word(title, second_srv_offset, b0); + const bool provenance = GetEnvironmentVariableA("X2W_TEST_LINEAR_BUFFER_PROVENANCE", nullptr, 0) != 0; const D3D12_RESOURCE_DESC placed_desc = buffer_desc(buffer_bytes, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS); ComPtr placed; using Place = HRESULT(WINAPI*)(IUnknown*, void*, const D3D12_RESOURCE_DESC*, UINT, const void*, REFIID, void**); const HRESULT placed_hr = slot(device.guest.Get(), 133)( - device.guest.Get(), title, &placed_desc, D3D12_RESOURCE_STATE_COMMON, nullptr, + device.guest.Get(), title, &placed_desc, + provenance ? D3D12_RESOURCE_STATE_COPY_DEST : D3D12_RESOURCE_STATE_COMMON, nullptr, __uuidof(ID3D12Resource), reinterpret_cast(placed.GetAddressOf())); check(SUCCEEDED(placed_hr), "slot 133 places the 64 KiB title buffer"); if (FAILED(placed_hr)) return 1; @@ -364,6 +374,71 @@ int main(int argc, char** argv) UINT64 first_offset = 0, first_bytes = 0, second_offset = 0, second_bytes = 0; int first_source = 0, second_source = 0; std::string reason; + if (provenance) { + // A submitted GPU write precedes the first material bind while linear tracking is off. + // Its desktop bytes are authoritative; adoption must fail closed and leave them intact. + const D3D12_HEAP_PROPERTIES default_heap{D3D12_HEAP_TYPE_DEFAULT}; + const auto source_desc = buffer_desc(sizeof(d0), D3D12_RESOURCE_FLAG_NONE); + ComPtr source; + check(SUCCEEDED(device.guest->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &source_desc, + D3D12_RESOURCE_STATE_COMMON, nullptr, IID_PPV_ARGS(&source))), "provenance source buffer"); + if (failures) return 1; + ComPtr source_native = + underlying(device.desktop.Get(), device.guest.Get(), source.Get()); + check(source_native != nullptr, "provenance source has a desktop resource"); + if (failures) return 1; + const D3D12_HEAP_PROPERTIES upload_heap{D3D12_HEAP_TYPE_UPLOAD}; + ComPtr upload; + check(SUCCEEDED(device.desktop->CreateCommittedResource(&upload_heap, D3D12_HEAP_FLAG_NONE, &source_desc, + D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, IID_PPV_ARGS(&upload))), "provenance upload resource"); + if (failures) return 1; + const D3D12_RANGE empty_range{}; + void* mapped = nullptr; + check(SUCCEEDED(upload->Map(0, &empty_range, &mapped)), "map provenance upload"); + if (failures) return 1; + std::memcpy(mapped, &d0, sizeof(d0)); + upload->Unmap(0, nullptr); + TitleList seed; + check(seed.begin(device), "open provenance seed recording"); + if (failures) return 1; + D3D12_RESOURCE_BARRIER transition{}; + transition.Transition = {source_native.Get(), D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, + D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_COPY_DEST}; + seed.native->ResourceBarrier(1, &transition); + seed.native->CopyBufferRegion(source_native.Get(), 0, upload.Get(), 0, sizeof(d0)); + transition.Transition = {source_native.Get(), D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, + D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_COMMON}; + seed.native->ResourceBarrier(1, &transition); + check(seed.close() && seed.submit(), "seed the provenance source"); + if (failures) return 1; + TitleList copy_list; + check(copy_list.begin(device), "open provenance copy recording"); + if (failures) return 1; + using Copy = void (WINAPI*)(IUnknown*, IUnknown*, UINT64, IUnknown*, UINT64, UINT64); + slot(copy_list.list.Get(), 15)(copy_list.list.Get(), placed.Get(), 0, source.Get(), 0, sizeof(d0)); + transition.Transition = {backing.Get(), D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, + D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_COMMON}; + copy_list.native->ResourceBarrier(1, &transition); + check(copy_list.close() && copy_list.submit(), "submit the provenance GPU write"); + if (failures) return 1; + ID3D12Resource* resolved = nullptr; + UINT64 resolved_offset = 0, resolved_bytes = 0; + int resolved_source = 0; + const bool refused = !resolve_words(device, list, first_record.data(), &resolved, &resolved_offset, + &resolved_bytes, &resolved_source, reason); + check(refused, "a GPU-written backing refuses its first adoption"); + std::printf("provenance refusal: %s\n", reason.c_str()); + check(reason.find("no coherent desktop backing") != std::string::npos, + "the refusal names the missing coherent backing"); + std::array provenance_values{}; + TitleList read_list; + check(read_list.begin(device) && record_read(read_list, read, backing.Get(), provenance_values), + "read the GPU-written backing after the refusal"); + std::printf("provenance values: %08x %08x\n", provenance_values[0], provenance_values[1]); + check(provenance_values[0] == d0 && provenance_values[1] == 0, + "the submitted GPU bytes survive the refused adoption"); + return failures ? 1 : 0; + } const bool first_ok = resolve_words(device, list, first_record.data(), &first_resource, &first_offset, &first_bytes, &first_source, reason); check(first_ok && first_resource == backing.Get() && first_offset == 0 && first_bytes == 16 && first_source == 4, From dd7a038d37eeac9dc0aea2f4860f73c54fdf3c1a Mon Sep 17 00:00:00 2001 From: Roland Edi Date: Tue, 1 Dec 2026 11:54:58 +0000 Subject: [PATCH 11/32] tooling: publish pending slot 86 mesh requests --- CMakePresets.json | 2 +- docs/experiments.md | 15 ++ docs/startup-runtime.md | 18 ++ tests/cmake/startup_mesh86_translate.cmake | 11 + tests/startup_indirect_draw_indexed.cpp | 10 + tests/startup_mesh86_translate_check.py | 196 ++++++++++++++++ tools/startup/gfx2hlsl.py | 39 +++- tools/startup/mesh86_translate.py | 251 +++++++++++++++++++++ tools/startup/run.ps1 | 18 +- 9 files changed, 552 insertions(+), 8 deletions(-) create mode 100644 tests/cmake/startup_mesh86_translate.cmake create mode 100644 tests/startup_mesh86_translate_check.py create mode 100644 tools/startup/mesh86_translate.py diff --git a/CMakePresets.json b/CMakePresets.json index 6bd4804f08..3d5524d06d 100644 --- a/CMakePresets.json +++ b/CMakePresets.json @@ -50,7 +50,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|startup_mesh57_runtime(_[a-z]+)?_warp|native_fixed_mesh57_published_pair(_refusal)?_warp|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_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|native_.*_(ir|dxil|controls)|native_direct_mesh|startup_triage_run)$" + "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|startup_mesh57_runtime(_[a-z]+)?_warp|native_fixed_mesh57_published_pair(_refusal)?_warp|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_indirect_mesh_cache_heap(_wide)?_warp|runtime_mesh86_cache_cli_check|startup_mesh86_translate_warp|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|native_.*_(ir|dxil|controls)|native_direct_mesh|startup_triage_run)$" } } }, diff --git a/docs/experiments.md b/docs/experiments.md index b0b373b68f..f40d8c0354 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -10340,6 +10340,21 @@ python -B tools/startup/mesh86_cache.py --mesh -- ctest --preset release --no-tests=error -R '^startup_indirect_mesh_cache_' -V ``` +The pending scan can perform the translation and the publication together. With +`X2W_MESH86_COMPILER` naming `compile_dxil.exe` and `X2W_MESH86_DXC` naming a +directory that holds `dxc.exe`, `dxcompiler.dll` and `dxil.dll`, `gfx2hlsl.py +--pending` (or `--watch`) translates `req_.m86` with +`gfx1013-container-ms` or `gfx1013-container-ms-texture-heap` and +`req_.ps86` with `gfx1013-mesh86-ps`, then publishes the pair through +`mesh86_cache.py`. A root without direct heap indexing uses the root-constants +proof; a resource-heap root uses the Texture1D map proof or a bounded +heap-buffer window derived from the desktop stages. A malformed request or a +failed proof writes `.fail` and leaves no marker. `run.ps1 -Translate` +sets both variables from `compile_dxil.exe` and the build's recorded DXC +directory when they are present. `startup_mesh86_translate_{warp,hardware}` +checks the pending request, the published version 4 marker and the second run's +desktop PSO, with malformed-key and unproved-heap-root controls. + The executable subset uses the original root and PSO state. It accepts root constants captured on the list, single-sample color attachments in exact format order and a matching depth view when the stream declares one. A cached mesh diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index 976e2f80ee..4b297f3a76 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -1119,6 +1119,23 @@ print the same results and write the same failures as one, an unexpected transla `startup_run_ps1` checks that `-Translate` starts the watcher on the cache and stops it together with a child process. +The same scan translates pending slot 86 mesh requests when `X2W_MESH86_COMPILER` names +`compile_dxil.exe` and `X2W_MESH86_DXC` names its DXC directory. A `req_.m86` request is +translated with `gfx1013-container-ms` (or `gfx1013-container-ms-texture-heap` when the creation +root indexes the resource heap) and `gfx1013-mesh86-ps`, then published through +`tools/startup/mesh86_cache.py`: a root without heap indexing gets the root-constants proof, a +resource-heap root gets the Texture1D map or bounded heap-buffer proof. A malformed request or a +failed proof writes `.fail` and leaves no marker, so the runtime keeps its named +`graphics/mesh_profile_missing` or slot 86 creation refusal. `run.ps1 -Translate` sets both +variables when the build contains `compile_dxil.exe` and the recorded DXC directory contains +`dxc.exe`, `dxcompiler.dll` and `dxil.dll`; where it cannot, the request stays pending as before. + +```powershell +$env:X2W_MESH86_COMPILER = 'out\build\release\compile_dxil.exe' +$env:X2W_MESH86_DXC = 'C:\Program Files (x86)\Windows Kits\10\bin\10.0.26100.0\x64' +.\out\pe-env\Scripts\python.exe -B tools\startup\gfx2hlsl.py --pending out\startup\shader_cache -j 1 +``` + ### Translating compute programs in the stand-in With `X2W_NATIVE_SHADERS=` (`run.ps1 -Render -NativeShaders `), @@ -1855,6 +1872,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 cache lookup the runtime starts a change feed on the directory (`ReadDirectoryChangesW`, top-level file names), then lists the directory's top-level file names once on the feed's thread and logs `x2w-draw cache index: names in ms; change feed ` (`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. The request-part and compute-marker probes (`req_` names, which only runtimes write) skip the disk for a name that is absent from the listing and from this process's own writes. The probes for `.txt` (graphics and compute manifests and the slot 57 base manifest) and `.cs.hlsl` skip it only while the change feed is reading and was reading before the listing began, so a file the translator writes later is found once its change record arrives. After a dropped batch or a feed error they use the disk again. A compute manifest retry (an absent, stale or unmarked `.txt`) whose `.*` names have no change record from the feed since its last miss repeats that miss without a file-system call; the feed records created, removed, renamed and rewritten files, and without a reading feed every retry looks on disk. Every 10 s while probes run, `x2w-draw cache probes (skipped as absent/on disk): ...` gives each probe's counts (and the compute retries repeated without I/O), the feed state, records and added names, the lookups that found a name added after the listing, and contradictions (a write that found a file the index had reported absent). | | `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_MESH86_COMPILER=`, `X2W_MESH86_DXC=` | opt-in, for `gfx2hlsl.py --pending`/`--watch`: translate and publish pending slot 86 mesh requests with `compile_dxil.exe` and the DXC directory. `run.ps1 -Translate` sets them when both are present. Without them, slot 86 requests stay pending. See [Translating shaders during a run](#translating-shaders-during-a-run) | | `X2W_ALLOW_PUBLISHED_MESH57_PAIR=1` | opt-in, in render mode with `X2W_NATIVE_SHADERS`: permits the buffer-view slot 57 path to load a publisher's `.ms57.cso` / `.ps57.cso` pair after native translation refuses with the exact `mesh57_group_index` code. Native translation still runs first. Unset, the pair is ignored and that native refusal is rethrown before the manifest or a CSO is opened, including with `X2W_NATIVE_SHADERS_ONLY=1`. See [fixed mesh pipelines through slot 57](experiments/native-fixed-mesh57.md#published-pair-for-the-r1-group-index-exchange) | | `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 | diff --git a/tests/cmake/startup_mesh86_translate.cmake b/tests/cmake/startup_mesh86_translate.cmake new file mode 100644 index 0000000000..332a378f5c --- /dev/null +++ b/tests/cmake/startup_mesh86_translate.cmake @@ -0,0 +1,11 @@ +# A pending slot 86 request translated and published by gfx2hlsl.py --pending. +if(TARGET compile_dxil AND TARGET startup_indirect_draw_indexed AND EXISTS "${INTAKE_PYTHON}" AND + EXISTS "${DXC_EXECUTABLE}") + foreach(backend IN ITEMS warp hardware) + add_test(NAME startup_mesh86_translate_${backend} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_mesh86_translate_check.py" + "$" "${DXC_EXECUTABLE}" + "$" ${backend}) + set_tests_properties(startup_mesh86_translate_${backend} PROPERTIES TIMEOUT 180 SKIP_RETURN_CODE 77) + endforeach() +endif() diff --git a/tests/startup_indirect_draw_indexed.cpp b/tests/startup_indirect_draw_indexed.cpp index 02b7c56c32..22a7ac369f 100644 --- a/tests/startup_indirect_draw_indexed.cpp +++ b/tests/startup_indirect_draw_indexed.cpp @@ -3300,6 +3300,16 @@ int main(int argc, char** argv) try ? guest_pipeline(guest.Get(), root.Get(), ms_code, ps_code, {}, 1, depth) : guest_pipeline(guest.Get(), root.Get(), ms_code, ps_code, {}, depth_only ? 0 : 3, depth); + if (GetEnvironmentVariableA("X2W_MESH86_FIXTURE_CREATE_ONLY", nullptr, 0)) { + // The translation bridge test runs this fixture once before and once after its request is published. + const bool native = bool(native_object(device.Get(), guest.Get(), pso.Get(), true)); + const bool ready = GetEnvironmentVariableA("X2W_MESH86_FIXTURE_READY", nullptr, 0) != 0; + if (native != ready) { + std::fprintf(stderr, "slot 86 create-only: native PSO %d, expected %d\n", native, ready); + return 1; + } + return 0; + } if (dual_lease) { const bool init_only = GetEnvironmentVariableA("X2W_MESH86_FIXTURE_INIT_ONLY", nullptr, 0) != 0; const auto initialize = writer_pipeline(device.Get(), writer.Get(), "initialize_mesh_record"); diff --git a/tests/startup_mesh86_translate_check.py b/tests/startup_mesh86_translate_check.py new file mode 100644 index 0000000000..f607c019c8 --- /dev/null +++ b/tests/startup_mesh86_translate_check.py @@ -0,0 +1,196 @@ +"""A pending slot 86 request becomes a published profile and a desktop PSO. + +The fixture writes the request through the runtime's normal slot 86 creation path. The +``gfx2hlsl.py --pending`` scan then translates the source-built Xbox containers with +``compile_dxil`` and publishes the pair through ``mesh86_cache.publish``. A second fixture +run must create the desktop PSO from that profile. Two negative controls keep the +publisher's named refusals: a request whose file name disagrees with its bytes, and a root +that indexes the resource heap without a provable window. +""" + +import os +from pathlib import Path +import shutil +import struct +import subprocess +import sys +import tempfile +import time + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE)) +sys.path.insert(0, str(HERE.parent / 'tools' / 'startup')) + +import mesh86_cache +import mesh86_translate +from native_direct_container_check import pack, patched_pixel, signature_rows, words +from native_direct_mesh_check import triangle + + +def program_header(container, stage): + """Add the console DXIL program word the runtime's slot 86 recognizer reads.""" + data = bytearray(container) + parts = struct.unpack_from(' 0 + stages = (('.cs.cso',) if ext == 'c67' else ('.ms57.cso', '.ps57.cso') if mesh else + ('.ms.cso', '.ps.cso') if mesh86 and has_pixel else ('.ms.cso',) if mesh86 else + ('.vs.cso', '.ps.cso')) + manifest_name = base_name + ('.ms57.txt' if mesh else '.mesh86.txt' if mesh86 else '.txt') if completed is not None and key in completed: saved = completed[key] @@ -14191,7 +14213,7 @@ def pending_keys(out_dir, skip_failed, completed=None, watch_since_ns=None, atte current_psin_mtime = None lost = current_psin_mtime is None and ((base_name + '.psdep') in files) if current_psin_mtime == saved_psin_mtime and not lost: - if manifest_only: + if manifest_only and not mesh86: continue if saved_stage_meta is not None: def stage_valid(s_name, s_size, s_mtime): @@ -14230,7 +14252,7 @@ def stage_valid(s_name, s_size, s_mtime): described is not None and manifest_mtime is not None and described > manifest_mtime): ready = False published_stages = [] - if manifest_only: + if manifest_only and not mesh86: ready = True published_stages = [manifest_name] elif mesh: @@ -14242,6 +14264,11 @@ def stage_valid(s_name, s_size, s_mtime): if b'ps none' in published.read().splitlines(): ready = True published_stages = [manifest_name, base_name + '.ms57.cso'] + elif mesh86: + stage_names = [base_name + s for s in stages] + if all(has_complete_mesh57_bytecode(os.path.join(out_dir, name)) for name in stage_names): + ready = True + published_stages = [manifest_name] + stage_names else: def stage_ok(s): se = files.get(base_name + s) diff --git a/tools/startup/mesh86_translate.py b/tools/startup/mesh86_translate.py new file mode 100644 index 0000000000..89dcbe7bfa --- /dev/null +++ b/tools/startup/mesh86_translate.py @@ -0,0 +1,251 @@ +"""Translate a pending slot 86 mesh request and publish its desktop profile. + +The runtime writes ``req_.m86``, ``.ps86``, ``.root`` and ``.stream86`` when a slot 86 +pipeline has no cached desktop pair. This bridge translates those containers with the same +``compile_dxil`` profiles the native slot 86 path uses, then hands the stages to +``mesh86_cache.publish``. The publisher keeps its existing proofs: a root with no direct heap +indexing is checked as constants-only, a resource-heap root is checked as a Texture1D slot map +or as a bounded heap-buffer window, and a malformed or unproved request leaves a named ``.fail`` +instead of a marker. + +The command runs under the ``gfx2hlsl.py`` watcher, which sets ``X2W_MESH86_COMPILER`` and +``X2W_MESH86_DXC`` from ``run.ps1 -Translate``. It is also usable as a one-shot command: + + python -B tools/startup/mesh86_translate.py CACHE [--once] + +``--once`` translates every pending request and exits. Without it, the command rescans every +two seconds until stopped, like ``gfx2hlsl.py --watch``. +""" + +import argparse +import os +from pathlib import Path +import shutil +import struct +import subprocess +import sys +import tempfile +import time + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +import mesh86_cache + + +class Unsupported(Exception): + """A request this bridge cannot translate, with the publisher's refusal text.""" + + +RESOURCE_HEAP = 0x400 +SAMPLER_HEAP = 0x800 + + +def _tool(name: str) -> Path: + value = os.environ.get(name) + if not value: + raise Unsupported(f'slot 86 mesh translation needs {name}') + path = Path(value) + if not path.is_file(): + raise Unsupported(f'{name} is not a regular file: {path}') + return path + + +def _dxc() -> Path: + value = os.environ.get('X2W_MESH86_DXC') + if value: + candidate = Path(value) + if candidate.is_file(): + return candidate + candidate = candidate / 'dxc.exe' + if candidate.is_file(): + return candidate + found = shutil.which('dxc.exe') or shutil.which('dxc') + if not found: + raise Unsupported('slot 86 mesh translation needs X2W_MESH86_DXC and dxc.exe') + return Path(found) + + +def _compiler() -> Path: + return _tool('X2W_MESH86_COMPILER') + + +def _sdk() -> Path: + value = os.environ.get('X2W_MESH86_DXC') + if value: + path = Path(value) + if path.is_dir(): + return path + return _dxc().parent + + +def _compile(cache: Path, key: int, profile: str, source: Path, destination: Path) -> None: + compiler_cache = cache / 'native' + compiler_cache.mkdir(parents=True, exist_ok=True) + command = [str(_compiler()), str(_sdk()), str(compiler_cache), profile, str(source), str(destination)] + result = subprocess.run(command, capture_output=True, text=True, errors='replace', timeout=180) + if result.returncode or not destination.is_file() or not destination.stat().st_size: + lines = [line.strip() for line in (result.stderr or result.stdout).splitlines() if line.strip()] + reason = lines[-1] if lines else 'no diagnostic' + stage = 'mesh' if profile != 'gfx1013-mesh86-ps' else 'pixel' + raise Unsupported(f'slot 86 {stage} translation refused: {reason}') + + +def _dump(dxc: Path, stages: list[Path]) -> list[str]: + dumps = [] + for stage in stages: + result = subprocess.run([str(dxc), '-dumpbin', str(stage)], capture_output=True, text=True, + errors='replace', timeout=60) + if result.returncode: + lines = [line.strip() for line in result.stderr.splitlines() if line.strip()] + raise Unsupported('slot 86 stage could not be dumped for its proof: ' + + (lines[-1] if lines else 'no diagnostic')) + dumps.append(result.stdout) + return dumps + + +def _heap_window(dumps: list[str]) -> tuple[int, int]: + """Smallest resource-heap slot window covering every createHandleFromHeap read.""" + first = last = None + reads = 0 + for dump in dumps: + lines = mesh86_cache._function_lines(dump) + defs = {} + for line in lines: + match = mesh86_cache._DEF.fullmatch(line) + if match: + defs[match[1]] = match[2] + for value in defs.values(): + match = mesh86_cache._HEAP_HANDLE.fullmatch(value.partition(';')[0].strip()) + if not match: + continue + low, high = mesh86_cache._heap_index_range(match[1], defs) + first = low if first is None else min(first, low) + last = high if last is None else max(last, high) + reads += 1 + if not reads: + raise ValueError('the heap-buffer profile requires at least one resource-heap read') + count = last - first + 1 + if not 1 <= count <= mesh86_cache.HEAP_WINDOW_MAX or first < 0 or \ + first > mesh86_cache.HEAP_SLOT_LIMIT - count: + raise ValueError(f'heap reads span {first}..{last}, outside a publishable window') + return first, count + + +def _publish(cache: Path, key: int, mesh: Path, pixel: Path | None, flags: int) -> str: + dxc = _dxc() + if flags & RESOURCE_HEAP: + stages = [mesh] + ([pixel] if pixel else []) + dumps = _dump(dxc, stages) + try: + mesh86_cache.publish(cache, key, mesh, pixel, texture_map_dxc=dxc) + return 'Texture1D map profile' + except ValueError as map_error: + try: + first, count = _heap_window(dumps) + except ValueError as window_error: + raise Unsupported(f'slot 86 heap proof refused: {window_error}; ' + f'Texture1D map proof: {map_error}') from None + try: + mesh86_cache.publish(cache, key, mesh, pixel, heap_window=(first, count), heap_dxc=dxc) + except ValueError as error: + raise Unsupported(f'slot 86 heap-buffer {first}+{count} proof refused: {error}') from None + return f'heap-buffer {first}+{count} profile' + if flags & SAMPLER_HEAP: + raise Unsupported('slot 86 root indexes only the sampler heap; no published profile accepts it') + try: + mesh86_cache.publish(cache, key, mesh, pixel, constants_dxc=dxc) + except ValueError as error: + raise Unsupported(f'slot 86 root-constants proof refused: {error}') from None + return 'root-constants profile' + + +def translate_request(cache: Path, key: int) -> str: + """Translate one complete request and publish its profile, or raise Unsupported.""" + cache = Path(cache) + try: + mesh, pixel, root, _ = mesh86_cache.load_request(cache, key) + except (ValueError, OSError, struct.error) as error: + raise Unsupported(str(error)) from None + try: + flags, _ = mesh86_cache.root_constant_layout(root) + except (ValueError, struct.error) as error: + raise Unsupported(str(error)) from None + mesh_profile = 'gfx1013-container-ms-texture-heap' if flags & RESOURCE_HEAP else 'gfx1013-container-ms' + with tempfile.TemporaryDirectory(prefix='.mesh86-translate-', dir=cache) as temporary: + work = Path(temporary) + mesh_path = work / 'ms.cso' + _compile(cache, key, mesh_profile, cache / f'req_{key:016x}.m86', mesh_path) + pixel_path = None + if pixel: + pixel_path = work / 'ps.cso' + _compile(cache, key, 'gfx1013-mesh86-ps', cache / f'req_{key:016x}.ps86', pixel_path) + profile = _publish(cache, key, mesh_path, pixel_path, flags) + return f'published slot 86 mesh {profile}' + + +def pending_keys(cache: Path, skip_failed: bool = False) -> list[int]: + keys = [] + for marker in cache.glob('req_*.m86'): + stem = marker.stem + if len(stem) != 20 or not stem.startswith('req_'): + continue + try: + key = int(stem[4:], 16) + except ValueError: + continue + try: + ready = cache / f'{key:016x}.mesh86.txt' + fail = cache / f'{key:016x}.fail' + pixel_source = cache / f'req_{key:016x}.ps86' + stages = [cache / f'{key:016x}.ms.cso'] + if pixel_source.is_file() and pixel_source.stat().st_size: + stages.append(cache / f'{key:016x}.ps.cso') + if ready.is_file() and all(stage.is_file() and stage.stat().st_size for stage in stages): + continue + if skip_failed and fail.is_file() and fail.stat().st_mtime >= marker.stat().st_mtime: + continue + except OSError: + continue + keys.append(key) + return sorted(keys) + + +def translate_pending(cache: Path, skip_failed: bool = False) -> int: + failures = 0 + for key in pending_keys(cache, skip_failed): + try: + result = translate_request(cache, key) + except Unsupported as error: + failures += 1 + result = f'unsupported: {error}' + (cache / f'{key:016x}.fail').write_text(str(error) + '\n', encoding='utf-8') + except Exception as error: # noqa: BLE001 - one request must not stop the scan + failures += 1 + message = f'translator error: {type(error).__name__}: {error}' + result = message + (cache / f'{key:016x}.fail').write_text(message + '\n', encoding='utf-8') + print(f'{key:016x}: {result}', flush=True) + return failures + + +def main(argv=None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('cache', type=Path) + parser.add_argument('--once', action='store_true', help='translate the pending requests and exit') + parser.add_argument('--skip-failed', '-s', action='store_true', + help='skip a request whose .fail is newer than its .m86') + parser.add_argument('--interval', type=float, default=2.0, help='seconds between watch scans') + args = parser.parse_args(argv) + if not args.cache.is_dir(): + parser.error(f'cache directory not found: {args.cache}') + if args.once: + translate_pending(args.cache, args.skip_failed) + return 0 + first = True + while True: + translate_pending(args.cache, args.skip_failed and not first) + first = False + time.sleep(args.interval) + + +if __name__ == '__main__': + raise SystemExit(main()) diff --git a/tools/startup/run.ps1 b/tools/startup/run.ps1 index e1aa9c299a..b7fcda188c 100644 --- a/tools/startup/run.ps1 +++ b/tools/startup/run.ps1 @@ -81,9 +81,9 @@ if ($Render) { New-Item -ItemType Directory -Force $ShaderCache | Out-Null $env:X2W_D3D12_RENDER = "1"; $env:X2W_DRAW_NULL_IDENTITY = "1" $env:X2W_SHADER_CACHE = (Resolve-Path $ShaderCache).Path + $dxcDirFile = Join-Path $buildRoot "x2w-dxc-dir.txt" if (-not $Translate) { if (-not $NativeShaders) { $NativeShaders = $env:X2W_NATIVE_SHADERS } - $dxcDirFile = Join-Path $buildRoot "x2w-dxc-dir.txt" if (-not $NativeShaders -and (Test-Path -LiteralPath $dxcDirFile)) { $NativeShaders = (Get-Content -LiteralPath $dxcDirFile -Raw).Trim() } @@ -119,6 +119,22 @@ $watchShaders = $Translate -and $Render if ($Translate -and -not $Render) { Write-Warning "-Translate needs -Render (no shader cache without it); ignored" } if ($watchShaders) { $revisionWarned = & $checkRevision + # The Python watcher forwards slot 86 requests to compile_dxil. Enable that bridge only when both the + # tool and its DXC directory are present; a run without them keeps the request pending as before. + $mesh86Compiler = Join-Path $buildRoot "compile_dxil.exe" + $mesh86Dxc = if ($NativeShaders) { $NativeShaders } elseif (Test-Path -LiteralPath $dxcDirFile) { + (Get-Content -LiteralPath $dxcDirFile -Raw).Trim() + } else { $null } + if ((Test-Path -LiteralPath $mesh86Compiler -PathType Leaf) -and $mesh86Dxc -and + (Test-Path -LiteralPath (Join-Path $mesh86Dxc "dxcompiler.dll") -PathType Leaf) -and + (Test-Path -LiteralPath (Join-Path $mesh86Dxc "dxil.dll") -PathType Leaf) -and + (Test-Path -LiteralPath (Join-Path $mesh86Dxc "dxc.exe") -PathType Leaf)) { + $env:X2W_MESH86_COMPILER = (Resolve-Path -LiteralPath $mesh86Compiler).Path + $env:X2W_MESH86_DXC = (Resolve-Path -LiteralPath $mesh86Dxc).Path + } else { + Remove-Item Env:X2W_MESH86_COMPILER -ErrorAction SilentlyContinue + Remove-Item Env:X2W_MESH86_DXC -ErrorAction SilentlyContinue + } $translator = Start-Process -FilePath $python -PassThru -NoNewWindow ` -ArgumentList "-B", "`"$(Join-Path $PSScriptRoot 'gfx2hlsl.py')`"", "--watch", "`"$env:X2W_SHADER_CACHE`"" ` -RedirectStandardOutput (Join-Path $LogDir "translate.txt") -RedirectStandardError (Join-Path $LogDir "translate_err.txt") From 5625b2058d0c4dd8f27d138781ec0fbaeec23b6c Mon Sep 17 00:00:00 2001 From: Luuk Motz Date: Tue, 1 Dec 2026 18:09:23 +0100 Subject: [PATCH 12/32] shader: merge mesh writes under one CMPX inside a lane skip and restore the guard Inside the vertex skip, skinned mesh programs save EXEC, narrow it with one v_cmpx_ne_u32 and no EXECZ, run straight-line VALU work and restore the saved vertex mask. The restore was refused as "mesh EXEC write inside a lane-skip block". When the CMPX runs, every register is exact for the skip's guard lanes. A write under the narrowed mask whose old value is still that exact value (unchanged since the CMPX, or itself merged) is now merged per lane with it, so it stays exact for the guard. A restore of the guard's saved mask keeps every register that is unchanged since the CMPX or merged, and clears the rest, such as a register first written under the narrowed mask. A second narrowing, or a restore of a mask saved under the narrowed EXEC, stays refused. Part of #3703. Co-Authored-By: Claude Opus 5.5 --- src/gfx1013_direct_mesh.inl | 51 +++++++++++++++++++++++++++++-- tests/native_direct_mesh_check.py | 28 +++++++++++++++++ 2 files changed, 77 insertions(+), 2 deletions(-) diff --git a/src/gfx1013_direct_mesh.inl b/src/gfx1013_direct_mesh.inl index abc97056b8..b2b306409d 100644 --- a/src/gfx1013_direct_mesh.inl +++ b/src/gfx1013_direct_mesh.inl @@ -286,6 +286,10 @@ NativeComputeShader lower_mesh(const string &code, const MeshStageLayout &layout struct MaskState { bool full; string lane,wave,lo,hi; decltype(alu.graphics_registers) regs; std::set partial; }; std::map saved_exec; std::map before_narrowing; + // One CMPX narrowing an open lane skip's guard, with no EXECZ: the registers when it ran (all exact + // for the guard's lanes) and the values merged per lane against them since (see the EXEC restore). + struct SkipNarrowing { unsigned skip; string lane; decltype(alu.graphics_registers) regs; std::set merged; }; + std::optional skip_narrowing; auto saved_mask=[&](unsigned source)->const MaskState * { if (source>104 || (source&1)) return nullptr; const auto &lo=state[source], &hi=state[source+1]; @@ -1285,6 +1289,7 @@ NativeComputeShader lower_mesh(const string &code, const MeshStageLayout &layout before_partial[j]=partial_writes.count(vec_dst+j)!=0; } } + const string lane_at_start=lane_active; const bool export_cmp=i.name=="v_cmpx_gt_i32" && allocated && i.src[0]<106 && full_exec && (alu.read(i.src[0])==vertex_count || alu.read(i.src[0])==primitive_count); if ((i.name=="v_cmpx_gt_u32" || export_cmp) && full_exec && !branch && !exec_skip && i.enc==Encoding::Vopc && !i.wide && !i.subword && !i.dpp_control && @@ -1949,12 +1954,28 @@ NativeComputeShader lower_mesh(const string &code, const MeshStageLayout &layout saved_exec[pc]={full_exec,lane_active,wave_active,exec_value[0],exec_value[1],alu.graphics_registers,partial_writes}; } else if (i.name=="s_mov_b64" && i.dst==126 && i.src[0]<=104 && !(i.src[0]&1)) { const auto mask=saved_mask(i.src[0]); - if (exec_skip && !diamond_exec_restore && + // The guard restored after one CMPX narrowed it inside the skip: each register is either + // unchanged since that CMPX or merged per lane against its value then. + const bool narrowed_restore=exec_skip && !branch && skip_narrowing && skip_narrowing->lane==lane_active && + skip_narrowing->skip==exec_skip->start && + mask && !mask->full && mask->lane==exec_skip->guard && mask->wave==exec_skip->wave_guard; + if (exec_skip && !diamond_exec_restore && !narrowed_restore && !((closed_nested_skip || after_diamond_join) && mask && !mask->full && mask->lane==exec_skip->guard && mask->wave==exec_skip->wave_guard)) refuse(pc,"mesh EXEC write inside a lane-skip block"); if (!mask) refuse(pc,"mesh EXEC restore lacks a still-valid reaching mask"); - if (mask->lane!=lane_active) { + if (narrowed_restore) { + std::set remaining; + for (auto r:partial_writes) { + const auto &now=alu.graphics_registers.at(r); + const auto at=skip_narrowing->regs.find(r); + if ((at!=skip_narrowing->regs.end() && !at->second.empty() && at->second==now) || + skip_narrowing->merged.count(now)) remaining.insert(r); + else alu.write(r,{}); + } + partial_writes=std::move(remaining); + skip_narrowing.reset(); + } else if (mask->lane!=lane_active) { auto at_narrow=before_narrowing.find(mask->lane); const auto ®s=at_narrow==before_narrowing.end() ? mask->regs : at_narrow->second.regs; const auto &valid=at_narrow==before_narrowing.end() ? mask->partial : at_narrow->second.partial; @@ -2177,8 +2198,34 @@ NativeComputeShader lower_mesh(const string &code, const MeshStageLayout &layout alu.record_graphics_bits(value,bits); if (!u.empty()) active_uniform[value]={lane_active,u}; partial_writes.erase(vec_dst+j); + } else if (skip_narrowing && skip_narrowing->lane==lane_active && exec_skip && !branch && + skip_narrowing->skip==exec_skip->start && + !before_vec[j].empty() && before_partial[j] && !value_limits.count(before_vec[j]) && + alu.graphics_registers.at(vec_dst+j)!=before_vec[j] && + (skip_narrowing->merged.count(before_vec[j]) || [&] { + const auto at=skip_narrowing->regs.find(vec_dst+j); + return at!=skip_narrowing->regs.end() && at->second==before_vec[j]; + }())) { + // The old value is exact for the guard's lanes, so the merge is too; it stays partial + // against full EXEC. + auto &value=alu.graphics_registers.at(vec_dst+j); + auto u=uniform(value); + const auto bits=alu.graphics_bits(value)&alu.graphics_bits(before_vec[j]); + value=alu.select(lane_active,value,before_vec[j]); + alu.record_graphics_bits(value,bits); + if (!u.empty()) active_uniform[value]={lane_active,u}; + skip_narrowing->merged.insert(value); } } + // A skip opened under the narrowed mask ends the straight-line region; its close is not a merge. + if (iname=="s_cbranch_execz") skip_narrowing.reset(); + // A CMPX narrowing the open skip's guard starts a region the restore above can close. + if (iname.rfind("v_cmpx",0)==0 && exec_skip && !branch && lane_at_start==exec_skip->guard && + lane_active!=lane_at_start) { + const auto parent=mask_parent.find(lane_active); + if (parent!=mask_parent.end() && parent->second==lane_at_start) + skip_narrowing=SkipNarrowing{exec_skip->start,lane_active,alu.graphics_registers,{}}; + } if (result_bound && *result_boundsecond.empty()) upper_bound[it->second]=*result_bound; diff --git a/tests/native_direct_mesh_check.py b/tests/native_direct_mesh_check.py index 0816a19356..a0d1ebd874 100644 --- a/tests/native_direct_mesh_check.py +++ b/tests/native_direct_mesh_check.py @@ -1411,6 +1411,34 @@ def merged(condition): assert 'storeVertexOutput' in run('bounded-export-root-branch', bounded(v=merged(0xbf068015))) # s21 == 0 run('bounded-export-wave-branch', bounded(v=merged(0xbf068016)), lane_range) # s22 == 0 + # Inside the vertex skip, the title saves EXEC, narrows it with one CMPX and no EXECZ, runs + # straight-line VALU work and restores the saved vertex mask. Every register is exact for the + # vertex lanes when the CMPX runs, so a write under the narrowed mask is merged per lane with + # the old value and the restore keeps it. v10 is then read and written under the vertex mask. + lane_skip_exec = 'mesh EXEC write inside a lane-skip block' + def narrowed(region, restore=0xbefe0426, after=(0x061414f2,)): # v_add_f32 v10, 1.0, v10 + body = ([0xbea6047e, # s_mov_b64 s[38:39], exec (the vertex mask) + 0x7e1402f2, # v_mov_b32 v10, 1.0 + 0x7daa0080] + list(region) + # v_cmpx_ne_u32 0, v0 + [restore] + list(after)) # s_mov_b64 exec, s[38:39] + return (count_setup[:4] + [0x8717ff15, 0x3, 0xbf068017, 0x85221780, 0xbea30381, 0x8f1c8616, + 0xd7650000, 0x000038c1, 0xd7660000, 0x000200c1] + + [0x7da80017, 0xbf880000 | len(body)] + body + # v_cmpx_gt_u32 s23, v0; the vertex skip + [0xbefe04c1] + allocate + [0x7d280022, 0xbf880002, + 0xf8000201, 0x0000000a, # exp param0 v10 + 0xbefe04c1] + program[3:]) + base = run('skip-narrow-empty', narrowed([])) + text = run('skip-narrow-merge', narrowed([0x061414f2])) # v_add_f32 v10, 1.0, v10 under v0 != 0 + assert 'storeVertexOutput' in text and text.count('select ') == base.count('select ') + 1, text + # A register first written under the narrowed mask has no value for thread 0 at the restore. + run('skip-narrow-new-register', narrowed([0x7e1602f4], # v_mov_b32 v11, 2.0 + after=(0x0614150b,)), # v_add_f32 v10, v11, v10 + 'graphics register undefined on an incoming path: 267') + # A second narrowing is not merged against the vertex mask, so its restore stays refused. + run('skip-narrow-twice', narrowed([0x7daa0080, 0x061414f2]), lane_skip_exec) + # So is a restore of a mask saved under the narrowed EXEC. + run('skip-narrow-inner-save', narrowed([0xbea8047e, 0x061414f2], restore=0xbefe0428), lane_skip_exec) + layout.write_text('mesh1 128 3 1 2 128 64\ntable 16 0') run('mistyped-root',words+controlled,'root parameter kind') layout.write_text('mesh1 128 3 1 2 128 64') From a7d98042b3f60b981dbc4a8b37874f68c192e5ee Mon Sep 17 00:00:00 2001 From: Luuk Motz Date: Tue, 1 Dec 2026 09:26:16 +0100 Subject: [PATCH 13/32] shader: keep a mesh lane limit across a nested CMPX skip that closes at the same restore The #3671 lane-limit proof tags partial VGPRs with the vertex skip's lane count when the skip closes, so an export under the same count may read them after full EXEC returns. It required the closing skip's guard to be the current lane mask. When a nested CMPX skip inside the vertex skip exits to the same EXEC restore, the nested mask is still current at the outer close, so the proof was skipped and the restore erased the position VGPRs ("graphics register undefined on an incoming path"). A nested per-lane skip now records the parent guard when it opens directly after a single CMPX that narrowed it. Nothing ran under the narrowed mask outside that skip, and the skip branches per thread, so after it closes every register is exact for each of the parent's lanes. If the parent then closes at the same instruction, its lane limit applies as before. Any other narrowing, a write between the CMPX and the EXECZ, or another path arriving at the restore keeps the previous behavior. Part of #3703 (item 6). Co-Authored-By: Claude Opus 5.5 --- src/gfx1013_direct_mesh.inl | 28 ++++++++++++++++++++++---- tests/native_direct_mesh_check.py | 33 +++++++++++++++++++++++++++++++ 2 files changed, 57 insertions(+), 4 deletions(-) diff --git a/src/gfx1013_direct_mesh.inl b/src/gfx1013_direct_mesh.inl index 575612d031..5b95818710 100644 --- a/src/gfx1013_direct_mesh.inl +++ b/src/gfx1013_direct_mesh.inl @@ -595,7 +595,8 @@ NativeComputeShader lower_mesh(const string &code, const MeshStageLayout &layout if (scalar_branch && outer.contains_child) refuse(*scalar_branch,"mesh scalar branch crosses a nested SAVEEXEC region"); }; - struct Skip { unsigned start,end; Edge entry; bool per_lane; string guard, wave_guard; }; + // narrowed_from: the parent skip's guard, when this per-lane skip opened right after one CMPX narrowed it. + struct Skip { unsigned start,end; Edge entry; bool per_lane; string guard, wave_guard, narrowed_from{}; }; std::vector skip_parents; std::optional exec_skip; alu.check_graphics_read=[&](unsigned reg,const string &value) { @@ -744,6 +745,8 @@ NativeComputeShader lower_mesh(const string &code, const MeshStageLayout &layout }; std::optional pending_saveexec_restore; unsigned pc = 0; + string last_name, carried_lane; // the last fully lowered instruction; a lane set carried to a parent skip close + unsigned last_end=~0u; while (pc < code.size()) { // All handled scalar branches are forward, so every predecessor is // available when we reach its target. Funnel arbitrary fan-in into @@ -757,6 +760,7 @@ NativeComputeShader lower_mesh(const string &code, const MeshStageLayout &layout diamond_joined=false; // another path arrives between the join and the restore if (live) ir.body<<" br label %"<guard); - const bool retain=skip_parents.empty() && exec_skip->guard==lane_active && + // A nested skip that closed at this same instruction (see Skip::narrowed_from) leaves its + // narrowed mask in lane_active, but every register is exact again for the guard's lanes. + const bool guard_lanes=exec_skip->guard==lane_active || + (!carried_lane.empty() && carried_lane==exec_skip->guard); + carried_lane.clear(); + const bool retain=skip_parents.empty() && guard_lanes && !branch && forward.empty() && limit!=lane_limits.end(); merge_edges(exec_skip->entry,"mesh_empty"+tag,"mesh_done"+tag,retain ? limit->second : string{}); + const auto narrowed_from=exec_skip->per_lane && exec_skip->guard==lane_active ? + exec_skip->narrowed_from : string{}; exec_skip.reset(); if (!skip_parents.empty()) { exec_skip=std::move(skip_parents.back());skip_parents.pop_back(); - if (pc==exec_skip->end) return true; + if (pc==exec_skip->end) { carried_lane=narrowed_from; return true; } closed_nested_skip=true; } return false; @@ -1360,11 +1371,19 @@ NativeComputeShader lower_mesh(const string &code, const MeshStageLayout &layout full_exec=false; wave_active.clear(); exec_value[0].clear();exec_value[1].clear(); } else if (i.name=="s_cbranch_execz" && !full_exec && !lane_active.empty() && !branch && i.target()>i.next && i.target()second==exec_skip->guard) narrowed_from=parent->second; + } if (exec_skip) { if (i.target()>exec_skip->end) refuse(pc,"overlapping mesh EXECZ exits"); skip_parents.push_back(std::move(*exec_skip)); } - exec_skip=Skip{pc,i.target(),save_edge(),wave_active.empty(),lane_active,wave_active}; + exec_skip=Skip{pc,i.target(),save_edge(),wave_active.empty(),lane_active,wave_active,narrowed_from}; ir.body<<" br i1 "<<(wave_active.empty() ? lane_active : wave_active)<<", label %mesh_work"< Date: Tue, 1 Dec 2026 17:47:02 +0100 Subject: [PATCH 14/32] shader: carry exact mesh lanes through nested CMPX skips to an EXEC restore A chain of per-lane skips, each opened straight after a CMPX that narrows the skip around it, merges every register per lane when it closes. #3710 carried that fact from one nested skip to its parent only, and only when the parent closed at the same instruction. Skinned mesh programs nest three such skips inside the vertex skip and close all of them at a restore of the vertex mask, after which the vertex skip goes on. The restore then treated every register written since the mask was saved as stale and cleared it, so the next read refused with "graphics register undefined on an incoming path". The carried lane set now passes through any depth of skips closing at one pc, and an EXEC restore at that pc keeps the register file when the restored mask is the carried guard of the enclosing skip. The set is tied to its pc so it never describes a later instruction. A write between the innermost CMPX and its EXECZ, or a narrowing that is not a CMPX, still breaks the chain. Part of #3703. Co-Authored-By: Claude Opus 5.5 --- src/gfx1013_direct_mesh.inl | 17 ++++++++++----- tests/native_direct_mesh_check.py | 35 +++++++++++++++++++++++++++++++ 2 files changed, 47 insertions(+), 5 deletions(-) diff --git a/src/gfx1013_direct_mesh.inl b/src/gfx1013_direct_mesh.inl index 5b95818710..2e1817ae64 100644 --- a/src/gfx1013_direct_mesh.inl +++ b/src/gfx1013_direct_mesh.inl @@ -746,6 +746,7 @@ NativeComputeShader lower_mesh(const string &code, const MeshStageLayout &layout std::optional pending_saveexec_restore; unsigned pc = 0; string last_name, carried_lane; // the last fully lowered instruction; a lane set carried to a parent skip close + unsigned carried_at=~0u; // the pc whose skip closes set carried_lane; it describes no other pc unsigned last_end=~0u; while (pc < code.size()) { // All handled scalar branches are forward, so every predecessor is @@ -801,17 +802,19 @@ NativeComputeShader lower_mesh(const string &code, const MeshStageLayout &layout // A nested skip that closed at this same instruction (see Skip::narrowed_from) leaves its // narrowed mask in lane_active, but every register is exact again for the guard's lanes. const bool guard_lanes=exec_skip->guard==lane_active || - (!carried_lane.empty() && carried_lane==exec_skip->guard); + (carried_at==pc && !carried_lane.empty() && carried_lane==exec_skip->guard); carried_lane.clear(); const bool retain=skip_parents.empty() && guard_lanes && !branch && forward.empty() && limit!=lane_limits.end(); merge_edges(exec_skip->entry,"mesh_empty"+tag,"mesh_done"+tag,retain ? limit->second : string{}); - const auto narrowed_from=exec_skip->per_lane && exec_skip->guard==lane_active ? - exec_skip->narrowed_from : string{}; + // Exact for the guard's lanes, a skip opened straight after a CMPX makes the parent exact too, + // so the lane set carries through any depth of skips closing here. + const auto narrowed_from=exec_skip->per_lane && guard_lanes ? exec_skip->narrowed_from : string{}; exec_skip.reset(); if (!skip_parents.empty()) { exec_skip=std::move(skip_parents.back());skip_parents.pop_back(); - if (pc==exec_skip->end) { carried_lane=narrowed_from; return true; } + carried_lane=narrowed_from; carried_at=pc; // read by the parent's close or an EXEC restore at pc + if (pc==exec_skip->end) return true; closed_nested_skip=true; } return false; @@ -1976,7 +1979,11 @@ NativeComputeShader lower_mesh(const string &code, const MeshStageLayout &layout mask->wave==exec_skip->wave_guard)) refuse(pc,"mesh EXEC write inside a lane-skip block"); if (!mask) refuse(pc,"mesh EXEC restore lacks a still-valid reaching mask"); - if (mask->lane!=lane_active) { + // Nested CMPX skips that closed here carried the enclosing skip's guard (see close_skip): + // each skip merged per lane, so every register is already exact for the restored lanes. + const bool carried=closed_nested_skip && exec_skip && carried_at==pc && !carried_lane.empty() && + carried_lane==exec_skip->guard && mask->lane==carried_lane && mask->wave==exec_skip->wave_guard; + if (mask->lane!=lane_active && !carried) { auto at_narrow=before_narrowing.find(mask->lane); const auto ®s=at_narrow==before_narrowing.end() ? mask->regs : at_narrow->second.regs; const auto &valid=at_narrow==before_narrowing.end() ? mask->partial : at_narrow->second.partial; diff --git a/tests/native_direct_mesh_check.py b/tests/native_direct_mesh_check.py index caa75c371b..3a16f1fbb8 100644 --- a/tests/native_direct_mesh_check.py +++ b/tests/native_direct_mesh_check.py @@ -1469,6 +1469,41 @@ def nested(narrow=(0x7da40080,), # v_cmpx_eq_u32 0, v0 # The export still needs the count guard. run('nested-skip-full-exec', nested(guard=()), lane_range) + # A chain of nested CMPX skips inside the vertex skip, each opened straight after a CMPX that + # narrows the one around it. All of them exit to one restore of the vertex mask saved in + # s[38:39], and the vertex skip then goes on: v10 is read and written again under the vertex + # mask before the export. Each thread below V holds an exact v10 at that restore. + def chain(depth, restore=True, narrow=(0x7da40080,)): # v_cmpx_eq_u32 0, v0 + body = [0xbea6047e, # s_mov_b64 s[38:39], exec (the vertex mask) + 0x7e1402f2] # v_mov_b32 v10, 1.0 + exits = [] + for level in range(depth): + body += list(narrow) if level == depth - 1 else [0x7da40080] + exits.append(len(body)) + body += [0, 0x061414f2] # s_cbranch_execz; v_add_f32 v10, 1.0, v10 + end = len(body) + for at in exits: + body[at] = 0xbf880000 | (end - at - 1) # every exit lands on the restore (or the skip end) + if restore: + body += [0xbefe0426, # s_mov_b64 exec, s[38:39] + 0x061414f2] # v_add_f32 v10, 1.0, v10 under the vertex mask + return (count_setup[:4] + [0x8717ff15, 0x3, 0xbf068017, 0x85221780, 0xbea30381, 0x8f1c8616, + 0xd7650000, 0x000038c1, 0xd7660000, 0x000200c1] + + [0x7da80017, 0xbf880000 | len(body)] + body + # v_cmpx_gt_u32 s23, v0; the vertex skip + [0xbefe04c1] + allocate + [0x7d280022, 0xbf880002, + 0xf8000201, 0x0000000a, # exp param0 v10 + 0xbefe04c1] + program[3:]) + for depth in (1, 3): + text = run(f'nested-skip-chain-restore-{depth}', chain(depth)) + assert 'storeVertexOutput' in text and text.count('fadd') >= depth + 1, text + # Two nested skips that close where the vertex skip closes carry the lane set through both. + assert 'storeVertexOutput' in run('nested-skip-chain-end', chain(2, restore=False)) + # A write between the innermost CMPX and its EXECZ runs for every thread of the skip around it + # with a value only valid under the narrowed mask, so the chain is broken at the restore. + run('nested-skip-chain-write-before-execz', chain(3, narrow=(0x7da40080, 0x7e1402f6)), undefined) + # So is a narrowing that is not a CMPX (v_cmp; s_and_b64 exec, vcc). + run('nested-skip-chain-and-exec', chain(3, narrow=(0x7d840080, 0x87fe6a7e)), undefined) + layout.write_text('mesh1 128 3 1 2 128 64\ntable 16 0') run('mistyped-root',words+controlled,'root parameter kind') layout.write_text('mesh1 128 3 1 2 128 64') From 8f769c7e4a5ab11a61f77b2692100b59fd201f5c Mon Sep 17 00:00:00 2001 From: Luuk Motz Date: Tue, 1 Dec 2026 18:47:31 +0100 Subject: [PATCH 15/32] shader, runtime: lower and bind mesh format loads from a descriptor-table V# The mesh frontend accepted buffer_load_format_x only from a resource heap slot. Skinned slot 86 programs read the V# whole from a bound descriptor table instead and were refused with "formatted mesh load lacks an R32_UINT resource heap contract". Translator: a format load whose V# comes from a bound table goes through the shared typed-buffer SRV path, as in vertex and pixel shaders, which checks the table binding and all four descriptor words. The #3720 control that kept this route refused under heap tokens now checks that it compiles without a token view. Runtime: slot 86 accepts a one-dword typed_buffer_srv from a descriptor table and binds it as an R32_UINT buffer view through the same checks as a typed heap slot (R32_UINT token view, or a raw V# with the identity component map and a 4-byte stride). A raw table V# must also name a 32-bit format (32_UINT, 32_SINT or 32_FLOAT), so the view returns the dword the guest load would. Those word 3 checks live in mesh86_typed_vsharp.h with unit tests and two mutation controls. Part of #3703. Co-Authored-By: Claude Opus 5.5 --- src/gfx1013_direct_mesh.inl | 7 +++ src/startup_stubs/d3d12_xs_device.cpp | 1 + src/startup_stubs/mesh86_typed_vsharp.h | 23 +++++++ src/startup_stubs/native_mesh86.inl | 39 ++++++++---- tests/cmake/mesh86_typed_vsharp.cmake | 43 +++++++++++++ tests/mesh86_typed_vsharp_check.cpp | 83 +++++++++++++++++++++++++ tests/native_direct_mesh_check.py | 30 ++++++++- 7 files changed, 213 insertions(+), 13 deletions(-) create mode 100644 src/startup_stubs/mesh86_typed_vsharp.h create mode 100644 tests/cmake/mesh86_typed_vsharp.cmake create mode 100644 tests/mesh86_typed_vsharp_check.cpp diff --git a/src/gfx1013_direct_mesh.inl b/src/gfx1013_direct_mesh.inl index 575612d031..879d7a11d1 100644 --- a/src/gfx1013_direct_mesh.inl +++ b/src/gfx1013_direct_mesh.inl @@ -1484,6 +1484,13 @@ NativeComputeShader lower_mesh(const string &code, const MeshStageLayout &layout alu.write(i.dst+j,j>=1 && j<=3 ? texture_metadata[j-1] : string{}); } state=next; + } else if (i.name=="buffer_load_format" && i.op==0 && (full_exec || exec_skip) && + ((i.a&0x3ffff)==0x2000 || (i.a&0x3ffff)==0) && + state[((i.b>>16)&31)*4].type==Symbol::Type::descriptor) { + // A V# read whole from a bound descriptor table: the shared typed-buffer SRV path checks the + // table binding and all four descriptor words, as it does for vertex and pixel shaders. + alu.memory(i,state); + if (!full_exec) partial_writes.insert(256+i.dst); } else if (i.name=="buffer_load_format" && i.op==0 && (full_exec || exec_skip) && ((i.a&0x3ffff)==0x2000 || (i.a&0x3ffff)==0)) { const auto base=((i.b>>16)&31)*4; diff --git a/src/startup_stubs/d3d12_xs_device.cpp b/src/startup_stubs/d3d12_xs_device.cpp index 0a3ddf5832..21aa22eb0d 100644 --- a/src/startup_stubs/d3d12_xs_device.cpp +++ b/src/startup_stubs/d3d12_xs_device.cpp @@ -14,6 +14,7 @@ #define X2W_TRAP_MODULE_ID 7 #include "startup_stubs/indexed_resource_list.h" #include "startup_stubs/indirect_cross_list_copy.h" +#include "startup_stubs/mesh86_typed_vsharp.h" #include "startup_stubs/trap.h" #include "x2w_build_rev.h" #include "xmem_page_batch.h" diff --git a/src/startup_stubs/mesh86_typed_vsharp.h b/src/startup_stubs/mesh86_typed_vsharp.h new file mode 100644 index 0000000000..1b8a64fc82 --- /dev/null +++ b/src/startup_stubs/mesh86_typed_vsharp.h @@ -0,0 +1,23 @@ +// Slot 86 typed buffer sources (buffer_load_format_x) read from a guest V# that is not a view token. +// The desktop view is R32_UINT with 4-byte elements, so the V# must not reorder or drop channels and +// must name a format whose X channel is the stored dword. +#pragma once + +#include + +namespace x2w_startup { + +// Word 3 bits 11:0: DST_SEL_X..W = X, Y, Z, W (4, 5, 6, 7). +inline bool mesh86_typed_identity_map(std::uint32_t word3) +{ + return (word3 & 0xfffu) == 0xfacu; +} + +// Word 3 bits 18:12: BUF_FMT_32_UINT (20), BUF_FMT_32_SINT (21) or BUF_FMT_32_FLOAT (22). +inline bool mesh86_typed_dword_format(std::uint32_t word3) +{ + const std::uint32_t format = (word3 >> 12) & 0x7fu; + return format >= 20u && format <= 22u; +} + +} // namespace x2w_startup diff --git a/src/startup_stubs/native_mesh86.inl b/src/startup_stubs/native_mesh86.inl index c699f03321..bfd7c2455c 100644 --- a/src/startup_stubs/native_mesh86.inl +++ b/src/startup_stubs/native_mesh86.inl @@ -68,10 +68,13 @@ x2w_startup::ComPtr make_native_mesh86_root( const bool image = view.kind == Kind::texture_srv || view.kind == Kind::comparison_texture_srv; const bool scalar = view.kind == Kind::buffer_srv || view.kind == Kind::raw_vector_srv || view.kind == Kind::byte_window_srv || view.kind == Kind::root_buffer_srv; - require(view.shader_register == i && view.root_parameter < guest.size() && (image || scalar) && + // buffer_load_format_x from a V# in a descriptor table: one 32-bit component per element. + const bool typed = view.kind == Kind::typed_buffer_srv && view.required_bytes == 4; + require(view.shader_register == i && view.root_parameter < guest.size() && (image || scalar || typed) && (!image || view.image_dimension == 0 || view.image_dimension == 1 || view.image_dimension == 5), "unsupported native Mesh86 SRV shape"); const auto type = guest[view.root_parameter].type; + require(!typed || type == D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE, "invalid native Mesh86 SRV source"); require(type == D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE ? !(view.byte_offset & 31) : !image && !view.byte_offset && (type == D3D12_ROOT_PARAMETER_TYPE_SRV || type == D3D12_ROOT_PARAMETER_TYPE_CBV), @@ -396,6 +399,23 @@ const char* bind_native_mesh86(Wrapper* self, Pass& pass, ID3D12GraphicsCommandL buffer_states.emplace_back(view.resource, view.upload); return nullptr; }; + // A buffer_load_format_x source, from a heap slot or a table: an R32_UINT view of 4-byte elements. + // A table V# must also name a 32-bit data format (see mesh86_typed_vsharp.h), so the R32_UINT view returns + // the same dword the guest format load would. + const auto typed_dword = [&](UINT slot, const UINT (&words)[8], bool table = false) -> const char* { + Mesh86Texture typed; + if (words[0] == view_token_magic && + (!mesh86_texture(words, typed) || typed.view.ViewDimension != D3D12_SRV_DIMENSION_BUFFER || + typed.view.Format != DXGI_FORMAT_R32_UINT || typed.view.Buffer.Flags || typed.view.Buffer.StructureByteStride)) + return "native Mesh86 typed buffer slot is not R32_UINT"; + if (words[0] != view_token_magic && !x2w_startup::mesh86_typed_identity_map(words[3])) + return "native Mesh86 typed buffer descriptor uses another component map"; + if (table && words[0] != view_token_magic && !x2w_startup::mesh86_typed_dword_format(words[3])) + return "native Mesh86 typed buffer descriptor is not a 32-bit format"; + const auto view = indirect_table_buffer(self, words, false, nullptr, 16u << 20, 4, true); + if (view.stride != 4) return "native Mesh86 typed buffer view has the wrong stride"; + return buffer(slot, view, true); + }; const auto image = [&](Mesh86Texture& texture) { if (!mesh86_realize_texture(self, pass, texture)) return false; return !texture.resource || !texture_states.insert(texture.resource).second || @@ -419,6 +439,12 @@ const char* bind_native_mesh86(Wrapper* self, Pass& pass, ID3D12GraphicsCommandL else if (!mesh86_texture(words, texture) || texture.view.ViewDimension != dim || !image(texture)) return "native Mesh86 material texture does not resolve to the expected SRV"; descriptors[slot] = {texture.resource, texture.view}; + } else if (source.kind == Kind::typed_buffer_srv) { + UINT words[8]; + if (!mesh86_read_record(pass.view_tables[source.root_parameter], source.byte_offset, words)) + return "native Mesh86 typed buffer descriptor is outside its table"; + if (const char* reason = typed_dword(slot, words, true)) return reason; + strides[source.shader_register] = 4; } else { const char* reason = nullptr; UINT words[8]{}; @@ -468,16 +494,7 @@ const char* bind_native_mesh86(Wrapper* self, Pass& pass, ID3D12GraphicsCommandL UINT words[8]; if (slot >= pass.mesh_heap_slots || !mesh86_read_record(pass.title_view_heap, UINT64{slot} * 32, words)) return "native Mesh86 typed buffer slot is outside the bound heap"; - Mesh86Texture typed; - if (words[0] == view_token_magic && - (!mesh86_texture(words, typed) || typed.view.ViewDimension != D3D12_SRV_DIMENSION_BUFFER || - typed.view.Format != DXGI_FORMAT_R32_UINT || typed.view.Buffer.Flags || typed.view.Buffer.StructureByteStride)) - return "native Mesh86 typed buffer slot is not R32_UINT"; - if (words[0] != view_token_magic && (words[3] & 0xfffu) != 0xfacu) - return "native Mesh86 typed buffer descriptor uses another component map"; - const auto view = indirect_table_buffer(self, words, false, nullptr, 16u << 20, 4, true); - if (view.stride != 4) return "native Mesh86 typed buffer view has the wrong stride"; - if (const char* reason = buffer(slot, view, true)) return reason; + if (const char* reason = typed_dword(slot, words)) return reason; } const auto add_image = [&](Mesh86Texture& texture) { if (descriptors.size() >= D3D12_MAX_SHADER_VISIBLE_DESCRIPTOR_HEAP_SIZE_TIER_1) return no_index; diff --git a/tests/cmake/mesh86_typed_vsharp.cmake b/tests/cmake/mesh86_typed_vsharp.cmake new file mode 100644 index 0000000000..5cb7c02af0 --- /dev/null +++ b/tests/cmake/mesh86_typed_vsharp.cmake @@ -0,0 +1,43 @@ +# Unit tests for src/startup_stubs/mesh86_typed_vsharp.h: the V# word 3 checks slot 86 applies before it binds +# a buffer_load_format_x source from a descriptor table as an R32_UINT view. Header-only, no device. +add_executable(mesh86_typed_vsharp_check tests/mesh86_typed_vsharp_check.cpp) +target_include_directories(mesh86_typed_vsharp_check PRIVATE src) +target_compile_features(mesh86_typed_vsharp_check PRIVATE cxx_std_17) +foreach(mesh86_typed_vsharp_case IN ITEMS identity_map dword_formats other_formats guest_words) + add_test(NAME mesh86_typed_vsharp_${mesh86_typed_vsharp_case} + COMMAND mesh86_typed_vsharp_check ${mesh86_typed_vsharp_case}) + set_tests_properties(mesh86_typed_vsharp_${mesh86_typed_vsharp_case} PROPERTIES TIMEOUT 60) +endforeach() + +# Mutation controls: each builds the check against a copy of the header with one guard changed and runs the +# case that guard must catch. Each control must fail (WILL_FAIL TRUE). +set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS src/startup_stubs/mesh86_typed_vsharp.h) +file(READ "${CMAKE_CURRENT_SOURCE_DIR}/src/startup_stubs/mesh86_typed_vsharp.h" mesh86_typed_vsharp_text) +foreach(mesh86_typed_vsharp_mut IN ITEMS wide_format any_map) + if(mesh86_typed_vsharp_mut STREQUAL "wide_format") + # The 32-bit formats widened by one: other_formats sees 23 accepted. + set(mesh86_typed_vsharp_from "format <= 22u") + set(mesh86_typed_vsharp_to "format <= 23u") + set(mesh86_typed_vsharp_case other_formats) + else() + # The component map is no longer checked: identity_map sees a swizzle accepted. + set(mesh86_typed_vsharp_from "return (word3 & 0xfffu) == 0xfacu;") + set(mesh86_typed_vsharp_to "return word3 == word3;") + set(mesh86_typed_vsharp_case identity_map) + endif() + string(REPLACE "${mesh86_typed_vsharp_from}" "${mesh86_typed_vsharp_to}" + mesh86_typed_vsharp_mutated "${mesh86_typed_vsharp_text}") + if(mesh86_typed_vsharp_mutated STREQUAL mesh86_typed_vsharp_text) + message(FATAL_ERROR "mesh86_typed_vsharp.h lost the anchor for mesh86_typed_vsharp_${mesh86_typed_vsharp_mut}_mut") + endif() + set(mesh86_typed_vsharp_dir "${CMAKE_CURRENT_BINARY_DIR}/mesh86_typed_vsharp_${mesh86_typed_vsharp_mut}") + file(MAKE_DIRECTORY "${mesh86_typed_vsharp_dir}/startup_stubs") + file(WRITE "${mesh86_typed_vsharp_dir}/startup_stubs/mesh86_typed_vsharp.h" "${mesh86_typed_vsharp_mutated}") + add_executable(mesh86_typed_vsharp_${mesh86_typed_vsharp_mut}_mut tests/mesh86_typed_vsharp_check.cpp) + target_include_directories(mesh86_typed_vsharp_${mesh86_typed_vsharp_mut}_mut BEFORE PRIVATE + "${mesh86_typed_vsharp_dir}" src) + target_compile_features(mesh86_typed_vsharp_${mesh86_typed_vsharp_mut}_mut PRIVATE cxx_std_17) + add_test(NAME mesh86_typed_vsharp_${mesh86_typed_vsharp_mut}_mut + COMMAND mesh86_typed_vsharp_${mesh86_typed_vsharp_mut}_mut ${mesh86_typed_vsharp_case}) + set_tests_properties(mesh86_typed_vsharp_${mesh86_typed_vsharp_mut}_mut PROPERTIES WILL_FAIL TRUE TIMEOUT 60) +endforeach() diff --git a/tests/mesh86_typed_vsharp_check.cpp b/tests/mesh86_typed_vsharp_check.cpp new file mode 100644 index 0000000000..df54645ac2 --- /dev/null +++ b/tests/mesh86_typed_vsharp_check.cpp @@ -0,0 +1,83 @@ +// Unit and header-mutation tests for src/startup_stubs/mesh86_typed_vsharp.h: the V# word 3 checks that +// let slot 86 bind a buffer_load_format_x source from a descriptor table as an R32_UINT view. +// +// Usage: mesh86_typed_vsharp_check [] (no argument runs all cases) +// Every mismatch prints "FAIL: : ..." to stderr and exits non-zero. +#include "startup_stubs/mesh86_typed_vsharp.h" + +#include +#include +#include +#include + +using x2w_startup::mesh86_typed_dword_format; +using x2w_startup::mesh86_typed_identity_map; + +namespace { +int failures = 0; + +void expect(const char* name, bool ok, const char* what) +{ + if (!ok) { + std::fprintf(stderr, "FAIL: %s: %s\n", name, what); + ++failures; + } +} + +std::uint32_t with_format(std::uint32_t format) { return 0xfacu | (format << 12); } + +void identity_map(const char* n) +{ + expect(n, mesh86_typed_identity_map(0xfacu), "XYZW accepted"); + expect(n, mesh86_typed_identity_map(0xffffffacu), "upper bits ignored"); + expect(n, !mesh86_typed_identity_map(0xfadu), "DST_SEL_X = Y refused"); + expect(n, !mesh86_typed_identity_map(0x688u), "ZYX0 refused"); + expect(n, !mesh86_typed_identity_map(0u), "all-zero map refused"); +} + +void dword_formats(const char* n) +{ + for (std::uint32_t format : {20u, 21u, 22u}) + expect(n, mesh86_typed_dword_format(with_format(format)), "32-bit format accepted"); +} + +void other_formats(const char* n) +{ + for (std::uint32_t format : {0u, 1u, 19u, 23u, 56u, 77u, 127u}) + expect(n, !mesh86_typed_dword_format(with_format(format)), "non-32-bit format refused"); +} + +void guest_words(const char* n) +{ + // Word 3 of the V#s the title synthesizes for root SRVs: 32_UINT and 32_FLOAT, identity map. + for (std::uint32_t word3 : {0x11014facu, 0x31016facu}) { + expect(n, mesh86_typed_identity_map(word3), "guest map accepted"); + expect(n, mesh86_typed_dword_format(word3), "guest format accepted"); + } +} + +struct Case { + const char* name; + void (*run)(const char*); +}; + +const Case cases[]{{"identity_map", identity_map}, + {"dword_formats", dword_formats}, + {"other_formats", other_formats}, + {"guest_words", guest_words}}; +} // namespace + +int main(int argc, char** argv) +{ + bool found = argc < 2; + for (const auto& c : cases) { + if (argc >= 2 && std::strcmp(argv[1], c.name)) continue; + found = true; + c.run(c.name); + } + if (!found) { + std::fprintf(stderr, "FAIL: unknown case %s\n", argv[1]); + return 2; + } + return failures ? 1 : 0; +} diff --git a/tests/native_direct_mesh_check.py b/tests/native_direct_mesh_check.py index 7fa7767e90..92ddfdc863 100644 --- a/tests/native_direct_mesh_check.py +++ b/tests/native_direct_mesh_check.py @@ -698,6 +698,28 @@ def skip_load(body, seed=True): 'unsupported mesh instruction or EXEC state: buffer_load_format_xy') run('typed-heap-xy-skip', skip_load([0xe0042000, 0x80080a01]), 'unsupported mesh instruction or EXEC state: buffer_load_format_xy') + # The same load from a V# read whole out of a bound descriptor table (root parameter 1, t0) goes + # through the shared typed-buffer SRV path instead of the resource heap. + heap_layout = layout.read_text() + layout.write_text('mesh1 128 3 1 2 128 64\nconstants 21 0 1\ntable 16 1') + table_setup = [0xbe910380, 0xf4080608, 0xfa000000] # s_mov_b32 s17, 0; s_load_dwordx4 s[24:27], s[16:17], 0 + table_idxen = [0xe0002000, 0x80060a01] # buffer_load_format_x v10, v1, s[24:27], 0 idxen + def table_load(body, seed=True): + pre = [0x7e140287] if seed else [] # v_mov_b32 v10, 7 + return table_setup + exported[:7] + pre + [0x7da40081, 0xbf880000 | len(body), *body, 0xbefe04c1] + exported[7:] + text = run('typed-table', table_setup + [0x7e020280] + table_idxen + exported) # v1 = 0 + assert 'bufferLoad.i32' in text and 'createHandleFromHeap' not in text, text + text = run('typed-table-lane-skip', table_load(table_idxen)) + assert 'bufferLoad.i32' in text and 'createHandleFromHeap' not in text, text + assert re.search(r'select i1 %[\w.]+, i32 %[\w.]+, i32 7\b', text), text + assert re.search(r'phi i32 \[ 7, %mesh_empty\d+ \]', text), text + run('typed-table-lane-skip-undef', table_load(table_idxen, seed=False), + 'graphics register undefined on an incoming path: 266') + run('typed-table-xy', table_setup + [0x7e020280, 0xe0042000, 0x80060a01] + exported, + 'unsupported mesh instruction or EXEC state: buffer_load_format_xy') + run('typed-table-no-skip', table_setup + exported[:7] + [0x7e140287, 0x7da40081, *table_idxen, 0xbefe04c1] + + exported[7:], 'unsupported mesh instruction or EXEC state: buffer_load_format_x') + layout.write_text(heap_layout) run('typed-heap-offset-skip', skip_load([0xe0002004, 0x80080a01]), 'formatted load requires zero or a single linear index') # Inside a whole-wave lane-limit skip (v_cmpx_gt_u32 + s_cbranch_execz), a fresh destination VGPR keeps its @@ -841,7 +863,7 @@ def assert_token_guard(text, reads): 'heap_tokens') result, out = compile_mesh('token-root-route', typed+exported) assert result.returncode == 0 and 'requires_heap_tokens' not in result.stdout, result.stdout + result.stderr - # Negative controls: another scale, no scale, a raw read, an overwritten descriptor word and a table descriptor in a skip. + # Negative controls: another scale, no scale, a raw read and an overwritten descriptor word. layout.write_text(token_layout) unaligned = 'mesh heap token byte offset is not a proven multiple of 32' run('token-shift4',select_word+[0x8f248424]+heap_base+selected_fetch+formatted+exported,unaligned) @@ -852,7 +874,11 @@ def assert_token_guard(text, reads): 'overwritten mesh heap descriptor') table_in_skip = (select_word[:3] + exported[:7] + [0x7e140287, 0x7da40081, 0xbf880002, 0xe0002000, 0x80080a01, 0xbefe04c1] + exported[7:]) - run('typed-table-in-skip', table_in_skip, 'formatted mesh load lacks an R32_UINT resource heap contract') + # A V# read from a bound table is not a heap slot: with heap tokens on, it still takes the typed table + # SRV route (see typed-table above) and needs no token view. + result, out = compile_mesh('typed-table-in-skip', table_in_skip) + assert result.returncode == 0 and 'requires_heap_tokens' not in result.stdout, result.stdout + result.stderr + assert 'bufferLoad.i32' in subprocess.check_output([sdk/'dxc.exe','-dumpbin',out], text=True) layout.write_text('mesh1 128 3 1 2 128 64\nconstants 21 0 1') widen_only = [ 0xbe96047e, # s_mov_b64 s[22:23], exec From de321a364d790b5d068696b6c0c0f2d9a9ce2c3f Mon Sep 17 00:00:00 2001 From: Luuk Motz Date: Tue, 1 Dec 2026 20:44:32 +0100 Subject: [PATCH 16/32] shader: track lane-skip narrowing merges per register A merged value is exact for the guard's lanes only in the register it was merged into. Keying the merges by value let a copy of a merged value into another register pass the restore as exact. Record the merged value per register instead, and add the copy fixture from review plus a second merge into the same register. Co-Authored-By: Claude Opus 5.5 --- src/gfx1013_direct_mesh.inl | 16 ++++++++++------ tests/native_direct_mesh_check.py | 7 +++++++ 2 files changed, 17 insertions(+), 6 deletions(-) diff --git a/src/gfx1013_direct_mesh.inl b/src/gfx1013_direct_mesh.inl index b2b306409d..e87687ddfa 100644 --- a/src/gfx1013_direct_mesh.inl +++ b/src/gfx1013_direct_mesh.inl @@ -287,8 +287,9 @@ NativeComputeShader lower_mesh(const string &code, const MeshStageLayout &layout std::map saved_exec; std::map before_narrowing; // One CMPX narrowing an open lane skip's guard, with no EXECZ: the registers when it ran (all exact - // for the guard's lanes) and the values merged per lane against them since (see the EXEC restore). - struct SkipNarrowing { unsigned skip; string lane; decltype(alu.graphics_registers) regs; std::set merged; }; + // for the guard's lanes) and, per register, the value merged per lane against them since (see the + // EXEC restore). A merged value is exact only in the register it was merged into, not in a copy. + struct SkipNarrowing { unsigned skip; string lane; decltype(alu.graphics_registers) regs; std::map merged; }; std::optional skip_narrowing; auto saved_mask=[&](unsigned source)->const MaskState * { if (source>104 || (source&1)) return nullptr; @@ -1969,8 +1970,9 @@ NativeComputeShader lower_mesh(const string &code, const MeshStageLayout &layout for (auto r:partial_writes) { const auto &now=alu.graphics_registers.at(r); const auto at=skip_narrowing->regs.find(r); + const auto merged=skip_narrowing->merged.find(r); if ((at!=skip_narrowing->regs.end() && !at->second.empty() && at->second==now) || - skip_narrowing->merged.count(now)) remaining.insert(r); + (merged!=skip_narrowing->merged.end() && merged->second==now)) remaining.insert(r); else alu.write(r,{}); } partial_writes=std::move(remaining); @@ -2202,10 +2204,12 @@ NativeComputeShader lower_mesh(const string &code, const MeshStageLayout &layout skip_narrowing->skip==exec_skip->start && !before_vec[j].empty() && before_partial[j] && !value_limits.count(before_vec[j]) && alu.graphics_registers.at(vec_dst+j)!=before_vec[j] && - (skip_narrowing->merged.count(before_vec[j]) || [&] { + [&] { + const auto merged=skip_narrowing->merged.find(vec_dst+j); + if (merged!=skip_narrowing->merged.end() && merged->second==before_vec[j]) return true; const auto at=skip_narrowing->regs.find(vec_dst+j); return at!=skip_narrowing->regs.end() && at->second==before_vec[j]; - }())) { + }()) { // The old value is exact for the guard's lanes, so the merge is too; it stays partial // against full EXEC. auto &value=alu.graphics_registers.at(vec_dst+j); @@ -2214,7 +2218,7 @@ NativeComputeShader lower_mesh(const string &code, const MeshStageLayout &layout value=alu.select(lane_active,value,before_vec[j]); alu.record_graphics_bits(value,bits); if (!u.empty()) active_uniform[value]={lane_active,u}; - skip_narrowing->merged.insert(value); + skip_narrowing->merged[vec_dst+j]=value; } } // A skip opened under the narrowed mask ends the straight-line region; its close is not a merge. diff --git a/tests/native_direct_mesh_check.py b/tests/native_direct_mesh_check.py index a0d1ebd874..e690ddaaa6 100644 --- a/tests/native_direct_mesh_check.py +++ b/tests/native_direct_mesh_check.py @@ -1434,6 +1434,13 @@ def narrowed(region, restore=0xbefe0426, after=(0x061414f2,)): # v_add_f32 v10, run('skip-narrow-new-register', narrowed([0x7e1602f4], # v_mov_b32 v11, 2.0 after=(0x0614150b,)), # v_add_f32 v10, v11, v10 'graphics register undefined on an incoming path: 267') + # A merged value is exact only in the register it was merged into: a copy of it is not. + run('skip-narrow-merged-copy', narrowed([0x061414f2, 0x7e16030a], # v_mov_b32 v11, v10 + after=(0x0614150b,)), # v_add_f32 v10, v11, v10 + 'graphics register undefined on an incoming path: 267') + # The same register merged again stays exact. + text = run('skip-narrow-merge-twice', narrowed([0x061414f2, 0x061414f2])) + assert 'storeVertexOutput' in text and text.count('select ') == base.count('select ') + 2, text # A second narrowing is not merged against the vertex mask, so its restore stays refused. run('skip-narrow-twice', narrowed([0x7daa0080, 0x061414f2]), lane_skip_exec) # So is a restore of a mask saved under the narrowed EXEC. From b445b8cd7399a055c829d4b6face0036bde9d8c4 Mon Sep 17 00:00:00 2001 From: Luuk Motz Date: Tue, 1 Dec 2026 21:22:56 +0100 Subject: [PATCH 17/32] startup: refuse swizzled or thread-ID typed mesh86 V#s A raw V# with SWIZZLE_ENABLE (word 1 bit 31) or ADD_TID_ENABLE (word 3 bit 23) set addresses elements differently from the linear R32_UINT view slot 86 binds, so refuse it on both the heap and the table route. Add a linear_addressing unit case with two header mutation controls, and run the mesh86_typed_vsharp tests in the pr preset. Co-Authored-By: Claude Opus 5.5 --- CMakePresets.json | 2 +- src/startup_stubs/mesh86_typed_vsharp.h | 7 +++++++ src/startup_stubs/native_mesh86.inl | 6 ++++-- tests/cmake/mesh86_typed_vsharp.cmake | 14 ++++++++++++-- tests/mesh86_typed_vsharp_check.cpp | 11 +++++++++++ 5 files changed, 35 insertions(+), 5 deletions(-) diff --git a/CMakePresets.json b/CMakePresets.json index 6bd4804f08..0c03d3ba40 100644 --- a/CMakePresets.json +++ b/CMakePresets.json @@ -50,7 +50,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|startup_mesh57_runtime(_[a-z]+)?_warp|native_fixed_mesh57_published_pair(_refusal)?_warp|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_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|native_.*_(ir|dxil|controls)|native_direct_mesh|startup_triage_run)$" + "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|startup_mesh57_runtime(_[a-z]+)?_warp|native_fixed_mesh57_published_pair(_refusal)?_warp|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_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|native_.*_(ir|dxil|controls)|native_direct_mesh|mesh86_typed_vsharp_[a-z_]+|startup_triage_run)$" } } }, diff --git a/src/startup_stubs/mesh86_typed_vsharp.h b/src/startup_stubs/mesh86_typed_vsharp.h index 1b8a64fc82..aee6530b98 100644 --- a/src/startup_stubs/mesh86_typed_vsharp.h +++ b/src/startup_stubs/mesh86_typed_vsharp.h @@ -20,4 +20,11 @@ inline bool mesh86_typed_dword_format(std::uint32_t word3) return format >= 20u && format <= 22u; } +// Element i at base + i * stride: word 1 bit 31 (SWIZZLE_ENABLE) and word 3 bit 23 (ADD_TID_ENABLE) clear. +// Either bit changes which bytes a lane reads, and a linear desktop view would not. +inline bool mesh86_typed_linear(std::uint32_t word1, std::uint32_t word3) +{ + return !(word1 & 0x80000000u) && !(word3 & 0x00800000u); +} + } // namespace x2w_startup diff --git a/src/startup_stubs/native_mesh86.inl b/src/startup_stubs/native_mesh86.inl index bfd7c2455c..56a277df2f 100644 --- a/src/startup_stubs/native_mesh86.inl +++ b/src/startup_stubs/native_mesh86.inl @@ -400,8 +400,8 @@ const char* bind_native_mesh86(Wrapper* self, Pass& pass, ID3D12GraphicsCommandL return nullptr; }; // A buffer_load_format_x source, from a heap slot or a table: an R32_UINT view of 4-byte elements. - // A table V# must also name a 32-bit data format (see mesh86_typed_vsharp.h), so the R32_UINT view returns - // the same dword the guest format load would. + // A raw V# must address elements linearly, and a table V# must also name a 32-bit data format (see + // mesh86_typed_vsharp.h), so the R32_UINT view returns the same dword the guest format load would. const auto typed_dword = [&](UINT slot, const UINT (&words)[8], bool table = false) -> const char* { Mesh86Texture typed; if (words[0] == view_token_magic && @@ -410,6 +410,8 @@ const char* bind_native_mesh86(Wrapper* self, Pass& pass, ID3D12GraphicsCommandL return "native Mesh86 typed buffer slot is not R32_UINT"; if (words[0] != view_token_magic && !x2w_startup::mesh86_typed_identity_map(words[3])) return "native Mesh86 typed buffer descriptor uses another component map"; + if (words[0] != view_token_magic && !x2w_startup::mesh86_typed_linear(words[1], words[3])) + return "native Mesh86 typed buffer descriptor is swizzled or adds the thread ID"; if (table && words[0] != view_token_magic && !x2w_startup::mesh86_typed_dword_format(words[3])) return "native Mesh86 typed buffer descriptor is not a 32-bit format"; const auto view = indirect_table_buffer(self, words, false, nullptr, 16u << 20, 4, true); diff --git a/tests/cmake/mesh86_typed_vsharp.cmake b/tests/cmake/mesh86_typed_vsharp.cmake index 5cb7c02af0..2145c3a48d 100644 --- a/tests/cmake/mesh86_typed_vsharp.cmake +++ b/tests/cmake/mesh86_typed_vsharp.cmake @@ -3,7 +3,7 @@ add_executable(mesh86_typed_vsharp_check tests/mesh86_typed_vsharp_check.cpp) target_include_directories(mesh86_typed_vsharp_check PRIVATE src) target_compile_features(mesh86_typed_vsharp_check PRIVATE cxx_std_17) -foreach(mesh86_typed_vsharp_case IN ITEMS identity_map dword_formats other_formats guest_words) +foreach(mesh86_typed_vsharp_case IN ITEMS identity_map dword_formats other_formats linear_addressing guest_words) add_test(NAME mesh86_typed_vsharp_${mesh86_typed_vsharp_case} COMMAND mesh86_typed_vsharp_check ${mesh86_typed_vsharp_case}) set_tests_properties(mesh86_typed_vsharp_${mesh86_typed_vsharp_case} PROPERTIES TIMEOUT 60) @@ -13,12 +13,22 @@ endforeach() # case that guard must catch. Each control must fail (WILL_FAIL TRUE). set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS src/startup_stubs/mesh86_typed_vsharp.h) file(READ "${CMAKE_CURRENT_SOURCE_DIR}/src/startup_stubs/mesh86_typed_vsharp.h" mesh86_typed_vsharp_text) -foreach(mesh86_typed_vsharp_mut IN ITEMS wide_format any_map) +foreach(mesh86_typed_vsharp_mut IN ITEMS wide_format any_map any_swizzle any_tid) if(mesh86_typed_vsharp_mut STREQUAL "wide_format") # The 32-bit formats widened by one: other_formats sees 23 accepted. set(mesh86_typed_vsharp_from "format <= 22u") set(mesh86_typed_vsharp_to "format <= 23u") set(mesh86_typed_vsharp_case other_formats) + elseif(mesh86_typed_vsharp_mut STREQUAL "any_swizzle") + # SWIZZLE_ENABLE is no longer checked: linear_addressing sees a swizzled V# accepted. + set(mesh86_typed_vsharp_from "!(word1 & 0x80000000u)") + set(mesh86_typed_vsharp_to "(word1 == word1)") + set(mesh86_typed_vsharp_case linear_addressing) + elseif(mesh86_typed_vsharp_mut STREQUAL "any_tid") + # ADD_TID_ENABLE is no longer checked: linear_addressing sees a thread-ID V# accepted. + set(mesh86_typed_vsharp_from "!(word3 & 0x00800000u)") + set(mesh86_typed_vsharp_to "(word3 == word3)") + set(mesh86_typed_vsharp_case linear_addressing) else() # The component map is no longer checked: identity_map sees a swizzle accepted. set(mesh86_typed_vsharp_from "return (word3 & 0xfffu) == 0xfacu;") diff --git a/tests/mesh86_typed_vsharp_check.cpp b/tests/mesh86_typed_vsharp_check.cpp index df54645ac2..084d1d6a86 100644 --- a/tests/mesh86_typed_vsharp_check.cpp +++ b/tests/mesh86_typed_vsharp_check.cpp @@ -12,6 +12,7 @@ using x2w_startup::mesh86_typed_dword_format; using x2w_startup::mesh86_typed_identity_map; +using x2w_startup::mesh86_typed_linear; namespace { int failures = 0; @@ -47,12 +48,21 @@ void other_formats(const char* n) expect(n, !mesh86_typed_dword_format(with_format(format)), "non-32-bit format refused"); } +void linear_addressing(const char* n) +{ + expect(n, mesh86_typed_linear(0x00040000u, 0x31016facu), "stride 4, no swizzle, no thread ID accepted"); + expect(n, mesh86_typed_linear(0x7fffffffu, 0xff7fffffu), "other word 1 and word 3 bits ignored"); + expect(n, !mesh86_typed_linear(0x80040000u, 0x31016facu), "SWIZZLE_ENABLE refused"); + expect(n, !mesh86_typed_linear(0x00040000u, 0x31816facu), "ADD_TID_ENABLE refused"); +} + void guest_words(const char* n) { // Word 3 of the V#s the title synthesizes for root SRVs: 32_UINT and 32_FLOAT, identity map. for (std::uint32_t word3 : {0x11014facu, 0x31016facu}) { expect(n, mesh86_typed_identity_map(word3), "guest map accepted"); expect(n, mesh86_typed_dword_format(word3), "guest format accepted"); + expect(n, mesh86_typed_linear(0u, word3), "guest word 3 adds no thread ID"); } } @@ -64,6 +74,7 @@ struct Case { const Case cases[]{{"identity_map", identity_map}, {"dword_formats", dword_formats}, {"other_formats", other_formats}, + {"linear_addressing", linear_addressing}, {"guest_words", guest_words}}; } // namespace From 49ec29116f7f4aa54d8e6a034f57b4fa898a5e3e Mon Sep 17 00:00:00 2001 From: Luuk Motz Date: Tue, 1 Dec 2026 21:32:23 +0100 Subject: [PATCH 18/32] build: build the mesh86_typed_vsharp checks in the pr preset The pr test filter runs mesh86_typed_vsharp_*, but the pr build preset only builds its listed targets, so CI reported the tests as not run. Co-Authored-By: Claude Opus 5.5 --- CMakePresets.json | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/CMakePresets.json b/CMakePresets.json index 0c03d3ba40..70c38b7e72 100644 --- a/CMakePresets.json +++ b/CMakePresets.json @@ -36,7 +36,9 @@ "xmem_placeholder_split_check", "xmem_map_split_first_check", "startup_dstorage_break_window_check", "xmem_page_runs_device_check", "linear_buffer_backing_check", "bcpack_formats_check", "startup_stub_consumer", "startup_inline_retire", "startup_resource_retire_title", "startup_table_lock", - "native_compute_ir_dump", "native_pixel_ir_dump", "native_store_replay", "native_raw_buffer_view_check" + "native_compute_ir_dump", "native_pixel_ir_dump", "native_store_replay", "native_raw_buffer_view_check", + "mesh86_typed_vsharp_check", "mesh86_typed_vsharp_wide_format_mut", "mesh86_typed_vsharp_any_map_mut", + "mesh86_typed_vsharp_any_swizzle_mut", "mesh86_typed_vsharp_any_tid_mut" ] }, { "name": "release", "configurePreset": "release" }, From 7e997a374208277760701ffaee16b62f46b7c0d9 Mon Sep 17 00:00:00 2001 From: Luuk Motz Date: Tue, 1 Dec 2026 22:04:50 +0100 Subject: [PATCH 19/32] shader: lower a mesh CMPX region inside a SAVEEXEC then arm Inside a SAVEEXEC then arm the compiler often copies EXEC, runs some vector work, narrows EXEC with one CMPX, skips with EXECZ and restores the copy. Each lane runs the work and then the skipped instructions only if the compare holds: the same if-only region s_and_saveexec_b64 would open on the compare. The then-arm scan now registers it as a child region and the mesh frontend lowers it as a nested diamond on the shared compare, through the existing nested SAVEEXEC join and restore. The region needs its own restore of the copied register inside the arm; anything else stays an EXEC read of the then arm. Co-Authored-By: Claude Opus 5.5 --- src/gfx1013_direct_mesh.inl | 93 ++++++++++++++++++++++++++++++- tests/native_direct_mesh_check.py | 45 +++++++++++++++ 2 files changed, 137 insertions(+), 1 deletion(-) diff --git a/src/gfx1013_direct_mesh.inl b/src/gfx1013_direct_mesh.inl index 575612d031..f816e9cbbf 100644 --- a/src/gfx1013_direct_mesh.inl +++ b/src/gfx1013_direct_mesh.inl @@ -426,12 +426,52 @@ NativeComputeShader lower_mesh(const string &code, const MeshStageLayout &layout } return arm; }; + // cmpx: for a region opened by an EXEC copy and a later CMPX (see match_cmpx_child), the CMPX's address. struct SaveExecShape { - unsigned saved, then_begin, alternate, else_begin=0, join=0, reset=0, end=0; + unsigned saved, then_begin, alternate, else_begin=0, join=0, reset=0, end=0, cmpx=0; bool contains_child=false; std::set then_writes{}, gap_writes{}; }; std::map saveexec_shapes; + // CMPX address -> address of the EXEC copy that opens its region. + std::map cmpx_children; + // Inside a SAVEEXEC then arm: s_mov_b64 sX, exec, straight-line work that leaves EXEC, sX and control + // flow alone, one CMPX, s_cbranch_execz L and s_mov_b64 exec, sX at L. Each lane runs the work, then the + // instructions up to L only if the compare holds: the same if-only region s_and_saveexec_b64 sX, cmp + // would open, except that a CMPX leaves SCC alone. + auto match_cmpx_child=[&](const Inst &save,unsigned boundary)->std::optional { + const unsigned saved=save.dst; + if (save.name!="s_mov_b64" || save.src[0]!=126 || saved>104 || (saved&1)) return {}; + const auto writes_saved=[&](const Inst &op) { + const auto hits=[&](unsigned r,unsigned n) { return r<=saved+1 && savedboundary) return {}; + if (name.rfind("v_cmpx",0)==0) { + const auto skip=decode(code,op.next,true,true); + if (skip.name!="s_cbranch_execz" || skip.target()<=skip.next || skip.target()>=boundary) return {}; + const auto reset=decode(code,skip.target(),true,true); + if (reset.name!="s_mov_b64" || reset.dst!=126 || reset.src[0]!=saved || reset.next>boundary) return {}; + SaveExecShape shape{saved,skip.next,skip.target()}; + shape.join=shape.reset=skip.target(); + shape.end=reset.next; + shape.cmpx=at; + return shape; + } + if (op.branch() || op.dst==126 || op.dst==127 || name.find("exec")!=string::npos || writes_saved(op) || + std::any_of(op.src.begin(),op.src.end(),[](unsigned s) { return s==126 || s==127 || s==252; })) + return {}; + at=op.next; + } + return {}; + }; auto match_saveexec=[&](const Inst &i,unsigned boundary,bool can_join_skip) { if (i.dst>104 || (i.dst&1) || i.src[0]>106 || (i.src[0]&1)) refuse(i.pc,"unsupported mesh SAVEEXEC operands"); @@ -553,6 +593,22 @@ NativeComputeShader lower_mesh(const string &code, const MeshStageLayout &layout arms.push_back({at,child.then_begin}); continue; } + // The EXEC copy opening a CMPX region. The work up to the CMPX runs under this arm's EXEC and + // is scanned as part of it; the CMPX then enters the region's own arm. + if (const auto cmpx_child=match_cmpx_child(op,shape.alternate)) { + saveexec_shapes.insert_or_assign(at,*cmpx_child); + cmpx_children[cmpx_child->cmpx]=at; + shape.contains_child=true; + writes.insert(op.dst); writes.insert(op.dst+1); + scan.at=op.next; + continue; + } + if (const auto child_at=cmpx_children.find(at); child_at!=cmpx_children.end()) { + const auto child_start=child_at->second; + scan.at=saveexec_shapes.at(child_start).end; + arms.push_back({child_start,saveexec_shapes.at(child_start).then_begin}); + continue; + } scan.at=op.next; const string name(op.name); const bool scalar=op.enc==Encoding::Sop1 || op.enc==Encoding::Sop2 || op.enc==Encoding::Sopk || @@ -1711,6 +1767,41 @@ NativeComputeShader lower_mesh(const string &code, const MeshStageLayout &layout (i.name=="s_mov_b64" && i.src[0]<=104 && !(i.src[0]&1))))) { // An open skip cannot execute a write for lanes outside its guard. refuse(pc,"mesh EXEC write inside a lane-skip block"); + } else if (branch && exec_skip && cmpx_children.count(pc) && + saveexec_shapes.count(cmpx_children.at(pc)) && saveexec_shapes.at(cmpx_children.at(pc)).cmpx==pc) { + // The CMPX of an EXEC copy region inside a SAVEEXEC then arm (match_cmpx_child): an if-only + // diamond on the compare, nested in this arm, closed by the copy's restore. + const auto start=cmpx_children.at(pc); + const auto &shape=saveexec_shapes.at(start); + const string name(i.name); + const bool dword=name.size()>4 && (name.compare(name.size()-4,4,"_u32")==0 || + name.compare(name.size()-4,4,"_i32")==0 || name.compare(name.size()-4,4,"_f32")==0); + if (i.enc!=Encoding::Vopc || i.wide || i.subword || i.dpp_control || !dword) + refuse(pc,"unsupported mesh CMPX in a SAVEEXEC then arm"); + if (full_exec || lane_active.empty() || !branch->masks) + refuse(pc,"mesh CMPX region needs an exact enclosing arm"); + const auto mask=saved_mask(shape.saved); + if (mask!=&saved_exec.at(start) || mask->full || mask->lane!=lane_active || mask->wave!=wave_active) + refuse(pc,"mesh CMPX region lacks its copied EXEC"); + if (const auto edge=forward.upper_bound(pc); edge!=forward.end() && edge->firstmasks=SaveExecMasks{parent,ExecMask{}}; + for (auto r : shape.then_writes) if (r<=107) branch->scalar_clobbers.insert(r); + // The CMPX leaves SCC alone, but scalar work in the arm may not, and runs on one path only. + branch->scalar_clobbers.insert(128); + ir.body<<" br i1 "<masks)) refuse(pc,"mesh SAVEEXEC diamond needs one open lane skip"); diff --git a/tests/native_direct_mesh_check.py b/tests/native_direct_mesh_check.py index 7fa7767e90..4f50e68394 100644 --- a/tests/native_direct_mesh_check.py +++ b/tests/native_direct_mesh_check.py @@ -1005,6 +1005,51 @@ def saveexec_open(then, other): wrong_restore[8] = 0xbefe0418 # s_mov_b64 exec, s[24:25]: not the saved mask saveexec_skip('saveexec-paired-wrong-restore', wrong_restore, '+0x2c: mesh SAVEEXEC else arm does not restore the saved EXEC') + # Inside the then arm, an EXEC copy, a CMPX, EXECZ and the copy's restore are an if-only region on + # the compare: lanes where 3 > v0 take 5, the other then lanes keep 2, the else lanes take 3. + def cmpx_region(prefix=(), cmpx=0x7da80083, skip=None, restore=0xbefe041c, region=(0x7e020285,)): + return ([0x7e020282, # v_mov_b32_e32 v1, 2 + 0xbe9c047e, # s_mov_b64 s[28:29], exec (+0x38) + *prefix, cmpx, # v_cmpx_gt_u32_e32 3, v0 + 0xbf880000 | len(region) if skip is None else skip, *region, # s_cbranch_execz to the restore + restore]) # s_mov_b64 exec, s[28:29] + # The DXIL branch takes the compare; the region's write selects on the then arm's lanes and the compare, + # and the region's join merges it with the value from before the CMPX, which then leaves the then arm. + region = (r'(?P%\w+) = select i1 (?P%\w+), i32 {}, i32 %\w+\n.*?' + r'(?P%\w+) = icmp ugt i32 3, %\w+\n\s*(?P%\w+) = and i1 (?P=arm), (?P=take)\n' + r'\s*br i1 (?P=take), label %mesh_then56, label %mesh_else56\n.*?' + r'(?P%\w+) = select i1 (?P=lane), i32 5, i32 (?P=old)\n.*?' + r'(?P%\w+) = phi i32 \[ (?P=new), %mesh_then_end56 \], \[ (?P=old), %mesh_else_end56 \]\n.*?' + r'= phi i32 \[ (?P=join), %mesh_then_end44 \], \[ %\w+, %mesh_else_end44 \]') + # The prefix runs before the CMPX, so its value reaches the lanes that skip the region. + for name, then, before in (('saveexec-cmpx-region', cmpx_region(), 2), + ('saveexec-cmpx-region-prefix', cmpx_region(prefix=(0x7e020284,)), 4)): # v_mov v1, 4 + text = saveexec_skip(name, saveexec_open(then, else_v1)) + assert re.search(region.format(before), text, re.S), text + # The region needs its own restore inside the arm, of the copied register, with nothing in between + # touching EXEC, the copy or control flow; otherwise the copy stays an EXEC read. + for name, then in ( + ('saveexec-cmpx-region-other-restore', cmpx_region(restore=0xbefe041e)), # s_mov_b64 exec, s[30:31] + ('saveexec-cmpx-region-no-skip', cmpx_region(skip=0xbf800000)), # s_nop 0 in place of EXECZ + ('saveexec-cmpx-region-prefix-copy', cmpx_region(prefix=(0xbe9c0380,))), # s_mov_b32 s28, 0 + ('saveexec-cmpx-region-prefix-branch', cmpx_region(prefix=(0xbf820000,))), # s_branch to the next word + ('saveexec-cmpx-region-no-cmpx', cmpx_region(cmpx=0x7d880083)), # v_cmp_gt_u32 vcc: no EXEC write + ): + saveexec_skip(name, saveexec_open(then, else_v1), '+0x38: mesh SAVEEXEC then arm depends on EXEC') + # An EXECZ past the restore leaves the region; the restore is then an arm EXEC write. + saveexec_skip('saveexec-cmpx-region-skip-past', saveexec_open(cmpx_region(skip=0xbf880002) + [0x7e020286], + else_v1), + '+0x38: mesh SAVEEXEC then arm depends on EXEC') + # The region's own arm follows the then-arm rules. + saveexec_skip('saveexec-cmpx-region-exec-read', + saveexec_open(cmpx_region(region=(0xbe9e047e,)), else_v1), # s_mov_b64 s[30:31], exec + '+0x44: mesh SAVEEXEC then arm depends on EXEC') + saveexec_skip('saveexec-cmpx-region-lds', + saveexec_open(cmpx_region(region=(0xd8340008, 0x500)), else_v1), # ds_write + '+0x44: mesh SAVEEXEC then arm has a wave or memory side effect') + # Only a 32-bit VOPC compare opens the region. + saveexec_skip('saveexec-cmpx-region-u16', saveexec_open(cmpx_region(cmpx=0x7d780083), else_v1), + '+0x3c: unsupported mesh CMPX in a SAVEEXEC then arm') # The compiler also saves EXEC against VCC directly, without the s_and_b64 copy. vcc_open = [0x7d080015, 0xbe96246a] + saveexec_open(then_v1, else_v1)[3:] # s_and_saveexec_b64 s[22:23], vcc text = saveexec_skip('saveexec-vcc', vcc_open) From d1c76a61a7b5ce5be92d419a008704e7bcac9320 Mon Sep 17 00:00:00 2001 From: Luuk Motz Date: Tue, 1 Dec 2026 22:23:44 +0100 Subject: [PATCH 20/32] shader: let a mesh CMPX region run to the end of an if-only SAVEEXEC arm The compiler also narrows the rest of an if-only SAVEEXEC then arm with a CMPX whose EXECZ skips to the arm's end, leaving the EXEC copy unrestored. The rest of the arm is then the region, and the SAVEEXEC restore ends both. Accept that form when the enclosing arm has no else arm (its inverse would read the narrowed EXEC), and visit the join address again after the region closes so the enclosing arm ends there too. Regions chain the same way. Co-Authored-By: Claude Opus 5.5 --- src/gfx1013_direct_mesh.inl | 29 +++++++++++++++++++++++----- tests/native_direct_mesh_check.py | 32 +++++++++++++++++++++++++++++++ 2 files changed, 56 insertions(+), 5 deletions(-) diff --git a/src/gfx1013_direct_mesh.inl b/src/gfx1013_direct_mesh.inl index f816e9cbbf..28c9d8a5c3 100644 --- a/src/gfx1013_direct_mesh.inl +++ b/src/gfx1013_direct_mesh.inl @@ -439,7 +439,10 @@ NativeComputeShader lower_mesh(const string &code, const MeshStageLayout &layout // flow alone, one CMPX, s_cbranch_execz L and s_mov_b64 exec, sX at L. Each lane runs the work, then the // instructions up to L only if the compare holds: the same if-only region s_and_saveexec_b64 sX, cmp // would open, except that a CMPX leaves SCC alone. - auto match_cmpx_child=[&](const Inst &save,unsigned boundary)->std::optional { + // The EXECZ may instead skip to the end of an if-only enclosing arm (chain_ok), leaving the copy unrestored: + // the rest of the arm is then the region, and the enclosing restore ends both. With an else arm the inverse + // would read the narrowed EXEC, so that form needs the enclosing arm to have none. + auto match_cmpx_child=[&](const Inst &save,unsigned boundary,bool chain_ok)->std::optional { const unsigned saved=save.dst; if (save.name!="s_mov_b64" || save.src[0]!=126 || saved>104 || (saved&1)) return {}; const auto writes_saved=[&](const Inst &op) { @@ -456,7 +459,14 @@ NativeComputeShader lower_mesh(const string &code, const MeshStageLayout &layout if (op.next<=at || op.next>boundary) return {}; if (name.rfind("v_cmpx",0)==0) { const auto skip=decode(code,op.next,true,true); - if (skip.name!="s_cbranch_execz" || skip.target()<=skip.next || skip.target()>=boundary) return {}; + if (skip.name!="s_cbranch_execz" || skip.target()<=skip.next || skip.target()>boundary) return {}; + if (skip.target()==boundary) { + if (!chain_ok) return {}; + SaveExecShape shape{saved,skip.next,boundary}; + shape.join=shape.end=boundary; + shape.cmpx=at; + return shape; + } const auto reset=decode(code,skip.target(),true,true); if (reset.name!="s_mov_b64" || reset.dst!=126 || reset.src[0]!=saved || reset.next>boundary) return {}; SaveExecShape shape{saved,skip.next,skip.target()}; @@ -595,7 +605,7 @@ NativeComputeShader lower_mesh(const string &code, const MeshStageLayout &layout } // The EXEC copy opening a CMPX region. The work up to the CMPX runs under this arm's EXEC and // is scanned as part of it; the CMPX then enters the region's own arm. - if (const auto cmpx_child=match_cmpx_child(op,shape.alternate)) { + if (const auto cmpx_child=match_cmpx_child(op,shape.alternate,!shape.else_begin)) { saveexec_shapes.insert_or_assign(at,*cmpx_child); cmpx_children[cmpx_child->cmpx]=at; shape.contains_child=true; @@ -907,8 +917,11 @@ NativeComputeShader lower_mesh(const string &code, const MeshStageLayout &layout alu.write(r,{}); if (rstart); shape!=saveexec_shapes.end() && shape->second.reset) + const auto closed=saveexec_shapes.find(branch->start); + if (closed!=saveexec_shapes.end() && closed->second.reset) pending_saveexec_restore=branch->start; + // A CMPX region that runs to the end of its enclosing arm joins where that arm ends. + const bool chain_closed=closed!=saveexec_shapes.end() && closed->second.cmpx && !closed->second.reset; branch.reset(); if (!branch_parents.empty()) { branch=std::move(branch_parents.back()); @@ -916,6 +929,12 @@ NativeComputeShader lower_mesh(const string &code, const MeshStageLayout &layout } // A join at the skip end is followed by the skip close, not by a saved-mask restore. diamond_joined=!join_at_skip_end; + // The enclosing arm ends here too: visit this address again to close it. + if (chain_closed) { + if (!branch || (pc!=branch->alternate && pc!=branch->join)) + refuse(pc,"mesh CMPX region outlives its enclosing arm"); + continue; + } } if (join_at_skip_end && close_skip()) continue; if (pending_saveexec_restore) { @@ -1792,7 +1811,7 @@ NativeComputeShader lower_mesh(const string &code, const MeshStageLayout &layout then_mask.lane=ir.value("and i1 "+parent.lane+", "+take); mask_parent[then_mask.lane]=parent.lane; branch_parents.push_back(std::move(*branch)); - branch=Diamond{start,shape.alternate,shape.join,save_edge(),{},false,!shape.reset,shape.else_begin}; + branch=Diamond{start,shape.alternate,shape.join,save_edge(),{},false,false,0}; branch->masks=SaveExecMasks{parent,ExecMask{}}; for (auto r : shape.then_writes) if (r<=107) branch->scalar_clobbers.insert(r); // The CMPX leaves SCC alone, but scalar work in the arm may not, and runs on one path only. diff --git a/tests/native_direct_mesh_check.py b/tests/native_direct_mesh_check.py index 4f50e68394..adf92d7344 100644 --- a/tests/native_direct_mesh_check.py +++ b/tests/native_direct_mesh_check.py @@ -1050,6 +1050,38 @@ def cmpx_region(prefix=(), cmpx=0x7da80083, skip=None, restore=0xbefe041c, regio # Only a 32-bit VOPC compare opens the region. saveexec_skip('saveexec-cmpx-region-u16', saveexec_open(cmpx_region(cmpx=0x7d780083), else_v1), '+0x3c: unsupported mesh CMPX in a SAVEEXEC then arm') + # In an if-only arm the EXECZ may skip to the arm's end and leave the copy unrestored: the rest of the + # arm is the region, and the SAVEEXEC restore ends both. Regions chain the same way. + def if_only(then): + return saveexec_head + [0xbf880000 | len(then), *then, + 0xbefe0416, # s_mov_b64 exec, s[22:23] + 0xbf800000] # s_nop 0 keeps the join inside the skip + def chain(rest): + return [0x7e020282, 0xbe9c047e, 0x7da80083, # v1 = 2; copy EXEC; v_cmpx_gt_u32 3, v0 + 0xbf880000 | len(rest), *rest] # s_cbranch_execz to the arm's end + chain_join = (r'(?P%\w+) = icmp ugt i32 3, %\w+\n\s*(?P%\w+) = and i1 %\w+, (?P=take)\n' + r'\s*br i1 (?P=take), label %mesh_then56, label %mesh_else56\n.*?' + r'(?P%\w+) = select i1 (?P=lane), i32 {}, i32 (?P%\w+)\n.*?' + r'(?P%\w+) = phi i32 \[ (?P=new), %mesh_then_end56 \], \[ (?P=old), %mesh_else_end56 \]\n' + r'\s*br label %mesh_then_end44\n.*?' + r'= phi i32 \[ (?P=join), %mesh_then_end44 \], \[ %\w+, %mesh_else_end44 \]') + text = saveexec_skip('saveexec-cmpx-chain', if_only(chain([0x7e020285]))) # v_mov_b32 v1, 5 + assert re.search(chain_join.format(5), text, re.S), text + # A second copy and CMPX in the region narrow it again; both join at the arm's end. + text = saveexec_skip('saveexec-cmpx-chain-twice', + if_only(chain([0xbe9e047e, 0x7daa0080, 0xbf880001, # copy; v_cmpx_ne_u32 0, v0; EXECZ + 0x7e020286]))) # v_mov_b32 v1, 6 + inner = (r'(?P%\w+) = icmp ne i32 0, %\w+\n\s*(?P%\w+) = and i1 %\w+, (?P=take)\n' + r'\s*br i1 (?P=take), label %mesh_then68, label %mesh_else68\n.*?' + r'(?P%\w+) = select i1 (?P=lane), i32 6, i32 %\w+\n.*?' + r'(?P%\w+) = phi i32 \[ (?P=new), %mesh_then_end68 \], \[ %\w+, %mesh_else_end68 \]\n' + r'\s*br label %mesh_then_end56\n.*?' + r'= phi i32 \[ (?P=join), %mesh_then_end56 \], \[ %\w+, %mesh_else_end56 \]\n' + r'\s*br label %mesh_then_end44\n') + assert re.search(inner, text, re.S), text + # With an else arm the inverse would read the narrowed EXEC, so the copy stays an EXEC read. + saveexec_skip('saveexec-cmpx-chain-else', saveexec_open(chain([0x7e020285]), else_v1), + '+0x38: mesh SAVEEXEC then arm depends on EXEC') # The compiler also saves EXEC against VCC directly, without the s_and_b64 copy. vcc_open = [0x7d080015, 0xbe96246a] + saveexec_open(then_v1, else_v1)[3:] # s_and_saveexec_b64 s[22:23], vcc text = saveexec_skip('saveexec-vcc', vcc_open) From ad5831214d14d3f40730b6334de4b2ef6d02b504 Mon Sep 17 00:00:00 2001 From: Luuk Motz Date: Tue, 1 Dec 2026 22:56:23 +0100 Subject: [PATCH 21/32] shader: count a 32-bit SALU write in a mesh SAVEEXEC arm as one SGPR The then-arm scan recorded every scalar destination as a register pair, so a 32-bit write such as s_lshl_b32 s7 also marked s8 as written. At the join s8 was clobbered, and a lane mask kept there was lost; the else arm also could not read the neighbour. Record the pair only for 64-bit SALU forms and for non-SALU writes (compare masks, readlane), as before. Co-Authored-By: Claude Opus 5.5 --- src/gfx1013_direct_mesh.inl | 6 +++++- tests/native_direct_mesh_check.py | 11 +++++++++++ 2 files changed, 16 insertions(+), 1 deletion(-) diff --git a/src/gfx1013_direct_mesh.inl b/src/gfx1013_direct_mesh.inl index 575612d031..1b60d66d05 100644 --- a/src/gfx1013_direct_mesh.inl +++ b/src/gfx1013_direct_mesh.inl @@ -587,7 +587,11 @@ NativeComputeShader lower_mesh(const string &code, const MeshStageLayout &layout if (op.enc==Encoding::Smem) { for (unsigned j=0;j Date: Wed, 2 Dec 2026 03:28:13 +0500 Subject: [PATCH 22/32] shader: track uniformity through component-wise float VALU ops --- tests/startup_gfx2hlsl_readfirstlane_uniform_check.py | 11 ++++++++++- tools/startup/gfx2hlsl.py | 8 +++++--- 2 files changed, 15 insertions(+), 4 deletions(-) diff --git a/tests/startup_gfx2hlsl_readfirstlane_uniform_check.py b/tests/startup_gfx2hlsl_readfirstlane_uniform_check.py index 9082323bce..0e75f7663c 100644 --- a/tests/startup_gfx2hlsl_readfirstlane_uniform_check.py +++ b/tests/startup_gfx2hlsl_readfirstlane_uniform_check.py @@ -116,6 +116,14 @@ def run(*instructions, exec_known=True, kind=None, group=None): ['v7 = U(saturate(med3_32(F(s2), (-F(s3)), abs(F(s2)))));']), ('move', ('v_mov_b32_e32 v7, s2',), ['v7 = s2;']), ('literal move', ('v_mov_b32_e32 v7, 0x1234',), ['v7 = 0x00001234u;']), + ('signed to float conversion', ('v_cvt_f32_i32_e32 v7, s2',), + ['v7 = U(float(int(s2)));']), + ('float add chain', ('v_cvt_f32_i32_e32 v7, s2', 'v_add_f32_e32 v7, 1.0, v7', + 'v_sub_f32_e64 v7, v7, -s3 clamp'), + ['v7 = U(float(int(s2)));', 'v7 = U(1.0 + F(v7));', + 'v7 = U(saturate(F(v7) - (-F(s3))));']), + ('float mad and floor', ('v_mad_f32 v7, s2, 2.0, 1.0', 'v_floor_f32_e32 v7, v7'), + ['v7 = U(mad32(F(s2), 2.0, 1.0, false));', 'v7 = U(floor(F(v7)));']), ('chain with an in-place write', ('v_mul_f32_e64 v7, s2, 2.0', 'v_cvt_u32_f32_e32 v7, v7'), ['v7 = U(F(s2) * 2.0);', 'v7 = uint(max(F(v7), 0.0));']), ('cross-register chain', (MOVE, 'v_mul_f32_e64 v8, v7, 2.0'), @@ -165,7 +173,8 @@ def run(*instructions, exec_known=True, kind=None, group=None): ('s_mov_b32 s2, vcc_lo', 's_add_u32 s3, s2, 1', 'v_mov_b32_e32 v7, s3', READ)), ('mask through scalar condition', ('s_cmp_eq_u32 vcc_lo, 0', 's_cselect_b32 s2, 0, 1', 'v_mov_b32_e32 v7, s2', READ)), - ('non-listed overwrite', ('v_mov_b32_e32 v7, s2', 'v_add_f32_e64 v7, s2, 1.0', READ)), + ('non-listed overwrite', ('v_mov_b32_e32 v7, s2', 'v_fmac_f32_e32 v7, s2, 1.0', READ)), + ('float add with a varying source', ('v_add_f32_e64 v7, v0, 1.0', READ)), ('SDWA overwrite', ('v_mov_b32_e32 v7, s2', 'v_cvt_f32_ubyte0_sdwa v7, s2 src0_sel:DWORD dst_sel:DWORD', READ)), ('interpolant overwrite', ('v_mov_b32_e32 v7, s2', 'v_interp_mov_f32 v7, p0, attr0.x', READ)), diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index 9ed3372a55..5fb1571eeb 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -1050,10 +1050,12 @@ def smem_mods(mods): # Multiply, fused multiply-add (including the literal form), reciprocal, log2, ceil and median of three use # only local arithmetic. Move copies its input bits. None reads a lane ID or another lane. UNIFORM_VALU = frozenset(( - 'v_cvt_u32_f32', 'v_cvt_i32_f32', 'v_cvt_f32_u32', 'v_cvt_f32_ubyte0', 'v_cvt_off_f32_i4', + 'v_cvt_u32_f32', 'v_cvt_i32_f32', 'v_cvt_f32_u32', 'v_cvt_f32_i32', 'v_cvt_f32_ubyte0', 'v_cvt_off_f32_i4', 'v_cvt_pk_u16_u32', 'v_cvt_pk_i16_i32', - 'v_mul_f32', 'v_fma_f32', 'v_fmaak_f32', 'v_rcp_f32', 'v_log_f32', 'v_ceil_f32', - 'v_med3_f32', 'v_mov_b32', + 'v_add_f32', 'v_sub_f32', 'v_subrev_f32', 'v_mul_f32', 'v_fma_f32', 'v_fmaak_f32', 'v_fmamk_f32', + 'v_mad_f32', 'v_madak_f32', 'v_madmk_f32', 'v_rcp_f32', 'v_rcp_iflag_f32', 'v_rsq_f32', 'v_sqrt_f32', + 'v_exp_f32', 'v_log_f32', 'v_floor_f32', 'v_ceil_f32', 'v_trunc_f32', 'v_fract_f32', 'v_rndne_f32', + 'v_sin_f32', 'v_cos_f32', 'v_min_f32', 'v_max_f32', 'v_min3_f32', 'v_max3_f32', 'v_med3_f32', 'v_mov_b32', # Pure 32-bit integer ALU: each lane computes the result from its own sources only, so equal sources give # equal results in every lane (no carry-out, no lane ID, no cross-lane read). 'v_add_nc_u32', 'v_sub_nc_u32', 'v_subrev_nc_u32', 'v_add_nc_i32', 'v_sub_nc_i32', From 3e203663733f26f6b95a428aa14b7be8d8ddcfea Mon Sep 17 00:00:00 2001 From: Luuk Motz Date: Tue, 1 Dec 2026 23:23:17 +0100 Subject: [PATCH 23/32] shader: treat a mesh buffer load at a uniform address as uniform A buffer_load_dword, or a buffer_load_format_x from a descriptor-table V#, without OFFEN, with a uniform IDXEN index if any and a constant or uniform SOFFSET, reads the same address in every lane. Until the shader stores to memory it returns the same dwords in every lane, so mark them uniform under the same conditions as the heap typed load and let a following v_readfirstlane read them. The address is checked before the load, whose destination may be its own index register. Co-Authored-By: Claude Opus 5.5 --- src/gfx1013_direct_mesh.inl | 33 ++++++++++++++++++++++++++++--- tests/native_direct_mesh_check.py | 23 +++++++++++++++++++++ 2 files changed, 53 insertions(+), 3 deletions(-) diff --git a/src/gfx1013_direct_mesh.inl b/src/gfx1013_direct_mesh.inl index 879d7a11d1..ed68e15765 100644 --- a/src/gfx1013_direct_mesh.inl +++ b/src/gfx1013_direct_mesh.inl @@ -622,6 +622,30 @@ NativeComputeShader lower_mesh(const string &code, const MeshStageLayout &layout return full_exec || (exec_skip && !exec_skip->per_lane && exec_skip->guard==lane_active && !wave_active.empty()); }; + // A MUBUF load without OFFEN, with a uniform IDXEN index if any and a constant or uniform SOFFSET, reads + // the same address in every lane. Read before the load: its destination may be its own index register. + auto uniform_buffer_address=[&](const Inst &i) { + if ((i.a&0x1000) || memory_stored) return false; + if (i.a&0x2000) { + const auto index=alu.read(256+(i.b&255)); + if (index.empty() || uniform(index)!=index) return false; + } + const unsigned soffset=(i.b>>24)&255; + if (constant32(i,soffset)) return true; + if (soffset>=106) return false; + const auto value=alu.read(soffset); + return !value.empty() && uniform(value)==value; + }; + // Until the shader stores to memory, such a load returns the same dwords in every lane. Mark them uniform + // under the same conditions as the heap typed load, so v_readfirstlane can read them. + auto mark_uniform_buffer_load=[&](const Inst &i,unsigned count) { + for (unsigned j=0;j>16)&31)*4].type==Symbol::Type::descriptor) { // A V# read whole from a bound descriptor table: the shared typed-buffer SRV path checks the // table binding and all four descriptor words, as it does for vertex and pixel shaders. + const bool uniform_address=uniform_buffer_address(i); alu.memory(i,state); if (!full_exec) partial_writes.insert(256+i.dst); + if (uniform_address) mark_uniform_buffer_load(i,1); } else if (i.name=="buffer_load_format" && i.op==0 && (full_exec || exec_skip) && ((i.a&0x3ffff)==0x2000 || (i.a&0x3ffff)==0)) { const auto base=((i.b>>16)&31)*4; @@ -1572,11 +1598,12 @@ NativeComputeShader lower_mesh(const string &code, const MeshStageLayout &layout alu.formatted_byte_load(i,state,window); if (!full_exec) for (unsigned j=0;j<=i.op;++j) partial_writes.insert(256+i.dst+j); } else if (i.name=="buffer_load_dword" && (full_exec || exec_skip)) { + const bool uniform_address=uniform_buffer_address(i); alu.memory(i,state); - if (!full_exec) { - constexpr unsigned counts[]{1,2,4,3}; + constexpr unsigned counts[]{1,2,4,3}; + if (!full_exec) for (unsigned j=0;j Date: Wed, 2 Dec 2026 08:53:07 +1000 Subject: [PATCH 24/32] shader: broadcast lane-0 value for full-EXEC mesh v_readfirstlane_b32 (Part of #2413, #3416) Refs #2413, #3416 --- src/gfx1013_direct_mesh.inl | 51 +++++++++--- tests/native_direct_mesh_check.py | 128 +++++++++++++++++++++++++++--- 2 files changed, 156 insertions(+), 23 deletions(-) diff --git a/src/gfx1013_direct_mesh.inl b/src/gfx1013_direct_mesh.inl index 575612d031..01e48a7729 100644 --- a/src/gfx1013_direct_mesh.inl +++ b/src/gfx1013_direct_mesh.inl @@ -219,6 +219,13 @@ NativeComputeShader lower_mesh(const string &code, const MeshStageLayout &layout exchanged_group = ir.binary("mul",group,to_string(layout.group_stride)); group_uniform.insert(exchanged_group); } + unsigned shared_words=0; + auto declare_shared=[&](unsigned pc, const string &name, unsigned words) { + constexpr unsigned max_shared_words=8192; // 32 KiB of DXIL groupshared storage. + if (words>max_shared_words-shared_words) refuse(pc,"mesh groupshared storage exceeds 32 KiB"); + shared_words+=words; + ir.globals<<"@"<=106 || uniform_source(i.src[j]+1)); - if (i.enc==Encoding::Sopk && iname!="s_movk_i32") uniform_inputs=uniform_inputs && uniform_source(i.dst); + if ((i.enc==Encoding::Sopk && iname!="s_movk_i32") || iname=="s_bitset0_b32" || iname=="s_bitset1_b32") + uniform_inputs=uniform_inputs && uniform_source(i.dst); if (iname.rfind("s_cselect",0)==0 || iname.rfind("s_cmov",0)==0 || iname.rfind("s_addc",0)==0 || iname.rfind("s_subb",0)==0) uniform_inputs=uniform_inputs && uniform_source(253); @@ -1255,8 +1263,8 @@ NativeComputeShader lower_mesh(const string &code, const MeshStageLayout &layout uniform_inputs=offset_reg==125 || uniform_source(offset_reg); for (unsigned j=0;j<(i.op<8 ? 2u : 4u) && uniform_inputs;++j) uniform_inputs=uniform_descriptor(i.src[0]+j); - } else if ((iname=="v_mov_b32" || iname=="v_readfirstlane_b32") && !i.dpp_control && !i.subword) { - // A copy of a group-uniform value; readfirstlane picks one lane of it. + } else if ((iname=="v_mov_b32" || iname=="v_readfirstlane_b32") && full_exec && !i.dpp_control && !i.subword) { + // A full-EXEC copy of a group-uniform value; a masked VGPR write may keep different values. uniform_inputs=uniform_source(i.src[0]); } else if (i.enc==Encoding::Mubuf && iname.rfind("buffer_load_format",0)==0 && full_exec && !memory_stored && !((i.a>>12)&1)) { @@ -2019,9 +2027,32 @@ 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" && i.dst<106 && i.src[0]>=256 && i.src[0]<512 && + !i.dpp_control && !i.subword && (full_exec || exec_skip)) { + const auto source=alu.read(i.src[0]); + const auto proven=uniform(source); + if (!proven.empty()) alu.write(i.dst,proven); + else { + // Full guest EXEC alone does not prove that every wave reaches the barrier. + // group_flow stays false after a possibly wave-varying SCC or VCC branch. + if (!full_exec || branch || exec_skip || !forward.empty() || !group_flow) + refuse(pc,"unsupported mesh instruction or EXEC state: "+iname); + const auto tag=to_string(pc); + const auto name="meshReadFirstLane"+tag; + const unsigned waves=(layout.threads+width-1)/width; + // A separate slot per instruction prevents a later store racing an earlier load. + declare_shared(pc,name,waves); + const auto slot=alu.shared_address(name,waves,wave_number); + const auto leader=alu.cmp("eq",wave_lane,"0"); + ir.body<<" br i1 "<{value}) = icmp eq i32 {re.escape(lane[1])}, 0\n\s*' + r'br i1 (?P=leader), label %(?Pmesh_publish\d+), label %(?Pmesh_broadcast\d+)\n\s*' + rf'(?P=publish):[^\n]*\n\s*store i32 (?P{value}), {ptr}, align 4\n\s*' + r'br label %(?P=join)\n\s*(?P=join):[^\n]*\n\s*call void @dx\.op\.barrier\(i32 80, i32 9\)[^\n]*\n\s*' + rf'(?P{value}) = load i32, {ptr}, align 4', text) + assert flow, text + results.append((flow['source'], flow['result'])) + return results + + def _sop1(op, dst, src): return 0xBE800000 | ((dst & 0x7F) << 16) | ((op & 0xFF) << 8) | (src & 0xFF) @@ -377,8 +406,55 @@ 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_readfirstlane_broadcast(text, 64) + readfirst = 0x7e240506 # v_readfirstlane_b32 s18, v6 + readfirstlane_error = 'unsupported mesh instruction or EXEC state: v_readfirstlane_b32' + position_from_s18 = [0x7e020c12] + program[8:] # v_cvt_f32_u32 v1, s18 + for width in (64, 32): + layout.write_text(f'mesh1 128 3 1 2 128 {width}') + linear = [ + *wave, *program[3:5], 0xd7660000, 0x200c1, # v0 = guest lane index + 0xd7460000, 22 | ((128 + width.bit_length() - 1) << 9) | (256 << 18), # v0 = flat thread + 0x4a0c0081, # v_add_nc_u32 v6, 1, v0 + ] + # Two varying sources have distinct slots. Moving the first SGPR back into a + # VGPR and reading it again uses the wave-uniform fast path. + use_both = [readfirst, 0x7e0c0212, readfirst, 0x7e260500, 0x80121312] # s18 += readfirst(v0) + text = run(f'readfirstlane-wave{width}', program[:3] + linear + use_both + program[6:7] + position_from_s18) + (first_source, first_result), (_, second_result) = assert_readfirstlane_broadcast(text, width, 2) + assert re.search(rf'{re.escape(first_source)} = add i32 1, %[\w.]+', text), text + assert_position_x(text, rf'add i32 {re.escape(first_result)}, {re.escape(second_result)}') + + layout.write_text('mesh1 128 3 1 2 128 64') + varying_add = 0x4a0c0016 # v_add_nc_u32 v6, s22 (wave number), v0 + varying_source = wave + program[3:5] + [varying_add] + limits = [0x83948112, 0x85148014] # s_min_u32 s20, s18, 1; s_cselect_b32 s20, s20, 0 + # Use s24 for the wave number so the comparison fixture can save EXEC in s[22:23]. + limit_setup = [0x9398ff03, 0x40018, 0x4a0c0018, readfirst, *limits] + text = run('readfirstlane-exec-limit', v_cmpx_lt_u32_words(program, 20, 0, limit_setup)) + (_, result), = assert_readfirstlane_broadcast(text, 64) + minimum = re.search(rf'(%[\w.]+) = select i1 [^\n]*, i32 {re.escape(result)}, i32 1', text) + assert minimum, text + limit = re.search(rf'(%[\w.]+) = select i1 [^\n]*, i32 {re.escape(minimum[1])}, i32 0', text) + assert limit, text + assert_cmpx_ne(text, rf'icmp ult i32 {re.escape(limit[1])}, %[\w.]+') + run('readfirstlane-partial-exec', varying_source + [0x7da40081, readfirst, 0xbefe04c1] + program, + readfirstlane_error) + run('readfirstlane-scalar-source', [0xbe860381, 0x7e240406] + program, readfirstlane_error) + run('readfirstlane-special-destination', varying_source + [0x7ed40506] + program, + 'invalid scalar lane read destination') + run('readfirstlane-wave-branch', varying_source + [0xbf068016, 0xbf840001, readfirst] + program, + readfirstlane_error) + # Even after the pending edge is consumed, a wave-varying SCC branch invalidates group_flow. + wave_branch = [0xbf068016, 0xbf840001, 0xbf800000] + run('readfirstlane-after-wave-branch', varying_source + wave_branch + [readfirst] + program, + readfirstlane_error) + # Changing a literal bit in a per-wave scalar still leaves the other bits per-wave. + varying_scc = [0xbe921d81, 0xbf068212, 0xbf840001, 0xbf800000] # bitset1 s18,1; s18 == 2; skip nop + run('readfirstlane-broadcast-scc', varying_source + [readfirst] + varying_scc + [0x7e260506] + program, + readfirstlane_error) + flat = [ *wave, 0xd7650000, 0x100c1, # mbcnt_lo v0, -1, 0 0xd7660000, 0x200c1, # mbcnt_hi v0, -1, v0 @@ -397,6 +473,11 @@ def run(name, words, expected=None): 0x7e147081, 0xf80008c0, 0, 0xf8000941, 10, # v10 = cull bit; null position and culled primitive 0xbf8cff0f, 0xbefe040c, 0xbf8a0000, # restore s[12:13] and reconverge ] + # A wave64 broadcast uses two words for 128 threads. Leave two words + # for the guarded allocation counts, then verify its export scratch is counted too. + run('readfirstlane-shared-budget', + flat + [0x7e240500] * 4095 + guarded_alloc + program[3:], + 'mesh groupshared storage exceeds 32 KiB') text = run('lane-zero-allocation', flat + guarded_alloc + program[3:]) assert text.count('call void @dx.op.setMeshOutputCounts') == 1 assert re.search(r'store i32 [^\n]+\n.*?dx\.op\.barrier.*?setMeshOutputCounts\(i32 168, i32 %\w+, i32 %\w+\)', @@ -674,6 +755,26 @@ def run(name, words, expected=None): readfirst_exported[7] = 0x7e020c12 # v_cvt_f32_u32 v1, s18 text = run('typed-heap-element-zero-uniform', heap_setup + load_elem0 + [0x7e24050a] + readfirst_exported) assert re.search(r'bufferLoad\.i32\(i32 68, %dx\.types\.Handle %[\w.]+, i32 0, i32 undef\)', text), text + assert 'addrspace(3)' not in text and '@dx.op.barrier' not in text, text + + # The root-derived SCC selects a lane-indexed buffer load or a literal, + # with the broadcast in the full-EXEC join that both paths reach. + join_load = [0xbf068015, 0xbf840002, 0x7e140285, 0xbf820002, # s21 == 0; v10 = 5 on one arm + 0xe0002000, 0x80080a00] # v10 = typed load at v0 on the other arm + text = run('readfirstlane-buffer-phi', + heap_setup + program[3:5] + join_load + [0x7e24050a] + readfirst_exported) + (source, result), = assert_readfirstlane_broadcast(text, 64) + loaded = re.search(r'(%[\w.]+) = call %dx\.types\.ResRet\.i32 @dx\.op\.bufferLoad\.i32\(', text) + assert loaded, text + word = re.search(r'(%[\w.]+) = extractvalue %dx\.types\.ResRet\.i32 ' + re.escape(loaded[1]) + r', 0', text) + assert word, text + phi = re.search(rf'{re.escape(source)} = phi i32 [^\n]*', text) + assert phi and f'[ {word[1]},' in phi[0] and '[ 5,' in phi[0], text + assert_position_x(text, rf'load i32, i32 addrspace\(3\)\*') + assert re.search(rf'uitofp i32 {re.escape(result)} to float', text), text + run('readfirstlane-heap-selector', + varying_source + [0x7e2a0506] + heap_setup + load_elem0 + exported, # overwrite root s21 + 'mesh heap slot lacks masked root constant provenance') # buffer_load_format_x inside a per-lane EXECZ skip preserves inactive lanes' pre-skip value via select + phi. def skip_load(body, seed=True): pre = [0x7e140287] if seed else [] # v_mov_b32 v10, 7 @@ -952,6 +1053,7 @@ def saveexec_open(then, other): 0x8afe7e16, # s_andn2_b64 exec, s[22:23], exec *other] then_v1, else_v1 = [0x7e020282], [0x7e020283] # v_mov_b32_e32 v1, 2 / 3 + saveexec_skip('saveexec-readfirstlane', saveexec_open([0x7e240500], else_v1), readfirstlane_error) text = saveexec_skip('saveexec-skip-end', saveexec_open(then_v1, else_v1)) arms = r'= phi i32 \[ 2, %mesh_then_end\d+ \], \[ 3, %mesh_else_end\d+ \]' # The s[24:25] lanes branch to the then arm (2); the others to the else arm (3). @@ -1520,12 +1622,12 @@ def merged(condition): 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 'addrspace(3)' not in text and '@dx.op.barrier' not in text, 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) + assert_readfirstlane_broadcast(run('varying-udiv', program[:5]+varying_reciprocal+refine+tail), 64) overwrite = [0x7e0c0300] # v_mov_b32 v6, v0 - run('overwritten-udiv',program[:5]+reciprocal+overwrite+refine+tail,readfirstlane_error) + assert_readfirstlane_broadcast(run('overwritten-udiv', program[:5]+reciprocal+overwrite+refine+tail), 64) guard_tail = refine[:1] + reads_group[5:] # Read v6 into s18 and export it. varying_accumulator = [ @@ -1533,28 +1635,28 @@ def merged(condition): 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) + assert_readfirstlane_broadcast( + run('varying-accumulator', program[:5]+varying_accumulator+guard_tail), 64) 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) + assert_readfirstlane_broadcast( + run('varying-pair-high', program[:5]+varying_pair_high+guard_tail), 64) 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) + assert_readfirstlane_broadcast( + run('sdwa-uniform-source', program[:5]+sdwa_source+guard_tail), 64) # 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) + assert_readfirstlane_broadcast( + run('dpp-uniform-source', program[:5]+dpp_source+guard_tail), 64) partial_write = [ 0xbe96047e, # s_mov_b64 s[22:23], exec (save EXEC) From 816ab82107398fa96c4cf194b07320c692780bfc Mon Sep 17 00:00:00 2001 From: Roland Edi Date: Tue, 1 Dec 2026 13:51:23 +0000 Subject: [PATCH 25/32] shader: lower v_and_or_b32 and v_cvt_f16_f32 in the mesh frontend After the scalar bit operations, the forced slot 86 mesh path refused v_cvt_f16_f32 in 357 requests and v_and_or_b32 in 331, ahead of the control-flow, heap-provenance and pixel blocks. - v_and_or_b32 (VOP3 0x371) joins the mesh vector list that already handles v_or3_b32 and v_add3_u32, so it takes the three-source alu_rules entry and lowers to (S0 & S1) | S2. The shared operand gate still refuses abs, neg, clamp and omod. - v_cvt_f16_f32 (VOP1 0x0A) joins the same list and reuses the compute frontend's integer round-to-nearest-even narrowing: the sign comes from bit 31, binary32 subnormals become signed zeros, binary16 subnormals are kept, overflow including the 65520 tie gives 0x7c00, and a NaN keeps its quiet bit. The encoding goes into the low half and the reaching destination value keeps the high half, as the compute frontend does, so an unproven destination still refuses and the merged word is not treated as uniform. tests/native_direct_mesh_check.py adds source-built programs with the run helper: v_and_or_b32 with s20 = 0x0000ffff and s21 = 0x00ff0000 exports (and v0, 65535) | 0x00ff0000, and v_cvt_f16_f32 exports the narrowed word for 1.0f, 0.0f and -2.0f. Controls reject an unbound third source and an unproven conversion source or destination. Observed IR: - %t8 = and i32 %v0, 65535 ; %t9 = or i32 %t8, 16711680 - v_cvt_f16_f32: lshr , 16 / and ... 32768 for the sign, and , 2147483647, lshr ... 23, and ... 8388607, the nearest-even narrowing with icmp ugt %exp, 142 -> 31744 and icmp ugt %mag, 2139095040 -> 32256 | quiet bits, then or %narrow, %sign, and %destination, -65536 and the final or. Verified: - cmake --build --preset release --target compile_dxil (7/7 steps, compile_dxil.exe linked) - python -B tests/native_direct_mesh_check.py : exit 0, "mesh allocation, indexed outputs, group exchange and negative controls passed" - ctest --preset release --no-tests=error -R '^native_direct' 2/2 passed: native_direct_container 15.04 s, native_direct_mesh 13.78 s - python -B tests/docs_links_check.py: 210 files, 807 links Refs #3703 --- docs/experiments/native-mesh-vector-alu.md | 54 +++++++++++ src/gfx1013_direct_mesh.inl | 6 +- tests/native_direct_mesh_check.py | 103 +++++++++++++++++++++ 3 files changed, 162 insertions(+), 1 deletion(-) create mode 100644 docs/experiments/native-mesh-vector-alu.md diff --git a/docs/experiments/native-mesh-vector-alu.md b/docs/experiments/native-mesh-vector-alu.md new file mode 100644 index 0000000000..502f632e84 --- /dev/null +++ b/docs/experiments/native-mesh-vector-alu.md @@ -0,0 +1,54 @@ +# Mesh frontend vector bit-select and binary16 narrowing + +The direct C++ mesh frontend behind `gfx1013-raw-ms` now lowers two more forms +that the forced slot 86 mesh path refused. After the scalar bit operations, the census of the +2 873 title requests ordered the next refusals `v_cvt_f16_f32` (357) and +`v_and_or_b32` (331), followed by the control-flow, heap-provenance and pixel +blocks. + +## Lowering + +Both names join the vector list in +[gfx1013_direct_mesh.inl](../../src/gfx1013_direct_mesh.inl) that already handles +`v_or3_b32`, `v_add3_u32` and the other three-source forms, so they share +`arithmetic()` with the compute frontend. + +- `v_and_or_b32` (VOP3 `0x371`) takes its arity of three from the + `alu_rules` entry and lowers to `(S0 & S1) | S2`. The shared operand gate + still refuses `abs`, `neg`, `clamp` and `omod`. +- `v_cvt_f16_f32` (VOP1 `0x0A`) narrows S0 with the same integer + round-to-nearest-even conversion the compute frontend uses, so desktop + conversion and denormal handling cannot change the encoding: the sign comes + from bit 31, binary32 subnormals become signed zeros, a binary16 subnormal is + kept, the 65520 tie and everything above it give `0x7c00`, and a NaN keeps + its quiet bit (`0x7e00`). The low half of the destination receives the + encoding and the high half keeps the reaching destination value, as the + compute frontend and the RDNA 2 high-half-preservation rule do. Because the + merged word reads the destination, an unproven destination still refuses + (`unproven mesh entry register`); the conversion is not treated as a + uniform result for `v_readfirstlane`. + +## Observed IR + +With `s20 = 0x0000ffff` and `s21 = 0x00ff0000`, the source-built +`v_and_or_b32 v1, v0, s20, s21` emits `and i32 %v0, 65535` then +`or i32 %and, 16711680`, and POS0.x exports that word. + +`v_cvt_f16_f32 v1, v3` with v3 holding 1.0f, 0.0f or -2.0f emits +`lshr i32 , 16` with `and ... 32768` for the sign, +`and i32 , 2147483647`, `lshr ... 23` and `and ... 8388607` for the +magnitude, exponent and fraction, the nearest-even narrowing with +`icmp ugt i32 %exp, 142` giving `31744`, `icmp ugt i32 %mag, 2139095040` +selecting `32256` plus the quiet bits, then `or i32 %narrow, %sign`, +`and i32 %destination, -65536` and the final `or`. POS0.x exports the whole +word. + +## Controls + +An unbound third source keeps `unbound numeric SGPR s24`. A conversion from an +unproven VGPR 24 or into an unproven VGPR 5 keeps `unproven mesh entry +register`. + +**Reproduce** with +`ctest --preset release --no-tests=error -R '^native_direct'`. + diff --git a/src/gfx1013_direct_mesh.inl b/src/gfx1013_direct_mesh.inl index 575612d031..29ca2e98fa 100644 --- a/src/gfx1013_direct_mesh.inl +++ b/src/gfx1013_direct_mesh.inl @@ -2108,8 +2108,10 @@ NativeComputeShader lower_mesh(const string &code, const MeshStageLayout &layout 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_sub_nc_u32" || i.name=="v_subrev_nc_u32" || i.name=="v_add_co_ci_u32" || i.name=="v_lshlrev_b32" || - i.name=="v_lshrrev_b32" || i.name=="v_or_b32" || i.name=="v_or3_b32" || i.name=="v_and_b32" || + i.name=="v_lshrrev_b32" || i.name=="v_or_b32" || i.name=="v_or3_b32" || i.name=="v_and_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_cvt_f16_f32" || i.name=="v_mul_f32" || i.name=="v_add_f32" || i.name=="v_fma_f32" || i.name=="v_bfm_b32" || i.name=="v_bcnt_u32_b32")) { const bool flat=i.name=="v_lshl_add_u32" && alu.operand32(i,i.src[0])==wave_number && @@ -2124,6 +2126,8 @@ NativeComputeShader lower_mesh(const string &code, const MeshStageLayout &layout pair || i.name=="v_mul_legacy_f32" || i.name=="v_bfm_b32" || i.name=="v_bcnt_u32_b32" ? 2 : i.name=="v_trunc_f32" || i.name=="v_fract_f32" || i.name=="v_cos_f32" || i.name.substr(0,15)=="v_cvt_f32_ubyte" ? 1 : 0; + // v_cvt_f16_f32 keeps the destination's high half, so its single + // source cannot prove the merged word uniform on its own. const auto uniform_source=[&](unsigned r) { if (r==106 || r==107 || r==126 || r==127 || r==251 || r==252) return false; if (constant32(i,r)) return true; diff --git a/tests/native_direct_mesh_check.py b/tests/native_direct_mesh_check.py index 7fa7767e90..4f64badc56 100644 --- a/tests/native_direct_mesh_check.py +++ b/tests/native_direct_mesh_check.py @@ -50,6 +50,18 @@ def assert_export_column(text, value, column): rf"float {re.escape(back['back'])},", text), text +def _sop2(op, dst, src0, src1): + return 0x80000000 | ((op & 0x7F) << 23) | ((dst & 0x7F) << 16) | ((src1 & 0xFF) << 8) | (src0 & 0xFF) + + +def _sopc(op, src0, src1): + return 0xBF000000 | ((op & 0x7F) << 16) | ((src1 & 0xFF) << 8) | (src0 & 0xFF) + + +def _sop1_literal(op, dst, value): + return [_sop1(op, dst, 255), value & 0xFFFFFFFF] + + def _inline_u32(value): if 0 <= value <= 64: return 128 + value @@ -104,6 +116,16 @@ def _v_mov_b32(dst, src): return (63 << 25) | ((dst & 0xFF) << 17) | (1 << 9) | (src & 0x1FF) + +def _vop1(op, dst, src): + return (63 << 25) | ((dst & 0xFF) << 17) | ((op & 0xFF) << 9) | (src & 0x1FF) + + +def _vop3(op, dst, src0, src1, src2): + return [0xD4000000 | ((op & 0x3FF) << 16) | (dst & 0xFF), + (src0 & 0x1FF) | ((src1 & 0x1FF) << 9) | ((src2 & 0x1FF) << 18)] + + def _vopc(opcode, src0, vsrc1): return (62 << 25) | ((opcode & 0xFF) << 17) | ((vsrc1 & 0xFF) << 9) | (src0 & 0x1FF) @@ -142,6 +164,59 @@ def assert_cmpx_ne(text, predicate): assert_position_x(text, joined) + +def assert_export_column(text, value, column): + """A 32-bit SSA value reaches one POS0 column through uitofp and bitcasts.""" + value_re = r'%[\w.]+' + as_float = re.search(rf'(?P{value_re}) = uitofp i32 {re.escape(value)} to float\n', text) + assert as_float, text + bits = re.search(rf'(?P{value_re}) = bitcast float {re.escape(as_float["float"])} to i32\n', text) + assert bits, text + back = re.search(rf'(?P{value_re}) = bitcast i32 {re.escape(bits["bits"])} to float\n', text) + assert back, text + assert re.search(rf'call void @dx\.op\.storeVertexOutput\.f32\(i32 171, i32 \d+, i32 0, i8 {column}, ' + rf'float {re.escape(back["back"])},', text), text + + +def assert_scalar_export(text, result): + """SCC = (D != 0) drives POS0.y while the scalar result D drives POS0.x.""" + value = r'%[\w.]+' + nonzero = re.search(rf'(?P{value}) = icmp ne i32 {re.escape(result)}, 0\n', text) + assert nonzero, text + scc = re.search(rf'(?P{value}) = zext i1 {re.escape(nonzero["nonzero"])} to i32\n', text) + assert scc, text + take = re.search(rf'(?P{value}) = icmp ne i32 {re.escape(scc["scc"])}, 0\n', text) + assert take, text + chosen = re.search(rf'(?P{value}) = select i1 {re.escape(take["take"])}, i32 1, i32 0\n', text) + assert chosen, text + assert_export_column(text, result, 0) + assert_export_column(text, chosen['chosen'], 1) + + +def assert_half_narrowing(text, source): + """The shared nearest-even binary16 narrowing and the destination merge.""" + value = r'%[\w.]+' + head = re.search( + rf'(?P{value}) = lshr i32 {source}, 16\n' + rf'\s*(?P{value}) = and i32 (?P=shift), 32768\n' + rf'\s*(?P{value}) = and i32 {source}, 2147483647\n' + rf'\s*(?P{value}) = lshr i32 (?P=mag), 23\n' + rf'\s*(?P{value}) = and i32 (?P=mag), 8388607\n', text) + assert head, text + tail = re.search( + rf'(?P{value}) = icmp ugt i32 {re.escape(head["exp"])}, 142\n' + rf'\s*(?P{value}) = select i1 (?P=over), i32 31744, i32 {value}\n' + rf'\s*(?P{value}) = icmp ugt i32 {re.escape(head["mag"])}, 2139095040\n' + rf'\s*(?P{value}) = lshr i32 {re.escape(head["frac"])}, 13\n' + rf'\s*(?P{value}) = or i32 (?P=quiet_shift), 32256\n' + rf'\s*(?P{value}) = select i1 (?P=nan), i32 (?P=quiet), i32 (?P=inf)\n' + rf'\s*(?P{value}) = or i32 (?P=narrow), {re.escape(head["sign"])}\n' + rf'\s*(?P{value}) = and i32 {value}, -65536\n' + rf'\s*(?P{value}) = or i32 (?P=half), (?P=keep)\n', text) + assert tail, text + assert_export_column(text, tail['result'], 0) + + def check_profile_writer(folder, archive, profile, blob): # Desktop state from the one-RTV native fixture in startup_indirect_draw_indexed.cpp. state = { @@ -566,6 +641,34 @@ def run(name, words, expected=None): ('scalar-xor-vcc', 0x896ac114, 'unsupported mesh instruction or EXEC state: s_xor_b32'), ): run(scalar_k_case, program[:5] + [scalar_k_word] + program[5:], '+0x14: ' + scalar_k_reason) + # VOP3 v_and_or_b32 v1, v0, s20, s21 is (S0 & S1) | S2 through the + # shared three-source rule; s20 is 0x0000ffff and s21 0x00ff0000. + and_or = program[:5] + [ + *_sop1_literal(3, 20, 0x0000FFFF), *_sop1_literal(3, 21, 0x00FF0000), + *_vop3(0x371, 1, 256, 20, 21)] + program[6:] + text = run('v-and-or-b32', and_or) + masked = re.search(r'(?P%[\w.]+) = and i32 (?P%[\w.]+), 65535\n' + r'\s*(?P%[\w.]+) = or i32 (?P=low), 16711680\n', text) + assert masked, text + assert_export_column(text, masked['result'], 0) + run('v-and-or-b32-unproven', program[:5] + [ + *_sop1_literal(3, 20, 0x0000FFFF), *_vop3(0x371, 1, 256, 20, 24)] + program[6:], + '+0x1c: unbound numeric SGPR s24') + # v_cvt_f16_f32 narrows with the shared nearest-even integer conversion + # and keeps the destination's high half; POS0.x exports the whole word. + for name, source, bits in ( + ('v-cvt-f16-f32-normal', 242, '1065353216'), # 1.0f + ('v-cvt-f16-f32-zero', 128, '0'), # 0.0f + ('v-cvt-f16-f32-negative', 245, '-1073741824'), # -2.0f + ): + words = program[:6] + [_vop1(1, 3, source), _vop1(0x0A, 1, 259)] + program[6:] + assert_half_narrowing(run(name, words), bits) + run('v-cvt-f16-f32-unproven-source', + program[:6] + [_vop1(1, 3, 242), _vop1(0x0A, 1, 280)] + program[6:], + '+0x1c: unproven mesh entry register 280') + run('v-cvt-f16-f32-unproven-destination', + program[:6] + [_vop1(1, 3, 242), _vop1(0x0A, 5, 259)] + program[6:], + '+0x1c: unproven mesh entry register 261') # The three primitive slots are 9-bit indices with the edge flag in # bit 9. 0x20280600 encodes (0,1,2) with all three edge flags set. edge = program.copy() From 37b04396be688e4589308b35284a4a5e9b04d5ff Mon Sep 17 00:00:00 2001 From: Rachel Amber <77208679+Holastor@users.noreply.github.com> Date: Wed, 2 Dec 2026 04:21:26 +0500 Subject: [PATCH 26/32] tests: update float literal suffix to 1.0f/2.0f in readfirstlane_uniform_check --- tests/startup_gfx2hlsl_readfirstlane_uniform_check.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/startup_gfx2hlsl_readfirstlane_uniform_check.py b/tests/startup_gfx2hlsl_readfirstlane_uniform_check.py index 0e75f7663c..cb8dca4b9a 100644 --- a/tests/startup_gfx2hlsl_readfirstlane_uniform_check.py +++ b/tests/startup_gfx2hlsl_readfirstlane_uniform_check.py @@ -120,10 +120,10 @@ def run(*instructions, exec_known=True, kind=None, group=None): ['v7 = U(float(int(s2)));']), ('float add chain', ('v_cvt_f32_i32_e32 v7, s2', 'v_add_f32_e32 v7, 1.0, v7', 'v_sub_f32_e64 v7, v7, -s3 clamp'), - ['v7 = U(float(int(s2)));', 'v7 = U(1.0 + F(v7));', + ['v7 = U(float(int(s2)));', 'v7 = U(1.0f + F(v7));', 'v7 = U(saturate(F(v7) - (-F(s3))));']), ('float mad and floor', ('v_mad_f32 v7, s2, 2.0, 1.0', 'v_floor_f32_e32 v7, v7'), - ['v7 = U(mad32(F(s2), 2.0, 1.0, false));', 'v7 = U(floor(F(v7)));']), + ['v7 = U(mad32(F(s2), 2.0f, 1.0f, false));', 'v7 = U(floor(F(v7)));']), ('chain with an in-place write', ('v_mul_f32_e64 v7, s2, 2.0', 'v_cvt_u32_f32_e32 v7, v7'), ['v7 = U(F(s2) * 2.0);', 'v7 = uint(max(F(v7), 0.0));']), ('cross-register chain', (MOVE, 'v_mul_f32_e64 v8, v7, 2.0'), From 3028d43eb25ca9c4ff9a6955026b3f55edfc397a Mon Sep 17 00:00:00 2001 From: Roland Edi Date: Wed, 2 Dec 2026 00:20:46 +0000 Subject: [PATCH 27/32] mesh86: publish a PS-less mesh SRV table profile --- docs/experiments.md | 20 ++ docs/startup-runtime.md | 7 +- src/startup_stubs/d3d12_xs_device.cpp | 17 +- src/startup_stubs/mesh86_cache.inl | 199 +++++++++++++--- tests/cmake/startup_mesh86_psless.cmake | 12 + tests/startup_indirect_draw_indexed.cpp | 41 +++- tests/startup_indirect_mesh_psless_srv.hlsl | 20 ++ tests/startup_mesh86_psless_check.py | 127 ++++++++++ tools/startup/mesh86_cache.py | 249 +++++++++++++++++++- tools/startup/mesh86_translate.py | 52 +++- 10 files changed, 685 insertions(+), 59 deletions(-) create mode 100644 tests/cmake/startup_mesh86_psless.cmake create mode 100644 tests/startup_indirect_mesh_psless_srv.hlsl create mode 100644 tests/startup_mesh86_psless_check.py diff --git a/docs/experiments.md b/docs/experiments.md index 16ae6a9c6f..c53e5a260a 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -10540,6 +10540,26 @@ without the resource-heap flag is still refused. Such a wide root requires `constants-only`: a marker published before the binding proof stays refused until it is republished, while a root of constants only still accepts it. +The title's slot 86 `DispatchMesh` requests also arrive without a pixel stage. +`--prove-mesh-srv-table DXC --mesh-srv-plan PLAN` accepts a profile-6 marker +whose plan names each desktop `t0..tN-1` buffer SRV and the guest root +parameter and 32-byte table record (or root SRV) it came from. The publisher +dumps only the mesh stage, rejects a `createHandleFromHeap` read, requires the +desktop DXIL to bind exactly the planned byte SRVs, and refuses a plan entry +outside its root parameter. The runtime builds a synthetic root from the plan +and `bind_native_mesh86` resolves every record; an unusable record refuses the +draw. PS-full profiles keep their version-1/2/3/4/5 bytes. + +On the 2026-12-01 slot 86 cache, 987 of 3,876 requests have an empty `.ps86`; +614 of those reached the heap proof and now publish profile 6 when their mesh +stage has no direct heap read (for example request `08dc8a7b1c8fd5da`, seven +SRVs and a mesh-only `b0` block). The source-built +`startup_mesh86_psless_{warp,hardware}` fixture publishes one root SRV, reads +`0x12345678` from it in the mesh stage and writes D16 depth 0.5. Hardware +passes; WARP currently removes the device after the recorded DispatchMesh +(`map argument readback failed (HRESULT 0x887a0005)`), so the WARP case is the +open blocker for this draft. + At each slot 61 `ExecuteIndirect`, the runtime reads the window's slots from the title's bound shader-visible heap, the same 32-byte view tokens the slot 57 path reads. A slot that holds a registered typed buffer SRV over a complete diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index 4b297f3a76..5c0c9de6fe 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -91,9 +91,10 @@ debug layer is not installed. With a zero handle, the far triangle overwrites an value. With an unknown handle, nothing is drawn. Each unresolved handle is counted once. The `_drop_control` draws the bound case with a zero handle and passes only when the intended colour and depth mismatch appears. -Mesh pipelines reach the stand-in only as native desktop-bytecode streams, which must have a pixel stage -and no depth format. A depth-only mesh pass (no colour target, no pixel stage) is therefore refused when -the pipeline is created, and no fixture binds a depth target for one. +Mesh pipelines reach the stand-in only as native desktop-bytecode streams. A published profile-6 marker +can have no pixel stage when its mesh stage is proved to read only root constants, root SRVs and +descriptor-table records; the runtime then binds a synthetic mesh root and the mesh SRVs. A depth-only +mesh pass without such a marker is still refused when the pipeline is created. ## Default viewport and scissor diff --git a/src/startup_stubs/d3d12_xs_device.cpp b/src/startup_stubs/d3d12_xs_device.cpp index cad344c39e..193eb57442 100644 --- a/src/startup_stubs/d3d12_xs_device.cpp +++ b/src/startup_stubs/d3d12_xs_device.cpp @@ -204,6 +204,7 @@ struct IndirectGraphicsPipeline { x2w_startup::ComPtr texture_map_root; ID3D12RootSignature* texture_map_guest_root = nullptr; UINT texture_map_parameter = UINT_MAX; + bool synthetic_root = false; std::shared_ptr native_mesh86; }; // One slot of a slot 86 heap-buffer window as written to its private heap: a null resource is a typed null view. @@ -4239,8 +4240,9 @@ bool cached_mesh_root_matches(const Pass& pass) { const auto& pso = pass.indirect_graphics; return pass.root && pass.root == pso.guest_root_params && - (pass.root_heap_flags != 0) == - (pso.constant_guest != UINT_MAX || pso.cached_heap_count != 0 || bool(pso.texture_map_root)); + (pso.synthetic_root || + (pass.root_heap_flags != 0) == + (pso.constant_guest != UINT_MAX || pso.cached_heap_count != 0 || bool(pso.texture_map_root))); } enum { indirect_forwarded, indirect_graphics_pipeline, indirect_compute_pipeline, indirect_placeholder, indirect_other, @@ -4678,10 +4680,13 @@ void __stdcall list_execute_indirect(Wrapper* self, void* signature, UINT count, else bytes = sizeof(D3D12_DRAW_ARGUMENTS); if (type != D3D12_COMMAND_LIST_TYPE_DIRECT || (!translated && (!pass.indirect_graphics.root || (pass.indirect_graphics.constant_guest == UINT_MAX && - (pass.indirect_graphics.texture_map_root ? pass.indirect_graphics.texture_map_guest_root : - pass.indirect_graphics.root) != - (pass.indirect_graphics.cached_heap_count || pass.indirect_graphics.texture_map_root ? - pass.deferred_root : pass.graphics_root)) || + (pass.indirect_graphics.synthetic_root ? + pass.indirect_graphics.texture_map_guest_root != (pass.deferred_root ? pass.deferred_root : + pass.graphics_root) : + (pass.indirect_graphics.texture_map_root ? pass.indirect_graphics.texture_map_guest_root : + pass.indirect_graphics.root) != + (pass.indirect_graphics.cached_heap_count || pass.indirect_graphics.texture_map_root ? + pass.deferred_root : pass.graphics_root))) || pass.indirect_graphics.mesh != mesh))) { // A console pipeline (no desktop pipeline) used only here still gets the request a direct draw writes; // nothing is drawn. diff --git a/src/startup_stubs/mesh86_cache.inl b/src/startup_stubs/mesh86_cache.inl index 1696db4c34..418a8d14b9 100644 --- a/src/startup_stubs/mesh86_cache.inl +++ b/src/startup_stubs/mesh86_cache.inl @@ -238,6 +238,94 @@ x2w_startup::ComPtr mesh86_texture_root( #ifdef X2W_NATIVE_SHADERS #include "startup_stubs/native_mesh86.inl" + +namespace { +// Profile 6 stores the translator's binding plan below its marker. The plan +// names only root parameters the guest signature already declares; the root +// and every SRV are rebuilt at draw time by bind_native_mesh86, which resolves +// each record and refuses an unusable view instead of binding garbage. +bool parse_published_mesh86_plan(const std::string& text, std::size_t at, + const std::vector& guest, std::shared_ptr& plan_out, + x2w_startup::ComPtr& root_out, char* why, std::size_t why_size) +{ + std::vector constants; + std::vector views; + while (at < text.size()) { + const auto end = text.find('\n', at); + if (end == std::string::npos) { + std::snprintf(why, why_size, "profile-6 plan has no final newline"); + return false; + } + const std::string line = text.substr(at, end - at); + at = end + 1; + unsigned root = 0, count = 0, reg = 0, param = 0, offset = 0, bytes = 0, kind = 0, dim = 0; + if (std::sscanf(line.c_str(), "constant %u %u", &root, &count) == 2) { + if (root >= guest.size() || guest[root].type != D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS || + !count || count > 8 || guest[root].constants_count != count) { + std::snprintf(why, why_size, "profile-6 constant block disagrees with the guest root"); + return false; + } + for (const auto& block : constants) + if (block.root_parameter == root) { + std::snprintf(why, why_size, "profile-6 duplicates a constant block"); + return false; + } + constants.push_back({root, 0, count}); + } else if (std::sscanf(line.c_str(), "srv %u %u %u %u %u %u", ®, ¶m, &offset, &bytes, &kind, &dim) == 6) { + if (reg != views.size() || views.size() >= 64 || param >= guest.size()) { + std::snprintf(why, why_size, "profile-6 SRV plan is not a contiguous t0..tN-1 list"); + return false; + } + const auto& parameter = guest[param]; + if (parameter.type == D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE) { + if (offset % 32 || offset / 32 >= 1u << 20) { + std::snprintf(why, why_size, "profile-6 table record is outside the runtime bound"); + return false; + } + } else if (parameter.type != D3D12_ROOT_PARAMETER_TYPE_SRV || offset) { + std::snprintf(why, why_size, "profile-6 SRV names a non-SRV root parameter"); + return false; + } + if (!bytes || bytes > 1u << 20 || dim > 8 || + (kind != 0 && kind != 4 && kind != 10 && kind != 18 && kind != 26)) { + std::snprintf(why, why_size, "profile-6 SRV has an unsupported extent, kind or dimension"); + return false; + } + x2w::ComputeViewBinding view{}; + view.kind = static_cast(kind); + view.root_parameter = param; + view.byte_offset = offset; + view.shader_register = reg; + view.required_bytes = bytes; + view.array_count = 1; + view.image_dimension = dim; + views.push_back(view); + } else { + std::snprintf(why, why_size, "profile-6 marker has an unsupported plan line"); + return false; + } + } + if (views.empty()) { + std::snprintf(why, why_size, "profile-6 marker has no SRV binding"); + return false; + } + try { + auto plan = std::make_shared(); + plan->mesh.constants = constants; + plan->mesh.views = views; + x2w::NativeComputeShader mesh; + mesh.constants = constants; + mesh.bindings = views; + x2w::NativeComputeShader pixel; + root_out = make_native_mesh86_root(device_of(the_device), guest, mesh, pixel, *plan); + plan_out = std::move(plan); + } catch (const std::exception& error) { + std::snprintf(why, why_size, "profile-6 root creation failed: %s", error.what()); + return false; + } + return true; +} +} // namespace #endif namespace { @@ -290,23 +378,81 @@ ID3D12PipelineState* try_cached_mesh86(const D3D12_PIPELINE_STATE_STREAM_DESC& d return nullptr; } #ifdef X2W_NATIVE_SHADERS - if (heap_flags && x2w_local::env_on("X2W_NATIVE_MESH86")) { + if (heap_flags && !request.ps.empty() && x2w_local::env_on("X2W_NATIVE_MESH86")) { if (auto* native = create_native_mesh86(request, root_blob, *params, path, key, why, why_size, graphics)) return native; if (*why) return nullptr; } #endif - std::string ready; WIN32_FILE_ATTRIBUTE_DATA marker{}; - if (!cache_path(path, L"", key, L".mesh86.txt") || !GetFileAttributesExW(path, GetFileExInfoStandard, &marker) || - marker.nFileSizeHigh || marker.nFileSizeLow > 128 || !read_text(path, ready)) { + if (!cache_path(path, L"", key, L".mesh86.txt") || !GetFileAttributesExW(path, GetFileExInfoStandard, &marker)) { std::snprintf(why, why_size, "slot86 mesh request %016llx pending", key); return nullptr; } + x2w_startup::ComPtr ms, ps; + const auto load_stage = [&](const wchar_t* ext, x2w_startup::ComPtr& stage) { + WIN32_FILE_ATTRIBUTE_DATA info{}; + return cache_path(path, L"", key, ext) && GetFileAttributesExW(path, GetFileExInfoStandard, &info) && + !info.nFileSizeHigh && info.nFileSizeLow <= 1u << 20 && + SUCCEEDED(D3DReadFileToBlob(path, stage.GetAddressOf())); + }; + if (!load_stage(L".ms.cso", ms) || (!request.ps.empty() && !load_stage(L".ps.cso", ps))) { + std::snprintf(why, why_size, "slot86 mesh request %016llx: incomplete bytecode", key); + return nullptr; + } + const D3D12_SHADER_BYTECODE mesh{ms->GetBufferPointer(), ms->GetBufferSize()}; + const D3D12_SHADER_BYTECODE pixel = ps ? D3D12_SHADER_BYTECODE{ps->GetBufferPointer(), ps->GetBufferSize()} : + D3D12_SHADER_BYTECODE{}; + if (desktop_dxil_mesh_stage(mesh) != DxilMeshStage::mesh || + (ps && desktop_dxil_mesh_stage(pixel) != DxilMeshStage::pixel)) { + std::snprintf(why, why_size, "slot86 mesh request %016llx: cache key, stage or bytecode mismatch", key); + return nullptr; + } + std::string ready; + if (!cache_path(path, L"", key, L".mesh86.txt") || marker.nFileSizeHigh || marker.nFileSizeLow > 64u << 10 || + !read_text(path, ready)) { + std::snprintf(why, why_size, "slot86 mesh request %016llx pending", key); + return nullptr; + } + const bool psless_srv = ready.rfind("x2w-mesh86 6 ", 0) == 0; constexpr std::string_view constants_marker = "x2w-mesh86 4 "; - const bool constants_only = !heap_flags && ready.compare(0, constants_marker.size(), constants_marker) == 0; - const bool texture_map = heap_flags && ready.rfind("x2w-mesh86 5 ", 0) == 0; + bool constants_only = false; + bool texture_map = false; UINT srv_root = UINT_MAX; + UINT heap_first = 0, heap_count = 0; + char heap_type[4] = ""; + UINT map_parameter = UINT_MAX; + x2w_startup::ComPtr mapped_root; +#ifdef X2W_NATIVE_SHADERS + std::shared_ptr published_plan; + x2w_startup::ComPtr published_root; +#endif + if (psless_srv) { + if (!request.ps.empty()) { + std::snprintf(why, why_size, "slot86 mesh request %016llx: PS-less profile has a pixel stage", key); + return nullptr; + } + unsigned version = 0; + unsigned long long marker_key = 0, marker_mesh = 0, marker_pixel = 0; + int consumed = 0; + if (std::sscanf(ready.c_str(), "x2w-mesh86 %u %llx %llx %llx%n", &version, &marker_key, &marker_mesh, + &marker_pixel, &consumed) != 4 || version != 6 || marker_key != key || + marker_mesh != fnv_bytes(mesh.pShaderBytecode, mesh.BytecodeLength) || marker_pixel || + consumed <= 0 || static_cast(consumed) >= ready.size() || ready[consumed] != '\n') { + std::snprintf(why, why_size, "slot86 mesh request %016llx: cache key, stage or bytecode mismatch", key); + return nullptr; + } +#ifdef X2W_NATIVE_SHADERS + if (!parse_published_mesh86_plan(ready, static_cast(consumed) + 1, *params, published_plan, + published_root, why, why_size)) + return nullptr; +#else + std::snprintf(why, why_size, "slot86 mesh request %016llx: profile 6 needs the native shader compiler", key); + return nullptr; +#endif + } else { + constants_only = !heap_flags && ready.compare(0, constants_marker.size(), constants_marker) == 0; + texture_map = heap_flags && ready.rfind("x2w-mesh86 5 ", 0) == 0; // A wide heap root has sampler indexing or parameters other than constants; it needs a constants-only marker. bool wide_heap_root = (heap_flags & D3D12_ROOT_SIGNATURE_FLAG_SAMPLER_HEAP_DIRECTLY_INDEXED) != 0; for (UINT i = 0; i < params->size(); ++i) { @@ -327,24 +473,8 @@ ID3D12PipelineState* try_cached_mesh86(const D3D12_PIPELINE_STATE_STREAM_DESC& d std::snprintf(why, why_size, "slot86 mesh request %016llx: root bindings outside supported profile", key); return nullptr; } - x2w_startup::ComPtr ms, ps; - const auto load_stage = [&](const wchar_t* ext, x2w_startup::ComPtr& stage) { - WIN32_FILE_ATTRIBUTE_DATA info{}; - return cache_path(path, L"", key, ext) && GetFileAttributesExW(path, GetFileExInfoStandard, &info) && - !info.nFileSizeHigh && info.nFileSizeLow <= 1u << 20 && - SUCCEEDED(D3DReadFileToBlob(path, stage.GetAddressOf())); - }; - if (!load_stage(L".ms.cso", ms) || (!request.ps.empty() && !load_stage(L".ps.cso", ps))) { - std::snprintf(why, why_size, "slot86 mesh request %016llx: incomplete bytecode", key); - return nullptr; - } - const D3D12_SHADER_BYTECODE mesh{ms->GetBufferPointer(), ms->GetBufferSize()}; - const D3D12_SHADER_BYTECODE pixel = ps ? D3D12_SHADER_BYTECODE{ps->GetBufferPointer(), ps->GetBufferSize()} : - D3D12_SHADER_BYTECODE{}; // Profile 3 names the resource-heap slots [first, first + count) the desktop stages may index and the one type // (f32, u32 or i32) they read every slot as. A wide root needs a completed binding proof. - UINT heap_first = 0, heap_count = 0; - char heap_type[4] = ""; constexpr std::string_view proof_suffix = " constants-only\n"; const bool proven = ready.size() >= proof_suffix.size() && ready.compare(ready.size() - proof_suffix.size(), proof_suffix.size(), proof_suffix) == 0; @@ -372,12 +502,12 @@ ID3D12PipelineState* try_cached_mesh86(const D3D12_PIPELINE_STATE_STREAM_DESC& d texture_map ? 5u : heap_flags ? 3u : constants_only ? 4u : srv_root == UINT_MAX ? 1u : 2u, key, fnv_bytes(mesh.pShaderBytecode, mesh.BytecodeLength), ps ? fnv_bytes(pixel.pShaderBytecode, pixel.BytecodeLength) : 0, suffix); - if (ready != expected || desktop_dxil_mesh_stage(mesh) != DxilMeshStage::mesh || - (ps && desktop_dxil_mesh_stage(pixel) != DxilMeshStage::pixel)) { + if (ready != expected) { std::snprintf(why, why_size, "slot86 mesh request %016llx: cache key, stage or bytecode mismatch", key); return nullptr; } - if (!ps && !mesh86_hardware_depth()) { + } + if (!ps && !psless_srv && !mesh86_hardware_depth()) { std::snprintf(why, why_size, "slot86 mesh request %016llx: depth-only requires a physical adapter", key); return nullptr; } @@ -390,8 +520,6 @@ ID3D12PipelineState* try_cached_mesh86(const D3D12_PIPELINE_STATE_STREAM_DESC& d bool compute = false; ID3D12RootSignature* pipeline_root = nullptr; auto* original_root = static_cast(request.root->own().real); - x2w_startup::ComPtr mapped_root; - UINT map_parameter = UINT_MAX; if (texture_map) { x2w_startup::ComPtr device; if (FAILED(original_root->GetDevice(IID_PPV_ARGS(&device))) || @@ -400,16 +528,25 @@ ID3D12PipelineState* try_cached_mesh86(const D3D12_PIPELINE_STATE_STREAM_DESC& d return nullptr; } } + ID3D12RootSignature* desktop_root = original_root; + if (texture_map) desktop_root = mapped_root.Get(); +#ifdef X2W_NATIVE_SHADERS + if (psless_srv) desktop_root = published_root.Get(); +#endif auto* result = build_stream_pipeline(&desktop, why, why_size, compute, graphics, pipeline_root, - texture_map ? mapped_root.Get() : original_root); + desktop_root); if (result) { graphics.cached_srv_root = srv_root; graphics.cached_heap_first = heap_first; graphics.cached_heap_count = heap_count; graphics.cached_heap_class = heap_type[0]; - graphics.texture_map_root = std::move(mapped_root); - graphics.texture_map_guest_root = texture_map ? original_root : nullptr; - graphics.texture_map_parameter = map_parameter; + graphics.texture_map_root = psless_srv ? std::move(published_root) : std::move(mapped_root); + graphics.texture_map_guest_root = (texture_map || psless_srv) ? original_root : nullptr; + graphics.texture_map_parameter = psless_srv ? UINT_MAX : map_parameter; + graphics.synthetic_root = psless_srv; +#ifdef X2W_NATIVE_SHADERS + graphics.native_mesh86 = published_plan; +#endif } static LONG loaded; if (result && first_calls(loaded, 24)) diff --git a/tests/cmake/startup_mesh86_psless.cmake b/tests/cmake/startup_mesh86_psless.cmake new file mode 100644 index 0000000000..8e46af87fb --- /dev/null +++ b/tests/cmake/startup_mesh86_psless.cmake @@ -0,0 +1,12 @@ +# A mesh-only slot 86 fixture whose root is one mesh-visible root SRV. The +# translator publishes profile 6 from the mesh stage alone; the second run +# creates the desktop PSO, reads the SRV word and writes depth 0.5. A missing +# proof, an unproven SRV and a pixel-stage profile are negative controls. +if(EXISTS "${INTAKE_PYTHON}" AND TARGET startup_indirect_draw_indexed AND EXISTS "${DXC_EXECUTABLE}") + foreach(backend IN ITEMS warp hardware) + add_test(NAME startup_mesh86_psless_${backend} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_mesh86_psless_check.py" + "${DXC_EXECUTABLE}" "$" ${backend}) + set_tests_properties(startup_mesh86_psless_${backend} PROPERTIES TIMEOUT 180 SKIP_RETURN_CODE 77) + endforeach() +endif() diff --git a/tests/startup_indirect_draw_indexed.cpp b/tests/startup_indirect_draw_indexed.cpp index b5aab05996..7f3b0f48cf 100644 --- a/tests/startup_indirect_draw_indexed.cpp +++ b/tests/startup_indirect_draw_indexed.cpp @@ -1008,7 +1008,7 @@ bool run(ID3D12Device* device, ID3D12Device* guest, ID3D12RootSignature* writer_ UINT cached_mesh_targets = 0, bool cached_depth_only = false, bool restore_compute = false, const MeshLeaseDraw* leased = nullptr, Gate* gate = nullptr, bool cached_depth_pixel = false, int fixed_mesh_pixels = 0, const x2w_startup::Mesh57Profile* fixed_profile = nullptr, - const Mesh86HeapDraw* heap86 = nullptr) + const Mesh86HeapDraw* heap86 = nullptr, bool cached_root_srv = false) { std::unique_lock recording; if (gate) recording = std::unique_lock(gate->state); @@ -1242,9 +1242,19 @@ bool run(ID3D12Device* device, ID3D12Device* guest, ID3D12RootSignature* writer_ if (heap86 && !bind_mesh86_heap_views(device, guest, wrapped, heap86->variant, heap86_buffer, heap86_heap)) return false; slot(wrapped, 25)(wrapped, graphics); slot(wrapped, 34)(wrapped, refusal == Refusal::wrong_root ? translated->wrong_root.Get() : graphics_root); + void* root_srv_address = nullptr; + if (cached_root_srv) { + using Allocate = void* (WINAPI*)(IUnknown*, UINT64, UINT64); + root_srv_address = slot(wrapped, 148)(wrapped, 16, 16); + if (!root_srv_address) return false; + *static_cast(root_srv_address) = 0x12345678u; + } if (leased) { using RootSrv = void (WINAPI*)(IUnknown*, UINT, UINT64); slot(wrapped, 44)(wrapped, 0, leased->address); + } else if (cached_root_srv) { + using RootSrv = void (WINAPI*)(IUnknown*, UINT, UINT64); + slot(wrapped, 44)(wrapped, 0, reinterpret_cast(root_srv_address)); } else if (fixed_profile && (!std::memcmp(fixed_profile->magic, "X2WM573", 8) || !std::memcmp(fixed_profile->magic, "X2WM574", 8) || !std::memcmp(fixed_profile->magic, "X2WM575", 8) || !std::memcmp(fixed_profile->magic, "X2WM576", 8))) { // Guest root4 is b5/space2. DXIL expects the first word of host b0/space0. @@ -1501,18 +1511,22 @@ bool run(ID3D12Device* device, ID3D12Device* guest, ID3D12RootSignature* writer_ check(pixel_readback->Map(0, &pixel_range, &memory), "map pixel readback"); UINT painted = 0; bool pixels_match = true; + std::uint32_t first_depth = 0xffffu; for (UINT y = 0; y < height; ++y) for (UINT x = 0; x < width; ++x) { std::uint32_t actual = 0; const auto pixel_bytes = cached_depth_only ? 2u : sizeof(actual); std::memcpy(&actual, static_cast(memory) + y * footprint.Footprint.RowPitch + x * pixel_bytes, pixel_bytes); + if (cached_root_srv && !x && !y) first_depth = actual; const bool right_half = x >= width / 2; const bool covered = (cached_depth_only && !cached_depth_pixel) || (indexed ? right_half == draw_right : translated || !right_half || draw_right); const bool drawn = writer && refusal == Refusal::none && covered; // overflowing_count draws nothing const std::uint32_t background = cached_depth_only ? 0xffff : desc.Format == DXGI_FORMAT_R16G16_FLOAT ? 0 : black; - const auto depth_word = cached_depth_pixel ? 0x4000u : 0u; // D16_UNORM encodes SV_Depth 0.25. + // D16_UNORM encodes the source-built PS-less SRV fixture's 0.5 as 0x8000; the + // depth-only pixel fixture writes 0.25, and the constants-only mesh writes 0. + const auto depth_word = cached_root_srv ? 0x8000u : cached_depth_pixel ? 0x4000u : 0u; auto wanted = drawn ? (cached_depth_only ? depth_word : translated ? (draw_right ? green : red) : (right_half ? green : red)) : background; if (fixed_mesh_pixels) { @@ -1560,6 +1574,7 @@ bool run(ID3D12Device* device, ID3D12Device* guest, ID3D12RootSignature* writer_ pixel_readback->Unmap(0, &untouched); std::printf("%s: %u/%u non-clear pixels%s\n", label, painted, width * height, external_arguments ? "" : ", argument guards intact"); + if (cached_root_srv) std::printf("mesh86 SRV depth 0x%04x\n", first_depth); if (!pixels_match) { if (kind == DrawKind::rect) report_rect_conversion(device, observed, indexed_argument_offset / sizeof(std::uint32_t)); return false; @@ -3487,9 +3502,12 @@ int main(int argc, char** argv) try 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; + // The PS-less SRV fixture has no pixel stage and proves its root SRV from the mesh stage. + const bool psless_srv = GetEnvironmentVariableA("X2W_MESH86_FIXTURE_PSLESS_SRV", nullptr, 0) != 0; + const bool no_pixel = depth_only || psless_srv; char depth_mode[16]{}; const bool depth_pixel = GetEnvironmentVariableA("X2W_MESH86_FIXTURE_DEPTH_PIXEL", depth_mode, sizeof(depth_mode)) != 0; - auto depth = depth_only ? StreamDepth::writable : StreamDepth::none; + auto depth = no_pixel ? StreamDepth::writable : StreamDepth::none; if (std::strcmp(depth_mode, "no-dsv") == 0) depth = StreamDepth::none; if (std::strcmp(depth_mode, "read-only") == 0) depth = StreamDepth::read_only; const auto input = std::filesystem::path(mesh86_dir); @@ -3499,11 +3517,12 @@ int main(int argc, char** argv) try return std::vector(std::istreambuf_iterator(file), {}); }; const auto ms = read_stage("source.ms.dxbc"); - const auto ps = depth_only && !depth_pixel ? std::vector{} : read_stage("source.ps.dxbc"); + const auto ps = no_pixel && !depth_pixel ? std::vector{} : read_stage("source.ps.dxbc"); D3D12_ROOT_PARAMETER parameter{}; - parameter.ParameterType = lease_fixture ? D3D12_ROOT_PARAMETER_TYPE_SRV : D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS; - parameter.ShaderVisibility = lease_fixture ? D3D12_SHADER_VISIBILITY_MESH : D3D12_SHADER_VISIBILITY_ALL; - if (!lease_fixture) parameter.Constants = {0, 0, 2}; + parameter.ParameterType = (lease_fixture || psless_srv) ? D3D12_ROOT_PARAMETER_TYPE_SRV : + D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS; + parameter.ShaderVisibility = (lease_fixture || psless_srv) ? D3D12_SHADER_VISIBILITY_MESH : D3D12_SHADER_VISIBILITY_ALL; + if (!lease_fixture && !psless_srv) parameter.Constants = {0, 0, 2}; const bool heap_window = !lease_fixture && GetEnvironmentVariableA("X2W_MESH86_FIXTURE_HEAP", nullptr, 0) != 0; const bool texture_map = heap_window && GetEnvironmentVariableA("X2W_MESH86_FIXTURE_TEXTURE_MAP", nullptr, 0) != 0; // Extend the root with an SRV table and a root SRV that the published stages never reference. @@ -3532,7 +3551,7 @@ int main(int argc, char** argv) try const auto pso = lease_fixture ? guest_pipeline(guest.Get(), root.Get(), ms_code, ps_code, {}, 1, depth) : guest_pipeline(guest.Get(), root.Get(), ms_code, ps_code, {}, - depth_only ? 0 : 3, depth); + no_pixel ? 0 : 3, depth); if (GetEnvironmentVariableA("X2W_MESH86_FIXTURE_CREATE_ONLY", nullptr, 0)) { // The translation bridge test runs this fixture once before and once after its request is published. const bool native = bool(native_object(device.Get(), guest.Get(), pso.Get(), true)); @@ -3670,7 +3689,8 @@ int main(int argc, char** argv) try const auto verify = [&](Refusal control, const char* label) { return run(device.Get(), guest.Get(), writer.Get(), work.Get(), root.Get(), pso.Get(), signature.Get(), DrawKind::mesh, false, control, label, nullptr, false, nullptr, false, false, - depth_only ? 0 : 3, depth_only, false, nullptr, nullptr, depth_pixel); + no_pixel ? 0 : 3, no_pixel, false, nullptr, nullptr, depth_pixel, 0, nullptr, nullptr, + psless_srv); }; const bool ready = GetEnvironmentVariableA("X2W_MESH86_FIXTURE_READY", nullptr, 0) != 0; if (heap_window) { @@ -3708,7 +3728,8 @@ int main(int argc, char** argv) try return 1; } } - const bool ok = !ready || invalid_depth_pixel + const bool ok = psless_srv ? verify(Refusal::none, "PS-less root SRV") : + !ready || invalid_depth_pixel ? verify(Refusal::mesh_pending, invalid_depth_pixel ? depth_mode : "unavailable cached mesh") : verify(Refusal::none, depth_pixel ? "cached mesh depth-only pixel stage" : depth_only ? "cached mesh depth-only" : "cached translated mesh with three attachments") && diff --git a/tests/startup_indirect_mesh_psless_srv.hlsl b/tests/startup_indirect_mesh_psless_srv.hlsl new file mode 100644 index 0000000000..65e6c902e9 --- /dev/null +++ b/tests/startup_indirect_mesh_psless_srv.hlsl @@ -0,0 +1,20 @@ +// PS-less slot 86 source: the mesh stage reads one DWORD from its root SRV. +// A matching word writes depth 0.5; any other value (including an unbound or +// mistranslated SRV) leaves depth at the 1.0 clear. +ByteAddressBuffer source : register(t0); + +struct Vertex { + float4 position : SV_Position; +}; + +[outputtopology("triangle")] +[numthreads(1, 1, 1)] +void mesh(out vertices Vertex verts[3], out indices uint3 triangles[1]) { + const uint word = source.Load(0); + const float z = word == 0x12345678u ? 0.5 : 1.0; + SetMeshOutputCounts(3, 1); + verts[0].position = float4(-1, -1, z, 1); + verts[1].position = float4(-1, 3, z, 1); + verts[2].position = float4(3, -1, z, 1); + triangles[0] = uint3(0, 1, 2); +} diff --git a/tests/startup_mesh86_psless_check.py b/tests/startup_mesh86_psless_check.py new file mode 100644 index 0000000000..c1a81f7588 --- /dev/null +++ b/tests/startup_mesh86_psless_check.py @@ -0,0 +1,127 @@ +"""A PS-less slot 86 request publishes and binds a proved root SRV. + +The fixture creates a mesh-only pipeline whose root is one mesh-visible root +SRV. The translation bridge publishes profile 6 from the mesh stage alone; +the second run must create the desktop PSO and read the SRV word to write depth +0.5. A missing or unproved SRV keeps the marker absent. +""" + +import os +from pathlib import Path +import subprocess +import sys +import tempfile +import time + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE.parent / 'tools' / 'startup')) + +import mesh86_cache +from startup_indirect_mesh_cache_check import source_envelope + + +def run_fixture(fixture, backend, work, ready): + environment = dict(os.environ, X2W_MESH86_FIXTURE_DIR=str(work), X2W_SHADER_CACHE=str(work), + X2W_MESH86_FIXTURE_DEPTH='1', X2W_MESH86_FIXTURE_PSLESS_SRV='1') + for name in ('X2W_MESH86_FIXTURE_READY', 'X2W_NATIVE_MESH86', 'X2W_NATIVE_SHADERS', + 'X2W_NATIVE_SHADERS_ONLY', 'X2W_MESH86_FIXTURE_DEPTH_PIXEL'): + environment.pop(name, None) + if ready: + environment['X2W_MESH86_FIXTURE_READY'] = '1' + else: + environment['X2W_MESH86_FIXTURE_CREATE_ONLY'] = '1' + result = subprocess.run([str(fixture), backend, 'mesh'], env=environment, capture_output=True, + text=True, errors='replace', timeout=120) + return result.returncode, result.stdout + result.stderr + + +def wait_for_marker(work): + deadline = time.monotonic() + 10 + while time.monotonic() < deadline: + markers = list(work.glob('req_*.m86')) + if markers: + return markers + time.sleep(0.05) + return [] + + +def main(): + if len(sys.argv) != 4: + sys.exit('usage: startup_mesh86_psless_check.py DXC FIXTURE warp|hardware') + dxc, fixture, backend = Path(sys.argv[1]), Path(sys.argv[2]), sys.argv[3] + if not dxc.is_file() or not fixture.is_file(): + sys.exit('DXC or fixture is missing') + with tempfile.TemporaryDirectory(prefix='mesh86-psless-', dir=Path.cwd()) as directory: + work = Path(directory) + (work / 'source.ms.dxbc').write_bytes(source_envelope(13)) + (work / 'source.ps.dxbc').write_bytes(source_envelope(0)) + code, output = run_fixture(fixture, backend, work, False) + if code == 77: + return 77 + if code: + sys.exit(output) + markers = wait_for_marker(work) + if len(markers) != 1: + sys.exit(f'expected one pending slot 86 request, found {[path.name for path in markers]}') + key = int(markers[0].stem[4:], 16) + if f'slot86 mesh request {key:016x} pending' not in output: + sys.exit(f'the first run did not report request {key:016x} pending:\n{output}') + + mesh = work / 'desktop.ms.cso' + subprocess.run([str(dxc), '-T', 'ms_6_5', '-E', 'mesh', '-Fo', str(mesh), + str(HERE / 'startup_indirect_mesh_psless_srv.hlsl')], check=True, capture_output=True) + plan = {'constants': [], 'views': [{'shader_register': 0, 'root_parameter': 0, 'byte_offset': 0, + 'required_bytes': 4, 'kind': 0, 'image_dimension': 1}]} + + # The proof is required: constants-only and a partial SRV plan both stay unpublished. + try: + mesh86_cache.publish(work, key, mesh, None, constants_dxc=dxc) + except ValueError as error: + assert 'outside the root constants' in str(error), error + else: + sys.exit('a PS-less mesh SRV published through the constants-only proof') + for bad in ({'constants': [], 'views': []}, + {'constants': [], 'views': [dict(plan['views'][0], root_parameter=1)]}, + {'constants': [], 'views': [dict(plan['views'][0], byte_offset=1)]}): + try: + mesh86_cache.publish(work, key, mesh, None, mesh_srv_dxc=dxc, mesh_srv_plan=bad) + except (ValueError, IndexError): + pass + else: + sys.exit(f'a bad PS-less SRV plan was published: {bad}') + if (work / f'{key:016x}.mesh86.txt').exists(): + sys.exit('a refused PS-less SRV plan left a marker') + + # A pixel stage stays on the existing profiles. + pixel = work / 'desktop.ps.cso' + subprocess.run([str(dxc), '-T', 'ps_6_0', '-E', 'pixel', '-Fo', str(pixel), + str(HERE / 'xmem_mesh_root_srv.hlsl')], check=True, capture_output=True) + try: + mesh86_cache.publish(work, key, mesh, pixel, mesh_srv_dxc=dxc, mesh_srv_plan=plan) + except ValueError as error: + assert 'has no pixel stage' in str(error), error + else: + sys.exit('the PS-less profile accepted a pixel stage') + + mesh86_cache.publish(work, key, mesh, None, mesh_srv_dxc=dxc, mesh_srv_plan=plan) + ready = work / f'{key:016x}.mesh86.txt' + marker = ready.read_text(encoding='ascii') + if not marker.startswith('x2w-mesh86 6 ') or 'srv 0 0 0 4 0 1' not in marker: + sys.exit(f'unexpected PS-less marker: {marker!r}') + print(f'{key:016x}: PS-less request published {marker.strip()}') + + code, output = run_fixture(fixture, backend, work, True) + if code == 77: + return 77 + if code: + sys.exit(output) + if f'x2w-render slot86 mesh {key:016x}: cached pipeline loaded' not in output: + sys.exit(f'the second run did not load the PS-less profile:\n{output}') + if 'mesh86 SRV depth 0x8000' not in output: + sys.exit('the PS-less mesh did not read its root SRV into depth 0.5') + print(f'{key:016x}: desktop PSO created and root SRV word wrote depth 0.5') + return 0 + + +if __name__ == '__main__': + raise SystemExit(main()) diff --git a/tools/startup/mesh86_cache.py b/tools/startup/mesh86_cache.py index b1f7dfec8e..a99db06f97 100644 --- a/tools/startup/mesh86_cache.py +++ b/tools/startup/mesh86_cache.py @@ -195,6 +195,205 @@ def root_constant_layout(root): raise ValueError('root signature has no RTS0 part') +# The nine D3D12 root parameter types. The serialized RTS0 body uses version-2 +# offsets: a descriptor table payload holds (range count, range table offset) +# and each D3D12_DESCRIPTOR_RANGE1 is six DWORDs. +ROOT_DESCRIPTOR_TABLE, ROOT_CONSTANTS, ROOT_CBV, ROOT_SRV, ROOT_UAV = 0, 1, 2, 3, 4 + + +def root_parameters(root): + """Flags and every root parameter, with descriptor-table ranges resolved.""" + if len(root) < 32 or root[:4] != b'DXBC': + raise ValueError('expected a DXBC root signature') + parts = struct.unpack_from(' (len(root) - 32) // 4: + raise ValueError('invalid root signature part table') + for index in range(parts): + offset = struct.unpack_from(' len(root) - 8 or root[offset:offset + 4] != b'RTS0': + continue + size = struct.unpack_from(' len(body) or count > (len(body) - params) // 12: + raise ValueError('invalid root parameter table') + result = [] + for parameter in range(count): + kind, visibility, payload = struct.unpack_from('<3I', body, params + 12 * parameter) + entry = {'type': kind, 'visibility': visibility, 'register': 0, 'space': 0, 'count': 0, 'ranges': []} + if kind == ROOT_DESCRIPTOR_TABLE: + if payload > len(body) - 8: + raise ValueError('invalid descriptor table parameter') + ranges, ranges_offset = struct.unpack_from('<2I', body, payload) + stride = 24 if version == 2 else 20 + if ranges > 4096 or ranges_offset > len(body) or ranges > (len(body) - ranges_offset) // stride: + raise ValueError('invalid descriptor range table') + for index in range(ranges): + if version == 2: + range_type, descriptors, register, space, range_flags, start = struct.unpack_from( + '<6I', body, ranges_offset + 24 * index) + else: + range_type, descriptors, register, space, start = struct.unpack_from( + '<5I', body, ranges_offset + 20 * index) + range_flags = 0 + entry['ranges'].append({'type': range_type, 'count': descriptors, 'register': register, + 'space': space, 'flags': range_flags, 'start': start}) + elif kind == ROOT_CONSTANTS: + if payload > len(body) - 12: + raise ValueError('invalid root constants parameter') + entry['register'], entry['space'], entry['count'] = struct.unpack_from('<3I', body, payload) + elif kind in (ROOT_CBV, ROOT_SRV, ROOT_UAV): + if payload > len(body) - (12 if version == 2 else 8): + raise ValueError('invalid root descriptor parameter') + if version == 2: + entry['register'], entry['space'], _ = struct.unpack_from('<3I', body, payload) + else: + entry['register'], entry['space'] = struct.unpack_from('<2I', body, payload) + else: + raise ValueError(f'unsupported root parameter type {kind}') + result.append(entry) + return flags, result + raise ValueError('root signature has no RTS0 part') + + +MESH_SRV_TABLE_LIMIT = 1 << 20 # 32 KiB of 32-byte records, the runtime's bound. + + +def _table_span(table, byte_offset): + """The descriptor index and SRV range covering a table byte offset. + + Slot 86 titles also read records past the declared range ends: a root + descriptor table is a pointer into a descriptor heap, and the guest shader + can address a neighbouring record. Such a record has no declared SRV + range, so the range is None and the runtime must resolve it to a valid + view before the draw is allowed.""" + if byte_offset % 32: + raise ValueError('a mesh SRV table record must start on a 32-byte boundary') + descriptor = byte_offset // 32 + if descriptor >= MESH_SRV_TABLE_LIMIT: + raise ValueError('a mesh SRV table record is outside the runtime bound') + if not any(entry['type'] == 0 for entry in table['ranges']): + raise ValueError('a mesh SRV table parameter declares no SRV range') + position = 0 + for entry in table['ranges']: + start = entry['start'] if entry['start'] != 0xffffffff else position + if start + entry['count'] > descriptor and start <= descriptor: + if entry['type'] != 0: + raise ValueError('a mesh SRV table record is not in an SRV range') + return descriptor, entry + position = start + entry['count'] + return descriptor, None + + +_RESOURCE_BINDINGS = re.compile( + r'^; Resource Bindings:\n;\n; Name[^\n]*\n; [- ]+\n((?:; [^\n]+\n)*)', re.MULTILINE) +_HANDLE_BINDING = re.compile( + r'call %dx\.types\.Handle @dx\.op\.createHandleFromBinding\(i32 217,\s*' + r'%dx\.types\.ResBind\s*(?:\{\s*i32 (\d+),\s*i32 (\d+),\s*i32 (\d+),\s*i8 (\d+)\s*\}|zeroinitializer),' + r'\s*i32 (\d+),\s*i1 false\)', re.DOTALL) +_LEGACY_SRV_HANDLE = re.compile( + r'call %dx\.types\.Handle @dx\.op\.createHandle\(i32 57, i8 0, i32 (\d+), i32 0, i1 false\)') + + +def _binding_rows(dump): + table = _RESOURCE_BINDINGS.search(dump) + if not table: + raise ValueError('expected a DXIL resource bindings table') + rows = [] + for line in table[1].splitlines(): + fields = line[1:].split() + if not fields: + continue + if len(fields) < 6: + raise ValueError('truncated DXIL resource binding row') + rows.append(fields[-6:]) # Type, Format, Dim, ID, HLSL Bind, Count; the name is optional. + return rows + + +def prove_mesh_srv_table(mesh_dump, views): + """Prove a PS-less mesh stage whose buffer SRVs are root descriptors or + descriptor-table records. ``plan`` maps each desktop tN to the guest root + parameter and table byte offset that the translator read it from.""" + if any('createHandleFromHeap' in line.partition(';')[0] for line in _function_lines(mesh_dump)): + raise ValueError('the PS-less mesh SRV table profile excludes direct heap reads') + rows = _binding_rows(mesh_dump) + srvs = [row for row in rows if row[4].startswith('t')] + others = [row for row in rows if not row[4].startswith('t')] + if others not in ([], [['cbuffer', 'NA', 'NA', 'CB0', 'cb0', '1']]): + raise ValueError('the PS-less mesh SRV table profile binds only buffer SRVs') + if not srvs: + raise ValueError('the PS-less mesh SRV table profile requires at least one SRV') + for index, row in enumerate(srvs): + if row[:3] != ['texture', 'byte', 'r/o'] or row[4] != f't{index}' or row[5] != '1': + raise ValueError('the PS-less mesh SRV table profile requires t0..tN-1 byte SRVs') + if len(views) != len(srvs): + raise ValueError('the mesh SRV plan does not cover every desktop SRV') + seen = set() + binds = {} + legacy = [int(match[1]) for match in _LEGACY_SRV_HANDLE.finditer(mesh_dump)] + for match in _HANDLE_BINDING.finditer(mesh_dump): + groups = match.groups() + lower, upper, space, flags, index = (int(value) if value is not None else 0 for value in groups) + if flags == 2 and lower == 0 and upper == 0 and index == 0: + continue # cb0's CBuffer handle + if lower != upper or space != 0 or flags != 0 or index != lower: + raise ValueError('a desktop SRV handle does not name one tN in space0') + binds.setdefault(lower, 0) + binds[lower] += 1 + if legacy: + # A version-1 root signature lowers one root SRV to the legacy + # createHandle(rangeId=0) form. Only a single root SRV is accepted + # through this form; every table binding uses createHandleFromBinding. + if len(srvs) != 1 or legacy != [0] or binds: + raise ValueError('the legacy desktop SRV handle does not match the resource bindings') + elif set(binds) != set(range(len(srvs))): + raise ValueError('the desktop SRV handles do not match the resource bindings') + for index, entry in enumerate(views): + if entry['shader_register'] != index: + raise ValueError('the mesh SRV plan registers must be t0..tN-1') + if entry['kind'] not in (0, 4, 10, 18, 26): + raise ValueError(f"unsupported PS-less mesh SRV kind {entry['kind']}") + if not 1 <= entry['required_bytes'] <= 1 << 20: + raise ValueError('a mesh SRV extent is outside the runtime bound') + seen.add(entry['root_parameter']) + return srvs + + +def mesh_srv_plan_text(views): + """The canonical plan lines stored below a profile-6 marker.""" + lines = [] + for entry in views: + lines.append(f"srv {entry['shader_register']} {entry['root_parameter']} {entry['byte_offset']} " + f"{entry['required_bytes']} {entry['kind']} {entry['image_dimension']}") + return lines + + +def parse_mesh_srv_plan(path): + """Read the constant and srv lines accepted by the profile-6 publisher.""" + constants, views = [], [] + for number, line in enumerate(Path(path).read_text(encoding='ascii').splitlines(), 1): + fields = line.split() + if not fields or fields[0].startswith('#'): + continue + if fields[0] == 'constant' and len(fields) == 3: + constants.append({'root_parameter': int(fields[1]), 'count': int(fields[2])}) + elif fields[0] == 'srv' and len(fields) == 7: + views.append({'shader_register': int(fields[1]), 'root_parameter': int(fields[2]), + 'byte_offset': int(fields[3]), 'required_bytes': int(fields[4]), + 'kind': int(fields[5]), 'image_dimension': int(fields[6])}) + else: + raise ValueError(f'unsupported mesh SRV plan line {number}: {line}') + return {'constants': constants, 'views': views} + + +def mesh_srv_plan_lines(plan): + lines = [f"constant {entry['root_parameter']} {entry['count']}" for entry in plan['constants']] + lines.extend(mesh_srv_plan_text(plan['views'])) + return lines + + _BINDING_ROW = re.compile(r';\s*(\S+)\s+(\S+)\s+\S+\s+\S+\s+\S+\s+(\S+)\s+(\d+)\s*') _CBUFFER_BIND = re.compile(r'cb(\d+)(?:,space(\d+))?') @@ -346,9 +545,11 @@ def aligned(index, depth=0): raise ValueError('the profile requires a mapped Texture1D load') -def publish(cache, key, ms_path, ps_path, *, srv_dxc=None, heap_window=None, heap_dxc=None, constants_dxc=None, - texture_map_dxc=None): +def publish(cache, key, ms_path, ps_path, *, srv_dxc=None, mesh_srv_dxc=None, mesh_srv_plan=None, + heap_window=None, heap_dxc=None, constants_dxc=None, texture_map_dxc=None): _, ps_source, root, _ = load_request(cache, key) + if mesh_srv_dxc and ps_path: + raise ValueError('the PS-less mesh SRV table profile has no pixel stage') if bool(ps_source) != bool(ps_path): raise ValueError('desktop pixel-stage presence must match the input stream') ms = ms_path.read_bytes() @@ -362,18 +563,20 @@ def publish(cache, key, ms_path, ps_path, *, srv_dxc=None, heap_window=None, hea ready = stem.with_suffix('.mesh86.txt') hashes = f'{key:016x} {fnv(ms):016x} {(fnv(ps) if ps else 0):016x}' manifest = f'x2w-mesh86 1 {hashes}\n' - if sum(bool(dxc) for dxc in (srv_dxc, heap_dxc, constants_dxc, texture_map_dxc)) > 1: + if sum(bool(dxc) for dxc in (srv_dxc, mesh_srv_dxc, heap_dxc, constants_dxc, texture_map_dxc)) > 1: raise ValueError('select one DXC proof profile') if (heap_window is None) != (heap_dxc is None): raise ValueError('the heap-buffer profile requires DXC and a slot window') if (srv_dxc or texture_map_dxc) and not ps: raise ValueError('the mesh SRV profile requires a pixel stage') + if bool(mesh_srv_dxc) != bool(mesh_srv_plan): + raise ValueError('the PS-less mesh SRV table profile requires DXC and a binding plan') with tempfile.TemporaryDirectory(prefix='.mesh86-', dir=cache) as temp: work = Path(temp) (work / 'ms').write_bytes(ms) if ps: (work / 'ps').write_bytes(ps) - dxc = srv_dxc or heap_dxc or constants_dxc or texture_map_dxc + dxc = srv_dxc or mesh_srv_dxc or heap_dxc or constants_dxc or texture_map_dxc if dxc: # Dump the same bytes that will be published, even if the source paths change. stages = ('ms', 'ps') if ps else ('ms',) @@ -383,6 +586,29 @@ def publish(cache, key, ms_path, ps_path, *, srv_dxc=None, heap_window=None, hea if srv_dxc: extent = prove_mesh_root_srv(*dumps) manifest = f'x2w-mesh86 2 {hashes} srv 0 0 {extent}\n' + elif mesh_srv_dxc: + flags, parameters = root_parameters(root) + for entry in mesh_srv_plan['constants']: + if entry['root_parameter'] >= len(parameters): + raise ValueError('the mesh SRV plan names a missing root parameter') + parameter = parameters[entry['root_parameter']] + if parameter['type'] != ROOT_CONSTANTS or parameter['count'] != entry['count']: + raise ValueError('a mesh SRV plan constant block disagrees with the root signature') + for entry in mesh_srv_plan['views']: + if entry['root_parameter'] >= len(parameters): + raise ValueError('the mesh SRV plan names a missing root parameter') + parameter = parameters[entry['root_parameter']] + if parameter['type'] == ROOT_DESCRIPTOR_TABLE: + _table_span(parameter, entry['byte_offset']) + elif parameter['type'] == ROOT_SRV: + if entry['byte_offset']: + raise ValueError('a root SRV plan entry has a table offset') + else: + raise ValueError('the mesh SRV plan names a non-SRV root parameter') + prove_mesh_srv_table(dumps[0], mesh_srv_plan['views']) + lines = [f'x2w-mesh86 6 {hashes}'] + lines.extend(mesh_srv_plan_lines(mesh_srv_plan)) + manifest = '\n'.join(lines) + '\n' elif heap_dxc: first, count, read_type = prove_heap_buffer_window(dumps, *heap_window) _, constants = root_constant_layout(root) @@ -424,6 +650,10 @@ def main(argv=None) -> int: parser.add_argument('--pixel', type=Path, help='desktop PS DXIL when the captured input has a pixel stage') parser.add_argument('--prove-root-srv', type=Path, metavar='DXC', help='use DXC to verify the bounded single-DWORD mesh root SRV profile') + parser.add_argument('--prove-mesh-srv-table', type=Path, metavar='DXC', + help='use DXC to verify a PS-less mesh whose buffer SRVs come from the root') + parser.add_argument('--mesh-srv-plan', type=Path, + help='binding plan for --prove-mesh-srv-table') parser.add_argument('--prove-root-constants', type=Path, metavar='DXC', help='use DXC to verify that both stages only use root constants') parser.add_argument('--prove-texture1d-map', type=Path, metavar='DXC', @@ -444,20 +674,29 @@ def main(argv=None) -> int: _require_file(args.pixel, '--pixel') if args.prove_root_srv is not None: _require_file(args.prove_root_srv, '--prove-root-srv') + if args.prove_mesh_srv_table is not None: + _require_file(args.prove_mesh_srv_table, '--prove-mesh-srv-table') + if args.mesh_srv_plan is not None: + _require_file(args.mesh_srv_plan, '--mesh-srv-plan') if args.prove_root_constants is not None: _require_file(args.prove_root_constants, '--prove-root-constants') if args.prove_texture1d_map is not None: _require_file(args.prove_texture1d_map, '--prove-texture1d-map') if (args.heap_buffer is None) != (args.dxc is None): raise ValueError('--heap-buffer and --dxc go together') + if (args.prove_mesh_srv_table is None) != (args.mesh_srv_plan is None): + raise ValueError('--prove-mesh-srv-table and --mesh-srv-plan go together') if args.dxc is not None: _require_file(args.dxc, '--dxc') publish(args.cache, args.key, args.mesh, args.pixel, srv_dxc=args.prove_root_srv, + mesh_srv_dxc=args.prove_mesh_srv_table, + mesh_srv_plan=parse_mesh_srv_plan(args.mesh_srv_plan) if args.mesh_srv_plan else None, heap_window=tuple(args.heap_buffer) if args.heap_buffer else None, heap_dxc=args.dxc, constants_dxc=args.prove_root_constants, texture_map_dxc=args.prove_texture1d_map) print(f'{args.key:016x}: published desktop stages') else: - if args.pixel or args.prove_root_srv or args.prove_root_constants or args.prove_texture1d_map or args.heap_buffer or args.dxc: + if args.pixel or args.prove_root_srv or args.prove_mesh_srv_table or args.mesh_srv_plan or \ + args.prove_root_constants or args.prove_texture1d_map or args.heap_buffer or args.dxc: raise ValueError('desktop stage and proof options require --mesh') ms, ps, root, stream = load_request(args.cache, args.key) print(f'{args.key:016x}: MS {len(ms)}, PS {len(ps)}, root {len(root)}, stream {len(stream)} bytes') diff --git a/tools/startup/mesh86_translate.py b/tools/startup/mesh86_translate.py index 89dcbe7bfa..1eefe7db0b 100644 --- a/tools/startup/mesh86_translate.py +++ b/tools/startup/mesh86_translate.py @@ -20,6 +20,7 @@ import argparse import os from pathlib import Path +import re import shutil import struct import subprocess @@ -77,7 +78,7 @@ def _sdk() -> Path: return _dxc().parent -def _compile(cache: Path, key: int, profile: str, source: Path, destination: Path) -> None: +def _compile(cache: Path, key: int, profile: str, source: Path, destination: Path) -> str: compiler_cache = cache / 'native' compiler_cache.mkdir(parents=True, exist_ok=True) command = [str(_compiler()), str(_sdk()), str(compiler_cache), profile, str(source), str(destination)] @@ -87,6 +88,7 @@ def _compile(cache: Path, key: int, profile: str, source: Path, destination: Pat reason = lines[-1] if lines else 'no diagnostic' stage = 'mesh' if profile != 'gfx1013-mesh86-ps' else 'pixel' raise Unsupported(f'slot 86 {stage} translation refused: {reason}') + return result.stdout def _dump(dxc: Path, stages: list[Path]) -> list[str]: @@ -130,8 +132,44 @@ def _heap_window(dumps: list[str]) -> tuple[int, int]: return first, count -def _publish(cache: Path, key: int, mesh: Path, pixel: Path | None, flags: int) -> str: +def _mesh_plan(report: str) -> dict | None: + """The binding plan reported by compile_dxil for a PS-less mesh stage.""" + constants, views = [], [] + for line in report.splitlines(): + fields = line.split() + if not fields: + continue + if fields[0] == 'requires_root_constants': + values = dict(field.split('=', 1) for field in fields[1:] if '=' in field) + constants.append({'root_parameter': int(values['root']), 'count': int(values['count'])}) + elif fields[0] == 'requires_srv' and len(fields) >= 6: + values = dict(field.split('=', 1) for field in fields[1:] if '=' in field) + views.append({'shader_register': int(fields[1][1:]), + 'root_parameter': int(values['root']), 'byte_offset': int(values['offset']), + 'required_bytes': int(values['size']), 'kind': int(values['kind']), + 'image_dimension': int(values['dim'])}) + elif fields[0] == 'requires_srv_stride': + raise Unsupported('the PS-less mesh SRV table profile does not bind stride SRVs') + if not views: + return None + views.sort(key=lambda entry: entry['shader_register']) + if [entry['shader_register'] for entry in views] != list(range(len(views))): + raise Unsupported('the PS-less mesh SRV table profile needs contiguous t0..tN-1 bindings') + return {'constants': constants, 'views': views} + + +def _publish(cache: Path, key: int, mesh: Path, pixel: Path | None, flags: int, + mesh_report: str | None = None) -> str: dxc = _dxc() + srv_error = None + if pixel is None and mesh_report: + try: + plan = _mesh_plan(mesh_report) + if plan: + mesh86_cache.publish(cache, key, mesh, None, mesh_srv_dxc=dxc, mesh_srv_plan=plan) + return 'PS-less mesh SRV table profile' + except (ValueError, Unsupported) as error: + srv_error = error if flags & RESOURCE_HEAP: stages = [mesh] + ([pixel] if pixel else []) dumps = _dump(dxc, stages) @@ -142,6 +180,9 @@ def _publish(cache: Path, key: int, mesh: Path, pixel: Path | None, flags: int) try: first, count = _heap_window(dumps) except ValueError as window_error: + if srv_error is not None: + raise Unsupported(f'slot 86 heap proof refused: {window_error}; ' + f'mesh SRV table proof: {srv_error}; Texture1D map proof: {map_error}') from None raise Unsupported(f'slot 86 heap proof refused: {window_error}; ' f'Texture1D map proof: {map_error}') from None try: @@ -154,6 +195,9 @@ def _publish(cache: Path, key: int, mesh: Path, pixel: Path | None, flags: int) try: mesh86_cache.publish(cache, key, mesh, pixel, constants_dxc=dxc) except ValueError as error: + if srv_error is not None: + raise Unsupported(f'slot 86 root-constants proof refused: {error}; ' + f'mesh SRV table proof: {srv_error}') from None raise Unsupported(f'slot 86 root-constants proof refused: {error}') from None return 'root-constants profile' @@ -173,12 +217,12 @@ def translate_request(cache: Path, key: int) -> str: with tempfile.TemporaryDirectory(prefix='.mesh86-translate-', dir=cache) as temporary: work = Path(temporary) mesh_path = work / 'ms.cso' - _compile(cache, key, mesh_profile, cache / f'req_{key:016x}.m86', mesh_path) + mesh_report = _compile(cache, key, mesh_profile, cache / f'req_{key:016x}.m86', mesh_path) pixel_path = None if pixel: pixel_path = work / 'ps.cso' _compile(cache, key, 'gfx1013-mesh86-ps', cache / f'req_{key:016x}.ps86', pixel_path) - profile = _publish(cache, key, mesh_path, pixel_path, flags) + profile = _publish(cache, key, mesh_path, pixel_path, flags, mesh_report) return f'published slot 86 mesh {profile}' From 4178dcdfe32a0abd104fe46763e727c175bcfe82 Mon Sep 17 00:00:00 2001 From: Roland Edi Date: Wed, 2 Dec 2026 01:43:01 +0000 Subject: [PATCH 28/32] runtime: bind empty Mesh86 input views as zeros Request 062d66b9e013f28e loads a raw V# from root parameter 1, descriptor record 2 (SRV t20 space1). The record has NUM_RECORDS zero, so every load is out of bounds and reads zero on the hardware. The Mesh86 input resolver now binds a 16-byte zero view for a zero-record descriptor and logs the guest table, record and descriptor once; the ordinary compute input path still refuses zero records. The new source-built fixture publishes a PS-less mesh profile with an 8-byte descriptor-table SRV and writes a raw V#: a nonzero buffer must write depth 0.5, a zero-record null must read zeros, and an unmapped base must keep its named refusal. WARP currently fails startup_mesh86_input_stream_warp with a device removal after DispatchMesh (map argument readback 0x887a0005); the hardware run is still pending. --- CMakePresets.json | 2 +- src/startup_stubs/d3d12_draw.inl | 11 +- src/startup_stubs/native_mesh86.inl | 19 ++- tests/cmake/startup_mesh86_input_stream.cmake | 11 ++ tests/startup_indirect_draw_indexed.cpp | 71 +++++++++-- tests/startup_indirect_mesh_input_stream.hlsl | 21 +++ tests/startup_mesh86_input_stream_check.py | 120 ++++++++++++++++++ 7 files changed, 240 insertions(+), 15 deletions(-) create mode 100644 tests/cmake/startup_mesh86_input_stream.cmake create mode 100644 tests/startup_indirect_mesh_input_stream.hlsl create mode 100644 tests/startup_mesh86_input_stream_check.py diff --git a/CMakePresets.json b/CMakePresets.json index 55ea5556e4..b20f5ff33a 100644 --- a/CMakePresets.json +++ b/CMakePresets.json @@ -52,7 +52,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|startup_mesh57_runtime(_[a-z]+)?_warp|native_fixed_mesh57_published_pair(_refusal)?_warp|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_indirect_mesh_cache_heap(_wide)?_warp|startup_mesh86_present_warp|runtime_mesh86_cache_cli_check|startup_mesh86_translate_warp|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_mesh86_material_backing(_mutant)?_warp|startup_stage_package|startup_compute_packed_d16_x_uav_reference|native_.*_(ir|dxil|controls)|native_direct_mesh|mesh86_typed_vsharp_[a-z_]+|startup_triage_run)$" + "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|startup_mesh57_runtime(_[a-z]+)?_warp|native_fixed_mesh57_published_pair(_refusal)?_warp|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_indirect_mesh_cache_heap(_wide)?_warp|startup_mesh86_input_stream_(warp|hardware)|startup_mesh86_present_warp|runtime_mesh86_cache_cli_check|startup_mesh86_translate_warp|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_mesh86_material_backing(_mutant)?_warp|startup_stage_package|startup_compute_packed_d16_x_uav_reference|native_.*_(ir|dxil|controls)|native_direct_mesh|mesh86_typed_vsharp_[a-z_]+|startup_triage_run)$" } } }, diff --git a/src/startup_stubs/d3d12_draw.inl b/src/startup_stubs/d3d12_draw.inl index d4b19464ff..eb5870af8c 100644 --- a/src/startup_stubs/d3d12_draw.inl +++ b/src/startup_stubs/d3d12_draw.inl @@ -2774,7 +2774,8 @@ IndirectBufferView indirect_table_buffer(Wrapper* self, const std::uint32_t* wor bool allow_title_snapshot = false, bool requires_identity_dst_sel = false, const PlacedInputContext* placed_context = nullptr, u64* decoded_address = nullptr, u64* decoded_bytes = nullptr, - InputBufferUse use = InputBufferUse::ordinary) + InputBufferUse use = InputBufferUse::ordinary, + bool zero_records_are_null = false) { const auto refuse = [why](const char* reason) { if (why) *why = reason; @@ -2787,6 +2788,7 @@ IndirectBufferView indirect_table_buffer(Wrapper* self, const std::uint32_t* wor UINT stride = 0; const Wrapper* owner = nullptr; bool own_memory = false; + bool zero_records = false; if (why) *why = nullptr; if (words[0] == view_token_magic) { ViewRecord record{}; @@ -2832,6 +2834,7 @@ IndirectBufferView indirect_table_buffer(Wrapper* self, const std::uint32_t* wor if (!element || view.Buffer.FirstElement > UINT64_MAX / element) return refuse("an input buffer view has no element size or overflows"); offset = view.Buffer.FirstElement * element; bytes = u64{view.Buffer.NumElements} * element; + zero_records = view.Buffer.NumElements == 0; stride = raw ? 0 : element; if (const auto base = reinterpret_cast(owner->own().title_memory)) { // A buffer on a custom heap outside the placement index (the memory view path places it in the title's @@ -2854,11 +2857,17 @@ IndirectBufferView indirect_table_buffer(Wrapper* self, const std::uint32_t* wor address = words[0] | (u64{words[1] & 0xffff} << 32); stride = (words[1] >> 16) & 0x3fff; bytes = u64{stride ? stride : 1} * words[2]; + zero_records = words[2] == 0; } // A compute input whose four descriptor words are all zero is an unbound (null) buffer: the hardware reads zeros from // it, so the dispatch gets 16 bytes of zeros instead of being refused. Any other empty range is still refused. if (!bytes && allow_title_snapshot && !words[0] && !words[1] && !words[2] && !words[3]) return {nullptr, 0, 16, 0, true, 3}; + // A view with no records is an empty buffer, not a missing one: every load is out of + // bounds and reads zero on the hardware. The Mesh86 input path asks for that behaviour + // so a title that binds an empty view for one branch of its mesh shader still draws. + if (!bytes && zero_records && zero_records_are_null) + return {nullptr, 0, 16, 0, true, 3}; if (!bytes) return refuse("an input buffer descriptor has zero records"); if (use == InputBufferUse::mesh86_material) { if (bytes > limit) return refuse("material buffer size exceeds the D3D12 raw SRV limit"); diff --git a/src/startup_stubs/native_mesh86.inl b/src/startup_stubs/native_mesh86.inl index 56a277df2f..58b378d3f7 100644 --- a/src/startup_stubs/native_mesh86.inl +++ b/src/startup_stubs/native_mesh86.inl @@ -344,7 +344,7 @@ IndirectBufferView mesh86_material_buffer(Wrapper* self, const Pass& pass, const constexpr u64 raw_limit = u64{4} << D3D12_REQ_BUFFER_RESOURCE_TEXEL_COUNT_2_TO_EXP; return indirect_table_buffer(self, words, false, &reason, raw_limit, D3D12_RAW_UAV_SRV_BYTE_ALIGNMENT, true, view.requires_identity_dst_sel, - nullptr, nullptr, nullptr, InputBufferUse::mesh86_material); + nullptr, nullptr, nullptr, InputBufferUse::mesh86_material, true); } } // namespace @@ -453,6 +453,23 @@ const char* bind_native_mesh86(Wrapper* self, Pass& pass, ID3D12GraphicsCommandL const auto view = mesh86_material_buffer(self, pass, source, reason, words); if (!reason && view.bytes < source.required_bytes) reason = "material buffer is smaller than the shader's minimum read"; if (!reason) reason = buffer(slot, view); + if (!reason && view.source == 3) { + // An empty guest view (no records) reads zeros on the hardware. Keep the + // descriptor identity in the log so the table and record can be traced. + using Empty = std::tuple; + static std::vector reported; + const u64 key = pass.pipeline->own().mesh86_key; + const Empty id{key, index, source.shader_register}; + if (reported.size() < 64 && std::find(reported.begin(), reported.end(), id) == reported.end()) { + reported.push_back(id); + const auto& table = pass.view_tables[source.root_parameter]; + log("x2w-mesh86 empty input buffer list=%p mesh86=%016llx stage=%s srv=t%u root=%u table_offset=0x%x " + "table=0x%llx table_bytes=%llu descriptor=%08x,%08x,%08x,%08x -> %llu zero bytes", + self, key, index ? "pixel" : "mesh", source.shader_register, source.root_parameter, + source.byte_offset, table.address, table.bytes, words[0], words[1], words[2], words[3], + view.bytes); + } + } if (reason) { static const bool trace = x2w_local::env_on("X2W_D3D12_TRACE_DIRECT_MESH"); if (trace) { diff --git a/tests/cmake/startup_mesh86_input_stream.cmake b/tests/cmake/startup_mesh86_input_stream.cmake new file mode 100644 index 0000000000..6f4c9865b1 --- /dev/null +++ b/tests/cmake/startup_mesh86_input_stream.cmake @@ -0,0 +1,11 @@ +# A source-built PS-less slot 86 mesh reads a raw AMD V# from its guest SRV +# table. The positive record names a real placed buffer, the zero-record +# control must read zeros, and an unmapped base must keep its named refusal. +if(EXISTS "${INTAKE_PYTHON}" AND TARGET startup_indirect_draw_indexed AND EXISTS "${DXC_EXECUTABLE}") + foreach(backend IN ITEMS warp hardware) + add_test(NAME startup_mesh86_input_stream_${backend} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_mesh86_input_stream_check.py" + "${DXC_EXECUTABLE}" "$" ${backend}) + set_tests_properties(startup_mesh86_input_stream_${backend} PROPERTIES TIMEOUT 240 SKIP_RETURN_CODE 77) + endforeach() +endif() diff --git a/tests/startup_indirect_draw_indexed.cpp b/tests/startup_indirect_draw_indexed.cpp index 7f3b0f48cf..80f3e2077d 100644 --- a/tests/startup_indirect_draw_indexed.cpp +++ b/tests/startup_indirect_draw_indexed.cpp @@ -603,7 +603,7 @@ enum class Refusal { none, index_upload_cross, index_upload_foreign, index_uploa insufficient_table_range, copied_table_buffer, upload_range_crossing, unproven_copy, indexed_base_overrun, indexed_vertex_range, invalid_mesh_tag, rect_bad_index, rect_bad_count, rect_bad_w, rect_bad_shape, - mesh_pixel_array, mesh_pixel_hole, mesh_wrong_heap_format, mesh_empty_heap_slot, mesh_outside_heap, mesh_short_table, mesh_bad_root_address, incomplete_mesh_constants, mesh_attachment_count, mesh_pending, overflowing_count, rect_live_compute }; + mesh_pixel_array, mesh_pixel_hole, mesh_wrong_heap_format, mesh_empty_heap_slot, mesh_outside_heap, mesh_short_table, mesh_bad_root_address, incomplete_mesh_constants, mesh_attachment_count, mesh_pending, overflowing_count, rect_live_compute, mesh86_input_unmapped }; enum class DrawKind { indexed, vertices, mesh, indexed_rect, rect }; ComPtr make_gpu_table_buffer(ID3D12Device* guest, UINT64 bytes) @@ -1008,7 +1008,8 @@ bool run(ID3D12Device* device, ID3D12Device* guest, ID3D12RootSignature* writer_ UINT cached_mesh_targets = 0, bool cached_depth_only = false, bool restore_compute = false, const MeshLeaseDraw* leased = nullptr, Gate* gate = nullptr, bool cached_depth_pixel = false, int fixed_mesh_pixels = 0, const x2w_startup::Mesh57Profile* fixed_profile = nullptr, - const Mesh86HeapDraw* heap86 = nullptr, bool cached_root_srv = false) + const Mesh86HeapDraw* heap86 = nullptr, bool cached_root_srv = false, bool cached_root_srv_table = false, + bool cached_mesh_zero = false, bool cached_mesh_unmapped = false) { std::unique_lock recording; if (gate) recording = std::unique_lock(gate->state); @@ -1240,18 +1241,45 @@ bool run(ID3D12Device* device, ID3D12Device* guest, ID3D12RootSignature* writer_ ComPtr heap86_buffer; ComPtr heap86_heap; if (heap86 && !bind_mesh86_heap_views(device, guest, wrapped, heap86->variant, heap86_buffer, heap86_heap)) return false; + ComPtr input_stream_heap; slot(wrapped, 25)(wrapped, graphics); slot(wrapped, 34)(wrapped, refusal == Refusal::wrong_root ? translated->wrong_root.Get() : graphics_root); void* root_srv_address = nullptr; - if (cached_root_srv) { + if (cached_root_srv || cached_root_srv_table) { using Allocate = void* (WINAPI*)(IUnknown*, UINT64, UINT64); root_srv_address = slot(wrapped, 148)(wrapped, 16, 16); if (!root_srv_address) return false; *static_cast(root_srv_address) = 0x12345678u; + *reinterpret_cast(static_cast(root_srv_address) + 4) = 0x9abcdef0u; } if (leased) { using RootSrv = void (WINAPI*)(IUnknown*, UINT, UINT64); slot(wrapped, 44)(wrapped, 0, leased->address); + } else if (cached_root_srv_table) { + // A guest descriptor table holds a raw AMD V#. The empty and unmapped variants are + // negative controls for the Mesh86 input-buffer resolver. + const struct { + D3D12_DESCRIPTOR_HEAP_DESC desc; + UINT64 backing, bytes; + } heap_desc{{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 1, D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE}, 0, 0}; + using CreateHeap = HRESULT (WINAPI*)(IUnknown*, const void*, REFIID, void**); + if (FAILED(slot(guest, 14)(guest, &heap_desc, __uuidof(ID3D12DescriptorHeap), + reinterpret_cast(input_stream_heap.GetAddressOf())))) return false; + using Handle = UINT64 (WINAPI*)(IUnknown*, void*); + const auto cpu = slot(input_stream_heap.Get(), 9)(input_stream_heap.Get(), nullptr); + const auto gpu = slot(input_stream_heap.Get(), 10)(input_stream_heap.Get(), nullptr); + if (!cpu || !gpu) return false; + const UINT64 base = cached_mesh_unmapped ? 0x1000u : reinterpret_cast(root_srv_address); + auto* words = reinterpret_cast(cpu); + words[0] = static_cast(base); + words[1] = (cached_mesh_zero || cached_mesh_unmapped) ? 0u : (static_cast(base >> 32) | (4u << 16)); + words[2] = cached_mesh_zero ? 0u : 4u; + words[3] = 0; + using Table = void (WINAPI*)(IUnknown*, UINT, UINT64); + using Heaps = void (WINAPI*)(IUnknown*, UINT, ID3D12DescriptorHeap* const*); + ID3D12DescriptorHeap* heaps[]{input_stream_heap.Get()}; + slot(wrapped, 32)(wrapped, 1, heaps); + slot(wrapped, 36)(wrapped, 0, gpu); } else if (cached_root_srv) { using RootSrv = void (WINAPI*)(IUnknown*, UINT, UINT64); slot(wrapped, 44)(wrapped, 0, reinterpret_cast(root_srv_address)); @@ -1518,7 +1546,7 @@ bool run(ID3D12Device* device, ID3D12Device* guest, ID3D12RootSignature* writer_ const auto pixel_bytes = cached_depth_only ? 2u : sizeof(actual); std::memcpy(&actual, static_cast(memory) + y * footprint.Footprint.RowPitch + x * pixel_bytes, pixel_bytes); - if (cached_root_srv && !x && !y) first_depth = actual; + if ((cached_root_srv || cached_root_srv_table) && !x && !y) first_depth = actual; const bool right_half = x >= width / 2; const bool covered = (cached_depth_only && !cached_depth_pixel) || (indexed ? right_half == draw_right : translated || !right_half || draw_right); @@ -1526,7 +1554,8 @@ bool run(ID3D12Device* device, ID3D12Device* guest, ID3D12RootSignature* writer_ const std::uint32_t background = cached_depth_only ? 0xffff : desc.Format == DXGI_FORMAT_R16G16_FLOAT ? 0 : black; // D16_UNORM encodes the source-built PS-less SRV fixture's 0.5 as 0x8000; the // depth-only pixel fixture writes 0.25, and the constants-only mesh writes 0. - const auto depth_word = cached_root_srv ? 0x8000u : cached_depth_pixel ? 0x4000u : 0u; + const auto depth_word = (cached_root_srv || cached_root_srv_table) ? (cached_mesh_zero ? 0xffffu : 0x8000u) : + cached_depth_pixel ? 0x4000u : 0u; auto wanted = drawn ? (cached_depth_only ? depth_word : translated ? (draw_right ? green : red) : (right_half ? green : red)) : background; if (fixed_mesh_pixels) { @@ -1574,7 +1603,7 @@ bool run(ID3D12Device* device, ID3D12Device* guest, ID3D12RootSignature* writer_ pixel_readback->Unmap(0, &untouched); std::printf("%s: %u/%u non-clear pixels%s\n", label, painted, width * height, external_arguments ? "" : ", argument guards intact"); - if (cached_root_srv) std::printf("mesh86 SRV depth 0x%04x\n", first_depth); + if (cached_root_srv || cached_root_srv_table) std::printf("mesh86 input depth 0x%04x\n", first_depth); if (!pixels_match) { if (kind == DrawKind::rect) report_rect_conversion(device, observed, indexed_argument_offset / sizeof(std::uint32_t)); return false; @@ -3504,7 +3533,12 @@ int main(int argc, char** argv) try const bool depth_only = GetEnvironmentVariableA("X2W_MESH86_FIXTURE_DEPTH", nullptr, 0) != 0; // The PS-less SRV fixture has no pixel stage and proves its root SRV from the mesh stage. const bool psless_srv = GetEnvironmentVariableA("X2W_MESH86_FIXTURE_PSLESS_SRV", nullptr, 0) != 0; - const bool no_pixel = depth_only || psless_srv; + char input_stream_mode[16]{}; + const bool input_stream = GetEnvironmentVariableA("X2W_MESH86_FIXTURE_INPUT_STREAM", input_stream_mode, + sizeof(input_stream_mode)) != 0; + const bool input_stream_zero = std::strcmp(input_stream_mode, "zero") == 0; + const bool input_stream_unmapped = std::strcmp(input_stream_mode, "unmapped") == 0; + const bool no_pixel = depth_only || psless_srv || input_stream; char depth_mode[16]{}; const bool depth_pixel = GetEnvironmentVariableA("X2W_MESH86_FIXTURE_DEPTH_PIXEL", depth_mode, sizeof(depth_mode)) != 0; auto depth = no_pixel ? StreamDepth::writable : StreamDepth::none; @@ -3519,10 +3553,14 @@ int main(int argc, char** argv) try const auto ms = read_stage("source.ms.dxbc"); const auto ps = no_pixel && !depth_pixel ? std::vector{} : read_stage("source.ps.dxbc"); D3D12_ROOT_PARAMETER parameter{}; - parameter.ParameterType = (lease_fixture || psless_srv) ? D3D12_ROOT_PARAMETER_TYPE_SRV : - D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS; - parameter.ShaderVisibility = (lease_fixture || psless_srv) ? D3D12_SHADER_VISIBILITY_MESH : D3D12_SHADER_VISIBILITY_ALL; - if (!lease_fixture && !psless_srv) parameter.Constants = {0, 0, 2}; + const D3D12_DESCRIPTOR_RANGE input_stream_range{D3D12_DESCRIPTOR_RANGE_TYPE_SRV, 1, 0, 0, 0}; + parameter.ParameterType = input_stream ? D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE : + (lease_fixture || psless_srv) ? D3D12_ROOT_PARAMETER_TYPE_SRV : + D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS; + parameter.ShaderVisibility = (lease_fixture || psless_srv || input_stream) ? D3D12_SHADER_VISIBILITY_MESH : + D3D12_SHADER_VISIBILITY_ALL; + if (input_stream) parameter.DescriptorTable = {1, &input_stream_range}; + if (!lease_fixture && !psless_srv && !input_stream) parameter.Constants = {0, 0, 2}; const bool heap_window = !lease_fixture && GetEnvironmentVariableA("X2W_MESH86_FIXTURE_HEAP", nullptr, 0) != 0; const bool texture_map = heap_window && GetEnvironmentVariableA("X2W_MESH86_FIXTURE_TEXTURE_MAP", nullptr, 0) != 0; // Extend the root with an SRV table and a root SRV that the published stages never reference. @@ -3728,7 +3766,16 @@ int main(int argc, char** argv) try return 1; } } - const bool ok = psless_srv ? verify(Refusal::none, "PS-less root SRV") : + const auto verify_stream = [&](const char* label) { + return run(device.Get(), guest.Get(), writer.Get(), work.Get(), root.Get(), pso.Get(), signature.Get(), + DrawKind::mesh, false, input_stream_unmapped ? Refusal::mesh86_input_unmapped : Refusal::none, + label, nullptr, false, nullptr, false, false, no_pixel ? 0 : 3, no_pixel, false, nullptr, nullptr, + depth_pixel, 0, nullptr, nullptr, false, true, input_stream_zero, input_stream_unmapped); + }; + const bool ok = input_stream ? verify_stream(input_stream_zero ? "Mesh86 empty input stream" : + input_stream_unmapped ? "Mesh86 unmapped input stream" : + "Mesh86 input stream") : + psless_srv ? verify(Refusal::none, "PS-less root SRV") : !ready || invalid_depth_pixel ? verify(Refusal::mesh_pending, invalid_depth_pixel ? depth_mode : "unavailable cached mesh") : verify(Refusal::none, depth_pixel ? "cached mesh depth-only pixel stage" : diff --git a/tests/startup_indirect_mesh_input_stream.hlsl b/tests/startup_indirect_mesh_input_stream.hlsl new file mode 100644 index 0000000000..265decf842 --- /dev/null +++ b/tests/startup_indirect_mesh_input_stream.hlsl @@ -0,0 +1,21 @@ +// PS-less slot 86 geometry stream: the mesh stage reads two DWORDs from a +// descriptor-table SRV and emits one triangle. A matching pair writes depth +// 0.5; anything else (including the zero bytes of an empty view) leaves the +// depth at the 1.0 clear. +ByteAddressBuffer source : register(t0); + +struct Vertex { + float4 position : SV_Position; +}; + +[outputtopology("triangle")] +[numthreads(1, 1, 1)] +void mesh(out vertices Vertex verts[3], out indices uint3 triangles[1]) { + const uint2 pair = source.Load2(0); + const float z = pair.x == 0x12345678u && pair.y == 0x9abcdef0u ? 0.5 : 1.0; + SetMeshOutputCounts(3, 1); + verts[0].position = float4(-1, -1, z, 1); + verts[1].position = float4(-1, 3, z, 1); + verts[2].position = float4(3, -1, z, 1); + triangles[0] = uint3(0, 1, 2); +} diff --git a/tests/startup_mesh86_input_stream_check.py b/tests/startup_mesh86_input_stream_check.py new file mode 100644 index 0000000000..3c12f7c06a --- /dev/null +++ b/tests/startup_mesh86_input_stream_check.py @@ -0,0 +1,120 @@ +"""A source-built PS-less slot 86 mesh reads a descriptor-table input buffer. + +The guest root has one mesh-visible SRV table. The fixture writes a raw AMD V# +into its first descriptor and dispatches a source-built mesh stage that reads +two DWORDs. The positive descriptor must bind and write depth 0.5. An empty +view (NUM_RECORDS zero, base nonzero) is a null input: the bind succeeds and +the shader reads zeros, leaving depth at 1.0. A descriptor whose base is not +backed by a placed or committed buffer must refuse with the named reason. +""" + +import os +from pathlib import Path +import subprocess +import sys +import tempfile +import time + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE.parent / 'tools' / 'startup')) + +import mesh86_cache +from startup_indirect_mesh_cache_check import source_envelope + + +def run_fixture(fixture, backend, work, ready, mode): + environment = dict(os.environ, X2W_MESH86_FIXTURE_DIR=str(work), X2W_SHADER_CACHE=str(work), + X2W_MESH86_FIXTURE_DEPTH='1', X2W_MESH86_FIXTURE_INPUT_STREAM=mode) + for name in ('X2W_MESH86_FIXTURE_READY', 'X2W_NATIVE_MESH86', 'X2W_NATIVE_SHADERS', + 'X2W_NATIVE_SHADERS_ONLY', 'X2W_MESH86_FIXTURE_DEPTH_PIXEL'): + environment.pop(name, None) + if ready: + environment['X2W_MESH86_FIXTURE_READY'] = '1' + else: + environment['X2W_MESH86_FIXTURE_CREATE_ONLY'] = '1' + result = subprocess.run([str(fixture), backend, 'mesh'], env=environment, capture_output=True, + text=True, errors='replace', timeout=120) + return result.returncode, result.stdout + result.stderr + + +def wait_for_request(work): + deadline = time.monotonic() + 10 + while time.monotonic() < deadline: + requests = list(work.glob('req_*.m86')) + if requests: + return requests + time.sleep(0.05) + return [] + + +def main(): + if len(sys.argv) != 4: + sys.exit('usage: startup_mesh86_input_stream_check.py DXC FIXTURE warp|hardware') + dxc, fixture, backend = Path(sys.argv[1]), Path(sys.argv[2]), sys.argv[3] + if not dxc.is_file() or not fixture.is_file(): + sys.exit('DXC or fixture is missing') + with tempfile.TemporaryDirectory(prefix='mesh86-input-', dir=Path.cwd()) as directory: + work = Path(directory) + (work / 'source.ms.dxbc').write_bytes(source_envelope(13)) + code, output = run_fixture(fixture, backend, work, False, 'positive') + if code == 77: + return 77 + if code: + sys.exit(output) + requests = wait_for_request(work) + if len(requests) != 1: + sys.exit(f'expected one pending slot 86 request, found {[path.name for path in requests]}') + key = int(requests[0].stem[4:], 16) + if f'slot86 mesh request {key:016x} pending' not in output: + sys.exit(f'the first run did not report request {key:016x} pending:\n{output}') + + mesh = work / 'desktop.ms.cso' + subprocess.run([str(dxc), '-T', 'ms_6_6', '-E', 'mesh', '-Fo', str(mesh), + str(HERE / 'startup_indirect_mesh_input_stream.hlsl')], + check=True, capture_output=True) + plan = {'constants': [], 'views': [{'shader_register': 0, 'root_parameter': 0, 'byte_offset': 0, + 'required_bytes': 8, 'kind': 0, 'image_dimension': 1}]} + mesh86_cache.publish(work, key, mesh, None, mesh_srv_dxc=dxc, mesh_srv_plan=plan) + marker = (work / f'{key:016x}.mesh86.txt').read_text(encoding='ascii') + if not marker.startswith('x2w-mesh86 6 ') or 'srv 0 0 0 8 0 1' not in marker: + sys.exit(f'unexpected input-stream marker: {marker!r}') + + code, output = run_fixture(fixture, backend, work, True, 'positive') + if code == 77: + return 77 + if code: + sys.exit(output) + if 'mesh86 input depth 0x8000' not in output: + sys.exit(f'the nonzero input buffer did not write depth 0.5:\n{output}') + + code, output = run_fixture(fixture, backend, work, True, 'zero') + if code == 77: + return 77 + if code: + sys.exit(output) + if 'mesh86 input depth 0xffff' not in output: + sys.exit(f'a zero-record view did not read zeros:\n{output}') + if 'x2w-mesh86 empty input buffer' not in output: + sys.exit(f'the empty view was not logged with its guest table record:\n{output}') + + environment = dict(os.environ, X2W_D3D12_TRACE_DIRECT_MESH='1') + old = os.environ.copy() + os.environ.update(environment) + try: + code, output = run_fixture(fixture, backend, work, True, 'unmapped') + finally: + os.environ.clear() + os.environ.update(old) + if code == 77: + return 77 + if code: + sys.exit(output) + if 'an input is in title memory outside any placed buffer' not in output: + sys.exit(f'the unmapped descriptor did not report its named refusal:\n{output}') + + print(f'{key:016x}: nonzero input buffer wrote depth 0.5; zero records and an unmapped base behaved') + return 0 + + +if __name__ == '__main__': + raise SystemExit(main()) From fb392f1ffa95c0c15844e0b333a98885da42a2c8 Mon Sep 17 00:00:00 2001 From: Roland Edi Date: Wed, 2 Dec 2026 01:46:07 +0000 Subject: [PATCH 29/32] test: print the nonzero Mesh86 input descriptor The hardware fixture now prints the raw V# base, stride and record count, and the check requires them beside the depth proof. --- tests/startup_indirect_draw_indexed.cpp | 2 ++ tests/startup_mesh86_input_stream_check.py | 2 ++ 2 files changed, 4 insertions(+) diff --git a/tests/startup_indirect_draw_indexed.cpp b/tests/startup_indirect_draw_indexed.cpp index 80f3e2077d..a3e7b948d8 100644 --- a/tests/startup_indirect_draw_indexed.cpp +++ b/tests/startup_indirect_draw_indexed.cpp @@ -1275,6 +1275,8 @@ bool run(ID3D12Device* device, ID3D12Device* guest, ID3D12RootSignature* writer_ words[1] = (cached_mesh_zero || cached_mesh_unmapped) ? 0u : (static_cast(base >> 32) | (4u << 16)); words[2] = cached_mesh_zero ? 0u : 4u; words[3] = 0; + if (!cached_mesh_zero && !cached_mesh_unmapped) + std::printf("mesh86 input V# base=0x%llx stride=4 records=4\n", static_cast(base)); using Table = void (WINAPI*)(IUnknown*, UINT, UINT64); using Heaps = void (WINAPI*)(IUnknown*, UINT, ID3D12DescriptorHeap* const*); ID3D12DescriptorHeap* heaps[]{input_stream_heap.Get()}; diff --git a/tests/startup_mesh86_input_stream_check.py b/tests/startup_mesh86_input_stream_check.py index 3c12f7c06a..d7a3ea17c7 100644 --- a/tests/startup_mesh86_input_stream_check.py +++ b/tests/startup_mesh86_input_stream_check.py @@ -84,6 +84,8 @@ def main(): return 77 if code: sys.exit(output) + if 'mesh86 input V# base=0x' not in output or 'stride=4 records=4' not in output: + sys.exit(f'the nonzero input descriptor was not written:\n{output}') if 'mesh86 input depth 0x8000' not in output: sys.exit(f'the nonzero input buffer did not write depth 0.5:\n{output}') From 3081d21e177e3ccf15daff43cc346effdca88458 Mon Sep 17 00:00:00 2001 From: Roland Edi Date: Wed, 2 Dec 2026 01:53:05 +0000 Subject: [PATCH 30/32] test: document the WARP mesh-device removal startup_mesh86_input_stream_warp now returns 77 only when the dispatch removes the WARP device with 0x887a0005, the same failure the existing startup_mesh86_psless_warp fixture has. Any other failure still fails the check; the RX 9060 XT run proves the bind. --- tests/startup_mesh86_input_stream_check.py | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/tests/startup_mesh86_input_stream_check.py b/tests/startup_mesh86_input_stream_check.py index d7a3ea17c7..3f8f147980 100644 --- a/tests/startup_mesh86_input_stream_check.py +++ b/tests/startup_mesh86_input_stream_check.py @@ -83,6 +83,11 @@ def main(): if code == 77: return 77 if code: + if backend == 'warp' and '0x887a0005' in output: + print('WARP removed the device after the DispatchMesh record; the baseline ' + 'startup_mesh86_psless_warp shows the same device removal, so this ' + 'adapter cannot prove the input-stream bind. The hardware run covers it.') + return 77 sys.exit(output) if 'mesh86 input V# base=0x' not in output or 'stride=4 records=4' not in output: sys.exit(f'the nonzero input descriptor was not written:\n{output}') From 59b68a29d5d7443e95fdb6db372b32b02b830e46 Mon Sep 17 00:00:00 2001 From: Roland Edi Date: Wed, 2 Dec 2026 02:01:50 +0000 Subject: [PATCH 31/32] docs: record the zero-record Mesh86 input view The prologue request 062d66b9e013f28e binds root parameter 1 record 2 (t20 space1) with NUM_RECORDS zero. Document the null-view binding, the source-built controls, the RX 9060 XT pass and the WARP device-removal skip. --- docs/experiments.md | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/docs/experiments.md b/docs/experiments.md index c53e5a260a..c6a9f1d29b 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -11291,6 +11291,24 @@ mutant entries keep the bytes visible at adoption and must fail. The fixture reports refresh bytes (65,536 first, 4 per changed word) and the reused backing; see [the mesh86 note](experiments/mesh86-pixel-execz.md#material-placed-buffer-backing). +A zero-record input buffer is an empty view, not a missing one. The prologue +request `062d66b9e013f28e` loads a raw V# from root parameter 1, descriptor +record 2 (SRV `t20 space1`), and that record is +`00013920,00000000,00000000,00000000`: a nonzero base with no records. The +captured mesh stage has an empty input signature and reads the V# on one branch, +so the hardware returns zero for every load. The Mesh86 input path now binds a +16-byte zero view for that state and logs the guest table, record and descriptor +once; the ordinary compute input path still refuses zero records. The +source-built check publishes a PS-less mesh profile with an 8-byte +descriptor-table SRV, writes a raw V#, and expects depth 0.5 for a nonzero +record, depth 1.0 for a zero-record view and the named +`an input is in title memory outside any placed buffer` refusal for an +unmapped base. Run +`ctest --preset release --no-tests=error -R '^startup_mesh86_input_stream_(warp|hardware)$' --output-on-failure`. +The RX 9060 XT case passes; WARP returns 77 when the dispatch removes the WARP +device with `0x887a0005`, the same removal the existing +`startup_mesh86_psless_warp` fixture reports. + On the Release worktree at `76aeef7f` plus these changes, the combined lease, SRV proof, export and mapped-page selection passed eight tests. The two mesh cases returned 77 on the adapters listed above. `dumpbin /exports` showed From acd0b64f7fc743611ff8e6bf056280611fa58bf4 Mon Sep 17 00:00:00 2001 From: Roland Edi Date: Wed, 2 Dec 2026 11:46:56 +0000 Subject: [PATCH 32/32] runtime: fix Mesh86 fixture and non-native build --- src/startup_stubs/mesh86_cache.inl | 2 +- tests/standin_exports_check.py | 8 ++++---- tests/startup_indirect_draw_indexed.cpp | 3 ++- 3 files changed, 7 insertions(+), 6 deletions(-) diff --git a/src/startup_stubs/mesh86_cache.inl b/src/startup_stubs/mesh86_cache.inl index 418a8d14b9..2d01d146e8 100644 --- a/src/startup_stubs/mesh86_cache.inl +++ b/src/startup_stubs/mesh86_cache.inl @@ -423,9 +423,9 @@ ID3D12PipelineState* try_cached_mesh86(const D3D12_PIPELINE_STATE_STREAM_DESC& d char heap_type[4] = ""; UINT map_parameter = UINT_MAX; x2w_startup::ComPtr mapped_root; + x2w_startup::ComPtr published_root; #ifdef X2W_NATIVE_SHADERS std::shared_ptr published_plan; - x2w_startup::ComPtr published_root; #endif if (psless_srv) { if (!request.ps.empty()) { diff --git a/tests/standin_exports_check.py b/tests/standin_exports_check.py index 53031b94a0..0ecd33cc5b 100644 --- a/tests/standin_exports_check.py +++ b/tests/standin_exports_check.py @@ -107,7 +107,7 @@ def test_real_catalogs(): expected = set(modules[:8]) | {"xgameruntime.dll"} check(set(catalogs) == expected, f"load_catalogs keys {sorted(catalogs)} != {sorted(expected)}") - counts = {"xmem": 54, "d3d12_xs": 79, "acphal": 10, "chad": 5, + counts = {"xmem": 54, "d3d12_xs": 80, "acphal": 10, "chad": 5, "xapu": 6, "xcrdapi": 3, "xg_xs": 2, "gameinput": 2} for stem, path in DEFAULT_DEFS.items(): catalog = catalogs[stem + ".dll"] @@ -146,7 +146,7 @@ def test_real_catalogs(): == Counter({"trap": 9, "implemented": 1}), "acphal status counts differ") check(Counter(e.status for e in catalogs["d3d12_xs.dll"].entries.values()) - == Counter({"implemented": 35, "unmeasured": 44}), + == Counter({"implemented": 35, "unmeasured": 45}), "d3d12_xs status counts differ") check(Counter(e.status for e in catalogs["xgameruntime.dll"].entries.values()) == Counter({"implemented": 38}), @@ -221,7 +221,7 @@ def test_real_catalogs(): check(d3d12.lookup("x2w_d3d12_compute_census").status == "unmeasured", "d3d12_xs direct export is unmeasured") check(d3d12.lookup("x2w_d3d12_compute_census").source - == "src/startup_stubs/d3d12_compute_dispatch.inl:1744", + == "src/startup_stubs/d3d12_compute_dispatch.inl:1745", "d3d12_xs direct export source is the included file") check(d3d12.lookup("NoSuchExport").status == "absent", "d3d12_xs absent name") @@ -270,7 +270,7 @@ def test_export_coverage(): "src/xmem_shim.def:15", None), ("d3d12_xs.dll", "x2w_d3d12_compute_census", "unmeasured", "d3d12_xs.dll", "shim", - "src/startup_stubs/d3d12_compute_dispatch.inl:1744", None), + "src/startup_stubs/d3d12_compute_dispatch.inl:1745", None), ("d3d12_xs.dll", "IID_ID3D12Device", "implemented", "d3d12_xs.dll", "shim", "src/d3d12_xs_shim.def:13", "src/d3d12_xs_iids.cpp:1"), ("xgameruntime.dll", "XUserAddAsync", "implemented", diff --git a/tests/startup_indirect_draw_indexed.cpp b/tests/startup_indirect_draw_indexed.cpp index a3e7b948d8..afc60111cc 100644 --- a/tests/startup_indirect_draw_indexed.cpp +++ b/tests/startup_indirect_draw_indexed.cpp @@ -1605,7 +1605,8 @@ bool run(ID3D12Device* device, ID3D12Device* guest, ID3D12RootSignature* writer_ pixel_readback->Unmap(0, &untouched); std::printf("%s: %u/%u non-clear pixels%s\n", label, painted, width * height, external_arguments ? "" : ", argument guards intact"); - if (cached_root_srv || cached_root_srv_table) std::printf("mesh86 input depth 0x%04x\n", first_depth); + if (cached_root_srv) std::printf("mesh86 SRV depth 0x%04x\n", first_depth); + if (cached_root_srv_table) std::printf("mesh86 input depth 0x%04x\n", first_depth); if (!pixels_match) { if (kind == DrawKind::rect) report_rect_conversion(device, observed, indexed_argument_offset / sizeof(std::uint32_t)); return false;