From 7c4de869a5348613f676d758373239b5952f3d8c Mon Sep 17 00:00:00 2001 From: Leyukaka <45659323+Leyukaka@users.noreply.github.com> Date: Tue, 1 Dec 2026 21:13:04 +0100 Subject: [PATCH] shader: preserve complete native frontend cache results --- CMakeLists.txt | 1 + CMakePresets.json | 3 +- src/direct_compute_cache.cpp | 332 +++++++++++++++++-------- src/direct_compute_cache.h | 5 + src/gfx1013_compute_native.cpp | 12 + src/gfx1013_compute_native.h | 6 + src/gfx1013_direct_compute.inl | 14 +- src/gfx1013_direct_graphics.inl | 2 +- src/gfx1013_direct_mesh.inl | 4 +- tests/cmake/native_direct_cache.cmake | 14 ++ tests/native_compute_pack_check.cpp | 8 +- tests/native_direct_cache_check.cpp | 65 +++++ tests/native_direct_container_check.py | 27 ++ 13 files changed, 364 insertions(+), 129 deletions(-) create mode 100644 tests/cmake/native_direct_cache.cmake create mode 100644 tests/native_direct_cache_check.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 278354d49..cc41c442e 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -15,6 +15,7 @@ if(WIN32) gfx1013_isa_tables.inl gfx1013_isa.cpp gfx1013_isa.h gfx1013_compute_alu.inl gfx1013_direct_compute.inl gfx1013_compute_ir.cpp gfx1013_compute_ir.h gfx1013_compute_mtbuf.inl gfx1013_direct_graphics.inl gfx1013_direct_mesh.inl gfx1013_pixel_waterfall.inl gfx1013_rect_geometry.cpp guest_shader_container.cpp guest_shader_container.h dxil_module.h mesh_pixel_heap.h direct_compute_cache.cpp direct_compute_cache.h + native_graphics_bindings.h native_compute_output.h shader_dxil_compiler.h shader_compute_request.cpp shader_compute_request.h shader_translation_error.h startup_stubs/inflate.h) set(native_shader_file "${CMAKE_CURRENT_SOURCE_DIR}/src/${source}") set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS "${native_shader_file}") diff --git a/CMakePresets.json b/CMakePresets.json index e78861977..7c84f4b0b 100644 --- a/CMakePresets.json +++ b/CMakePresets.json @@ -36,7 +36,8 @@ "xmem_placeholder_split_check", "xmem_map_split_first_check", "startup_dstorage_break_window_check", "xmem_page_runs_device_check", "linear_buffer_backing_check", "existing_heap_shared_buffer_check", "startup_request_publisher_check", "mesh86_typed_vsharp_check", "mesh86_typed_vsharp_wide_format_mut", "mesh86_typed_vsharp_any_map_mut", "mesh86_typed_vsharp_any_swizzle_mut", "mesh86_typed_vsharp_any_tid_mut", "bcpack_formats_check", "startup_stub_consumer", "startup_inline_retire", "startup_resource_retire_title", "startup_table_lock", - "native_compute_ir_dump", "native_pixel_ir_dump", "native_store_replay", "native_raw_buffer_view_check" + "native_compute_ir_dump", "native_pixel_ir_dump", "native_store_replay", "native_raw_buffer_view_check", + "native_direct_cache_check" ] }, { "name": "release", "configurePreset": "release" }, diff --git a/src/direct_compute_cache.cpp b/src/direct_compute_cache.cpp index 8cceb9747..cc0915e4c 100644 --- a/src/direct_compute_cache.cpp +++ b/src/direct_compute_cache.cpp @@ -20,6 +20,9 @@ #include #include #include +#include +#include +#include #include #include @@ -87,121 +90,225 @@ struct Reader { } }; -Bytes encode(const NativeComputeShader &program) { +// Structured bindings force a schema update whenever a cached aggregate gains +// a member. Update this visitor, the round-trip fixture, and the cache revision. +template +constexpr auto cache_fields(T &value) { + using Type = std::remove_cv_t; + if constexpr (std::is_same_v) { + auto &[pixel_heap_spans, mesh_heap_reads, mesh_texture_heap_slot_map, pixel_texture_heap_slot_map, + pixel_quad_coverage_branch, pixel_descriptor_word_tables, pixel_descriptor_records, mesh_heap_tokens, + inputs, outputs, constants, stride_sources, hlsl, dxil_ir, bindings, samplers, sampler_heap, + instruction_count, group, vertex_fetch, pixel_writes] = value; + return std::tie(pixel_heap_spans, mesh_heap_reads, mesh_texture_heap_slot_map, pixel_texture_heap_slot_map, + pixel_quad_coverage_branch, pixel_descriptor_word_tables, pixel_descriptor_records, mesh_heap_tokens, + inputs, outputs, constants, stride_sources, hlsl, dxil_ir, bindings, samplers, sampler_heap, + instruction_count, group, vertex_fetch, pixel_writes); + } else if constexpr (std::is_same_v) { + auto &[kind, root, offset, reg, bytes, count, position, dimension, table, identity] = value; + return std::tie(kind, root, offset, reg, bytes, count, position, dimension, table, identity); + } else if constexpr (std::is_same_v) { + auto &[root, sgpr, count] = value; + return std::tie(root, sgpr, count); + } else if constexpr (std::is_same_v) { + auto &[words, lod, comparison] = value; + return std::tie(words, lod, comparison); + } else if constexpr (std::is_same_v) { + auto &[name, index, row, first, width, component, used, kind, interpolation] = value; + return std::tie(name, index, row, first, width, component, used, kind, interpolation); + } else if constexpr (std::is_same_v) { + auto &[first, last, dimension, host_first] = value; + return std::tie(first, last, dimension, host_first); + } else if constexpr (std::is_same_v) { + auto &[root, dword, mask, shift, base] = value; + return std::tie(root, dword, mask, shift, base); + } else if constexpr (std::is_same_v) { + auto &[token, kinds, miss, reads] = value; + return std::tie(token, kinds, miss, reads); + } else if constexpr (std::is_same_v) { + auto &[reg, writable] = value; + return std::tie(reg, writable); + } else if constexpr (std::is_same_v>) { + return std::tie(value.first, value.second); + } +} +static_assert(std::tuple_size_v()))> == 21, + "Update the frontend cache visitor, round-trip fixture, and revision for new shader fields"); + +struct ShaderWriter { Bytes out; - word(out, program.instruction_count); - for (unsigned n : program.group) - word(out, n); - word(out, static_cast(program.bindings.size())); - for (const auto &b : program.bindings) { - word(out, static_cast(b.kind)); - for (unsigned n : {b.root_parameter, b.byte_offset, b.shader_register, b.required_bytes, b.array_count, - b.array_position, b.image_dimension, unsigned(b.scalar_table), unsigned(b.requires_identity_dst_sel)}) - word(out, n); - } - word(out, static_cast(program.constants.size())); - for (const auto &c : program.constants) - for (unsigned n : {c.root_parameter, c.first_sgpr, c.count}) - word(out, n); - word(out, program.sampler_heap); - word(out, static_cast(program.stride_sources.size())); - for (const auto& source : program.stride_sources) { - word(out, source.shader_register); - word(out, source.writable); - } - word(out, static_cast(program.samplers.size())); - for (const auto &s : program.samplers) { - for (auto n : s.words) - word(out, n); - word(out, s.explicit_lod); - word(out, s.comparison); - } - for (const auto *signature : {&program.inputs, &program.outputs}) { - word(out, static_cast(signature->size())); - for (const auto &row : *signature) { - word(out, static_cast(row.name.size())); - out += row.name; - for (auto field : - {row.index, row.row, row.first, row.width, row.component, row.used, row.kind, row.interpolation}) - word(out, field); - } + + void operator()(const Bytes &text) { + word(out, static_cast(text.size())); + out += text; + } + template + void operator()(const T &value) { + if constexpr (std::is_same_v || std::is_same_v || std::is_enum_v) + word(out, static_cast(value)); + else + std::apply([&](const auto &...fields) { ((*this)(fields), ...); }, cache_fields(value)); + } + template + void operator()(const std::array &array) { + for (const auto &value : array) (*this)(value); + } + template + void operator()(const std::vector &vector) { + word(out, static_cast(vector.size())); + for (const auto &value : vector) (*this)(value); + } + template + void operator()(const std::optional &value) { + (*this)(value.has_value()); + if (value) (*this)(*value); + } +}; + +template constexpr unsigned cached_vector_limit = 1u << 18; +template<> constexpr unsigned cached_vector_limit = 1000000; +template<> constexpr unsigned cached_vector_limit = 32; +template<> constexpr unsigned cached_vector_limit = 2048; +template<> constexpr unsigned cached_vector_limit = 128; +template<> constexpr unsigned cached_vector_limit = 32; +// The pixel descriptor tables name root parameters. +template<> constexpr unsigned cached_vector_limit = 64; + +struct ShaderReader { + Reader in; + + void operator()(Bytes &text) { text = in.take(in.word()); } + void operator()(unsigned &value) { value = in.word(); } + void operator()(bool &value) { value = in.count(1) != 0; } + void operator()(ComputeViewKind &kind) { + kind = static_cast(in.count(static_cast(ComputeViewKind::root_buffer_uav))); + } + void operator()(ComputeViewBinding::ScalarTable &table) { + using Table = ComputeViewBinding::ScalarTable; + table = static_cast(in.count(static_cast(Table::srv))); + } + void operator()(GraphicsLinkage &row) { + std::apply([&](Bytes &name, auto &...fields) { + name = in.take(in.count(4096)); + ((*this)(fields), ...); + }, cache_fields(row)); + } + template + void operator()(T &value) { + std::apply([&](auto &...fields) { ((*this)(fields), ...); }, cache_fields(value)); + } + template + void operator()(std::array &array) { + for (auto &value : array) (*this)(value); + } + template + void operator()(std::vector &vector) { + const auto count = in.count(cached_vector_limit); + if (count > in.remaining.size() / sizeof(uint32_t)) + throw std::runtime_error("short frontend cache vector"); + vector.resize(count); + for (auto &value : vector) (*this)(value); + } + template + void operator()(std::optional &value) { + if (in.count(1)) (*this)(value.emplace()); + } +}; + +struct ShaderEqual { + template + bool operator()(const T &left, const T &right) const { + if constexpr (std::is_arithmetic_v || std::is_enum_v || std::is_same_v) + return left == right; + else + return compare(cache_fields(left), cache_fields(right)); + } + template + bool operator()(const std::array &left, const std::array &right) const { + return left == right; + } + template + bool operator()(const std::vector &left, const std::vector &right) const { + return std::equal(left.begin(), left.end(), right.begin(), right.end(), *this); + } + template + bool operator()(const std::optional &left, const std::optional &right) const { + return left.has_value() == right.has_value() && (!left || (*this)(*left, *right)); + } + +private: + template + bool compare(const Tuple &left, const Tuple &right, std::index_sequence) const { + return ((*this)(std::get(left), std::get(right)) && ...); + } + template + bool compare(const std::tuple &left, const std::tuple &right) const { + return compare(left, right, std::index_sequence_for{}); + } +}; + +void validate_signature(const std::vector &signature, bool output) { + for (const auto &row : signature) { + const bool unpacked = row.row == UINT_MAX && (output || + (row.name == "SV_Barycentrics" && row.kind == 28 && row.component == 9 && + row.width == 3 && !row.first && row.index < 2 && row.interpolation >= 2)); + if (row.row >= 32 && !unpacked) + throw std::runtime_error("invalid cached signature register"); + if (row.name.empty() || row.first > 3 || !row.width || row.width > 4 || + row.first + row.width > 4 || row.used >= (1u << row.width) || row.kind > 31 || row.interpolation > 7) + throw std::runtime_error("invalid cached signature"); } - word(out, program.vertex_fetch); - for (auto mask : program.pixel_writes) - word(out, mask); - out += program.dxil_ir; - return out; } -NativeComputeShader decode(std::string_view bytes) { - Reader in{bytes}; - NativeComputeShader shader{}; - shader.instruction_count = in.count(1 << 18); - shader.group = {in.count(1024), in.count(1024), in.count(64)}; - unsigned n = in.count(1000000); - shader.bindings.reserve(n); - for (unsigned j = 0; j < n; ++j) { - auto kind = static_cast(in.count(static_cast(ComputeViewKind::root_buffer_uav))); - ComputeViewBinding b{kind, in.word(), in.word(), in.word(), in.word(), in.word(), in.word(), in.count(7)}; - b.scalar_table = static_cast(in.count(unsigned(ComputeViewBinding::ScalarTable::srv))); - b.requires_identity_dst_sel = in.count(1) != 0; - const bool sampler_heap = kind == ComputeViewKind::heap_sampler; - if (!b.array_count || b.array_position >= b.array_count || +void validate_shader(const NativeComputeShader &shader) { + if (shader.instruction_count > (1u << 18) || shader.group[0] > 1024 || shader.group[1] > 1024 || + shader.group[2] > 64 || shader.stride_sources.size() > 32 || + std::any_of(shader.stride_sources.begin(), shader.stride_sources.end(), + [](const ComputeStrideSource &source) { return source.shader_register > 31; }) || + std::any_of(shader.pixel_writes.begin(), shader.pixel_writes.end(), [](unsigned mask) { return mask > 15; })) + throw std::runtime_error("invalid frontend cache count"); + for (const auto &b : shader.bindings) { + const bool sampler_heap = b.kind == ComputeViewKind::heap_sampler; + if (!b.array_count || b.array_position >= b.array_count || b.image_dimension > 7 || (sampler_heap ? b.root_parameter != compute_sampler_heap : b.root_parameter >= 16 && b.root_parameter != compute_resource_heap)) throw std::runtime_error("invalid cached binding"); - shader.bindings.push_back(b); } - n = in.count(32); - for (unsigned j = 0; j < n; ++j) { - ComputeConstants c{in.count(15), in.count(105), in.count(32)}; - if (!c.count || c.count > 106 - c.first_sgpr) + for (const auto &c : shader.constants) + if (c.root_parameter > 15 || c.first_sgpr > 105 || !c.count || c.count > 32 || c.count > 106 - c.first_sgpr) throw std::runtime_error("invalid cached constants"); - shader.constants.push_back(c); - } - shader.sampler_heap = in.count(1) != 0; - n = in.count(32); - for (unsigned j = 0; j < n; ++j) - shader.stride_sources.push_back({in.count(31), in.count(1) != 0}); - n = in.count(2048); - for (unsigned j = 0; j < n; ++j) { - ComputeSampler sampler{}; - for (auto &w : sampler.words) - w = in.word(); - sampler.explicit_lod = in.count(1) != 0; - sampler.comparison = in.count(1) != 0; - shader.samplers.push_back(sampler); - } - for (auto *signature : {&shader.inputs, &shader.outputs}) { - unsigned count = in.count(128); - for (unsigned j = 0; j < count; ++j) { - GraphicsLinkage row{}; - row.name = in.take(in.count(4096)); - row.index = in.word(); - row.row = in.word(); - row.first = in.count(3); - row.width = in.count(4); - row.component = in.word(); - row.used = in.count(15); - row.kind = in.count(31); - row.interpolation = in.count(7); - const bool unpacked = row.row == UINT_MAX && (signature == &shader.outputs || - (row.name == "SV_Barycentrics" && row.kind == 28 && row.component == 9 && - row.width == 3 && !row.first && row.index < 2 && row.interpolation >= 2)); - if (row.row >= 32 && !unpacked) - throw std::runtime_error("invalid cached signature register"); - if (row.name.empty() || !row.width || row.first + row.width > 4 || row.used >= (1u << row.width)) - throw std::runtime_error("invalid cached signature"); - signature->push_back(std::move(row)); - } - } - shader.vertex_fetch = in.count(1) != 0; - for (auto &mask : shader.pixel_writes) - mask = in.count(15); - if (in.remaining.empty()) + validate_signature(shader.inputs, false); + validate_signature(shader.outputs, true); + if (shader.dxil_ir.empty()) throw std::runtime_error("missing cached DXIL IR"); - shader.dxil_ir = in.remaining; +} +} // namespace + +bool operator==(const NativeComputeShader &left, const NativeComputeShader &right) { + return ShaderEqual{}(left, right); +} + +namespace native_frontend_cache { +Bytes encode(const NativeComputeShader &program) { + ShaderWriter writer; + writer(program); + return std::move(writer.out); +} + +NativeComputeShader decode(std::string_view bytes) { + ShaderReader reader{{bytes}}; + NativeComputeShader shader{}; + reader(shader); + if (!reader.in.remaining.empty()) + throw std::runtime_error("trailing frontend cache data"); + validate_shader(shader); return shader; } +} // namespace native_frontend_cache + +namespace { +using native_frontend_cache::decode; +using native_frontend_cache::encode; + bool lookup(const fs::path &path, const Bytes &key, Bytes &payload) { HANDLE handle = CreateFileW(path.c_str(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, @@ -361,8 +468,14 @@ size_t index_graphics_interfaces(const fs::path &source, const fs::path &cache, return count; } namespace { +// Frontend-3 stores the complete translated shader in both loose entries and packs. +Bytes frontend_identity(std::string_view profile) { + Bytes identity = X2W_NATIVE_SHADER_REVISION "/frontend-3/"; + identity += profile; + return identity; +} Bytes slot67_digest(const ComputeRequest &request, unsigned entry) { - Bytes identity = X2W_NATIVE_SHADER_REVISION "/slot67/cs_6_6"; + Bytes identity = frontend_identity("slot67/cs_6_6"); word(identity, entry); for (const auto *part : {&request.code, &request.data, &request.root, &request.description, &request.sa, &request.sb}) identity += shader_digest(*part); @@ -382,7 +495,7 @@ NativeComputeShader cached_compute_ir(const fs::path &cache, const Bytes &key, b return program; } Bytes pack_version(unsigned entry) { - Bytes version = X2W_NATIVE_SHADER_REVISION "/slot67/cs_6_6/prepared-2"; + Bytes version = frontend_identity("slot67/cs_6_6/prepared-2"); word(version, entry); return shader_digest(version); } @@ -406,7 +519,7 @@ NativeComputeShader prepare_direct_compute(const fs::path &input, unsigned entry [&] { return translate_compute(request, entry, true); }); } auto packed = read_compute_container(input); - Bytes identity = X2W_NATIVE_SHADER_REVISION "/container/cs_6_6"; + Bytes identity = frontend_identity("container/cs_6_6"); word(identity, 0); if (heap_view != HeapViewContract::none) identity += heap_view == HeapViewContract::raw_buffer ? "/heap-view/raw_buffer" @@ -724,7 +837,8 @@ DirectGraphicsPair prepare_direct_graphics(std::string_view a, std::string_view std::array companions; const std::array raw{a, b}; const std::array digests{shader_digest(a), shader_digest(b)}; - Bytes identity = Bytes(X2W_NATIVE_SHADER_REVISION) + "/linked/vs_ps_6_6/"; + Bytes identity = frontend_identity("linked/vs_ps_6_6/"); + word(identity, translation_options().mesh_partial_zero); if (!cache.empty() && a.substr(0,4) != "DXBC" && b.substr(0,4) != "DXBC") { for (size_t i = 0; i < raw.size(); ++i) { auto file = cache / "interfaces" / (digests[i] + ".cdxil"); @@ -748,7 +862,7 @@ DirectGraphicsPair prepare_direct_graphics(std::string_view a, std::string_view const bool reflected = !companions[0].empty(); if (reflected != !companions[1].empty()) throw UnsupportedComputeShader("incomplete raw graphics interface pair"); if (reflected && root.empty()) throw UnsupportedComputeShader("missing captured root for reflected graphics"); - // The base pair keeps its key. A variant adds its target types, so formats of one type share an entry. + // A variant adds its target types, so formats of one type share an entry. const Bytes typed = rtv_formats.empty() ? Bytes{} : shader_digest(std::string_view(reinterpret_cast(targets.data()), targets.size())); const auto key = shader_digest(identity + shader_digest(root) + shader_digest(input_layout) + shader_digest(pixel_entry) + typed); diff --git a/src/direct_compute_cache.h b/src/direct_compute_cache.h index 30091211a..aa3e1a72e 100644 --- a/src/direct_compute_cache.h +++ b/src/direct_compute_cache.h @@ -5,6 +5,11 @@ // The result includes the emitted DXIL module and its exact desktop/guest binding layout. namespace x2w { +namespace native_frontend_cache { +std::string encode(const NativeComputeShader &program); +NativeComputeShader decode(std::string_view bytes); +} + enum class ComputePackResult { miss, prepared, unsupported }; struct ComputePackCounts { size_t prepared{}, unsupported{}, internal{}; diff --git a/src/gfx1013_compute_native.cpp b/src/gfx1013_compute_native.cpp index cc4aaa51e..c00b62809 100644 --- a/src/gfx1013_compute_native.cpp +++ b/src/gfx1013_compute_native.cpp @@ -20,6 +20,18 @@ #include #include +const x2w::TranslationOptions &x2w::translation_options() { + static const TranslationOptions options = [] { +#if defined(_MSC_VER) + // C4996: keep the existing read-only CRT environment lookup without allocating a copy. + #pragma warning(suppress: 4996) +#endif + const char *value = std::getenv("X2W_MESH57_PARTIAL_ZERO"); + return TranslationOptions{value && value[0] == '1'}; + }(); + return options; +} + namespace { using namespace x2w; using std::string; diff --git a/src/gfx1013_compute_native.h b/src/gfx1013_compute_native.h index dd20f9d62..104f3aa67 100644 --- a/src/gfx1013_compute_native.h +++ b/src/gfx1013_compute_native.h @@ -156,6 +156,11 @@ struct ComputeStrideSource { bool writable; }; +struct TranslationOptions { + bool mesh_partial_zero = false; +}; +// First-use process snapshot shared by the frontend cache and lowering. +const TranslationOptions &translation_options(); struct NativeComputeShader { std::vector pixel_heap_spans; std::vector mesh_heap_reads; @@ -179,6 +184,7 @@ struct NativeComputeShader { bool vertex_fetch = false; std::array pixel_writes{}; }; +bool operator==(const NativeComputeShader &left, const NativeComputeShader &right); // The view class a GPU-selected descriptor heap slot is read as. none: the slot and its view type are not known, so a // heap read is refused. raw_buffer: the capture says the selected slot is a raw buffer SRV. other: the capture names a // view type that is not translated (refused when the shader reads the heap). diff --git a/src/gfx1013_direct_compute.inl b/src/gfx1013_direct_compute.inl index 749b71c80..68ea2e644 100644 --- a/src/gfx1013_direct_compute.inl +++ b/src/gfx1013_direct_compute.inl @@ -1,14 +1,5 @@ // Lower the shared decoded CFG to DXIL operations. A scalar register holds one // 32-bit word per wave. Ordinary vector writes retain their old value on inactive lanes. -inline bool mesh_partial_zero() -{ -#if defined(_MSC_VER) - // C4996: keep the existing read-only CRT environment lookup without allocating a copy. - #pragma warning(suppress: 4996) -#endif - const char* value=std::getenv("X2W_MESH57_PARTIAL_ZERO"); - return value && value[0]=='1'; -} struct DirectCompute { // The nine inline float constants as binary16, which an f16 operand reads instead of the f32 pattern. static constexpr Word inline_half_words[]{0x3800, 0xb800, 0x3c00, 0xbc00, 0x4000, @@ -71,6 +62,7 @@ struct DirectCompute { refuse(i.pc, "lane read/write needs full waves"); } Emit &analysis; + const TranslationOptions options{}; const GuestShaderStage *graphics_interface = nullptr; DxilModule ir; std::set allocated; @@ -185,7 +177,7 @@ struct DirectCompute { string read(unsigned r) { if (compute_state && compute_state->has_spill(r)) refuse(compute_pc, "symbolic VGPR lane read of " + reg(r)); - if (graphics_input && !graphics_half_writes && mesh_partial_zero()) { + if (graphics_input && !graphics_half_writes && options.mesh_partial_zero) { const auto found = graphics_registers.find(r); if (found == graphics_registers.end() || found->second.empty()) { const auto partial = partial_values.find(r); @@ -195,7 +187,7 @@ struct DirectCompute { return read_storage(r); } string read_export(unsigned r) { - if (graphics_half_writes || !mesh_partial_zero()) return read_storage(r); + if (graphics_half_writes || !options.mesh_partial_zero) return read_storage(r); const auto found = graphics_registers.find(r); if (found != graphics_registers.end() && !found->second.empty()) return found->second; const auto partial = partial_values.find(r); diff --git a/src/gfx1013_direct_graphics.inl b/src/gfx1013_direct_graphics.inl index 0ee9bd2fc..bf786d955 100644 --- a/src/gfx1013_direct_graphics.inl +++ b/src/gfx1013_direct_graphics.inl @@ -1824,7 +1824,7 @@ NativeComputeShader lower_graphics(GuestShaderStage &stage, unsigned first_srv = emitter.srv = first_srv; emitter.uav = first_uav; emitter.first_sampler = first_sampler; - DirectCompute alu{emitter}; + DirectCompute alu{emitter, translation_options()}; const bool pixel = stage.stage == GpuStage::ps; alu.graphics_interface = &stage; alu.pixel_stage = pixel; diff --git a/src/gfx1013_direct_mesh.inl b/src/gfx1013_direct_mesh.inl index d1a4db04a..51b029024 100644 --- a/src/gfx1013_direct_mesh.inl +++ b/src/gfx1013_direct_mesh.inl @@ -66,7 +66,7 @@ NativeComputeShader lower_mesh(const string &code, const MeshStageLayout &layout program.before.emplace_back(); for (auto &s : program.before.front()) s.type=Symbol::Type::unbound; Emit emitter{{},program,root}; - DirectCompute alu{emitter}; + DirectCompute alu{emitter, translation_options()}; // A container stage reflects its table records; an IDXEN raw load takes its record stride from them. alu.graphics_interface=reflected; // The mesh tracks which half of a VGPR a 16-bit write defined: a mixed @@ -853,7 +853,7 @@ NativeComputeShader lower_mesh(const string &code, const MeshStageLayout &layout if (uniform_join && group_uniform_value(a) && group_uniform_value(b)) group_uniform.insert(v); return v; }; - const bool partial_zero=!layout.texture_heap_slot_map && mesh_partial_zero(); + const bool partial_zero=!layout.texture_heap_slot_map && alu.options.mesh_partial_zero; if (!branch || !branch->masks) remember_partial(); std::map> masks; for (unsigned reg=0;reg<=104;reg+=2) { diff --git a/tests/cmake/native_direct_cache.cmake b/tests/cmake/native_direct_cache.cmake new file mode 100644 index 000000000..fd273e832 --- /dev/null +++ b/tests/cmake/native_direct_cache.cmake @@ -0,0 +1,14 @@ +if(TARGET x2w_shader_compiler) + add_executable(native_direct_cache_check tests/native_direct_cache_check.cpp) + target_link_libraries(native_direct_cache_check PRIVATE x2w_shader_compiler) + set_property(TARGET native_direct_cache_check PROPERTY MSVC_RUNTIME_LIBRARY "MultiThreaded$<$:Debug>") + add_test(NAME native_direct_cache_controls COMMAND native_direct_cache_check) +endif() + +if(TARGET compile_dxil AND EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${DXC_BIN_DIR}/dxil.dll" + AND EXISTS "${INTAKE_PYTHON}") + add_test(NAME native_direct_cache_key_controls + COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/native_direct_container_check.py" + --cache-options "$" "${DXC_BIN_DIR}") + set_tests_properties(native_direct_cache_key_controls PROPERTIES TIMEOUT 60) +endif() diff --git a/tests/native_compute_pack_check.cpp b/tests/native_compute_pack_check.cpp index 5de50b4df..5718ee51c 100644 --- a/tests/native_compute_pack_check.cpp +++ b/tests/native_compute_pack_check.cpp @@ -54,8 +54,7 @@ static int same(const fs::path &input, const fs::path &a_file, const fs::path &b NativeComputeShader pa, pb; std::string da, db; const auto ra = a.lookup(r, 0, pa, da), rb = b.lookup(r, 0, pb, db); - check(ra == rb && da == db && pa.dxil_ir == pb.dxil_ir && pa.group == pb.group && - pa.instruction_count == pb.instruction_count && + check(ra == rb && da == db && pa == pb && format_compute_runtime_manifest(pa) == format_compute_runtime_manifest(pb), "lookup results differ"); found += ra != ComputePackResult::miss; } @@ -69,7 +68,7 @@ static int old_layout(const fs::path &file, const fs::path &out) { std::ifstream in(file, std::ios::binary); std::string bytes((std::istreambuf_iterator(in)), std::istreambuf_iterator()); check(bytes.size() > 128 + 72 && bytes.compare(128, 4, std::string("\1\0\0\0", 4)) == 0, "not a single-part pack"); - std::string version = X2W_NATIVE_SHADER_REVISION "/slot67/cs_6_6/prepared-1"; + std::string version = X2W_NATIVE_SHADER_REVISION "/frontend-3/slot67/cs_6_6/prepared-1"; version.append(4, '\0'); const auto payload = bytes.substr(132, 4) + bytes.substr(128 + 72); std::ofstream o(out, std::ios::binary); @@ -119,8 +118,7 @@ int main(int argc, char **argv) { std::string identity, manifest_digest; if (hit == ComputePackResult::prepared) { auto manifest = format_compute_runtime_manifest(cold); - check(warm.dxil_ir == cold.dxil_ir && warm.group == cold.group && - warm.instruction_count == cold.instruction_count && format_compute_runtime_manifest(warm) == manifest, + check(warm == cold && format_compute_runtime_manifest(warm) == manifest, "IR, layout or manifest differs"); status = "prepared"; identity = shader_digest(cold.dxil_ir); diff --git a/tests/native_direct_cache_check.cpp b/tests/native_direct_cache_check.cpp new file mode 100644 index 000000000..0b332570f --- /dev/null +++ b/tests/native_direct_cache_check.cpp @@ -0,0 +1,65 @@ +#include "direct_compute_cache.h" +#include + +using namespace x2w; +using native_frontend_cache::decode; +using native_frontend_cache::encode; + +static void check(bool ok, const char *reason) { + if (!ok) throw std::runtime_error(reason); +} + +static bool refuses(std::string_view bytes) { + try { decode(bytes); } + catch (const std::runtime_error &) { return true; } + return false; +} + +int main() { + try { + NativeComputeShader shader{}; + shader.pixel_heap_spans = {{4, 17, 5, 1024}, {60, 63, 1, 1038}}; + shader.mesh_heap_reads = {{2, 3, 1023, 4, 6}}; + shader.mesh_texture_heap_slot_map = true; + shader.pixel_texture_heap_slot_map = true; + shader.pixel_quad_coverage_branch = true; + shader.pixel_descriptor_word_tables = {2, 5}; + shader.pixel_descriptor_records = {{2, 32}, {5, 160}}; + shader.mesh_heap_tokens = MeshHeapTokens{5, 6, 7, 8}; + shader.inputs = {{"TEXCOORD", 3, 6, 1, 2, 9, 3, 1, 2}, + {"SV_Barycentrics", 1, ~0u, 0, 3, 9, 7, 28, 4}}; + shader.outputs = {{"SV_Target", 2, ~0u, 1, 3, 5, 7, 16, 1}}; + shader.constants = {{4, 28, 8}}; + shader.stride_sources = {{3, false}, {9, true}}; + shader.hlsl = "fixture HLSL\n"; + shader.dxil_ir = "fixture DXIL IR\n"; + shader.bindings = {{ComputeViewKind::cube_sample_srv, 3, 80, 5, 32, 4, 2, 3, + ComputeViewBinding::ScalarTable::srv, true}}; + shader.samplers = {{{17, 29, 61, 85}, true, true}}; + shader.sampler_heap = true; + shader.instruction_count = 73; + shader.group = {32, 7, 2}; + shader.vertex_fetch = true; + shader.pixel_writes = {15, 2, 13, 4, 11, 6, 9, 8}; + + const auto payload = encode(shader); + check(decode(payload) == shader, "populated frontend shader changed on round trip"); + check(refuses(std::string_view(payload).substr(0, payload.size() - 1)), "accepted truncated payload"); + check(refuses(payload + 'x'), "accepted trailing payload data"); + + auto different = shader; + different.mesh_heap_tokens.reset(); + check(!(different == shader), "comparison ignored absent mesh heap tokens"); + check(decode(encode(different)) == different, "absent mesh heap tokens changed on round trip"); + different = shader; + different.pixel_descriptor_records.back().second += 32; + check(!(different == shader), "comparison ignored a pixel descriptor record"); + different = shader; + different.hlsl.clear(); + check(!(different == shader), "comparison ignored HLSL"); + check(decode(encode(different)) == different, "empty HLSL changed on round trip"); + } catch (const std::exception &error) { + std::cerr << error.what() << '\n'; + return 1; + } +} diff --git a/tests/native_direct_container_check.py b/tests/native_direct_container_check.py index 413865f68..4bb2c131e 100644 --- a/tests/native_direct_container_check.py +++ b/tests/native_direct_container_check.py @@ -268,7 +268,34 @@ def check_scc_writer_mutant(): print("scc writer mutant: each new case is live once its overwrite entry is removed") +def check_cache_options(exe, sdk): + with tempfile.TemporaryDirectory() as tmp: + folder = pathlib.Path(tmp) + cache = folder / "cache" + vs, ps = folder / "vertex", folder / "pixel" + vs.write_bytes(vertex()) + ps.write_bytes(patched_pixel()) + vs_out, ps_out = folder / "vertex.cso", folder / "pixel.cso" + cmd = [exe, sdk, cache, "gfx1013-container-pair", vs, vs_out, ps, ps_out] + expected_dxil = None + for value, hit in (("0", 0), ("1", 0), ("1", 1), ("0", 1)): + env = dict(os.environ, X2W_MESH57_PARTIAL_ZERO=value) + result = subprocess.run(cmd, check=True, capture_output=True, text=True, env=env) + assert f"graphics_pair frontend_cache_hit={hit}" in result.stdout, result.stdout + dxil = (vs_out.read_bytes(), ps_out.read_bytes()) + if expected_dxil is None: + expected_dxil = dxil + assert dxil == expected_dxil, f"DXIL changed with option {value}, hit={hit}" + entries = list(cache.glob("*.pairir")) + assert len(entries) == 2, entries + # The fixture has no partial register writes. Both keys must store the same frontend payload. + assert entries[0].read_bytes()[128:] == entries[1].read_bytes()[128:] + + def main(): + if len(sys.argv) == 4 and sys.argv[1] == "--cache-options": + check_cache_options(*sys.argv[2:]) + return check_scc_writer_mutant() if len(sys.argv) == 4 and sys.argv[1] in ("--sampler-pso", "--graphics-sampler-pso"): sdk, probe = sys.argv[2:]