From 035ad7de6af1454ee118de3a8e41c5fd3daa1c59 Mon Sep 17 00:00:00 2001 From: Marcelo Frayha Date: Thu, 26 Nov 2026 16:53:53 -0300 Subject: [PATCH] runtime: pack barycentric geometry inputs separately from FP16 linking Link FP16 in the vertex/fragment namespace and compact the VS-to-GS edge independently on devices with low geometry input limits. Track typed pointer operand positions so numeric literals do not make unused inputs live. Cover the 64-component boundary and the literal-ID collision with synthetic tests. RT-BARY-FALLBACK-PACK-GS-INPUTS. Builds on the unused-input filtering proposed by ZroFreaks in robot00f/leonida#1. --- runtime/shims/d3d12_vulkan_device.cpp | 92 ++++----- runtime/src/spirv_bary_fallback.h | 226 ++++++++++++++++++++-- runtime/test/spirv_bary_fallback_test.cpp | 121 +++++++++++- 3 files changed, 364 insertions(+), 75 deletions(-) diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp index a05dc3e29a..ea2b78f7ee 100644 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ b/runtime/shims/d3d12_vulkan_device.cpp @@ -2337,7 +2337,7 @@ struct DeviceState { // Cached physical-device no-attachment sample counts for D3D12_OPTIONS19. UINT no_output_sample_counts = 0; std::uint32_t f16_half_top_location = 29; - std::uint32_t bary_f16_half_top_location = 29; + leonida::BaryFallbackGsLimits bary_geometry_limits{}; float max_sampler_lod_bias = 0; D3D12_CONSERVATIVE_RASTERIZATION_TIER conservative_raster_tier = D3D12_CONSERVATIVE_RASTERIZATION_TIER_NOT_SUPPORTED; bool conservative_post_depth_coverage = false; @@ -10984,6 +10984,7 @@ class PipelineState final Stage& gs_stage = stages[1]; Stage& ps_stage = stages[2]; const bool bary_fallback = ps_stage.entry && ps_stage.entry->bary_fallback_location.has_value(); + std::vector bary_words; if (bary_fallback) { const int bary_loc = int(*ps_stage.entry->bary_fallback_location); if (mesh) { @@ -11008,21 +11009,40 @@ class PipelineState final log_once("a --bary-fallback geometry stage takes triangles; topology type", desc.PrimitiveTopologyType); return E_INVALIDARG; } + leonida::BaryFallbackGsInfo bary_info{}; + std::string bary_error; + // The VS may need its output locations rewritten before its VkShaderModule is created. + if (!leonida::link_bary_fallback_stages( + vs_stage.words, *vs_stage.entry, ps_stage.words, *ps_stage.entry, device_.f16_half_top_location, + device_.bary_geometry_limits, bary_words, &bary_info, &bary_error)) { + std::fprintf(stderr, "[rt] d3d12: %s (%s -> %s)\n", bary_error.c_str(), + vs_stage.entry->name.c_str(), ps_stage.entry->name.c_str()); + return E_FAIL; + } + if (bary_info.clip_count && !device_.info.features.shaderClipDistance) { + return stream_unsupported( + "--bary-fallback geometry stage forwards ClipDistance, which needs shaderClipDistance; count", + int(bary_info.clip_count)); + } + if (bary_info.cull_count && !device_.info.features.shaderCullDistance) { + return stream_unsupported( + "--bary-fallback geometry stage forwards CullDistance, which needs shaderCullDistance; count", + int(bary_info.cull_count)); + } } if (vs_stage.entry && ps_stage.entry && !ps_stage.entry->f16_halves.empty() && gs_stage.entry) { log_once("--f16-interp-fallback halves are linked VS->PS only; this PSO has a geometry shader", 0); } - if (vs_stage.entry && ps_stage.entry && !gs_stage.entry && + if (!bary_fallback && vs_stage.entry && ps_stage.entry && !gs_stage.entry && (!ps_stage.entry->f16_halves.empty() || !vs_stage.entry->f16_halves.empty())) { std::string link_error; if (!link_f16_halves(vs_stage.words, *vs_stage.entry, ps_stage.words, *ps_stage.entry, - &link_error, bary_fallback)) { + &link_error)) { std::fprintf(stderr, "[rt] d3d12: %s\n", link_error.c_str()); return E_FAIL; } f16_linked_ = true; } - bary_fallback_ = bary_fallback; // A lazy pipeline keeps where each stage's words come from, not the words or a module: build() makes them // again, the same way, and drops them once the pipeline exists. lazy_ = lazy_graphics_pipelines(); @@ -11112,31 +11132,12 @@ class PipelineState final stage_infos.push_back(info); } if (bary_fallback) { // the stage that supplies (1,0,0)/(0,1,0)/(0,0,1) at bary_fallback_input.location - std::vector words; - leonida::BaryFallbackGsInfo bary_info{}; - std::string bary_error; - if (!leonida::build_bary_fallback_gs(vs_stage.words, ps_stage.words, - *ps_stage.entry->bary_fallback_location, words, &bary_info, - &bary_error)) { - std::fprintf(stderr, "[rt] d3d12: %s\n", bary_error.c_str()); - return E_FAIL; - } - if (bary_info.clip_count && !device_.info.features.shaderClipDistance) { - return stream_unsupported( - "--bary-fallback geometry stage forwards ClipDistance, which needs shaderClipDistance; count", - int(bary_info.clip_count)); - } - if (bary_info.cull_count && !device_.info.features.shaderCullDistance) { - return stream_unsupported( - "--bary-fallback geometry stage forwards CullDistance, which needs shaderCullDistance; count", - int(bary_info.cull_count)); - } - if (trace_pipeline_compile()) stage_bytes_ += words.size() * sizeof(std::uint32_t); + if (trace_pipeline_compile()) stage_bytes_ += bary_words.size() * sizeof(std::uint32_t); VkShaderModule module = VK_NULL_HANDLE; if (lazy_) { sources_.push_back({StageSource::bary_fallback}); } else { - module = shader_module(words); + module = shader_module(bary_words); if (!module) return E_FAIL; } VkPipelineShaderStageCreateInfo info{VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO}; @@ -12165,10 +12166,8 @@ class PipelineState final bool link_f16_halves(std::vector& vs_words, const leonida::ShaderEntry& vs_entry, std::vector& ps_words, const leonida::ShaderEntry& ps_entry, - std::string* error, bool bary_fallback = false) const { - const std::uint32_t top_loc = - bary_fallback ? device_.bary_f16_half_top_location : device_.f16_half_top_location; - return leonida::link_f16_halves(vs_words, vs_entry, ps_words, ps_entry, error, top_loc); + std::string* error) const { + return leonida::link_f16_halves(vs_words, vs_entry, ps_words, ps_entry, error, device_.f16_half_top_location); } public: @@ -12183,9 +12182,10 @@ class PipelineState final return false; } words.assign(sources_.size(), {}); - std::size_t vs = SIZE_MAX, ps = SIZE_MAX; + std::size_t vs = SIZE_MAX, ps = SIZE_MAX, bary = SIZE_MAX; for (std::size_t i = 0; i < sources_.size(); ++i) { const StageSource& source = sources_[i]; + if (source.kind == StageSource::bary_fallback) bary = i; if (source.kind != StageSource::library) continue; words[i] = library->spirv(*source.entry); if (words[i].empty()) { @@ -12201,8 +12201,14 @@ class PipelineState final } if (f16_linked_) { if (vs == SIZE_MAX || ps == SIZE_MAX || - !link_f16_halves(words[vs], *sources_[vs].entry, words[ps], *sources_[ps].entry, &why, - bary_fallback_)) + !link_f16_halves(words[vs], *sources_[vs].entry, words[ps], *sources_[ps].entry, &why)) + return false; + } + if (bary != SIZE_MAX) { + if (vs == SIZE_MAX || ps == SIZE_MAX || + !leonida::link_bary_fallback_stages( + words[vs], *sources_[vs].entry, words[ps], *sources_[ps].entry, device_.f16_half_top_location, + device_.bary_geometry_limits, words[bary], nullptr, &why)) return false; } for (std::size_t i = 0; i < sources_.size(); ++i) { @@ -12215,12 +12221,6 @@ class PipelineState final if (sources_[i].kind == StageSource::rect_list) { if (vs == SIZE_MAX) return false; words[i] = leonida::rect_list_geometry(words[vs], why); - } else if (sources_[i].kind == StageSource::bary_fallback) { - if (vs == SIZE_MAX || ps == SIZE_MAX || !sources_[ps].entry->bary_fallback_location || - !leonida::build_bary_fallback_gs(words[vs], words[ps], - *sources_[ps].entry->bary_fallback_location, words[i], nullptr, - &why)) - return false; } else if (sources_[i].kind == StageSource::depth_only) { words[i] = leonida::depth24_depth_only_fragment(depth24_bias_); } else { @@ -12265,9 +12265,8 @@ class PipelineState final const leonida::ShaderEntry* compute_entry_ = nullptr; // compute: the translated shader build_compute reads bool compute_failed_ = false; // compute: could not be built; not retried std::atomic skip_logged_{false}; // compute: the skipped program's first dispatch was logged - bool lazy_ = false; // graphics: built at the first draw (lazy_graphics_pipelines) - bool f16_linked_ = false; // graphics: the VS and PS words had their f16 halves linked - bool bary_fallback_ = false; // graphics: synthesized --bary-fallback geometry stage + bool lazy_ = false; // graphics: built at the first draw (lazy_graphics_pipelines) + bool f16_linked_ = false; // graphics: the VS and PS words had their f16 halves linked without a geometry stage leonida::Depth24Bias depth24_bias_{}; unsigned rgba4_mask_ = 0; // graphics: the B4G4R4A4 targets stored as RGBA8 that the pixel shader is quantised for bool dual_source_ = false; // graphics: a SRC1 blend factor; the pixel shader's SV_Target1 is Location 0, Index 1 @@ -13579,14 +13578,9 @@ class Device final ? info.f16_half_top_location : leonida::f16_half_top_location( props.limits.maxVertexOutputComponents, props.limits.maxFragmentInputComponents); - state_.bary_f16_half_top_location = state_.f16_half_top_location; - if (info.f16_half_top_location == 0 && - props.limits.maxGeometryInputComponents && props.limits.maxGeometryOutputComponents) { - state_.bary_f16_half_top_location = std::min( - state_.f16_half_top_location, - leonida::f16_half_top_location(props.limits.maxGeometryInputComponents, - props.limits.maxGeometryOutputComponents)); - } + state_.bary_geometry_limits = {props.limits.maxGeometryInputComponents, + props.limits.maxGeometryOutputComponents, + props.limits.maxGeometryTotalOutputComponents}; } if (const auto get_props2 = reinterpret_cast( info.get_instance_proc(info.instance, "vkGetPhysicalDeviceProperties2"))) { diff --git a/runtime/src/spirv_bary_fallback.h b/runtime/src/spirv_bary_fallback.h index 01194b8b67..5e66deff29 100644 --- a/runtime/src/spirv_bary_fallback.h +++ b/runtime/src/spirv_bary_fallback.h @@ -9,9 +9,9 @@ // triangle pass-through Geometry SPIR-V module (`tools/bary_fallback_gs.py` equivalent) in memory for the exact // `(VS, PS)` pair: // - copies `BuiltIn Position` across the triangle's 3 vertices (`Triangles` -> `OutputTriangleStrip`, 3 vertices); -// - copies every `vec4` `Location` input the PS reads (other than `bary_location`) that the VS exports, and -// zero-fills any declared PS `Location` input the VS omits without declaring a dangling GS `Input` (preserving -// `VUID-RuntimeSpirv-OpEntryPoint-08743` on both `VS -> GS` and `GS -> PS` interfaces); +// - copies each used `vec4` `Location` input other than `bary_location` that the VS exports. The runtime +// keeps unused or unexported PS locations as zero-filled GS outputs, and packs the VS -> GS interface +// independently of the GS -> PS interface when geometry input locations are scarce; // - forwards a VS `BuiltIn ClipDistance` or `BuiltIn CullDistance` `float[1..8]` array when present (rejecting // mixed clip+cull and `ShaderLayer` / `ShaderViewportIndex`, which a pass-through helper cannot forward); // - writes `(1, 0, 0)`, `(0, 1, 0)`, `(0, 0, 1)` at `bary_location` so perspective interpolation yields @@ -36,18 +36,77 @@ struct BaryFallbackGsInfo { std::uint32_t cull_count = 0; }; -inline bool build_bary_fallback_gs(std::span vs_words, - std::span ps_words, - std::uint32_t bary_location, - std::vector& gs_words, - BaryFallbackGsInfo* out_info = nullptr, - std::string* error = nullptr) { +struct BaryFallbackGsLimits { + std::uint32_t input_components = 0; + std::uint32_t output_components = 0; + std::uint32_t total_output_components = 0; +}; + +namespace spirv_detail { + +// The varyings are logical pointers to Input variables. Mark their first use, including when a copy, access chain +// or call passes a pointer onward. Inspect only pointer-capable ID operands: an ExtInst opcode, memory-access +// mask or similar literal may have the same numeric value as a live or dead variable's ID. +inline void visit_bary_input_pointer_operands(const Inst& inst, const auto& visit) { + const auto at = [&](std::size_t i) { + if (i < inst.words.size()) visit(inst.words[i]); + }; + const auto from = [&](std::size_t i) { + for (; i < inst.words.size(); ++i) visit(inst.words[i]); + }; + switch (inst.opcode) { + case kOpLoad: + case kOpAccessChain: + case kOpInBoundsAccessChain: + case 67: // OpPtrAccessChain + case 70: // OpInBoundsPtrAccessChain + case 83: // OpCopyObject + case 124: // OpBitcast + case 400: // OpCopyLogical + at(3); + break; + case kOpStore: + case 63: // OpCopyMemory + case 64: // OpCopyMemorySized + at(1); + at(2); + break; + case 57: // OpFunctionCall + case 169: // OpSelect (the condition is not a pointer) + from(4); + break; + case kOpExtInst: + case 4433: // OpExtInstWithForwardRefsKHR + from(5); // skip the instruction-set ID and literal opcode + break; + case 245: // OpPhi + for (std::size_t i = 3; i < inst.words.size(); i += 2) at(i); + break; + case 254: // OpReturnValue + at(1); + break; + case kOpVariable: // initializer of a function-local pointer variable + at(4); + break; + case 401: // OpPtrEqual + case 402: // OpPtrNotEqual + case 403: // OpPtrDiff + at(3); + at(4); + break; + } +} + +inline bool emit_bary_fallback_gs(std::span vs_words, + std::span ps_words, std::uint32_t bary_location, + std::vector& gs_words, BaryFallbackGsInfo* out_info, + std::string* error, BaryFallbackGsLimits limits = {}, + std::vector* packed_vs = nullptr) { const auto fail = [&](const std::string& msg) { if (error) *error = msg; return false; }; - using namespace spirv_detail; constexpr std::uint32_t kSpirvVersion15 = 0x00010500u; constexpr std::uint16_t kOpTypeVoid = 19; constexpr std::uint16_t kOpTypeArray = 28; @@ -96,6 +155,8 @@ inline bool build_bary_fallback_gs(std::span vs_words, std::map vs_var_builtins; // var_id -> BuiltIn std::map>> vs_member_builtins; std::vector> vs_loc_decs; // (target_id, loc) + std::set vs_component_targets; + bool vs_member_locations = false; for (const Inst& inst : vs_mod.insts) { if (inst.opcode == kOpFunction) break; @@ -109,8 +170,11 @@ inline bool build_bary_fallback_gs(std::span vs_words, } else if (inst.opcode == kOpDecorate && inst.words.size() >= 4) { if (inst.words[2] == kDecorationBuiltIn) vs_var_builtins[inst.words[1]] = inst.words[3]; if (inst.words[2] == kDecorationLocation) vs_loc_decs.emplace_back(inst.words[1], inst.words[3]); - } else if (inst.opcode == kOpMemberDecorate && inst.words.size() >= 5 && inst.words[3] == kDecorationBuiltIn) { - vs_member_builtins[inst.words[1]].emplace_back(inst.words[2], inst.words[4]); + if (inst.words[2] == kDecorationComponent) vs_component_targets.insert(inst.words[1]); + } else if (inst.opcode == kOpMemberDecorate && inst.words.size() >= 5) { + if (inst.words[3] == kDecorationBuiltIn) + vs_member_builtins[inst.words[1]].emplace_back(inst.words[2], inst.words[4]); + if (inst.words[3] == kDecorationLocation) vs_member_locations = true; } else if (inst.opcode == kOpTypeFloat && inst.words.size() == 3 && inst.words[2] == 32) { vs_float32_tys.insert(inst.words[1]); } else if (inst.opcode == kOpTypeInt && inst.words.size() == 4 && inst.words[2] == 32) { @@ -177,11 +241,10 @@ inline bool build_bary_fallback_gs(std::span vs_words, if (clip_count && cull_count) return fail("bary_fallback: cannot forward mixed ClipDistance and CullDistance"); - std::map vs_out_loc_pointee; // loc -> pointee_ty + std::map vs_out_var_by_loc; for (const auto& [target, loc] : vs_loc_decs) { - const auto it = vs_out_var_pointee.find(target); - if (it == vs_out_var_pointee.end()) continue; - if (!vs_out_loc_pointee.emplace(loc, it->second).second) + if (!vs_out_var_pointee.count(target)) continue; + if (!vs_out_var_by_loc.emplace(loc, target).second) return fail("bary_fallback: duplicate VS Output Location " + std::to_string(loc)); } @@ -192,6 +255,7 @@ inline bool build_bary_fallback_gs(std::span vs_words, std::set ps_v4float_tys; std::map ps_ptr_in_pointee; std::map ps_in_var_pointee; + std::map ps_in_var_by_loc; std::vector> ps_loc_decs; std::set ps_component_targets; @@ -224,6 +288,22 @@ inline bool build_bary_fallback_gs(std::span vs_words, return fail("bary_fallback: Component-decorated PS Input at Location " + std::to_string(loc)); if (!ps_in_loc_pointee.emplace(loc, it->second).second) return fail("bary_fallback: duplicate PS Input Location " + std::to_string(loc)); + ps_in_var_by_loc.emplace(loc, target); + } + + // The translator also declares inputs it never reads. A variable not referenced in any function is unused, + // even if listed in OpEntryPoint. + std::set referenced_ps_inputs; + if (packed_vs) { + bool in_function = false; + for (const Inst& inst : ps_mod.insts) { + if (inst.opcode == kOpFunction) in_function = true; + if (inst.opcode == kOpFunctionEnd) in_function = false; + if (!in_function) continue; + visit_bary_input_pointer_operands(inst, [&](std::uint32_t id) { + if (ps_in_var_pointee.count(id)) referenced_ps_inputs.insert(id); + }); + } } if (const auto bary_it = ps_in_loc_pointee.find(bary_location); @@ -240,9 +320,14 @@ inline bool build_bary_fallback_gs(std::span vs_words, if (!ps_v4float_tys.count(pt_ty)) return fail("bary_fallback: PS pass-through Input at Location " + std::to_string(loc) + " is not vec4"); pass_locs.push_back(loc); - const auto vs_it = vs_out_loc_pointee.find(loc); - if (vs_it != vs_out_loc_pointee.end()) { - if (!vs_v4float_tys.count(vs_it->second)) + if (packed_vs && !referenced_ps_inputs.count(ps_in_var_by_loc.at(loc))) { + zero_loc_set.insert(loc); + continue; + } + const auto vs_it = vs_out_var_by_loc.find(loc); + if (vs_it != vs_out_var_by_loc.end()) { + if (!vs_v4float_tys.count(vs_out_var_pointee.at(vs_it->second)) || + vs_component_targets.count(vs_it->second)) return fail("bary_fallback: VS Output at Location " + std::to_string(loc) + " is not vec4"); forwarded_locs.push_back(loc); } else { @@ -250,6 +335,54 @@ inline bool build_bary_fallback_gs(std::span vs_words, } } + const std::uint32_t builtin_components = 4 + clip_count + cull_count; + std::map remapped_inputs; // PS location -> new GS input location + std::map vs_location_edits; // VS variable ID -> new output location + if (limits.input_components) { + const std::uint64_t required = builtin_components + 4ull * forwarded_locs.size(); + if (required > limits.input_components) + return fail("bary_fallback: GS needs " + std::to_string(required) + " input components, device permits " + + std::to_string(limits.input_components)); + const std::uint32_t slots = (limits.input_components - builtin_components) / 4; + std::set used(forwarded_locs.begin(), forwarded_locs.end()); + std::uint32_t next_free = 0; + for (const std::uint32_t loc : forwarded_locs) { + if (loc < slots) continue; + // A free low slot may still contain an unread VS output. Swap it into the moved output's old slot, + // so the VS neither adds a location nor needs to rewrite any stores or pointer types. + while (used.count(next_free)) ++next_free; + const auto other = vs_out_var_by_loc.find(next_free); + if (other != vs_out_var_by_loc.end()) { + if (!vs_v4float_tys.count(vs_out_var_pointee.at(other->second)) || + vs_component_targets.count(other->second)) + return fail("bary_fallback: cannot repack a non-vec4 VS Output at Location " + + std::to_string(next_free)); + vs_location_edits.emplace(other->second, loc); + } + remapped_inputs.emplace(loc, next_free); + vs_location_edits.emplace(vs_out_var_by_loc.at(loc), next_free++); + } + if (!vs_location_edits.empty()) { + if (vs_member_locations) + return fail("bary_fallback: cannot repack VS outputs with member Locations"); + for (const auto& [loc, var] : vs_out_var_by_loc) { + if (!vs_v4float_tys.count(vs_out_var_pointee.at(var)) || vs_component_targets.count(var)) + return fail("bary_fallback: cannot repack a non-vec4 VS Output at Location " + std::to_string(loc)); + } + } + } + if (limits.output_components || limits.total_output_components) { + const std::uint64_t count = builtin_components + 3 + 4ull * pass_locs.size(); + const std::uint64_t last = std::max(4ull * bary_location + 3, + pass_locs.empty() ? 0ull : 4ull * pass_locs.back() + 4); + if (const auto required = std::max(count, last); limits.output_components && required > limits.output_components) + return fail("bary_fallback: GS needs " + std::to_string(required) + " output components per vertex, " + "device permits " + std::to_string(limits.output_components)); + if (limits.total_output_components && 3 * count > limits.total_output_components) + return fail("bary_fallback: GS needs " + std::to_string(3 * count) + " total output components, " + "device permits " + std::to_string(limits.total_output_components)); + } + // --- Synthesize Geometry SPIR-V module --- std::uint32_t next_id = 1; const auto alloc = [&]() { return next_id++; }; @@ -336,8 +469,11 @@ inline bool build_bary_fallback_gs(std::span vs_words, gs.insts.push_back(make_inst(kOpDecorate, {id_in_dist, kDecorationBuiltIn, dist_builtin})); gs.insts.push_back(make_inst(kOpDecorate, {id_out_dist, kDecorationBuiltIn, dist_builtin})); } - for (std::uint32_t loc : forwarded_locs) - gs.insts.push_back(make_inst(kOpDecorate, {id_in_loc[loc], kDecorationLocation, loc})); + for (std::uint32_t loc : forwarded_locs) { + const auto packed = remapped_inputs.find(loc); + gs.insts.push_back(make_inst(kOpDecorate, {id_in_loc[loc], kDecorationLocation, + packed == remapped_inputs.end() ? loc : packed->second})); + } for (std::uint32_t loc : pass_locs) gs.insts.push_back(make_inst(kOpDecorate, {id_out_loc[loc], kDecorationLocation, loc})); gs.insts.push_back(make_inst(kOpDecorate, {id_out_bary, kDecorationLocation, bary_location})); @@ -420,9 +556,57 @@ inline bool build_bary_fallback_gs(std::span vs_words, gs.insts.push_back(make_inst(kOpFunctionEnd, {})); gs.header = {kSpirvMagic, kSpirvVersion15, 0u, next_id, 0u}; + if (!vs_location_edits.empty()) { + for (Inst& inst : vs_mod.insts) { + if (inst.opcode != kOpDecorate || inst.words.size() != 4 || inst.words[2] != kDecorationLocation) continue; + const auto it = vs_location_edits.find(inst.words[1]); + if (it != vs_location_edits.end()) inst.words[3] = it->second; + } + *packed_vs = vs_mod.serialize(); + } gs_words = gs.serialize(); if (out_info) *out_info = {clip_count, cull_count}; return true; } +} // namespace spirv_detail + +inline bool build_bary_fallback_gs(std::span vs_words, + std::span ps_words, std::uint32_t bary_location, + std::vector& gs_words, BaryFallbackGsInfo* out_info = nullptr, + std::string* error = nullptr) { + return spirv_detail::emit_bary_fallback_gs(vs_words, ps_words, bary_location, gs_words, out_info, error); +} + +// Link the two interfaces separately. FP16 synthesis needs the ordinary varying namespace; only the VS outputs +// actually read by the GS need to land within its smaller input limit. The final GS -> PS locations stay put. +inline bool link_bary_fallback_stages(std::vector& vs_words, const ShaderEntry& vs_entry, + std::vector& ps_words, const ShaderEntry& ps_entry, + std::uint32_t f16_top_location, BaryFallbackGsLimits limits, + std::vector& gs_words, BaryFallbackGsInfo* info = nullptr, + std::string* error = nullptr) { + if (!ps_entry.bary_fallback_location) { + if (error) *error = "bary_fallback: missing pixel shader input location"; + return false; + } + const bool link_halves = !vs_entry.f16_halves.empty() || !ps_entry.f16_halves.empty(); + std::vector linked_vs, linked_ps; + if (link_halves) { + linked_vs = vs_words; + linked_ps = ps_words; + if (limits.output_components) + f16_top_location = std::min(f16_top_location, + f16_half_top_location(limits.output_components, limits.output_components)); + if (!link_f16_halves(linked_vs, vs_entry, linked_ps, ps_entry, error, f16_top_location)) return false; + } + std::vector packed_vs; + if (!spirv_detail::emit_bary_fallback_gs(link_halves ? linked_vs : vs_words, link_halves ? linked_ps : ps_words, + *ps_entry.bary_fallback_location, gs_words, info, error, limits, &packed_vs)) + return false; + if (!packed_vs.empty()) vs_words = std::move(packed_vs); + else if (link_halves) vs_words = std::move(linked_vs); + if (link_halves) ps_words = std::move(linked_ps); + return true; +} + } // namespace leonida diff --git a/runtime/test/spirv_bary_fallback_test.cpp b/runtime/test/spirv_bary_fallback_test.cpp index 5e06c555bb..fa9d9cc54d 100644 --- a/runtime/test/spirv_bary_fallback_test.cpp +++ b/runtime/test/spirv_bary_fallback_test.cpp @@ -5,7 +5,9 @@ // 4. VS ClipDistance[2] and CullDistance[3] forwarding (capabilities, BuiltIn arrays, no duplicate types). // 5. Combined link_f16_halves + build_bary_fallback_gs: f16 relocation preserves bary_location and forwards relocated halves. // 6. Clean refusals: mixed ClipDistance + CullDistance, ShaderLayer / ShaderViewportIndex, non-vec3 collision at bary_location. -// Optional `--dump-dir ` writes each synthesized GS binary for external `spirv-val` inspection. +// 7. RADV geometry input limit: preserve the GS -> PS layout while repacking only used VS -> GS varyings. +// 8. An extended instruction's literal opcode must not make an unused input appear live. +// Optional `--dump-dir ` writes synthetic SPIR-V for external `spirv-val` inspection. // No GPU or game files required. #include "../src/spirv_bary_fallback.h" @@ -139,9 +141,10 @@ std::vector build_vs(const VsSpec& spec) { } std::vector build_ps(const std::vector& raw_locs, - const std::set& flat_locs, - std::optional bary_v3_loc, - const std::map>& f16_halves = {}) { + const std::set& flat_locs, + std::optional bary_v3_loc, + const std::map>& f16_halves = {}, + const std::set& read_locs = {}, bool exp2 = false) { std::uint32_t next_id = 1; const auto alloc = [&]() { return next_id++; }; @@ -165,9 +168,18 @@ std::vector build_ps(const std::vector& raw_locs, in_v4_vars.push_back({alloc(), pair[0]}); in_v4_vars.push_back({alloc(), pair[1]}); } + std::vector> loads; + for (const auto& [var, loc] : in_v4_vars) + if (read_locs.count(loc)) loads.emplace_back(alloc(), var); + const std::uint32_t id_glsl = exp2 ? alloc() : 0; + const std::uint32_t id_one = exp2 ? alloc() : 0; + const std::uint32_t id_exp = exp2 ? alloc() : 0; + const std::uint32_t id_colour = exp2 ? alloc() : id_null_v4; std::vector w = {kSpirvMagic, 0x00010500u, 0, next_id, 0}; append_inst(w, kOpCapability, {1}); + if (exp2) + append_inst(w, kOpExtInstImport, {id_glsl, 0x4c534c47u, 0x6474732eu, 0x3035342eu, 0u}); // GLSL.std.450 append_inst(w, kOpMemoryModel, {0, 1}); std::vector ep = {kExecModelFragment, id_main, 0x6e69616du, 0x00000000u, id_out0}; @@ -192,6 +204,7 @@ std::vector build_ps(const std::vector& raw_locs, append_inst(w, kOpTypePointer, {id_ptr_in_v4, kStorageInput, id_v4float}); append_inst(w, kOpTypePointer, {id_ptr_out_v4, kStorageOutput, id_v4float}); append_inst(w, kOpConstantNull, {id_v4float, id_null_v4}); + if (exp2) append_inst(w, 43, {id_float, id_one, 0x3f800000u}); append_inst(w, kOpVariable, {id_ptr_out_v4, id_out0, kStorageOutput}); if (id_bary) append_inst(w, kOpVariable, {id_ptr_in_v3, id_bary, kStorageInput}); @@ -199,7 +212,12 @@ std::vector build_ps(const std::vector& raw_locs, append_inst(w, kOpFunction, {id_void, id_main, 0, id_fn}); append_inst(w, 248, {id_entry}); - append_inst(w, kOpStore, {id_out0, id_null_v4}); + for (const auto& [result, var] : loads) append_inst(w, kOpLoad, {id_v4float, result, var}); + if (exp2) { + append_inst(w, kOpExtInst, {id_float, id_exp, id_glsl, 29, id_one}); // Exp2 = literal 29 + append_inst(w, 80, {id_v4float, id_colour, id_exp, id_exp, id_exp, id_exp}); // OpCompositeConstruct + } + append_inst(w, kOpStore, {id_out0, id_colour}); append_inst(w, kOpReturn, {}); append_inst(w, kOpFunctionEnd, {}); return w; @@ -491,5 +509,98 @@ int main(int argc, char** argv) { CHECK(!build_bary_fallback_gs(vs_ok, ps_collide, 1, gs, nullptr, &err) && !err.empty() && gs == sentinel); } + // 7. The same layout as the GPU's combined case: the PS declares raw inputs 0..13 but reads only the halves. + { + ShaderEntry vs_e, ps_e; + ps_e.bary_fallback_location = 14; + ps_e.f16_halves = {{7, {15, 16}}}; + std::vector vs_raw, ps_raw; + for (std::uint32_t i = 0; i < 16; ++i) vs_raw.push_back(i); + for (std::uint32_t i = 0; i < 14; ++i) ps_raw.push_back(i); + const auto raw_vs = build_vs({.raw_locs = vs_raw}); + const auto raw_ps = build_ps(ps_raw, {}, 14, ps_e.f16_halves, {15, 16}); + auto vs = raw_vs; + auto ps = raw_ps; + std::vector gs; + std::string err; + CHECK(link_bary_fallback_stages(vs, vs_e, ps, ps_e, 29, {64, 128, 1024}, gs, nullptr, &err)); + GsInspection ins; + CHECK(verify_gs_module(gs, ins)); + CHECK((ins.in_locs == std::set{0, 1})); + CHECK(ins.out_loc_vec_len.size() == 17); + CHECK(ins.out_loc_vec_len.at(14) == 3); + CHECK(ins.out_loc_vec_len.at(28) == 4 && ins.out_loc_vec_len.at(29) == 4); + + auto linked_vs = raw_vs; + auto linked_ps = raw_ps; + CHECK(link_f16_halves(linked_vs, vs_e, linked_ps, ps_e, &err, 29)); + CHECK(ps == linked_ps); // repacking doesn't touch the GS -> PS interface + Module linked, packed; + CHECK(linked.parse(linked_vs) && packed.parse(vs)); + const auto original_outputs = collect_located_vars(linked, kStorageOutput); + const auto packed_outputs = collect_located_vars(packed, kStorageOutput); + CHECK(packed_outputs.size() == original_outputs.size()); + CHECK(packed_outputs.at(0) == original_outputs.at(28) && packed_outputs.at(1) == original_outputs.at(29)); + CHECK(packed_outputs.at(28) == original_outputs.at(0) && packed_outputs.at(29) == original_outputs.at(1)); + CHECK(packed_outputs.at(7) == original_outputs.at(7)); + maybe_dump(dump_dir, "vs_radv_packed", vs); + maybe_dump(dump_dir, "gs_radv_packed", gs); + maybe_dump(dump_dir, "ps_radv_linked", ps); + + vs = raw_vs; + ps = raw_ps; + const auto saved_gs = gs; + CHECK(!link_bary_fallback_stages(vs, vs_e, ps, ps_e, 29, {11, 128, 1024}, gs, nullptr, &err)); + CHECK(err == "bary_fallback: GS needs 12 input components, device permits 11"); + CHECK(vs == raw_vs && ps == raw_ps && gs == saved_gs); + CHECK(!link_bary_fallback_stages(vs, vs_e, ps, ps_e, 29, {64, 128, 212}, gs, nullptr, &err)); + CHECK(err == "bary_fallback: GS needs 213 total output components, device permits 212"); + CHECK(vs == raw_vs && ps == raw_ps && gs == saved_gs); + + std::set reads(ps_raw.begin(), ps_raw.end()); + reads.insert({15, 16}); + ps = build_ps(ps_raw, {}, 14, ps_e.f16_halves, reads); + const auto full_ps = ps; + CHECK(!link_bary_fallback_stages(vs, vs_e, ps, ps_e, 29, {64, 128, 1024}, gs, nullptr, &err)); + CHECK(err == "bary_fallback: GS needs 68 input components, device permits 64"); + CHECK(vs == raw_vs && ps == full_ps && gs == saved_gs); + } + + // 8. Position plus 15 real vec4 inputs fit in 64 components. An unused 16th input has the ID + // of GLSL.std.450 Exp2's instruction number (29) but is not itself an operand of the Exp2. + { + ShaderEntry vs_e, ps_e; + ps_e.bary_fallback_location = 16; + std::vector locs; + for (std::uint32_t i = 0; i < 16; ++i) locs.push_back(i); + const std::set reads(locs.begin(), locs.end() - 1); + auto vs = build_vs({.raw_locs = locs}); + auto ps = build_ps(locs, {}, 16, {}, reads, true); + Module m; + CHECK(m.parse(ps)); + CHECK(collect_located_vars(m, kStorageInput).at(15) == 29); + std::vector gs; + std::string err; + CHECK(link_bary_fallback_stages(vs, vs_e, ps, ps_e, 29, {64, 128, 1024}, gs, nullptr, &err)); + GsInspection ins; + CHECK(verify_gs_module(gs, ins)); + CHECK(ins.in_locs == reads && ins.out_loc_vec_len.at(15) == 4); + maybe_dump(dump_dir, "ps_literal_alias", ps); + maybe_dump(dump_dir, "gs_literal_alias", gs); + } + + // The first use can pass the input pointer onward rather than loading it directly. + { + const auto operands = [](const Inst& inst) { + std::vector ids; + visit_bary_input_pointer_operands(inst, [&](std::uint32_t id) { ids.push_back(id); }); + return ids; + }; + CHECK(operands(make_inst(kOpAccessChain, {1, 2, 29, 3})) == std::vector{29}); + CHECK(operands(make_inst(57, {1, 2, 3, 29})) == std::vector{29}); // OpFunctionCall + CHECK(operands(make_inst(kOpExtInst, {1, 2, 3, 76, 29})) == std::vector{29}); + CHECK(operands(make_inst(kOpLoad, {1, 2, 3, 2, 16})) == std::vector{3}); // Aligned 16 + } + return 0; }