diff --git a/CMakeLists.txt b/CMakeLists.txt index a59632f65d..c1744fd2e3 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -2038,6 +2038,12 @@ if(TARGET compile_dxil AND EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${ add_test(NAME native_fixed_mesh57_buffers_${backend} COMMAND startup_indirect_draw_indexed ${backend} mesh) set_tests_properties(native_fixed_mesh57_buffers_${backend} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77 ENVIRONMENT "X2W_TEST_NATIVE_MESH57=1;X2W_TEST_NATIVE_MESH57_BUFFERS=1;X2W_NATIVE_SHADERS=${DXC_BIN_DIR}") + add_test(NAME native_fixed_mesh57_published_pair_${backend} COMMAND startup_indirect_draw_indexed ${backend} mesh) + set_tests_properties(native_fixed_mesh57_published_pair_${backend} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77 + ENVIRONMENT "X2W_TEST_NATIVE_MESH57=1;X2W_TEST_NATIVE_MESH57_BUFFERS=1;X2W_TEST_NATIVE_MESH57_PUBLISHED_PAIR=1;X2W_ALLOW_PUBLISHED_MESH57_PAIR=1;X2W_NATIVE_SHADERS=${DXC_BIN_DIR}") + add_test(NAME native_fixed_mesh57_published_pair_refusal_${backend} COMMAND startup_indirect_draw_indexed ${backend} mesh) + set_tests_properties(native_fixed_mesh57_published_pair_refusal_${backend} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77 + ENVIRONMENT "X2W_TEST_NATIVE_MESH57=1;X2W_TEST_NATIVE_MESH57_CBV_UAV=1;X2W_TEST_NATIVE_MESH57_PUBLISHED_PAIR=1;X2W_ALLOW_PUBLISHED_MESH57_PAIR=1;X2W_NATIVE_SHADERS=${DXC_BIN_DIR}") add_test(NAME native_fixed_mesh57_constant_${backend} COMMAND startup_indirect_draw_indexed ${backend} mesh) set_tests_properties(native_fixed_mesh57_constant_${backend} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77 ENVIRONMENT "X2W_TEST_NATIVE_MESH57=1;X2W_TEST_NATIVE_MESH57_CONSTANT=1;X2W_NATIVE_SHADERS=${DXC_BIN_DIR}") diff --git a/CMakePresets.json b/CMakePresets.json index bffb3aeac4..6bd4804f08 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_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|startup_triage_run)$" } } }, diff --git a/docs/experiments.md b/docs/experiments.md index 2bb4312005..c6e06ea081 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -10703,7 +10703,17 @@ colour pairs with `offscreen_check --mesh-indexed`; lanes whose flat attribute 0 red is at or below 0.5 are killed, so two of the four triangles are dropped. Each draw must match the CPU rasteriser without them, and the same mesh with the pixel stage that does not kill must differ at exactly the 115 killed pixels. -Nothing here shows that a runtime path loads the pair. +The published pair is legacy input and stays unavailable without +`X2W_ALLOW_PUBLISHED_MESH57_PAIR=1`; the default native-only run rethrows the +exact `mesh57_group_index` refusal before reading the manifest or either CSO. +The runtime path that loads the opted-in pair, the native-first fallback order, +the manifest-derived reads and the revision tie are described in +[fixed mesh pipelines through slot 57](experiments/native-fixed-mesh57.md#published-pair-for-the-r1-group-index-exchange); +`startup_mesh57_runtime_{warp,hardware}` exercises them. Its gate control runs +the same on-disk pair first without the opt-in and requires a cleared target, +no forwarded `DispatchMesh` and the native refusal, then with the opt-in and +requires 1,024 matching pixels. The native-priority and non-R1-refusal controls +also set the opt-in, so they exercise the gate rather than its default refusal. The `startup_mesh57_skeleton_depth_{warp,hardware}` CTest checks draw a @@ -10719,8 +10729,11 @@ stage with a colour export before its null export, a pair whose pixel stage does not match its key, and the mesh shapes the paired path refuses next to the depth-only pixel stage; it checks that `pending_keys` keeps the pair pending until both `.ms57.cso` and `.ps57.cso` are complete. The -runtime does not load slot 57 results yet, so these draws are not submitted -through the guest path. +`startup_mesh57_runtime_{warp,hardware}` guest path loads the published pair +for the buffer-view profile, after the one R1 native refusal, only when +`X2W_ALLOW_PUBLISHED_MESH57_PAIR=1` is set, and submits these draws; the +offline depth-only readback above remains a separate +`offscreen_check` comparison. The pending scan checks the DXContainer header and file length for every required slot 57 bytecode artifact. A `ps none` result needs the mesh artifact diff --git a/docs/experiments/native-compile-dxil-rekey.md b/docs/experiments/native-compile-dxil-rekey.md index 0a886e986c..5a4e2490f6 100644 --- a/docs/experiments/native-compile-dxil-rekey.md +++ b/docs/experiments/native-compile-dxil-rekey.md @@ -16,7 +16,7 @@ This mode runs without `SDK_DIRECTORY` or DXC: (`.txt`, `.fail`, `.cso`, `.psdep`). - Validates and recomputes keys in parallel using the current output revision strings (`x2w-startup-shader-29`, `x2w-startup-shader-29cs`, - `x2w-startup-mesh-57-3` via shared helpers in `src/shader_compute_request.cpp`), + `x2w-startup-mesh-57-4` via shared helpers in `src/shader_compute_request.cpp`), while the readers retain `x2w-startup-shader-28` and `x2w-startup-shader-28cs` input compatibility. - Rewrites `.psin` and `.rtv` payloads under their updated keys while leaving all diff --git a/docs/experiments/native-fixed-mesh57.md b/docs/experiments/native-fixed-mesh57.md index d47bdaefba..e013e4fa67 100644 --- a/docs/experiments/native-fixed-mesh57.md +++ b/docs/experiments/native-fixed-mesh57.md @@ -15,6 +15,68 @@ cmake --build --preset dev --target startup_indirect_draw_indexed ctest --preset dev --no-tests=error --output-on-failure -R '^(native_fixed_mesh57(_mask|_mrt)?|startup_indirect_mesh_(request|cache))_(warp|hardware)$' ``` +## Published pair for the R1 group-index exchange + +The native mesh frontend still refuses one R1 group-index exchange shape +(`0xbefe0481`, `native compute +0x...: mesh group-index exchange shape or entry +state is not covered`). For a buffer-view profile (`X2WM574`), native +translation is attempted first. The publisher's `.ms57.cso` / `.ps57.cso` pair +is legacy input, so it is disabled by default. Set +`X2W_ALLOW_PUBLISHED_MESH57_PAIR=1` to permit the fallback; native translation +still wins whenever it succeeds. Only the exact `mesh57_group_index` refusal +may fall back. A different native refusal is rethrown, as are profiles that +need pixel spans or a directly indexed resource heap. Without the opt-in, the +exact native refusal is rethrown before the manifest or either CSO is opened, +including in the launchers' default `X2W_NATIVE_SHADERS_ONLY=1` mode. With the +opt-in and no published pair, the pipeline is refused. + +The fallback reads `.ms57.txt`, a version 4 mesh manifest: + +```text +x2w-manifest 4 +stage ms +srv 0 buf table 1 0 bytes 388 +``` + +The `srv` lines supply the reads in translated register order. Each carries +the table byte offset or `root` parameter and the accessed byte span computed +from the translated mesh stage's buffer loads. A descriptor whose usable range +is shorter than that span is refused, and each table offset resolves its own +record rather than aliasing the first descriptor. The profile's view entries +are checked for the root parameter and direct/table kind, but their order is not +used. The request-key revision is `x2w-startup-mesh-57-4`; an older pair or a +version 1 manifest is not loaded. + +The `startup_mesh57_runtime_{warp,hardware}` fixture creates the guest root +from the exact serialized root the request publisher compiled against. The +request key, profile key and CSO names therefore agree. A GPU compute pass +writes the `DispatchMesh(1,1,1)` record, the direct queue waits on its fence, +and the readback is compared with the CPU rasteriser. The gate control runs the +same on-disk pair twice in native-only mode. Without +`X2W_ALLOW_PUBLISHED_MESH57_PAIR`, the target must stay cleared, the indirect +census must report no forwarded mesh call, and stderr must carry the native +`mesh group-index exchange shape or entry state is not covered` refusal. With +the opt-in, the same bytes must load, report `dispatchmesh 1` and match all +1,024 pixels. The control also checks that the pair bytes did not change between +the two runs; each subprocess gets an explicit environment with inherited +switches removed. The fixture expects `dispatchmesh 1` and 1,024 matching pixels +for the opted-in compiled pair and for a two-descriptor table whose second +record supplies the colours. A four-byte view against the 388-byte accessed +span and a version 1 manifest must each leave the target cleared and forward no +mesh call. Missing or truncated MS/PS bytecode does the same, and a restored +pair must draw again. The `native_fixed_mesh57_published_pair_{warp,hardware}` +control places an unusable pair beside a native-translatable profile with the +opt-in set: the native translation must still win. The +`native_fixed_mesh57_published_pair_refusal_{warp,hardware}` control places the +same pair beside a profile whose native refusal is not the R1 shape, also with +the opt-in set; that refusal must stay a refusal instead of falling back. Run +`ctest --preset dev --no-tests=error -R '^startup_mesh57_runtime_(warp|hardware)$' -V` +to reproduce the gate control. + +Mesh pipelines no longer receive the vertex rectangle-list selector at the +start of their `cbuffer`. That word shifted the two mesh root constants by one +and made the shader read a zero vertex count, which rendered a black target. + The three fixture variants use one color target, six color targets with depth/stencil, and the same six with a red-only target-zero write mask. The six-target formats are 29, 28, 28, 28, 34 and 28, with depth/stencil format 20. Back-face culling, counterclockwise front faces, greater-or-equal depth, depth writes and stencil replacement are enabled. The four-by-two GPU readback has a single covered texel at (2,0). It is white with all channels enabled or red with the narrower write mask. Depth/stencil at that texel changes from 0.25/3 to 0.5/7. The other color attachments retain their clear values. Changing a fixed descriptor word or removing a color attachment produces no color or depth/stencil change. The ten tests above passed on the working tree based on `671b9ac`, Windows build 26200, with the debug layer enabled on WARP and an NVIDIA GeForce RTX 4060 Laptop GPU (driver 32.0.16.1656). diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index 6fc2f0ddfd..fe7153d674 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -220,7 +220,8 @@ loop iteration after an EXEC write. The two cache keys advance together. Revision 21 refuses a compute lane-mask form that revision 20 translated (`s_and_b32 M, X, exec_lo` with X data). Revision 20 decodes MTBUF/MUBUF format 50 (`R10G10B10A2_UNORM`) in the run-time FORMAT switch. Revision 19 folds `s_mov_b32` from a scalar register that holds a plain constant, so later reads of the copy use the constant word. The fixed slot 57 mesh -(`x2w-startup-mesh-57-3`) key stays, because that shader is not translated from guest code. +key stayed at its then-current revision because that shader is not translated from guest code; it is now `x2w-startup-mesh-57-4`, tied to the version 4 +mesh manifest and its opt-in published-pair fallback. Revisions before 19 read a register copied from a constant as a run-time value. Revision 18 preserves the sign of zero in floating-point min, max, min3, max3 and med3. Revisions before 17 lower `v_med3_f32` through a branchless median, which returns the smaller of the @@ -1844,6 +1845,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_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 | | `X2W_D3D12_ROOT_SRV_AT_DRAW=1` | opt-in, render mode: a graphics root SRV (slot 44) without an upload mapping is not copied into the upload ring, since no draw reads that desktop binding (default: a 64 KiB copy at every slot 44 call). Translated draws copy the SRV themselves and are unaffected (`startup_root_srv_draw_*`). See [the experiment note](experiments/startup-root-srv-at-draw.md) | diff --git a/src/gfx1013_compute_native.cpp b/src/gfx1013_compute_native.cpp index 19c9b2aac6..81c09051fc 100644 --- a/src/gfx1013_compute_native.cpp +++ b/src/gfx1013_compute_native.cpp @@ -48,10 +48,10 @@ struct SdwaProfile { bool src0_16 = false, src1_16 = false, dst_16 = false; }; -[[noreturn]] void refuse(unsigned pc, const string &reason) { +[[noreturn]] void refuse(unsigned pc, const string &reason, const char* code = nullptr) { std::ostringstream out; out << "native compute +0x" << std::hex << pc << ": " << reason; - throw UnsupportedComputeShader(out.str()); + throw UnsupportedComputeShader(out.str(), code); } Word word(const string &bytes, unsigned at) { if (at > bytes.size() || bytes.size() - at < 4) diff --git a/src/gfx1013_compute_native.h b/src/gfx1013_compute_native.h index 1fd9e934ae..b478740524 100644 --- a/src/gfx1013_compute_native.h +++ b/src/gfx1013_compute_native.h @@ -4,6 +4,7 @@ #include #include #include +#include #include #include @@ -14,7 +15,9 @@ enum class GpuStage; struct GuestShaderStage; class UnsupportedComputeShader : public std::runtime_error { public: - using std::runtime_error::runtime_error; + explicit UnsupportedComputeShader(const std::string& message, const char* code = nullptr) + : std::runtime_error(message), code(code) {} + const char* code; }; enum class ComputeViewKind { buffer_srv, diff --git a/src/gfx1013_direct_mesh.inl b/src/gfx1013_direct_mesh.inl index 8057a28c32..ca851ada1f 100644 --- a/src/gfx1013_direct_mesh.inl +++ b/src/gfx1013_direct_mesh.inl @@ -1740,7 +1740,7 @@ NativeComputeShader lower_mesh(const string &code, const MeshStageLayout &layout } } else { if (raw==0xbefe0481) - refuse(pc,"mesh group-index exchange shape or entry state is not covered"); + refuse(pc,"mesh group-index exchange shape or entry state is not covered", "mesh57_group_index"); // A barrier alone does not identify the count exchange. Its // next word compares the candidate wave SGPR against zero. if (raw==0xbf8a0000 && code.size()-pc>=8 && (word(code,pc+4)&0xffffff80u)==0xbf008000) diff --git a/src/shader_compute_request.cpp b/src/shader_compute_request.cpp index 563298b173..b2d6e338e2 100644 --- a/src/shader_compute_request.cpp +++ b/src/shader_compute_request.cpp @@ -200,7 +200,7 @@ uint64_t x2w::compute_request_key(std::string_view code, std::string_view data, } uint64_t x2w::mesh57_request_key(std::string_view code, std::string_view ps57, std::string_view root) { - constexpr char revision[] = "x2w-startup-mesh-57-3"; + constexpr char revision[] = "x2w-startup-mesh-57-4"; uint64_t key = fnv1a_64(std::string_view(revision, sizeof(revision) - 1)); for (const auto part_view : {code, ps57, root}) { const uint64_t size = part_view.size(); diff --git a/src/startup_stubs/d3d12_draw.inl b/src/startup_stubs/d3d12_draw.inl index 739a5cb6a4..cb82fa160e 100644 --- a/src/startup_stubs/d3d12_draw.inl +++ b/src/startup_stubs/d3d12_draw.inl @@ -533,7 +533,7 @@ bool append_pso_recipe(const wchar_t* path, const x2w_startup::PsoRecipe& recipe namespace shader_cache { constexpr char revision[] = "x2w-startup-shader-29"; constexpr char compute_revision[] = "x2w-startup-shader-29cs"; // tools/startup/gfx2hlsl.py compute_key -constexpr char mesh57_revision[] = "x2w-startup-mesh-57-3"; +constexpr char mesh57_revision[] = "x2w-startup-mesh-57-4"; } // namespace shader_cache // Once per process, before its first request: \revision.txt names this runtime's revisions, so diff --git a/src/startup_stubs/native_mesh57.inl b/src/startup_stubs/native_mesh57.inl index 99d72fe61b..3cb399a6e7 100644 --- a/src/startup_stubs/native_mesh57.inl +++ b/src/startup_stubs/native_mesh57.inl @@ -262,6 +262,146 @@ void mesh57_outcome_line(char (&line)[1536]) } } +// The native mesh frontend refuses one fixed R1 group-index exchange shape. Do not hide any +// other translation refusal behind the publisher's pair. The refusal carries a code so a +// reworded message cannot silently disable the fallback. +bool is_mesh57_group_index_refusal(const x2w::UnsupportedComputeShader& error) +{ + return error.code && std::strcmp(error.code, "mesh57_group_index") == 0; +} + +// The published pair is legacy input, so it needs its own opt-in. A default native-only +// run must keep the native refusal even when a pair is present on disk. +bool allow_published_mesh57_pair() +{ + return x2w_local::env_on("X2W_ALLOW_PUBLISHED_MESH57_PAIR"); +} + +// Version 4 is the publisher's slot 57 mesh manifest: stage ms, and every buffer SRV line +// carries the accessed byte span. The reads keep the translated register order and the table's +// own descriptor offset, instead of assuming the profile's view-entry order. +bool read_published_mesh57_manifest(u64 key, const D3D12_ROOT_SIGNATURE_DESC1& root, + const std::vector& views, + unsigned constant_parameter, unsigned constant_count, + std::vector& reads, + std::string& why) +{ + wchar_t path[MAX_PATH]; + std::string text; + reads.clear(); + if (!cache_path(path, L"", key, L".ms57.txt") || !read_text(path, text)) { + why = "published MS57 manifest is absent"; + return false; + } + bool header = false, stage = false, ud = false; + unsigned ud_count = 0; + std::vector ud_ok; + for (std::size_t at = 0; at < text.size();) { + std::size_t end = text.find('\n', at); + if (end == std::string::npos) end = text.size(); + std::string line = text.substr(at, end - at); + if (!line.empty() && line.back() == '\r') line.pop_back(); + at = end + 1; + if (line.empty()) continue; + if (line == "x2w-manifest 4") { + if (header) { + why = "published MS57 manifest repeats its header"; + return false; + } + header = true; + } else if (line == "stage ms") { + stage = true; + } else if (line.compare(0, 3, "ud ") == 0) { + unsigned count = 0; + int used = 0; + if (ud || std::sscanf(line.c_str(), "ud %u%n", &count, &used) != 1 || + used != static_cast(line.size()) || count > constant_count || count > 64) { + why = "published MS57 manifest constant layout differs from the profile: " + line; + return false; + } + ud = true; + ud_count = count; + ud_ok.assign(count, false); + } else if (line.compare(0, 6, "udsrc ") == 0) { + unsigned index = 0, parameter = 0, word = 0; + int used = 0; + if (!ud || std::sscanf(line.c_str(), "udsrc %u rootconst %u %u%n", &index, ¶meter, &word, &used) != 3 || + used != static_cast(line.size()) || index >= ud_count || ud_ok[index] || + parameter != constant_parameter || word != index) { + why = "published MS57 manifest constant layout differs from the profile: " + line; + return false; + } + ud_ok[index] = true; + } else if (line.compare(0, 4, "srv ") == 0) { + unsigned index = 0, parameter = 0, offset = 0, bytes = 0; + char kind[16] = "", source[16] = ""; + int used = 0; + int fields = std::sscanf(line.c_str(), "srv %u %15s %15s %u %u bytes %u%n", + &index, kind, source, ¶meter, &offset, &bytes, &used); + bool direct = false; + if (fields == 6 && used == static_cast(line.size())) { + direct = false; + } else { + used = 0; + fields = std::sscanf(line.c_str(), "srv %u %15s root %u bytes %u%n", + &index, kind, ¶meter, &bytes, &used); + if (fields != 4 || used != static_cast(line.size())) { + why = "invalid MS57 manifest srv line: " + line; + return false; + } + offset = 0; + direct = true; + } + if (std::strcmp(kind, "buf") || index != reads.size() || index >= 32 || parameter >= 16 || + !bytes || bytes % 4 || bytes > (1u << 20) || (!direct && offset % 32)) { + why = "unsupported MS57 manifest buffer read: " + line; + return false; + } + if (!direct && std::strcmp(source, "table")) { + why = "unsupported MS57 manifest read source: " + line; + return false; + } + reads.push_back({parameter, offset, bytes, direct}); + } else if (line.compare(0, 4, "uav ") == 0) { + why = "published MS57 pair writes a UAV, which the fallback does not bind"; + return false; + } + } + if (!header || !stage) { + why = "published MS57 manifest is not a version 4 mesh manifest"; + return false; + } + if (!ud || std::find(ud_ok.begin(), ud_ok.end(), false) != ud_ok.end()) { + why = "published MS57 manifest constant layout differs from the profile"; + return false; + } + if (reads.empty()) { + why = "published MS57 manifest names no mesh buffer read"; + return false; + } + for (const auto& read : reads) { + const bool mapped = std::any_of(views.begin(), views.end(), [&](const auto& view) { + return view.root_parameter == read.root_parameter && + (view.root_address != 0) == read.root_address; + }); + if (!mapped) { + why = "published MS57 manifest read is not mapped by the profile"; + return false; + } + if (read.root_parameter >= root.NumParameters) { + why = "published MS57 manifest read names no creation root parameter"; + return false; + } + const auto& parameter = root.pParameters[read.root_parameter]; + if (read.root_address ? parameter.ParameterType != D3D12_ROOT_PARAMETER_TYPE_SRV + : parameter.ParameterType != D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE) { + why = "published MS57 manifest read disagrees with the creation root"; + return false; + } + } + return true; +} + #ifdef X2W_NATIVE_SHADERS void prepare_native_mesh57(Wrapper* pipeline) { @@ -290,7 +430,7 @@ void prepare_native_mesh57(Wrapper* pipeline) return note_mesh57_outcome(Mesh57Outcome::missing_creation_root_or_state); root_blob = it->second; } - constexpr char revision[] = "x2w-startup-mesh-57-3"; + constexpr char revision[] = "x2w-startup-mesh-57-4"; const u64 key = fnv_part(root_blob, fnv_part(ps_bytes, fnv_part(ms_bytes, fnv_bytes(revision, sizeof(revision) - 1)))); const auto normalized = x2w_startup::normalize_mesh57_descriptor(info->desc); const auto variant = fnv_part(info->state_b, fnv_part(info->state_a, fnv_part(normalized, key))); @@ -394,100 +534,142 @@ void prepare_native_mesh57(Wrapper* pipeline) // This milestone overlaps the terminal counts below. note_mesh57_outcome(Mesh57Outcome::lowering_reached); refusal = Mesh57Outcome::lowering_refused; - auto native = mapped ? x2w::translate_mesh_program(ms, mesh_layout, guest_desc->Desc_1_1) - : x2w::translate_mesh_program(ms, mesh_layout); - const bool mapped_constants = mapped && native.constants.size() == 1 && - native.constants[0].root_parameter == mapping.root_parameter && native.constants[0].count == mapping.count && - native.constants[0].first_sgpr == mapping.sgpr; - if ((mapped ? !mapped_constants : !native.constants.empty()) || (!buffers && !native.bindings.empty()) || !native.samplers.empty() || native.sampler_heap || - (direct_heap ? native.mesh_heap_reads.empty() : !native.mesh_heap_reads.empty())) - throw std::runtime_error("MS needs root or heap bindings"); - // MeshStageLayout::heap_tokens is off here: the token views and cbuffer b1 are not bound yet. - if (native.mesh_heap_tokens) - throw std::runtime_error("MS heap token reads are not bound yet"); - UINT heap_word = UINT_MAX; - for (const auto& guard : native.mesh_heap_reads) { - if (guard.root_parameter != mapping.root_parameter || guard.dword >= mapping.count || guard.mask != 1023 || - (heap_word != UINT_MAX && heap_word != guard.dword)) - throw std::runtime_error("unsupported MS resource heap index contract"); - heap_word = guard.dword; - } std::vector reads; - if (buffers) { - if (native.bindings.empty() || native.bindings.size() > 32) - throw std::runtime_error("unsupported MS buffer binding count"); - for (auto b : native.bindings) { - if (b.shader_register != reads.size() || b.root_parameter >= guest_desc->Desc_1_1.NumParameters || - b.root_parameter >= 16 || !b.required_bytes || b.array_count != 1 || b.array_position) - throw std::runtime_error("unsupported MS buffer register or span"); - const bool direct = b.kind == x2w::ComputeViewKind::root_buffer_srv; - const auto& param = guest_desc->Desc_1_1.pParameters[b.root_parameter]; - if (direct) { - if (param.ParameterType != D3D12_ROOT_PARAMETER_TYPE_SRV || b.byte_offset) - throw std::runtime_error("MS root buffer requires a root SRV"); - } else { - if ((b.kind != x2w::ComputeViewKind::buffer_srv && b.kind != x2w::ComputeViewKind::byte_window_srv && - b.kind != x2w::ComputeViewKind::heap_buffer_srv) || - param.ParameterType != D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE) - throw std::runtime_error("MS table read requires a scalar SRV"); - // Validate this creation root's range even when reflection already classified the slot. - using Table = x2w::ComputeViewBinding::ScalarTable; - if (b.scalar_table != Table::unknown && b.scalar_table != Table::srv) - throw std::runtime_error("MS table binding is not an SRV"); - b.scalar_table = Table::unknown; - x2w::apply_scalar_table_layout(b, param.DescriptorTable); - // A CBV range is read here through its memory as raw dwords, exactly like a - // byte-window SRV: s_buffer_load has no format, filtering or typed element. - // The console also reads descriptors past the last declared range (a table is - // just a heap region); those stay unclassified here and the submission resolves - // the slot's token, refusing anything that is not a buffer SRV or a CBV. - using ScalarTable = x2w::ComputeViewBinding::ScalarTable; - uint64_t declared_slots = 0; - for (UINT r = 0; r < param.DescriptorTable.NumDescriptorRanges; ++r) { - const auto& range = param.DescriptorTable.pDescriptorRanges[r]; - const uint64_t first = range.OffsetInDescriptorsFromTableStart == D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND - ? declared_slots : range.OffsetInDescriptorsFromTableStart; - declared_slots = (std::max)(declared_slots, first + range.NumDescriptors); + std::vector spans; + std::vector samplers; + UINT heap_word = UINT_MAX; + std::vector ms_code, ps_code; + const auto prepare_native = [&] { + auto native = mapped ? x2w::translate_mesh_program(ms, mesh_layout, guest_desc->Desc_1_1) + : x2w::translate_mesh_program(ms, mesh_layout); + const bool mapped_constants = mapped && native.constants.size() == 1 && + native.constants[0].root_parameter == mapping.root_parameter && native.constants[0].count == mapping.count && + native.constants[0].first_sgpr == mapping.sgpr; + if ((mapped ? !mapped_constants : !native.constants.empty()) || (!buffers && !native.bindings.empty()) || !native.samplers.empty() || native.sampler_heap || + (direct_heap ? native.mesh_heap_reads.empty() : !native.mesh_heap_reads.empty())) + throw std::runtime_error("MS needs root or heap bindings"); + // MeshStageLayout::heap_tokens is off here: the token views and cbuffer b1 are not bound yet. + if (native.mesh_heap_tokens) + throw std::runtime_error("MS heap token reads are not bound yet"); + for (const auto& guard : native.mesh_heap_reads) { + if (guard.root_parameter != mapping.root_parameter || guard.dword >= mapping.count || guard.mask != 1023 || + (heap_word != UINT_MAX && heap_word != guard.dword)) + throw std::runtime_error("unsupported MS resource heap index contract"); + heap_word = guard.dword; + } + if (buffers) { + if (native.bindings.empty() || native.bindings.size() > 32) + throw std::runtime_error("unsupported MS buffer binding count"); + for (auto b : native.bindings) { + if (b.shader_register != reads.size() || b.root_parameter >= guest_desc->Desc_1_1.NumParameters || + b.root_parameter >= 16 || !b.required_bytes || b.array_count != 1 || b.array_position) + throw std::runtime_error("unsupported MS buffer register or span"); + const bool direct = b.kind == x2w::ComputeViewKind::root_buffer_srv; + const auto& param = guest_desc->Desc_1_1.pParameters[b.root_parameter]; + if (direct) { + if (param.ParameterType != D3D12_ROOT_PARAMETER_TYPE_SRV || b.byte_offset) + throw std::runtime_error("MS root buffer requires a root SRV"); + } else { + if ((b.kind != x2w::ComputeViewKind::buffer_srv && b.kind != x2w::ComputeViewKind::byte_window_srv && + b.kind != x2w::ComputeViewKind::heap_buffer_srv) || + param.ParameterType != D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE) + throw std::runtime_error("MS table read requires a scalar SRV"); + // Validate this creation root's range even when reflection already classified the slot. + using Table = x2w::ComputeViewBinding::ScalarTable; + if (b.scalar_table != Table::unknown && b.scalar_table != Table::srv) + throw std::runtime_error("MS table binding is not an SRV"); + b.scalar_table = Table::unknown; + x2w::apply_scalar_table_layout(b, param.DescriptorTable); + // A CBV range is read here through its memory as raw dwords, exactly like a + // byte-window SRV: s_buffer_load has no format, filtering or typed element. + // The console also reads descriptors past the last declared range (a table is + // just a heap region); those stay unclassified here and the submission resolves + // the slot's token, refusing anything that is not a buffer SRV or a CBV. + using ScalarTable = x2w::ComputeViewBinding::ScalarTable; + uint64_t declared_slots = 0; + for (UINT r = 0; r < param.DescriptorTable.NumDescriptorRanges; ++r) { + const auto& range = param.DescriptorTable.pDescriptorRanges[r]; + const uint64_t first = range.OffsetInDescriptorsFromTableStart == D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND + ? declared_slots : range.OffsetInDescriptorsFromTableStart; + declared_slots = (std::max)(declared_slots, first + range.NumDescriptors); + } + const bool past_table = b.scalar_table == ScalarTable::unknown && b.byte_offset / 32 >= declared_slots; + if ((b.scalar_table != ScalarTable::srv && b.scalar_table != ScalarTable::declared_cbv && + !past_table) || b.byte_offset % 32) + throw std::runtime_error("MS buffer slot outside a verified SRV range"); } - const bool past_table = b.scalar_table == ScalarTable::unknown && b.byte_offset / 32 >= declared_slots; - if ((b.scalar_table != ScalarTable::srv && b.scalar_table != ScalarTable::declared_cbv && - !past_table) || b.byte_offset % 32) - throw std::runtime_error("MS buffer slot outside a verified SRV range"); + reads.push_back({b.root_parameter, b.byte_offset, b.required_bytes, direct}); + } + } + std::string ps_ir; + if (varying_pixel) { + auto pixel = x2w::translate_mesh_pixel_program(ps, entry.enable, entry.address, entry.wave_size, pixel_heap ? &guest_desc->Desc_1_1 : nullptr); + if (pixel_heap) { + if (pixel.pixel_heap_spans.empty()) throw std::runtime_error("missing PS texture heap reads"); + spans=std::move(pixel.pixel_heap_spans); + for (const auto& c:pixel.constants) + if (c.root_parameter!=mapping.root_parameter || c.count!=mapping.count) + throw std::runtime_error("PS constants differ from the bound MS constant block"); + for (const auto& s:pixel.samplers) + samplers.push_back(x2w_startup::decode_sampler(s.words,static_cast(samplers.size()),s.comparison,s.explicit_lod)); } - reads.push_back({b.root_parameter, b.byte_offset, b.required_bytes, direct}); + if ((!pixel_heap && (!pixel.constants.empty() || !pixel.samplers.empty())) || !pixel.bindings.empty() || pixel.sampler_heap) + throw std::runtime_error("PS needs root or heap bindings"); + x2w::validate_raster_link(native, pixel); + ps_ir = std::move(pixel.dxil_ir); + } else { + ps_ir = x2w::direct_gfx1013_constant_pixel(ps); } + refusal = Mesh57Outcome::pipeline_refused; + auto compiler = x2w::ShaderDxilCompiler::runtime_worker(sdk); + const auto cache = std::filesystem::path(path).parent_path(); + const auto ms_output = compiler.compile(native.dxil_ir, L"ms_6_6", cache, x2w::ShaderSourceFormat::dxil_ir); + const auto ps_output = + compiler.compile(ps_ir, L"ps_6_6", cache, x2w::ShaderSourceFormat::dxil_ir); + ms_code.assign(ms_output.dxil.begin(), ms_output.dxil.end()); + ps_code.assign(ps_output.dxil.begin(), ps_output.dxil.end()); + }; + bool published = false; + std::string native_refusal; + try { + prepare_native(); + } catch (const x2w::UnsupportedComputeShader& error) { + if (!is_mesh57_group_index_refusal(error) || !allow_published_mesh57_pair()) throw; + if (!buffers || direct_heap) + throw std::runtime_error("published MS57 pair does not describe this profile"); + native_refusal = error.what(); + published = true; } - std::string ps_ir; - std::vector spans; - std::vector samplers; - if (varying_pixel) { - auto pixel = x2w::translate_mesh_pixel_program(ps, entry.enable, entry.address, entry.wave_size, pixel_heap ? &guest_desc->Desc_1_1 : nullptr); - if (pixel_heap) { - if (pixel.pixel_heap_spans.empty()) throw std::runtime_error("missing PS texture heap reads"); - spans=std::move(pixel.pixel_heap_spans); - for (const auto& c:pixel.constants) - if (c.root_parameter!=mapping.root_parameter || c.count!=mapping.count) - throw std::runtime_error("PS constants differ from the bound MS constant block"); - for (const auto& s:pixel.samplers) - samplers.push_back(x2w_startup::decode_sampler(s.words,static_cast(samplers.size()),s.comparison,s.explicit_lod)); + if (published) { + // The native mesh frontend does not cover every fixed group-index exchange. The + // publisher compiled the same source pair; use it with the reviewed profile state + // and the manifest's register order, table offsets and accessed spans. + refusal = Mesh57Outcome::pipeline_refused; + std::string reason; + if (!read_published_mesh57_manifest(key, guest_desc->Desc_1_1, view_entries, mapping.root_parameter, + mapping.count, reads, reason)) { + if (reason == "published MS57 manifest is absent") { + // With no published pair the native refusal is the result, as before. + refusal = Mesh57Outcome::lowering_refused; + throw x2w::UnsupportedComputeShader(native_refusal); + } + throw std::runtime_error(reason); } - if ((!pixel_heap && (!pixel.constants.empty() || !pixel.samplers.empty())) || !pixel.bindings.empty() || pixel.sampler_heap) - throw std::runtime_error("PS needs root or heap bindings"); - x2w::validate_raster_link(native, pixel); - ps_ir = std::move(pixel.dxil_ir); - } else { - ps_ir = x2w::direct_gfx1013_constant_pixel(ps); + const auto read_cso = [&](const wchar_t* extension, std::vector& out) { + wchar_t cso[MAX_PATH]; + if (!cache_path(cso, L"", key, extension)) return false; + std::ifstream file(std::filesystem::path(cso), std::ios::binary); + if (!file) return false; + out.assign(std::istreambuf_iterator(file), {}); + return !out.empty(); + }; + if (!read_cso(L".ms57.cso", ms_code) || !read_cso(L".ps57.cso", ps_code)) + throw std::runtime_error("published MS57 pair is incomplete"); } - refusal = Mesh57Outcome::pipeline_refused; - auto compiler = x2w::ShaderDxilCompiler::runtime_worker(sdk); - const auto cache = std::filesystem::path(path).parent_path(); - const auto ms_output = compiler.compile(native.dxil_ir, L"ms_6_6", cache, x2w::ShaderSourceFormat::dxil_ir); - const auto ps_output = - compiler.compile(ps_ir, L"ps_6_6", cache, x2w::ShaderSourceFormat::dxil_ir); x2w::meshlet::MeshOnlyPipelineStream stream{}; stream.root_signature.value = reinterpret_cast(root); - stream.ms.value = {ms_output.dxil.data(), ms_output.dxil.size()}; - stream.ps.value = {ps_output.dxil.data(), ps_output.dxil.size()}; + stream.ms.value = {ms_code.data(), ms_code.size()}; + stream.ps.value = {ps_code.data(), ps_code.size()}; stream.blend.value = profile.blend; stream.sample_mask.value = profile.sample_mask; stream.rasterizer.value = profile.rasterizer; diff --git a/tests/cmake/startup_mesh57_runtime.cmake b/tests/cmake/startup_mesh57_runtime.cmake new file mode 100644 index 0000000000..132636157a --- /dev/null +++ b/tests/cmake/startup_mesh57_runtime.cmake @@ -0,0 +1,14 @@ +# Slot 57 runtime acceptance (#3094 loader path): the consumer creates a fixed slot 57 pipeline from a mesh and +# pixel request, an earlier GPU compute dispatch writes the DispatchMesh arguments, and the draw reads that record, +# waits on a fence and renders 1024 pixels compared with the CPU rasteriser. Missing and truncated mesh or pixel +# bytecode must each leave the target cleared. The same published pair must keep the native refusal without +# X2W_ALLOW_PUBLISHED_MESH57_PAIR and draw only with that explicit opt-in. The publisher half reuses the mesh +# request exchange fixture. +if(EXISTS "${INTAKE_PYTHON}" AND TARGET startup_indirect_draw_indexed) + foreach(adapter IN ITEMS warp hardware) + add_test(NAME startup_mesh57_runtime_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_mesh57_runtime_check.py" + "$" "${DXC_EXECUTABLE}" ${adapter}) + set_tests_properties(startup_mesh57_runtime_${adapter} PROPERTIES TIMEOUT 180 SKIP_RETURN_CODE 77) + endforeach() +endif() diff --git a/tests/native_compile_dxil_rekey_check.py b/tests/native_compile_dxil_rekey_check.py index 390540d99d..02f15b4764 100644 --- a/tests/native_compile_dxil_rekey_check.py +++ b/tests/native_compile_dxil_rekey_check.py @@ -88,7 +88,7 @@ def check_revision_strings(): cpp_req = (ROOT / 'src' / 'shader_compute_request.cpp').read_text(encoding='utf-8') draw_inl = (ROOT / 'src' / 'startup_stubs' / 'd3d12_draw.inl').read_text(encoding='utf-8') py_text = (STARTUP / 'gfx2hlsl.py').read_text(encoding='utf-8') - for token in ('x2w-startup-shader-29', 'x2w-startup-shader-29cs', 'x2w-startup-mesh-57-3'): + for token in ('x2w-startup-shader-29', 'x2w-startup-shader-29cs', 'x2w-startup-mesh-57-4'): ok = (token in cpp_req) and (token in draw_inl) and (token in py_text) check('revision string %s matches across C++ and Python' % token, ok) diff --git a/tests/patch_manifest_check.py b/tests/patch_manifest_check.py index 75708a40bb..a7326db931 100644 --- a/tests/patch_manifest_check.py +++ b/tests/patch_manifest_check.py @@ -225,8 +225,8 @@ def test_shader_patches(self): ok + shader_patch(revision="x2w-startup-shader-12"), "s002 revision 'x2w-startup-shader-12cs' is not a graphics key revision (x2w-startup-shader-)": ok + shader_patch("s002", pipeline="graphics", revision="x2w-startup-shader-12cs"), - "revision 'x2w-startup-mesh-57-3' is not a mesh86 key revision (x2w-startup-mesh-86-)": - ok + shader_patch(pipeline="mesh86", revision="x2w-startup-mesh-57-3"), + "revision 'x2w-startup-mesh-57-4' is not a mesh86 key revision (x2w-startup-mesh-86-)": + ok + shader_patch(pipeline="mesh86", revision="x2w-startup-mesh-57-4"), "revision 'x2w-startup-shader-cs' is not a compute": ok + shader_patch(revision="x2w-startup-shader-cs"), "revision 'x2w-startup-shader-012cs' is not a compute": ok + shader_patch(revision="x2w-startup-shader-012cs"), diff --git a/tests/startup_indirect_draw_indexed.cpp b/tests/startup_indirect_draw_indexed.cpp index 697b33a37d..a6bfc97275 100644 --- a/tests/startup_indirect_draw_indexed.cpp +++ b/tests/startup_indirect_draw_indexed.cpp @@ -2509,6 +2509,7 @@ bool fixed_mesh_create_contract(ID3D12Device* guest) return true; } #include "startup_indirect_mesh_lease.inl" +#include "startup_mesh57_runtime.inl" } // namespace static int native_fixed_mesh_fixture(ID3D12Device* device, ID3D12Device* guest, ID3D12RootSignature* writer, @@ -2666,13 +2667,25 @@ static int native_fixed_mesh_fixture(ID3D12Device* device, ID3D12Device* guest, key = (key ^ p[i]) * 1099511628211ull; return key; }; - const char revision[] = "x2w-startup-mesh-57-3"; + const char revision[] = "x2w-startup-mesh-57-4"; auto key = fold(1469598103934665603ull, revision, sizeof(revision) - 1); const auto extend = [&](UINT64 base, const void* data, UINT64 n) { return fold(fold(base, &n, sizeof(n)), data, n); }; const auto part = [&](const void* data, UINT64 n) { key = extend(key,data,n); }; part(ms.data(), ms_size); part(ps.data(), ps_size); part(blob->GetBufferPointer(), blob->GetBufferSize()); + // A native-translatable profile with a published pair beside it must still translate + // natively. The pair is deliberately unusable, so choosing it fails the pipeline create. + if (GetEnvironmentVariableA("X2W_TEST_NATIVE_MESH57_PUBLISHED_PAIR", nullptr, 0)) { + char pair[64]; + for (const char* extension : {".ms57.cso", ".ps57.cso", ".ms57.txt"}) { + std::snprintf(pair, sizeof(pair), "%016llx%s", key, extension); + std::ofstream file(cache / pair, std::ios::binary); + const char* contents = std::strcmp(extension, ".ms57.txt") ? "not a shader" : "x2w-manifest 1\nstage ms\n"; + file.write(contents, static_cast(std::strlen(contents))); + if (!file) return 1; + } + } char name[64]; const auto variant = [&] { return extend(extend(extend(key,fields,sizeof(fields)),state_a.data(),sizeof(state_a)),state_b.data(),sizeof(state_b)); @@ -3072,6 +3085,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 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; const bool copy_off = argc == 3 && std::strcmp(argv[2], "copy-provenance-off") == 0; @@ -3111,7 +3125,7 @@ int main(int argc, char** argv) try const bool count_control = argc == 3 && std::strcmp(argv[2], "count-control") == 0; if ((translated && !translated_indexed) || (argc == 3 && std::strcmp(argv[2], "draw") == 0)) kind = DrawKind::vertices; else if (argc == 3 && std::strcmp(argv[2], "rect") == 0) kind = DrawKind::rect; - else if (lease_arguments || console_mesh || desktop_as || (argc == 3 && std::strcmp(argv[2], "mesh") == 0)) + else if (lease_arguments || console_mesh || desktop_as || 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) @@ -3150,7 +3164,7 @@ int main(int argc, char** argv) try wchar_t directory[MAX_PATH]; if (!GetTempPathW(MAX_PATH, directory)) return 4; const std::wstring log_path = std::wstring(directory) + L"x2w_indirect_counts_" + std::to_wstring(GetCurrentProcessId()) + L".log"; - if (indexed || lease_arguments || dual_lease || loose_root || refusal_census || other_refusal_census) { + if (indexed || lease_arguments || dual_lease || loose_root || refusal_census || other_refusal_census || runtime_mesh57) { DeleteFileW(log_path.c_str()); SetEnvironmentVariableW(L"X2W_TRAP_LOG", log_path.c_str()); SetEnvironmentVariableA("X2W_PRESENT_SIGNATURE_EVERY", "0"); @@ -3198,6 +3212,14 @@ int main(int argc, char** argv) try const auto root_flags = mesh ? D3D12_ROOT_SIGNATURE_FLAG_NONE : D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT; const D3D12_ROOT_SIGNATURE_DESC graphics_desc{0, nullptr, 0, nullptr, root_flags}; const auto writer = create_root(device.Get(), writer_desc); + if (runtime_mesh57) { + wchar_t directory[MAX_PATH]{}; + const DWORD size = GetEnvironmentVariableW(L"X2W_TEST_MESH57_EXCHANGE", directory, MAX_PATH); + check(size && size < MAX_PATH ? S_OK : E_FAIL, "get slot 57 fixture directory"); + const bool ok = run_mesh57_runtime(device.Get(), guest.Get(), writer.Get(), directory, log_path); + check_lease_debug(info.Get(), "size doesn't match specified size"); + return ok ? 0 : 1; + } if (mesh && GetEnvironmentVariableA("X2W_TEST_NATIVE_MESH57", nullptr, 0)) return native_fixed_mesh_fixture(device.Get(), guest.Get(), writer.Get(), log_path); wchar_t mesh86_dir[MAX_PATH]{}; @@ -3437,7 +3459,8 @@ int main(int argc, char** argv) try params[0].Constants = {0, 0, 2}; params[1].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; params[1].DescriptorTable = {1, &srv}; - const D3D12_ROOT_SIGNATURE_DESC source_root{2, params, 0, nullptr, D3D12_ROOT_SIGNATURE_FLAG_NONE}; + const D3D12_ROOT_SIGNATURE_DESC source_root{2, params, 0, nullptr, + D3D12_ROOT_SIGNATURE_FLAG_CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED}; const auto& desc = exchange_size ? source_root : graphics_desc; ComPtr root_blob; const auto root = create_root(guest.Get(), desc, &root_blob); diff --git a/tests/startup_indirect_mesh_lease.inl b/tests/startup_indirect_mesh_lease.inl index 0c4baaa5ed..c1dbdcadda 100644 --- a/tests/startup_indirect_mesh_lease.inl +++ b/tests/startup_indirect_mesh_lease.inl @@ -290,7 +290,7 @@ bool supports_lease_heap(ID3D12Device* device) return SUCCEEDED(check_feature(device, D3D12_FEATURE_EXISTING_HEAPS, &support, sizeof(support))) && support.Supported; } -void check_lease_debug(ID3D12InfoQueue* info) +void check_lease_debug(ID3D12InfoQueue* info, const char* allow = nullptr) { if (!info) return; for (UINT64 i = 0; i < info->GetNumStoredMessages(); ++i) { @@ -300,6 +300,10 @@ void check_lease_debug(ID3D12InfoQueue* info) auto* message = reinterpret_cast(storage.data()); check(info->GetMessage(i, message, &bytes), "read D3D12 debug message"); if (message->Severity <= D3D12_MESSAGE_SEVERITY_WARNING) { + // The slot 57 runtime fixture truncates a published CSO on purpose; the debug layer + // reports the resulting CreateMeshShader/CreatePixelShader size mismatch even though + // the runtime refuses the pair cleanly. + if (allow && std::strstr(message->pDescription, allow)) continue; std::fprintf(stderr, "%s\n", message->pDescription); check(E_FAIL, "D3D12 debug layer reported a warning or error"); } diff --git a/tests/startup_mesh57_runtime.inl b/tests/startup_mesh57_runtime.inl new file mode 100644 index 0000000000..cf0d3533d6 --- /dev/null +++ b/tests/startup_mesh57_runtime.inl @@ -0,0 +1,274 @@ +// The request publisher writes the exact creation blob it compiled the pair against. Create the guest +// root from those bytes so the loader keys the pipeline and the published CSOs identically. +ComPtr mesh57_published_root(ID3D12Device* guest, const std::vector& blob) +{ + ComPtr root; + check(guest->CreateRootSignature(0, blob.data(), blob.size(), IID_PPV_ARGS(&root)), + "create slot 57 root from the published blob"); + return root; +} + +std::uint64_t mesh57_fold(std::uint64_t key, const void* data, std::size_t bytes) +{ + const auto* p = static_cast(data); + for (std::size_t i = 0; i < bytes; ++i) key = (key ^ p[i]) * 1099511628211ull; + return key; +} + +std::uint64_t mesh57_extend(std::uint64_t key, const void* data, std::uint64_t bytes) +{ + return mesh57_fold(mesh57_fold(key, &bytes, sizeof(bytes)), data, static_cast(bytes)); +} + +// Write the reviewed source-built profile the runtime loader needs beside the request. The +// fixture has no state blocks and one table at s16 (root parameter 1). +void write_mesh57_profile(const std::filesystem::path& cache, const std::array& fields, + const std::vector& root_blob, const std::vector& ms, const std::vector& ps) +{ + std::vector raw(reinterpret_cast(fields.data()), + reinterpret_cast(fields.data()) + sizeof(fields)); + auto normalized = x2w_startup::normalize_mesh57_descriptor(std::move(raw)); + const char revision[] = "x2w-startup-mesh-57-4"; + std::uint64_t key = mesh57_fold(1469598103934665603ull, revision, sizeof(revision) - 1); + key = mesh57_extend(key, ms.data(), ms.size()); + key = mesh57_extend(key, ps.data(), ps.size()); + key = mesh57_extend(key, root_blob.data(), root_blob.size()); + std::uint64_t variant = mesh57_extend(key, normalized.data(), normalized.size()); + variant = mesh57_extend(variant, nullptr, 0); // state block A + variant = mesh57_extend(variant, nullptr, 0); // state block B + + x2w_startup::Mesh57Profile profile{}; + std::memcpy(profile.magic, "X2WM574", 8); + profile.lengths[0] = static_cast(normalized.size()); + profile.lengths[1] = 0; + profile.lengths[2] = 0; + profile.lengths[3] = static_cast(root_blob.size()); + profile.lengths[4] = static_cast(ms.size()); + profile.lengths[5] = static_cast(ps.size()); + profile.threads = 64; + profile.vertices = 3; + profile.primitives = 1; + profile.topology = 2; + profile.group_stride = 64; + profile.wave_size = 64; + profile.targets.NumRenderTargets = 1; + profile.targets.RTFormats[0] = DXGI_FORMAT_R8G8B8A8_UNORM; + profile.samples.Count = 1; + profile.samples.Quality = 0; + profile.sample_mask = UINT_MAX; + profile.rasterizer.FillMode = D3D12_FILL_MODE_SOLID; + profile.rasterizer.CullMode = D3D12_CULL_MODE_NONE; + profile.rasterizer.DepthClipEnable = TRUE; + auto& blend = profile.blend.RenderTarget[0]; + blend.SrcBlend = blend.SrcBlendAlpha = D3D12_BLEND_ONE; + blend.DestBlend = blend.DestBlendAlpha = D3D12_BLEND_ZERO; + blend.BlendOp = blend.BlendOpAlpha = D3D12_BLEND_OP_ADD; + blend.LogicOp = D3D12_LOGIC_OP_NOOP; + blend.RenderTargetWriteMask = D3D12_COLOR_WRITE_ENABLE_ALL; + profile.depth.DepthFunc = D3D12_COMPARISON_FUNC_ALWAYS; + + std::filesystem::create_directories(cache); + char name[64]{}; + std::snprintf(name, sizeof(name), "%016llx.mesh57-state", static_cast(variant)); + std::ofstream out(cache / name, std::ios::binary); + out.write(reinterpret_cast(&profile), sizeof(profile)); + const x2w_startup::Mesh57PixelEntry entry{0, 0, 64}; + out.write(reinterpret_cast(&entry), sizeof(entry)); + const x2w_startup::Mesh57ConstantEntry mapping{8, 0, 2}; + out.write(reinterpret_cast(&mapping), sizeof(mapping)); + const UINT view_count = 1; + const x2w_startup::Mesh57ViewEntry view{10, 1, 0}; + out.write(reinterpret_cast(&view_count), sizeof(view_count)); + out.write(reinterpret_cast(&view), sizeof(view)); + out.write(reinterpret_cast(normalized.data()), static_cast(normalized.size())); + out.write(reinterpret_cast(root_blob.data()), static_cast(root_blob.size())); + out.write(ms.data(), static_cast(ms.size())); + out.write(ps.data(), static_cast(ps.size())); +} + +bool run_mesh57_runtime(ID3D12Device* device, ID3D12Device* guest, ID3D12RootSignature* writer_root, + const std::filesystem::path& exchange, const std::wstring& log_path) +{ + constexpr UINT side = 32, geometry_size = 512; + const char* scenario = std::getenv("X2W_TEST_MESH57_SCENARIO"); + const bool two_views = scenario && !std::strcmp(scenario, "two-views"); + const bool short_view = scenario && !std::strcmp(scenario, "short-view"); + const auto read = [&](const char* name) { + std::ifstream file(exchange / name, std::ios::binary); + return std::vector(std::istreambuf_iterator(file), {}); + }; + const auto ms = read("ms.bin"), ps = read("ps.bin"), geometry = read("geometry.bin"), root_blob = read("root.bin"); + const auto geometry2 = two_views ? read("geometry2.bin") : std::vector{}; + if (ms.empty() || ps.empty() || root_blob.empty() || geometry.size() != geometry_size || + (two_views && geometry2.size() != geometry_size)) { + std::fputs("slot 57 fixture is missing its shader pair or geometry\n", stderr); + return false; + } + const auto cache = exchange / "requests"; + check(SetEnvironmentVariableW(L"X2W_SHADER_CACHE", cache.c_str()) ? S_OK : E_FAIL, "set slot 57 runtime cache"); + const auto root = mesh57_published_root(guest, root_blob); + std::array fields{}; + fields[0] = reinterpret_cast(root.Get()); + fields[5] = reinterpret_cast(ps.data()); + fields[6] = ps.size(); + fields[13] = reinterpret_cast(ms.data()); + fields[14] = ms.size(); + std::vector root_bytes(root_blob.begin(), root_blob.end()); + write_mesh57_profile(cache, fields, root_bytes, ms, ps); + using Create = HRESULT (WINAPI*)(IUnknown*, const void*, REFIID, void**); + ComPtr pso; + check(slot(guest, 57)(guest, fields.data(), __uuidof(ID3D12PipelineState), + reinterpret_cast(pso.GetAddressOf())), "create fixed slot 57 mesh pipeline"); + const D3D12_INDIRECT_ARGUMENT_DESC argument{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 slot 57 signature"); + + PlacedBuffer arguments(device, guest, static_cast(sizeof(initial)), D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS); + const auto vertex_guest = make_gpu_table_buffer(guest, geometry_size); + const auto vertex = native_object(device, guest, vertex_guest.Get()); + ComPtr colour_guest, colour; + if (two_views) { + colour_guest = make_gpu_table_buffer(guest, geometry_size); + colour = native_object(device, guest, colour_guest.Get()); + } + const auto upload = make_buffer(device, sizeof(initial) + (two_views ? 2u : 1u) * geometry_size, D3D12_HEAP_TYPE_UPLOAD, + D3D12_RESOURCE_STATE_GENERIC_READ); + const D3D12_RANGE empty{0, 0}; + void* mapped{}; + check(upload->Map(0, &empty, &mapped), "map slot 57 fixture inputs"); + std::memcpy(mapped, initial.data(), sizeof(initial)); + std::memcpy(static_cast(mapped) + sizeof(initial), geometry.data(), geometry.size()); + if (two_views) + std::memcpy(static_cast(mapped) + sizeof(initial) + geometry_size, geometry2.data(), geometry2.size()); + upload->Unmap(0, nullptr); + const auto writer = writer_pipeline(device, writer_root, "write_one_mesh_group"); + ComputeCommands producer(device, writer.Get()); + transition(producer.list.Get(), arguments.native.Get(), D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_COPY_DEST); + transition(producer.list.Get(), vertex.Get(), D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_COPY_DEST); + if (two_views) + transition(producer.list.Get(), colour.Get(), D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_COPY_DEST); + producer.list->CopyBufferRegion(arguments.native.Get(), 0, upload.Get(), 0, sizeof(initial)); + producer.list->CopyBufferRegion(vertex.Get(), 0, upload.Get(), sizeof(initial), geometry.size()); + if (two_views) + producer.list->CopyBufferRegion(colour.Get(), 0, upload.Get(), sizeof(initial) + geometry_size, geometry2.size()); + transition(producer.list.Get(), vertex.Get(), D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_COMMON); + if (two_views) + transition(producer.list.Get(), colour.Get(), D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_COMMON); + transition(producer.list.Get(), arguments.native.Get(), D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); + producer.list->SetComputeRootSignature(writer_root); + producer.list->SetComputeRootUnorderedAccessView(0, arguments.native->GetGPUVirtualAddress()); + producer.list->Dispatch(1, 1, 1); + transition(producer.list.Get(), arguments.native.Get(), D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COMMON); + check(producer.list->Close(), "close slot 57 producer"); + + const struct { + D3D12_DESCRIPTOR_HEAP_DESC desc; + UINT64 backing, bytes; + } table_desc{{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, two_views ? 2u : 1u, D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE}, 0, 0}; + using CreateHeap = HRESULT (WINAPI*)(IUnknown*, const void*, REFIID, void**); + ComPtr table; + check(slot(guest, 14)(guest, &table_desc, __uuidof(ID3D12DescriptorHeap), + reinterpret_cast(table.GetAddressOf())), "create slot 57 table"); + using Handle = UINT64 (WINAPI*)(IUnknown*, void*); + const auto cpu = slot(table.Get(), 9)(table.Get(), nullptr); + const auto gpu = slot(table.Get(), 10)(table.Get(), nullptr); + check(cpu && gpu ? S_OK : E_FAIL, "get slot 57 table handles"); + D3D12_SHADER_RESOURCE_VIEW_DESC srv{DXGI_FORMAT_R32_TYPELESS, D3D12_SRV_DIMENSION_BUFFER, + D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING}; + srv.Buffer.NumElements = short_view ? 1 : geometry_size / sizeof(UINT); + srv.Buffer.Flags = D3D12_BUFFER_SRV_FLAG_RAW; + using View = void (WINAPI*)(IUnknown*, ID3D12Resource*, const D3D12_SHADER_RESOURCE_VIEW_DESC*, UINT64, UINT64); + slot(guest, 18)(guest, vertex_guest.Get(), &srv, cpu, 0); + if (two_views) + slot(guest, 18)(guest, colour_guest.Get(), &srv, cpu + 32, 0); + + const D3D12_RESOURCE_DESC desc{D3D12_RESOURCE_DIMENSION_TEXTURE2D, 0, side, side, 1, 1, format, {1, 0}, + D3D12_TEXTURE_LAYOUT_UNKNOWN, D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET}; + constexpr float clear[]{0, 0, 0, 1}; + const D3D12_CLEAR_VALUE clear_value{format, {0, 0, 0, 1}}; + const auto target = resource(device, desc, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_STATE_COMMON, &clear_value); + const D3D12_DESCRIPTOR_HEAP_DESC rtv_desc{D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 1}; + ComPtr rtv_heap; + check(device->CreateDescriptorHeap(&rtv_desc, IID_PPV_ARGS(&rtv_heap)), "create slot 57 RTV heap"); + const auto rtv = rtv_heap->GetCPUDescriptorHandleForHeapStart(); + guest->CreateRenderTargetView(target.Get(), nullptr, rtv); + ComPtr allocator; + check(guest->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator)), "create slot 57 allocator"); + const auto wrapped = begin_guest_list(guest, allocator.Get()); + using Clear = void (WINAPI*)(IUnknown*, SIZE_T, const float*, UINT, const D3D12_RECT*); + using Targets = void (WINAPI*)(IUnknown*, UINT, const D3D12_CPU_DESCRIPTOR_HANDLE*, BOOL, const D3D12_CPU_DESCRIPTOR_HANDLE*); + using Bind = void (WINAPI*)(IUnknown*, IUnknown*); + using Constants = void (WINAPI*)(IUnknown*, UINT, UINT, const UINT*, UINT); + using Heaps = void (WINAPI*)(IUnknown*, UINT, ID3D12DescriptorHeap* const*); + using Table = void (WINAPI*)(IUnknown*, UINT, UINT64); + using Viewport = void (WINAPI*)(IUnknown*, UINT, const D3D12_VIEWPORT*); + using Scissor = void (WINAPI*)(IUnknown*, UINT, const D3D12_RECT*); + using Execute = void (WINAPI*)(IUnknown*, IUnknown*, UINT, IUnknown*, UINT64, IUnknown*, UINT64); + const D3D12_VIEWPORT viewport{0, 0, side, side, 0, 1}; + const D3D12_RECT scissor{0, 0, side, side}; + const UINT counts[]{4, 12}; + ID3D12DescriptorHeap* heaps[]{table.Get()}; + slot(wrapped.Get(), 52)(wrapped.Get(), rtv.ptr, clear, 0, nullptr); + slot(wrapped.Get(), 50)(wrapped.Get(), 1, &rtv, FALSE, nullptr); + slot(wrapped.Get(), 25)(wrapped.Get(), pso.Get()); + slot(wrapped.Get(), 34)(wrapped.Get(), root.Get()); + slot(wrapped.Get(), 40)(wrapped.Get(), 0, 2, counts, 0); + slot(wrapped.Get(), 32)(wrapped.Get(), 1, heaps); + slot(wrapped.Get(), 36)(wrapped.Get(), 1, gpu); + slot(wrapped.Get(), 21)(wrapped.Get(), 1, &viewport); + slot(wrapped.Get(), 22)(wrapped.Get(), 1, &scissor); + slot(wrapped.Get(), 61)(wrapped.Get(), signature.Get(), 1, arguments.wrapped.Get(), argument_offset, nullptr, 0); + check(slot(wrapped.Get(), 9)(wrapped.Get()), "close slot 57 consumer"); + + const D3D12_COMMAND_QUEUE_DESC queue_desc{}; + ComPtr queue; + check(guest->CreateCommandQueue(&queue_desc, IID_PPV_ARGS(&queue)), "create slot 57 DIRECT queue"); + const auto desktop_queue = native_object(device, guest, queue.Get()); + ComPtr produced, consumed; + check(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&produced)), "create slot 57 producer fence"); + check(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&consumed)), "create slot 57 consumer fence"); + ID3D12CommandList* lists[]{producer.list.Get()}; + producer.queue->ExecuteCommandLists(1, lists); + check(producer.queue->Signal(produced.Get(), 1), "signal slot 57 producer fence"); + check(desktop_queue->Wait(produced.Get(), 1), "wait for slot 57 producer on DIRECT queue"); + submit_wrapped(queue.Get(), wrapped.Get()); + check(desktop_queue->Signal(consumed.Get(), 1), "signal slot 57 consumer fence"); + check(mesh_fence_reached(consumed.Get(), 5000) ? S_OK : E_FAIL, "wait for slot 57 consumer"); + + D3D12_PLACED_SUBRESOURCE_FOOTPRINT footprint{}; + UINT64 bytes{}; + device->GetCopyableFootprints(&desc, 0, 1, 0, &footprint, nullptr, nullptr, &bytes); + const auto pixels = make_buffer(device, bytes, D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_STATE_COPY_DEST); + const auto record = make_buffer(device, sizeof(initial), D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_STATE_COPY_DEST); + ComputeCommands copy(device, nullptr, D3D12_COMMAND_LIST_TYPE_DIRECT); + transition(copy.list.Get(), target.Get(), D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_COPY_SOURCE); + const D3D12_TEXTURE_COPY_LOCATION src{target.Get(), D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, {}}; + D3D12_TEXTURE_COPY_LOCATION dst{pixels.Get(), D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, {}}; + dst.PlacedFootprint = footprint; + copy.list->CopyTextureRegion(&dst, 0, 0, 0, &src, nullptr); + copy.list->CopyBufferRegion(record.Get(), 0, arguments.native.Get(), 0, sizeof(initial)); + copy.submit_and_wait(device); + const D3D12_RANGE record_range{0, sizeof(initial)}; + check(record->Map(0, &record_range, &mapped), "map slot 57 argument guards"); + Words observed{}; + std::memcpy(observed.data(), mapped, sizeof(observed)); + record->Unmap(0, &empty); + Words expected = initial; + expected[1] = expected[2] = expected[3] = 1; + if (observed != expected) { + std::fputs("slot 57 GPU DispatchMesh record or guard changed\n", stderr); + return false; + } + const D3D12_RANGE pixels_range{0, static_cast(bytes)}; + check(pixels->Map(0, &pixels_range, &mapped), "map slot 57 color readback"); + std::ofstream output(exchange / "pixels.bin", std::ios::binary); + for (UINT y = 0; y < side; ++y) + output.write(static_cast(mapped) + y * footprint.Footprint.RowPitch, side * sizeof(UINT)); + pixels->Unmap(0, &empty); + output.close(); + const auto census = render_totals_line(guest, log_path, "x2w-render indirect:"); + std::puts(census.c_str()); + DeleteFileW(log_path.c_str()); + return output && !census.empty(); +} diff --git a/tests/startup_mesh57_runtime_check.py b/tests/startup_mesh57_runtime_check.py new file mode 100644 index 0000000000..d7b1f60195 --- /dev/null +++ b/tests/startup_mesh57_runtime_check.py @@ -0,0 +1,212 @@ +"""Verify the fixed slot-57 runtime path with the source-built mesh pair and CPU rasterizer.""" + +import argparse +import os +from pathlib import Path +import re +import subprocess +import tempfile + +import startup_mesh57_skeleton_check as fixture + + +def run_case(directory, consumer, adapter, label, expected, forwarded, scenario=None, stderr_contains=None, + allow_published=False): + output = directory / "pixels.bin" + output.unlink(missing_ok=True) + env = os.environ.copy() + env["X2W_TEST_MESH57_EXCHANGE"] = str(directory) + env.pop("X2W_TEST_MESH57_SCENARIO", None) + env.pop("X2W_ALLOW_PUBLISHED_MESH57_PAIR", None) + # The launchers' default is native-only; name it explicitly so an inherited shell + # setting cannot turn this gate control into the legacy translation route. + env["X2W_NATIVE_SHADERS_ONLY"] = "1" + if allow_published: + env["X2W_ALLOW_PUBLISHED_MESH57_PAIR"] = "1" + if scenario: + env["X2W_TEST_MESH57_SCENARIO"] = scenario + run = subprocess.run([consumer, adapter, "mesh57-runtime"], env=env, capture_output=True, text=True) + if run.returncode == 77: + print(run.stdout, end="") + return 77 + assert not run.returncode, f"{label}: runtime fixture exited {run.returncode}\n{run.stdout}\n{run.stderr}" + if stderr_contains: + assert stderr_contains in run.stderr, f"{label}: missing {stderr_contains!r} in stderr\n{run.stderr}" + actual = output.read_bytes() + assert len(actual) == len(expected), f"{label}: got {len(actual)} bytes, expected {len(expected)}" + census = re.search(r"^x2w-render indirect: forwarded: ([^;]+);", run.stdout, re.MULTILINE) + assert census, f"{label}: missing indirect census\n{run.stdout}" + assert census[1] == ("dispatchmesh 1" if forwarded else "0"), ( + f"{label}: expected {forwarded} forwarded mesh calls, observed {census[1]!r}\n" + f"stdout:\n{run.stdout}\nstderr:\n{run.stderr}" + ) + for index in range(0, len(expected), 4): + if actual[index:index + 4] != expected[index:index + 4]: + y, x = divmod(index // 4, fixture.SIDE) + raise AssertionError( + f"{label}: pixel ({x}, {y}) expected {expected[index:index + 4].hex()}, " + f"got {actual[index:index + 4].hex()}" + ) + print(f"{label}: {len(expected) // 4} pixels matched, {forwarded} forwarded mesh calls, argument guards intact") + return 0 + + +def publish(directory, consumer, adapter, mesh=fixture.MESH_R1): + directory.mkdir(parents=True, exist_ok=True) + status, published = fixture.publish_request(directory, consumer, adapter, mesh=mesh) + if status: + return status, None + cache, key, _ = published + result = fixture.G.translate_request(str(cache), key) + assert result == "ok", result + (directory / "root.bin").write_bytes((cache / f"req_{key:016x}.root").read_bytes()) + (directory / "ms.bin").write_bytes(fixture.code(mesh)) + (directory / "ps.bin").write_bytes(fixture.code(fixture.PIXEL)) + return 0, (cache, key) + + +def check(directory, consumer, adapter): + points, colours, indices = fixture.geometry() + words = [a | b << 10 | c << 20 for a, b, c in indices] + clear = bytes((0, 0, 0, 255)) * (fixture.SIDE * fixture.SIDE) + pixels = b"".join(bytes(pixel) for pixel in fixture.rasterise(points, colours, indices, 12, 4)) + assert pixels != clear + + one = directory / "one" + status, published = publish(one, consumer, adapter) + if status: + return status + cache, key = published + (one / "geometry.bin").write_bytes(fixture.buffer(points, colours, words)) + pair = {extension: (cache / f"{key:016x}{extension}").read_bytes() + for extension in (".ms57.cso", ".ps57.cso", ".ms57.txt")} + + # The same pair on disk must not be read in the default native-only mode, even + # though the publisher's manifest is complete beside the request. + status = run_case(one, consumer, adapter, "published pair without opt-in", clear, 0, + stderr_contains="mesh group-index exchange shape or entry state is not covered") + if status: + return status + status = run_case(one, consumer, adapter, "published pair with opt-in", pixels, 1, + allow_published=True) + if status: + return status + for extension, bytecode in pair.items(): + assert (cache / f"{key:016x}{extension}").read_bytes() == bytecode, ( + f"published pair changed during the gate control: {extension}") + + for stage in ("ms", "ps"): + artifact = cache / f"{key:016x}.{stage}57.cso" + bytecode = artifact.read_bytes() + try: + artifact.unlink() + status = run_case(one, consumer, adapter, f"missing {stage}", clear, 0, allow_published=True) + if status: + return status + artifact.write_bytes(bytecode[:-1]) + status = run_case(one, consumer, adapter, f"truncated {stage}", clear, 0, allow_published=True) + if status: + return status + finally: + artifact.write_bytes(bytecode) + status = run_case(one, consumer, adapter, "compiled pair restored", pixels, 1, allow_published=True) + if status: + return status + + # Without a published pair the native R1 refusal remains the result. + absent = directory / "absent" + status, published = publish(absent, consumer, adapter) + if status: + return status + cache, key = published + (absent / "geometry.bin").write_bytes(fixture.buffer(points, colours, words)) + for extension in (".ms57.cso", ".ps57.cso", ".ms57.txt"): + (cache / f"{key:016x}{extension}").unlink(missing_ok=True) + status = run_case(absent, consumer, adapter, "no published pair", clear, 0, allow_published=True, + stderr_contains="mesh group-index exchange shape or entry state is not covered") + if status: + return status + + # The manifest's span is 388 bytes. A four-byte view must be refused at draw time. + short = directory / "short" + status, published = publish(short, consumer, adapter) + if status: + return status + (short / "geometry.bin").write_bytes(fixture.buffer(points, colours, words)) + status = run_case(short, consumer, adapter, "short view", clear, 0, "short-view", allow_published=True) + if status: + return status + + # A version 1 manifest is an older publisher result: its reads carry no span. + old = directory / "old" + status, published = publish(old, consumer, adapter) + if status: + return status + cache, key = published + (old / "geometry.bin").write_bytes(fixture.buffer(points, colours, words)) + (cache / f"{key:016x}.ms57.txt").write_text("x2w-manifest 1\nstage ms\n") + status = run_case(old, consumer, adapter, "old revision manifest", clear, 0, allow_published=True, + stderr_contains="published MS57 manifest is not a version 4 mesh manifest") + if status: + return status + + # A manifest that sources the entry constants from another root parameter would feed the + # wrong words into b0: the draw fills it from the profile's constant parameter only. + foreign = directory / "foreign" + status, published = publish(foreign, consumer, adapter) + if status: + return status + cache, key = published + (foreign / "geometry.bin").write_bytes(fixture.buffer(points, colours, words)) + manifest = cache / f"{key:016x}.ms57.txt" + text = manifest.read_text(encoding="utf-8") + match = re.search(r"^udsrc 0 rootconst (\d+) 0$", text, re.MULTILINE) + assert match, text + other = "1" if match[1] != "1" else "0" + manifest.write_text(text[:match.start()] + f"udsrc 0 rootconst {other} 0" + text[match.end():], + encoding="utf-8") + status = run_case(foreign, consumer, adapter, "foreign constant", clear, 0, allow_published=True, + stderr_contains="published MS57 manifest constant layout differs from the profile") + if status: + return status + + # Two table entries: positions and indices come from descriptor 0, colours from + # descriptor 1 at byte offset 32. The first buffer's colours are red, so aliasing + # either read to the first record changes the image. + two = directory / "two" + status, published = publish(two, consumer, adapter, fixture.MESH_TWO_BUFFERS_R1) + if status: + return status + (two / "geometry.bin").write_bytes(fixture.buffer(points, [(255, 0, 0, 255)] * len(points), words)) + (two / "geometry2.bin").write_bytes(fixture.buffer(points, colours, words)) + if adapter == "warp": + # The CI WARP build (10.0.26100.33648) faults with exit code 2173 when the runtime + # writes the second descriptor's view token; the same fixture passes on the local + # WARP build and on the RX 9060 XT, which keep this coverage. + print("two table entries: skipped on WARP (descriptor write fault in the CI WARP build)") + else: + status = run_case(two, consumer, adapter, "two table entries", pixels, 1, "two-views", + allow_published=True) + if status: + return status + return 0 + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("consumer", type=Path) + parser.add_argument("dxc") + parser.add_argument("adapter", choices=("warp", "hardware")) + args = parser.parse_args() + dxc_dir = Path(args.dxc) + if dxc_dir.is_file(): + dxc_dir = dxc_dir.parent + os.environ["X2W_DXC"] = str(dxc_dir) + os.environ["X2W_NATIVE_SHADERS"] = str(dxc_dir) + os.environ.pop("X2W_FXC", None) + with tempfile.TemporaryDirectory(prefix="mesh57-live-") as work: + return check(Path(work), args.consumer.resolve(), args.adapter) + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tests/startup_mesh57_skeleton_check.py b/tests/startup_mesh57_skeleton_check.py index 1b25d7a85b..cfa21a4423 100644 --- a/tests/startup_mesh57_skeleton_check.py +++ b/tests/startup_mesh57_skeleton_check.py @@ -59,6 +59,23 @@ PIXEL_ASM = ('v_interp_mov_f32 v0, p0, attr0.x\nv_interp_mov_f32 v1, p0, attr0.y\nv_interp_mov_f32 v2, p0, attr0.z\n' 'v_interp_mov_f32 v3, p0, attr0.w\nexp mrt0 v0, v1, v2, v3 done vm\ns_endpgm\n') PIXEL = 'c8020002 c8060102 c80a0202 c80e0302 f800180f 03020100 bf810000'.split() +# The same body with two table descriptors: positions and indices come from descriptor 0, +# colours from descriptor 1 at byte offset 32. A runtime that aliases both reads to the first +# record renders the first buffer's colour words instead. +MESH_TWO_BUFFERS = ( + 'bfa00003 befe0481 be84047e 8706ff03 0f000000 bf850007 2c0a0a87 7e0c0280 d8340008 00000506' + ' bfa3ffe3 bf8a0000 bf820004 bf8a0000 7e0c0280 d8d80008 05000006 befe04c1 9386ff03 00040018' + ' 8f078606 d7650000 00000ec1 d7660000 000200c1 bf8cc07f 7e180505 f4080405 fa000000 f4080505' + ' fa000020 be8d0308 be8e0309 bf8a0000 bf008006 bf840010 befe0404 bf880007 7e02020d 7e040280' + ' 7e06020e d8340000 00000102 d8340004 00000302 befe04c1 bfa3ffe3 bf8a0000 8f048c0d 887c0e04' + ' bf900009 bf82000d bf8a0000 befe0404 bf880009 7e040280 d8d80000 01000002 d8d80004 03000002' + ' bf8cc17f 7e1a0501 bf8cc07f 7e1c0503 befe04c1 7d28000e 3608008f 34080884 e0381000 80041004' + ' e03810c0 80051404 bf8c3f70 f80008cf 13121110 f800020f 17161514 befe04c1 7d28000d 3608008f' + ' 34080882 e0301180 80041804 bf8c3f70 f8000941 00000018 bf810000').split() +# Defining v3 before the exchange makes the native R1 proof fail, while the publisher's +# mesh_skeleton still accepts the shape. This is the fallback case the runtime must handle. +MESH_R1 = MESH[:1] + ['befe04c1', '7e0a0280'] + MESH[1:] +MESH_TWO_BUFFERS_R1 = MESH_TWO_BUFFERS[:1] + ['befe04c1', '7e0a0280'] + MESH_TWO_BUFFERS[1:] # A depth-only pixel stage: no colour output, only the null-target export (done, vm, no channel). Lanes whose flat # attribute 0 red is not above 0.5 leave EXEC, so the vm export kills them and they write no depth. DEPTH_PIXEL_ASM = ('v_interp_mov_f32 v0, p0, attr0.x\nv_cmpx_lt_f32_e32 0.5, v0\n' @@ -702,7 +719,8 @@ def controls(): manifest = (Path(tmp) / ('%016x.ms57.txt' % key)).read_text().splitlines() expect('formatted mesh reads word 3 from its bound SRV', [s.split()[2:] for s in manifest if s.startswith('udsrc ') and 'descword3' in s], [['descword3', '0']]) - expect('formatted mesh SRV', [s for s in manifest if s.startswith('srv ')], ['srv 0 buf table 1 0']) + expect('formatted mesh SRV', [s for s in manifest if s.startswith('srv ')], + ['srv 0 buf table 1 0 bytes 388']) for what, mesh, reason in REFUSALS: with tempfile.TemporaryDirectory() as tmp: key, result = request(tmp, mesh) @@ -768,6 +786,12 @@ def assemble(mc, text): def binary(mc): mesh = (HERE / 'startup_mesh57_skeleton.s').read_text() expect('mesh words match llvm-mc', assemble(mc, mesh), MESH) + two = (HERE / 'startup_mesh57_two_buffers.s').read_text() + expect('two-buffer mesh words match llvm-mc', assemble(mc, two), MESH_TWO_BUFFERS) + r1 = mesh.replace('s_inst_prefetch 0x3', 's_inst_prefetch 0x3\ns_mov_b64 exec, -1\nv_mov_b32_e32 v5, 0') + expect('R1 entry-state mesh words match llvm-mc', assemble(mc, r1), MESH_R1) + two_r1 = two.replace('s_inst_prefetch 0x3', 's_inst_prefetch 0x3\ns_mov_b64 exec, -1\nv_mov_b32_e32 v5, 0') + expect('two-buffer R1 entry-state words match llvm-mc', assemble(mc, two_r1), MESH_TWO_BUFFERS_R1) expect('formatted mesh words match llvm-mc', assemble(mc, mesh.replace(COLOUR_LOAD, COLOUR_LOAD + '\n' + FORMAT_LOAD)), FORMATTED_MESH) expect('rewritten descriptor words match llvm-mc', @@ -928,8 +952,8 @@ def reference_per_lane(points, colours, triangles, bound, old, wave_red): return rasterise(points, rendered, triangles, 128, len(triangles)) -def publish_request(directory, publisher, adapter): - ms, ps = code(MESH), code(PIXEL) +def publish_request(directory, publisher, adapter, mesh=MESH, pixel=PIXEL): + ms, ps = code(mesh), code(pixel) (directory / 'ms.bin').write_bytes(ms) (directory / 'ps.bin').write_bytes(ps) env = dict(os.environ, X2W_MESH_REQUEST_FIXTURE='1', X2W_TEST_MESH57_EXCHANGE=str(directory)) diff --git a/tests/startup_mesh57_two_buffers.s b/tests/startup_mesh57_two_buffers.s new file mode 100644 index 0000000000..6318b31680 --- /dev/null +++ b/tests/startup_mesh57_two_buffers.s @@ -0,0 +1,73 @@ +// Source-built slot 57 mesh fixture with two table descriptors: the same group-memory count +// exchange and trivial body, but positions and indices come from descriptor 0 and colours from +// descriptor 1 (table byte offset 32). Entry: s3 bits 24..27 hold the wave index; root constants +// s8 = primitive count, s9 = vertex count; s[10:11] points at a descriptor table. +s_inst_prefetch 0x3 +s_mov_b64 exec, 1 +s_mov_b64 s[4:5], exec +s_and_b32 s6, s3, 0xf000000 +s_cbranch_scc1 7 // to the reading waves +v_lshrrev_b32 v5, 7, v5 +v_mov_b32 v6, 0 +ds_write_b32 v6, v5 offset:8 +s_waitcnt_depctr 0xffe3 +s_barrier +s_branch 4 // past the reading waves +s_barrier +v_mov_b32 v6, 0 +ds_read_b32 v5, v6 offset:8 +s_mov_b64 exec, -1 +s_bfe_u32 s6, s3, 0x40018 +s_lshl_b32 s7, s6, 6 +v_mbcnt_lo_u32_b32 v0, -1, s7 +v_mbcnt_hi_u32_b32 v0, -1, v0 +s_waitcnt lgkmcnt(0) +v_readfirstlane_b32 s12, v5 +s_load_dwordx4 s[16:19], s[10:11], 0 +s_load_dwordx4 s[20:23], s[10:11], 0x20 +s_mov_b32 s13, s8 +s_mov_b32 s14, s9 +s_barrier +s_cmp_eq_i32 s6, 0 +s_cbranch_scc0 16 // to the reading waves +s_mov_b64 exec, s[4:5] +s_cbranch_execz 7 // never taken: the saved mask is 1 +v_mov_b32 v1, s13 +v_mov_b32 v2, 0 +v_mov_b32 v3, s14 +ds_write_b32 v2, v1 +ds_write_b32 v2, v3 offset:4 +s_mov_b64 exec, -1 +s_waitcnt_depctr 0xffe3 +s_barrier +s_lshl_b32 s4, s13, 12 +s_or_b32 m0, s4, s14 +s_sendmsg sendmsg(MSG_GS_ALLOC_REQ) +s_branch 13 // past the reading waves +s_barrier +s_mov_b64 exec, s[4:5] +s_cbranch_execz 9 // never taken: the saved mask is 1 +v_mov_b32 v2, 0 +ds_read_b32 v1, v2 +ds_read_b32 v3, v2 offset:4 +s_waitcnt lgkmcnt(1) +v_readfirstlane_b32 s13, v1 +s_waitcnt lgkmcnt(0) +v_readfirstlane_b32 s14, v3 +s_mov_b64 exec, -1 +v_cmpx_gt_i32 s14, v0 +v_and_b32 v4, 15, v0 +v_lshlrev_b32 v4, 4, v4 +buffer_load_dwordx4 v[16:19], v4, s[16:19], 0 offen +buffer_load_dwordx4 v[20:23], v4, s[20:23], 0 offen offset:192 +s_waitcnt vmcnt(0) +exp pos0 v16, v17, v18, v19 done +exp param0 v20, v21, v22, v23 +s_mov_b64 exec, -1 +v_cmpx_gt_i32 s13, v0 +v_and_b32 v4, 15, v0 +v_lshlrev_b32 v4, 2, v4 +buffer_load_dword v24, v4, s[16:19], 0 offen offset:384 +s_waitcnt vmcnt(0) +exp prim v24, off, off, off done +s_endpgm diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index b19fd625ce..36da7cd06a 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -7227,7 +7227,6 @@ def op_s_buffer_load_dword(self, ops, mods, count=1): dst = reg_range(ops[0]) if not dst or dst[0] != 's' or dst[2] - dst[1] + 1 != count or dst[2] > 105: raise Unsupported('s_buffer_load destination %s for %d dwords' % (ops[0], count)) - buf = self.pipe.resource(self.descriptor(ops[1]), 'buf') token = smem_offset(ops[2]) is_lit = bool(re.fullmatch(r'-?(?:0[xX][0-9a-fA-F]+|\d+)', token)) if is_lit: @@ -7245,6 +7244,10 @@ def op_s_buffer_load_dword(self, ops, mods, count=1): if sreg and offset == ('s%d' % sreg[1]) and dst[1] <= sreg[1] < dst[2]: self.emit('a = %s;' % offset) offset = 'a' + # A literal offset is a lower bound the descriptor must expose. With a runtime + # soffset only the transfer width is known, as in the native path. + buf = self.resource_bytes(self.descriptor(ops[1]), 'buf', + 4 * count + (val if is_lit else 0)) # A word read from an unmodified table buffer at a literal offset or at a root constant word times a literal # plus a literal is the same for the whole dispatch: heap_record names it by (table parameter, table byte, # root constant parameter and word or None, scale, byte offset). Any other buffer word is only marked. @@ -7279,7 +7282,15 @@ def op_s_buffer_load_dwordx8(self, ops, mods): def op_s_buffer_load_dwordx16(self, ops, mods): self.op_s_buffer_load_dword(ops, mods, 16) - def buffer_address(self, ops, mods, *, is_formatted=False): + def resource_bytes(self, key, kind, span): + """Bind a buffer and record the lowest accessed byte span for the mesh manifest.""" + name = self.pipe.resource(key, kind) + r = getattr(self.pipe, 'resources', {}).get(key) + if isinstance(r, dict): + r['bytes'] = max(r.get('bytes', 0), span) + return name + + def buffer_address(self, ops, mods, *, is_formatted=False, span=0): # MUBUF and MTBUF share the same address calculation: optional index * stride (idxen), # optional byte VGPR offset (offen), scalar byte offset (soffset) and 12-bit immediate # offset. Cache-policy flags (glc, slc, dlc) do not change the loaded bytes; lds, tfe @@ -7337,6 +7348,11 @@ def buffer_address(self, ops, mods, *, is_formatted=False): if soffset is not None: terms.append(soffset) terms.append('%d' % offset) + # The lowest address this load can name is the immediate offset; the descriptor + # must expose at least that many bytes plus the transfer width. + r = getattr(self.pipe, 'resources', {}).get(key) + if isinstance(r, dict): + r['bytes'] = max(r.get('bytes', 0), max(offset, 0) + span) return buf, ' + '.join(terms) def op_buffer_load_dword(self, ops, mods, count=1): @@ -7346,7 +7362,7 @@ def op_buffer_load_dword(self, ops, mods, count=1): if not ops: raise Unsupported('buffer load with 0 operands, expected 4') dst = reg_range(ops[0]) - buf, address = self.buffer_address(ops, mods) + buf, address = self.buffer_address(ops, mods, span=4 * count) self.emit('a = %s;' % address) for i in range(count): self.set_v(dst[1] + i, '%s.Load(a + %d)' % (buf, 4 * i)) @@ -7414,7 +7430,7 @@ def op_global_load_dword(self, ops, mods): total_off = base_off + offset if total_off > 0xffffffff or total_off < -0xffffffff: raise Unsupported('global load byte offset %#x' % total_off) - buf = self.pipe.resource((p[1], None), 'buf') + buf = self.resource_bytes((p[1], None), 'buf', max(total_off, 0) + 4) # Guard the signed 64-bit view-relative byte offset (zext(vaddr) + base_off + sext(offset)) against # [0, 0xffffffff] before converting to a 32-bit ByteAddressBuffer offset so overflow above 4 GiB or # underflow below base cannot wrap into an in-bounds word of a bounded root view. @@ -7733,7 +7749,8 @@ def tbuffer(self, ops, mods, count): dst = reg_range(ops[0]) formats = [m for m in mods if m.startswith('format:')] fmt = formats[0][8:-1] if formats else 'BUF_FMT_8_UNORM' # the disassembler omits the default format - buf, address = self.buffer_address(ops, [m for m in mods if not m.startswith('format:')]) + buf, address = self.buffer_address(ops, [m for m in mods if not m.startswith('format:')], + span=4 * count) self.emit('a = %s;' % address) self.load_format(fmt, buf, dst[1], count) @@ -7955,7 +7972,7 @@ def mubuf_format(self, ops, mods, count): For compute, the caller must validate the native descriptor and reachable byte addresses, and bind the SRV and entry constants from that same descriptor snapshot. """ - buf, address = self.buffer_address(ops, mods, is_formatted=True) + buf, address = self.buffer_address(ops, mods, is_formatted=True, span=4 * count) dst = reg_range(ops[0]) if not dst or dst[0] != 'v' or dst[2] - dst[1] + 1 != count or dst[2] > 255: raise Unsupported('formatted buffer load destination %s for %d components' % (ops[0], count)) @@ -12101,7 +12118,9 @@ def __init__(self, vs_code, ps_code, root_blob, sampler_heap=None, rtv_formats=( refusals=None, decoded=None, ps_attr_map=None, srv_formats=()): self._init_pixel_context(root_blob, sampler_heap, rtv_formats, ps_hw_inputs, vs_fetch, ps_attr_map, srv_formats) - self.rect = self.ud(('rect',)) + # Only the vertex wrapper consumes the rectangle-list selector. Mesh pipelines have no such + # wrapper, and keeping the word first shifted their root constants by one in the published HLSL. + self.rect = self.ud(('rect',)) if self.vertex_kind == 'vs' else 0 if refusals is None: self.vs = Stage(self, self.vertex_kind, vs_code) self.ps = Stage(self, 'ps', ps_code) if ps_code is not None else None @@ -12164,7 +12183,7 @@ def resource(self, key, kind): return 'rh[NonUniformResourceIndex(%s)]' % expr if key in self.stored_images(): raise Unsupported('resource %s is both read and stored to' % (key,)) - r = self.resources.setdefault(key, dict(index=len(self.resources), kind=kind)) + r = self.resources.setdefault(key, dict(index=len(self.resources), kind=kind, bytes=0)) if r['kind'] != kind: raise Unsupported('resource %s used as %s and %s' % (key, r['kind'], kind)) return 'r%d' % r['index'] @@ -13016,6 +13035,27 @@ def mesh_param_line(self, line): return re.sub(r' o\.param(\d+) = [^;]*;', lambda m: m[0] if int(m[1]) in linear else '', line) + def manifest(self): + # Version 4 is the slot 57 mesh manifest: every buffer SRV line carries the number of + # bytes the translated stage can access, so the runtime can refuse a view that is too short. + lines = super().manifest().splitlines() + if not lines or not lines[0].startswith('x2w-manifest '): + raise Unsupported('slot 57 mesh manifest header is missing') + lines[0] = 'x2w-manifest 4' + lines.insert(1, 'stage ms') + by_index = {r['index']: r for r in self.resources.values()} + for i, line in enumerate(lines): + fields = line.split() + if len(fields) < 3 or fields[0] != 'srv' or fields[2] != 'buf': + continue + r = by_index.get(int(fields[1])) + if r is None: + raise Unsupported('slot 57 mesh manifest names an unknown buffer') + if not r.get('bytes'): + raise Unsupported('slot 57 mesh buffer %d has no accessed byte span' % r['index']) + lines[i] = line + ' bytes %d' % r['bytes'] + return '\n'.join(lines) + '\n' + def hlsl_ms(self): s = self.vs lines = [self.mesh_param_line( @@ -13511,7 +13551,7 @@ def read_slot57_entry(path): def mesh57_key(ms, ps, root): - value = fnv(b'x2w-startup-mesh-57-3') + value = fnv(b'x2w-startup-mesh-57-4') for part in (ms, ps, root): value = fnv(part, fnv(struct.pack('.ms57.hlsl and the compiled .ms57.cso, their .ps57 counterparts if present, and .ms57.txt (last). - No runtime path loads these names yet.""" + The native runtime reads the version 4 manifest and, for the one R1 group-index refusal, the published pair.""" source = os.path.join(out_dir, 'req_%016x' % key) ms, ps, root = (open(source + ext, 'rb').read() for ext in ('.m57', '.ps57', '.root')) if mesh57_key(ms, ps, root) != key: