From e3841ecdc577c6169ccdd025c21d1354c5f00494 Mon Sep 17 00:00:00 2001 From: Savvanis Spyros Date: Tue, 20 Oct 2026 11:33:06 +0300 Subject: [PATCH 1/5] perf(agc): bound vertex-indexed guest buffers by the draw's vertex range A GCN vertex shader reaches its fetch subroutine through s_swappc. The driver links that subroutine into the program, so its buffer loads stay generic guest-buffer loads indexed by v0 rather than lifted vertex attributes. Their V#s describe the whole vertex ring, so every draw bound and, when the draw cache reused a draw at a moved base, snapshotted the ring whole. The resource tracker now proves, per buffer resource, that every access is an IDXEN load whose index is the VertexIndex builtin and whose VGPR offset and SOFFSET are immediates, and records how far past index * stride those loads read (formatted loads count 16 bytes). The value reaches the driver as DescriptorBinding::bufferVertexExtent (shader disk cache format 37). For a direct draw on the vertex path without mesh or tessellation stages, a read-only element with that proof is bound, alias-checked and snapshotted when its V# moves only up to maxIndex * stride plus the extent, rounded up to 16 bytes and never past the V#'s own size. maxIndex is the bound vertex attributes already use: the highest index plus the base vertex, or the last vertex of an auto draw. A recipe hit whose template was bound for another vertex range is a miss. Indirect draws, written elements, swizzled or ADD_TID V#s and any other access keep the whole range. Monopoly Plus (CUSA03312) draws its quads from a 40 MB ring whose base advances 0x60 bytes per draw. Its 0x27ffff0-byte draw snapshots are gone, and its language screen runs at about 6.1 instead of 2.9 frames per second on an RX 9070 XT. Co-Authored-By: Claude Opus 5.5 --- core/libs/prx/libSceAgcDriver/CMakeLists.txt | 10 +- .../libSceAgcDriver/Graphics/include/Draw.hpp | 2 +- .../Graphics/include/ShaderResources.hpp | 9 +- .../prx/libSceAgcDriver/Graphics/src/Draw.cpp | 33 ++-- .../Graphics/src/ShaderResources.cpp | 47 +++++- .../prx/libSceAgcDriver/tests/Graphics.cpp | 107 +++++++++++++ .../libSceAgcDriver/tests/ShaderDiskCache.cpp | 3 +- .../libSceAgcDriver/tests/ShaderMemory.cpp | 65 ++++++++ .../tests/execution/VertexIndexedRing.cpp | 149 ++++++++++++++++++ .../IrMetadata/Resources.hpp | 1 + .../src/DescriptorBindingBuilder.cpp | 1 + .../Optimization/src/ResourceTracker.cpp | 29 +++- core/shader/recompiler/Recompiler.hpp | 1 + core/shader/recompiler/ShaderDiskCache.cpp | 8 +- core/shader/recompiler/ShaderDiskCache.hpp | 2 +- 15 files changed, 437 insertions(+), 30 deletions(-) create mode 100644 core/libs/prx/libSceAgcDriver/tests/execution/VertexIndexedRing.cpp diff --git a/core/libs/prx/libSceAgcDriver/CMakeLists.txt b/core/libs/prx/libSceAgcDriver/CMakeLists.txt index ada29c686f27..7dbccd0debef 100644 --- a/core/libs/prx/libSceAgcDriver/CMakeLists.txt +++ b/core/libs/prx/libSceAgcDriver/CMakeLists.txt @@ -1523,6 +1523,8 @@ if(BUILD_TESTING) set_tests_properties(agc_shader_srt_read_patching PROPERTIES ENVIRONMENT "ANYPS5_NO_SHADER_CACHE=1" WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}") add_test(NAME agc_shader_type_zero_image_materialization COMMAND agc_shader_memory_tests --type-zero-image-materialization) set_tests_properties(agc_shader_type_zero_image_materialization PROPERTIES ENVIRONMENT "ANYPS5_NO_SHADER_CACHE=1" WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}") + add_test(NAME agc_shader_vertex_index_extents COMMAND agc_shader_memory_tests --vertex-index-extents) + set_tests_properties(agc_shader_vertex_index_extents PROPERTIES ENVIRONMENT "ANYPS5_NO_SHADER_CACHE=1" WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}") add_test(NAME agc_shader_frontend_pair COMMAND agc_shader_memory_tests --frontend-pair) add_test(NAME agc_shader_quad_mask_no_demote COMMAND agc_shader_memory_tests --quad-mask-no-demote) set_tests_properties(agc_shader_quad_mask_no_demote PROPERTIES ENVIRONMENT "ANYPS5_NO_SHADER_CACHE=1" WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}" TIMEOUT 30) @@ -1537,7 +1539,7 @@ if(BUILD_TESTING) set_tests_properties(agc_shader_layout_pair PROPERTIES ENVIRONMENT "ANYPS5_NO_SHADER_CACHE=1" WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}") set_tests_properties(agc_shader_layout_pair_off PROPERTIES ENVIRONMENT "ANYPS5_NO_SHADER_CACHE=1;APS5_NO_PERF_LAYOUT_PAIR=1" WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}") if(WIN32) - set_tests_properties(agc_shader_bindless agc_shader_srt_read_patching agc_shader_type_zero_image_materialization agc_shader_frontend_pair agc_shader_frontend_pair_off agc_shader_layout_pair agc_shader_layout_pair_off PROPERTIES ENVIRONMENT_MODIFICATION "PATH=path_list_prepend:$") + set_tests_properties(agc_shader_bindless agc_shader_srt_read_patching agc_shader_type_zero_image_materialization agc_shader_vertex_index_extents agc_shader_frontend_pair agc_shader_frontend_pair_off agc_shader_layout_pair agc_shader_layout_pair_off PROPERTIES ENVIRONMENT_MODIFICATION "PATH=path_list_prepend:$") endif() foreach(agcTest IN ITEMS agc_vertex_input_tests agc_shared_write_tests agc_driver_tests agc_shader_memory_tests agc_structurizer_tests agc_spirv_module_tests agc_dpp_write_tests agc_masked_select_tests agc_ir_reclaim_tests agc_vector_window_tests agc_constant_bit_test_tests agc_integer_narrowing_tests agc_scalar_select_mask_tests agc_vop1_control_decode_tests agc_validate_program_tests agc_pass_hazards_tests agc_shader_disk_cache_tests agc_shader_device_profile_tests agc_placeholder_images_tests agc_shader_control_flow_tests agc_driver_flip_tests agc_driver_pm4_tests agc_driver_graphics_tests agc_driver_bda_device_tests agc_driver_mesh_tests agc_driver_cmask_fast_clear_tests agc_formatted_buffer_once_tests agc_formatted_buffer_byte_stores_tests ${agcExecutionTests} agc_fma_mix_once_tests) if(agcTest STREQUAL "agc_driver_constant_store_tests" OR agcTest STREQUAL "agc_driver_flat_apertures_tests" OR agcTest STREQUAL "agc_driver_pipeline_optimized_readback_tests") @@ -1563,6 +1565,12 @@ if(BUILD_TESTING) ENVIRONMENT_MODIFICATION "PATH=path_list_prepend:$") endif() add_test(NAME agc_sparse_buffer_holes COMMAND agc_driver_graphics_tests --sparse-buffer-holes) + add_test(NAME agc_driver_vertex_range_bindings COMMAND agc_driver_graphics_tests --vertex-range-bindings) + set_tests_properties(agc_driver_vertex_range_bindings PROPERTIES TIMEOUT 30) + if(WIN32) + set_tests_properties(agc_driver_vertex_range_bindings PROPERTIES ENVIRONMENT_MODIFICATION + "PATH=path_list_prepend:$") + endif() set_tests_properties(agc_driver_native_multisample_depth PROPERTIES TIMEOUT 30) add_test(NAME agc_driver_native_depth_retirement COMMAND agc_driver_native_multisample_depth_tests --retirement) set_tests_properties(agc_driver_native_depth_retirement PROPERTIES TIMEOUT 30 ENVIRONMENT "ANYPS5_NO_SHADER_CACHE=1" SKIP_RETURN_CODE 77 WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}") diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/Draw.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/Draw.hpp index 0286db6e8e39..f4e956b2e707 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/Draw.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/Draw.hpp @@ -65,7 +65,7 @@ MeshArguments ResolveMeshArguments(const Pm4::DrawArguments& record, const MeshA // storage cache, the template is gone, the pipeline is gone from the pipeline store, or the // template's proof failed (ShaderResources::ProveCurrent; the template is removed from the // resource cache and kept by the batch). -enum class DrawRecipeMiss : std::uint8_t { None, NotRecordable, TargetGone, TemplateGone, ObjectsGone, Proof, Count }; +enum class DrawRecipeMiss : std::uint8_t { None, NotRecordable, TargetGone, TemplateGone, ObjectsGone, Proof, VertexRange, Count }; const char* DrawRecipeMissName(DrawRecipeMiss miss); struct DrawRecipeOutcome { bool recorded = false; diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp index 8e25d227c9e6..eef8f48fc2f3 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp @@ -125,7 +125,7 @@ ImageTableReuseCounts ImageTableReuses(); class ShaderResources { public: ShaderResources(const Context& context, const ShaderRecompiler::RecompileResult& vertex, const ShaderRecompiler::RecompileResult& fragment, const ColorTarget& target, std::uint64_t indexAddress, std::size_t indexBytes); - ShaderResources(const Context& context, std::span shaders, const ColorTarget& target, std::uint32_t colorAttachments, std::uint64_t indexAddress, std::size_t indexBytes, std::span snapshots = {}); + ShaderResources(const Context& context, std::span shaders, const ColorTarget& target, std::uint32_t colorAttachments, std::uint64_t indexAddress, std::size_t indexBytes, std::span snapshots = {}, std::optional maxVertex = std::nullopt); ShaderResources(const Context& context, const CompiledShader& compute, std::span snapshots = {}); // Two-stage build for dispatches (see build): with `deferred` the constructor runs stage A only, // which needs no device lock, and Complete() runs stage B under GuestMemory::GpuMutex; until @@ -169,7 +169,9 @@ class ShaderResources { std::vector words; }; std::shared_ptr PrepareDrawBindings(Recorder& recorder, std::span moved = {}) const; - std::optional> MovedReadOnlyBuffers(std::span shaders, Recorder& recorder) const; + std::optional> MovedReadOnlyBuffers(std::span shaders, Recorder& recorder, std::optional maxVertex = std::nullopt) const; + bool BindsVertexRange(std::span shaders, std::optional maxVertex) const; + static std::uint64_t VertexBoundBytes(const ShaderRecompiler::DescriptorBinding& binding, std::uint32_t element, std::optional maxVertex); static std::size_t MaxDrawSnapshotBytes(); void WriteBack(); // Deferred completion: MarkGpuWrites registers the results the recorded work leaves on the GPU @@ -374,7 +376,7 @@ class ShaderResources { // `written` is the element's DescriptorBinding::bufferWritten: a read-only element binds the // same way but is left out of the write set (no write-back, no pending-write note). `atomic` // is its bufferAtomic (see GuestBufferMemory::AddWritable). - std::size_t addGuestBuffer(std::span words, const ColorTarget* target, std::uint64_t indexAddress, std::size_t indexBytes, bool written, bool atomic, bool read); + std::size_t addGuestBuffer(const ShaderRecompiler::DescriptorBinding& binding, std::uint32_t element, const ColorTarget* target, std::uint64_t indexAddress, std::size_t indexBytes, bool written, bool atomic, bool read); std::size_t addDataBuffer(std::span words); // Stage A: the layout entry of an image binding (samplers are taken at once, the sampler cache // locks itself); stage B looks the sampled textures and storage images up (resolveImageBinding). @@ -524,6 +526,7 @@ class ShaderResources { // notes (counted in MarkGpuWrites for the [buffers] line). std::size_t readOnlyBuffers = 0; bool drawBuild = false; + std::optional drawMaxVertex; std::uint64_t dispatchThreads = 0; std::vector> textures; std::vector textureFirstLayer; diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp index c3ad0dcbff29..0b67f635ba72 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp @@ -765,7 +765,7 @@ ResourceCache::Key DrawResourceKey(const Context& context, std::span shaders, const ColorTarget& target, std::uint64_t indexAddress, std::uint64_t indexBytes) { +void CheckBufferAliases(std::span shaders, const ColorTarget& target, std::uint64_t indexAddress, std::uint64_t indexBytes, std::optional maxVertex) { const auto overlap = [](std::uint64_t first, std::uint64_t firstSize, std::uint64_t second, std::uint64_t secondSize) { return first < second + secondSize && second < first + firstSize; }; for (const auto& shader : shaders) { for (const auto& binding : shader.program->bindings) { @@ -774,9 +774,9 @@ void CheckBufferAliases(std::span shaders, const ColorTarg for (std::size_t offset = 0; offset + 4 <= words.size(); offset += 4) { const ShaderRecompiler::ShaderBufferResource descriptor{{words[offset], words[offset + 1], words[offset + 2], words[offset + 3]}}; const auto address = descriptor.Base48(); - const auto size = descriptor.GetSize(); - if (size == 0 || address == 0) continue; const auto element = offset / 4; + const auto size = ShaderResources::VertexBoundBytes(binding, static_cast(element), maxVertex); + if (size == 0 || address == 0) continue; const bool written = element >= binding.bufferWritten.size() || binding.bufferWritten[element]; Require(!overlap(address, size, target.address, target.bytes), "shader buffer aliases the render target"); Require(!written || !overlap(address, size, indexAddress, indexBytes), "writable shader buffer aliases the index buffer"); @@ -850,7 +850,7 @@ bool DrawRecipes() { } const char* DrawRecipeMissName(DrawRecipeMiss miss) { - constexpr std::array(DrawRecipeMiss::Count)> names{"none", "not recordable", "target gone", "template gone", "objects gone", "proof"}; + constexpr std::array(DrawRecipeMiss::Count)> names{"none", "not recordable", "target gone", "template gone", "objects gone", "proof", "vertex range"}; return names[static_cast(miss)]; } @@ -996,6 +996,11 @@ struct DrawInputs { const VertexInputLayout& VertexLayout() const { return retainedVertexInput != nullptr ? *retainedVertexInput : vertexInput; } }; +std::optional drawVertexBound(const State& state, const Pm4::DrawParameters& draw, const DrawInputs& inputs) { + if (draw.indirect || state.stages.path != ShaderPath::Vertex || state.stages.mesh || state.stages.tessellation) return std::nullopt; + return inputs.maxIndex; +} + std::shared_ptr zeroVertexBuffer(const Context& context, const ShaderRecompiler::VertexAttribute& attribute) { auto zero = std::make_shared(context, DecodeVertexFormat(attribute).bytes, VK_BUFFER_USAGE_VERTEX_BUFFER_BIT); std::fill(zero->Bytes().begin(), zero->Bytes().end(), std::byte{0}); @@ -1275,7 +1280,7 @@ struct ResolvedResources { const ShaderResources::BuildTiming* built = nullptr; }; -ResolvedResources resolveDrawResources(const Context& context, const State& state, const Pm4::DrawParameters& draw, std::span shaders, std::span snapshots, std::uint64_t indexBytes, bool recordable, DrawOutcome& outcome, DrawTimer& timer) { +ResolvedResources resolveDrawResources(const Context& context, const State& state, const Pm4::DrawParameters& draw, std::span shaders, std::span snapshots, std::uint64_t indexBytes, std::optional maxVertex, bool recordable, DrawOutcome& outcome, DrawTimer& timer) { ResolvedResources resolved; APS5_LOG_CHARS_OUT_DEBUG("Creating ShaderResources"); // A recordable draw whose stages' compiled content repeats an earlier one binds that build's @@ -1296,9 +1301,9 @@ ResolvedResources resolveDrawResources(const Context& context, const State& stat const bool valid = cached->Revalidate(shaders); auto* recorder = Recorder::Active(); std::optional> moved; - if (valid && recorder != nullptr) moved = cached->MovedReadOnlyBuffers(shaders, *recorder); + if (valid && recorder != nullptr) moved = cached->MovedReadOnlyBuffers(shaders, *recorder, maxVertex); if (moved.has_value()) { - if (trimKey) CheckBufferAliases(shaders, state.color, draw.indexAddress, indexBytes); + if (trimKey) CheckBufferAliases(shaders, state.color, draw.indexAddress, indexBytes, maxVertex); resolved.resources = std::move(cached); resolved.moved = std::move(*moved); outcome.kind = KindTemplateHit; @@ -1315,7 +1320,7 @@ ResolvedResources resolveDrawResources(const Context& context, const State& stat } timer.phase(PhaseLookup); if (resolved.resources == nullptr) { - resolved.resources = std::make_shared(context, shaders, state.color, static_cast(state.colors.size()), draw.indexAddress, static_cast(indexBytes), snapshots); + resolved.resources = std::make_shared(context, shaders, state.color, static_cast(state.colors.size()), draw.indexAddress, static_cast(indexBytes), snapshots, maxVertex); resolved.built = &resolved.resources->Timing(); outcome.addressBased = resolved.resources->HoldsLease(); outcome.kind = outcome.addressBased ? KindBda : KindBuild; @@ -2073,7 +2078,8 @@ void Draw(const Context& context, const State& state, const Pm4::DrawParameters& const bool recordDraws = RecordDraws(); auto* recorder = Recorder::Active(); bool recordable = recordDraws && recorder != nullptr && dumpLimit == 0 && std::all_of(targets.begin(), targets.end(), [](const TargetBinding& binding) { return binding.resident != nullptr || binding.multisampled; }); - auto resolved = resolveDrawResources(context, state, draw, shaders, snapshots, indexBytes, recordable, outcome, timer); + const auto maxVertex = drawVertexBound(state, draw, inputs); + auto resolved = resolveDrawResources(context, state, draw, shaders, snapshots, indexBytes, maxVertex, recordable, outcome, timer); auto& resources = resolved.resources; if (!stencilReferences.empty() && resources->ChecksFaults()) recordable = false; if (!stencilReferences.empty()) { @@ -2214,7 +2220,7 @@ void Draw(const Context& context, const State& state, const Pm4::DrawParameters& if (binding.multisampled) Require(std::find(resources->MultisampleSources().begin(), resources->MultisampleSources().end(), binding.color.surfaceAddress) == resources->MultisampleSources().end(), "sampling a multisampled color target the draw renders to is not implemented"); } if (!lean && !resolved.moved.empty()) { - resolved.resources = std::make_shared(context, shaders, state.color, static_cast(state.colors.size()), draw.indexAddress, static_cast(indexBytes), snapshots); + resolved.resources = std::make_shared(context, shaders, state.color, static_cast(state.colors.size()), draw.indexAddress, static_cast(indexBytes), snapshots, maxVertex); resolved.moved.clear(); } if (state.depth) RequireNoNativeDepthFeedback_nid_no_patch(context, *state.depth, resources->SampledTextures()); @@ -2639,7 +2645,12 @@ DrawRecipeOutcome DrawWithRecipe(const Context& context, const State& state, con timer.phase(PhaseLookup); return miss(DrawRecipeMiss::Proof); } - CheckBufferAliases(shaders, state.color, draw.indexAddress, inputs.indexBytes); + const auto maxVertex = drawVertexBound(state, draw, inputs); + if (!resources->BindsVertexRange(shaders, maxVertex)) { + timer.phase(PhaseLookup); + return miss(DrawRecipeMiss::VertexRange); + } + CheckBufferAliases(shaders, state.color, draw.indexAddress, inputs.indexBytes, maxVertex); SharedResourceCache().Touch(recipe.key); countCache(&DrawProfile::cacheHits); timer.phase(PhaseLookup); diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp index d9c0124e4505..9845780f5024 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp @@ -1191,8 +1191,9 @@ bool SameAsPreviousStorageElement(const ShaderRecompiler::DescriptorBinding& bin ShaderResources::ShaderResources(const Context& context, const ShaderRecompiler::RecompileResult& vertex, const ShaderRecompiler::RecompileResult& fragment, const ColorTarget& target, std::uint64_t indexAddress, std::size_t indexBytes) : ShaderResources(context, std::array{{{ShaderRecompiler::ShaderStage::Vertex, &vertex, 0}, {ShaderRecompiler::ShaderStage::Fragment, &fragment, static_cast(vertex.pushConstants.size())}}}, target, 1, indexAddress, indexBytes) {} -ShaderResources::ShaderResources(const Context& context, std::span shaders, const ColorTarget& target, std::uint32_t colorAttachments, std::uint64_t indexAddress, std::size_t indexBytes, std::span snapshots) : context(context), guestMemory(context) { +ShaderResources::ShaderResources(const Context& context, std::span shaders, const ColorTarget& target, std::uint32_t colorAttachments, std::uint64_t indexAddress, std::size_t indexBytes, std::span snapshots, std::optional maxVertex) : context(context), guestMemory(context) { drawBuild = true; + drawMaxVertex = maxVertex; prepareAddressBindings(shaders, snapshots); build(shaders, &target, colorAttachments, indexAddress, indexBytes); } @@ -1630,7 +1631,7 @@ void ShaderResources::buildPrepare(std::span shaders, cons const bool written = element >= binding.bufferWritten.size() || binding.bufferWritten[element]; const bool atomic = element < binding.bufferAtomic.size() && binding.bufferAtomic[element]; const bool read = element < binding.bufferRead.size() && binding.bufferRead[element]; - const auto index = addGuestBuffer(std::span(binding.guestDescriptor).subspan(static_cast(element) * 4, 4), target, indexAddress, indexBytes, written, atomic, read); + const auto index = addGuestBuffer(binding, element, target, indexAddress, indexBytes, written, atomic, read); const auto& push = shader.program->pushConstants; if (!push.empty()) { const auto position = shader.program->memoryOffsetDword * 4u + element; @@ -3536,13 +3537,13 @@ DescriptorCache::Stats DescriptorCache::Counters() const { return stats; } -std::size_t ShaderResources::addGuestBuffer(std::span words, const ColorTarget* target, std::uint64_t indexAddress, std::size_t indexBytes, bool written, bool atomic, bool read) { - Require(words.size() == 4, "buffer descriptor must contain four DWORDs"); +std::size_t ShaderResources::addGuestBuffer(const ShaderRecompiler::DescriptorBinding& binding, std::uint32_t element, const ColorTarget* target, std::uint64_t indexAddress, std::size_t indexBytes, bool written, bool atomic, bool read) { + const auto words = std::span(binding.guestDescriptor).subspan(static_cast(element) * 4, 4); Require((words[1] & 0x40000000u) == 0, "buffer descriptor has reserved bits set"); const ShaderRecompiler::ShaderBufferResource descriptor{{words[0], words[1], words[2], words[3]}}; Require(descriptor.Type() == 0u, "buffer descriptor uses an unsupported type"); const auto address = descriptor.Base48(); - auto byteSize = descriptor.GetSize(); + auto byteSize = VertexBoundBytes(binding, element, drawMaxVertex); if (byteSize > context.limits.maxStorageBufferRange) { const auto mappedEnd = RegisteredReadableEnd(address); if (mappedEnd <= address) byteSize = 0; @@ -4462,7 +4463,7 @@ ShaderResources::DrawBindings::~DrawBindings() { release(fragmentLayout, fragmentAllocation); } -std::optional> ShaderResources::MovedReadOnlyBuffers(std::span shaders, Recorder& recorder) const { +std::optional> ShaderResources::MovedReadOnlyBuffers(std::span shaders, Recorder& recorder, std::optional maxVertex) const { std::vector moved; if ((_set == VK_NULL_HANDLE && fragment.set == VK_NULL_HANDLE) || usesBda) return moved; for (const auto& shader : shaders) { @@ -4488,7 +4489,7 @@ std::optional> ShaderResources::MovedR const auto* words = binding.guestDescriptor.data() + static_cast(element) * 4u; const ShaderRecompiler::ShaderBufferResource descriptor{{words[0], words[1], words[2], words[3]}}; const auto address = descriptor.Base48(); - const auto size = descriptor.GetSize(); + const auto size = VertexBoundBytes(binding, element, maxVertex); const auto index = kept->allocations[element]; const auto& item = allocations[index]; const bool empty = size == 0 || address == 0; @@ -4510,6 +4511,38 @@ std::optional> ShaderResources::MovedR return moved; } +bool ShaderResources::BindsVertexRange(std::span shaders, std::optional maxVertex) const { + for (const auto& shader : shaders) { + if (shader.program == nullptr) return false; + for (const auto& binding : shader.program->bindings) { + if (binding.role != ShaderRecompiler::DescriptorRole::GuestBuffers || binding.guestDescriptor.size() != static_cast(binding.count) * 4u) continue; + const auto kept = std::find_if(bindings.begin(), bindings.end(), [&](const Binding& item) { return item.layout.binding == binding.binding; }); + for (std::uint32_t element = 0; element < binding.count && element < binding.bufferVertexExtent.size(); ++element) { + if (binding.bufferVertexExtent[element] == 0u) continue; + if (kept == bindings.end() || kept->allocations.size() != binding.count) return false; + const auto* words = binding.guestDescriptor.data() + static_cast(element) * 4u; + const ShaderRecompiler::ShaderBufferResource descriptor{{words[0], words[1], words[2], words[3]}}; + const auto& item = allocations[kept->allocations[element]]; + if (!item.guest) continue; + if (item.address != descriptor.Base48() || item.size != VertexBoundBytes(binding, element, maxVertex)) return false; + } + } + } + return true; +} + +std::uint64_t ShaderResources::VertexBoundBytes(const ShaderRecompiler::DescriptorBinding& binding, std::uint32_t element, std::optional maxVertex) { + Require(binding.guestDescriptor.size() >= (static_cast(element) + 1u) * 4u, "buffer descriptor must contain four DWORDs"); + const auto* words = binding.guestDescriptor.data() + static_cast(element) * 4u; + const ShaderRecompiler::ShaderBufferResource descriptor{{words[0], words[1], words[2], words[3]}}; + const auto bytes = descriptor.GetSize(); + const bool written = element >= binding.bufferWritten.size() || binding.bufferWritten[element]; + const auto extent = element < binding.bufferVertexExtent.size() ? binding.bufferVertexExtent[element] : 0u; + if (!maxVertex.has_value() || written || extent == 0u || descriptor.SwizzleEnabled() || descriptor.AddTid()) return bytes; + const auto reach = (static_cast(*maxVertex) * descriptor.Stride() + extent + 15u) & ~std::uint64_t{15}; + return std::min(bytes, reach); +} + std::size_t ShaderResources::MaxDrawSnapshotBytes() { const char* text = std::getenv("APS5_DRAW_SNAPSHOT_MAX_MIB"); const auto mib = text != nullptr ? std::strtoull(text, nullptr, 10) : 64ull; diff --git a/core/libs/prx/libSceAgcDriver/tests/Graphics.cpp b/core/libs/prx/libSceAgcDriver/tests/Graphics.cpp index e2f1c2479643..f0e738df775f 100644 --- a/core/libs/prx/libSceAgcDriver/tests/Graphics.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/Graphics.cpp @@ -4306,6 +4306,107 @@ void descriptorSnapshotTests() { } } +void vertexRangeBindingTests() { + using AgcDriver::Graphics::CompiledShader; + using AgcDriver::Graphics::DescriptorCache; + using AgcDriver::Graphics::Recorder; + using AgcDriver::Graphics::ShaderResources; + constexpr std::size_t ringBytes = 65536; + constexpr std::uint32_t stride = 24; + constexpr std::uint32_t extent = 16; + constexpr std::uint32_t quad = 4 * stride; + constexpr std::size_t bound = 96; + void* ring = ::operator new(ringBytes, std::align_val_t{ringBytes}); + auto* bytes = static_cast(ring); + for (std::size_t i = 0; i < ringBytes; ++i) bytes[i] = static_cast(i * 5u + 1u); + { + auto* mutation = GuestAllocations::GuestAllocationsBegin_nid_postfix(); + GuestAllocations::GuestAllocationsAdd_nid_postfix(mutation, ring, ringBytes, true, true, true); + GuestAllocations::GuestAllocationsEnd_nid_postfix(mutation); + } + const auto records = [&](std::uint32_t first) { return static_cast(ringBytes / stride) - first; }; + const auto vertices = [&](std::uint32_t first) { + auto words = vsharp(bytes + static_cast(first) * stride, records(first)); + words[1] |= stride << 16u; + return words; + }; + const auto whole = [&](std::uint32_t first) { return static_cast(records(first)) * stride; }; + const auto ringBinding = [&](std::vector words, std::uint32_t vertexExtent) { + auto binding = makeBinding(Role::GuestBuffers, 0, 1, std::move(words)); + binding.bufferWritten = {false}; + binding.bufferRead = {true}; + binding.bufferVertexExtent = {vertexExtent}; + return binding; + }; + const auto address = [](const void* pointer) { return static_cast(reinterpret_cast(pointer)); }; + { + const auto binding = ringBinding(vertices(0), extent); + Require(ShaderResources::VertexBoundBytes(binding, 0, 3u) == bound, "a read-only element indexed by the vertex index was not cut to the draw's last vertex"); + Require(ShaderResources::VertexBoundBytes(binding, 0, 0u) == extent, "the first vertex's fetch was not bound alone"); + Require(ShaderResources::VertexBoundBytes(binding, 0, std::nullopt) == whole(0), "an element of a draw without a known vertex range was cut"); + Require(ShaderResources::VertexBoundBytes(binding, 0, 0x01000000u) == whole(0), "a vertex range past the V# grew the element beyond its V#"); + Require(ShaderResources::VertexBoundBytes(ringBinding(vertices(0), 0u), 0, 3u) == whole(0), "an element not proven to be indexed by the vertex index was cut"); + auto written = binding; + written.bufferWritten = {true}; + Require(ShaderResources::VertexBoundBytes(written, 0, 3u) == whole(0), "a written element was cut to the vertex range"); + auto unclassified = binding; + unclassified.bufferVertexExtent.clear(); + Require(ShaderResources::VertexBoundBytes(unclassified, 0, 3u) == whole(0), "an element the recompiler did not classify was cut to the vertex range"); + auto swizzled = binding; + swizzled.guestDescriptor[1] |= 0x80000000u; + Require(ShaderResources::VertexBoundBytes(swizzled, 0, 3u) == whole(0), "a swizzled V# was cut to the vertex range"); + auto threadIndexed = binding; + threadIndexed.guestDescriptor[3] |= 1u << 23u; + Require(ShaderResources::VertexBoundBytes(threadIndexed, 0, 3u) == whole(0), "a V# with ADD_TID_ENABLE was cut to the vertex range"); + auto strideless = ringBinding(vsharp(bytes, 4096), extent); + Require(ShaderResources::VertexBoundBytes(strideless, 0, 1000u) == extent, "a V# without a stride was not bound to one fetch"); + } + auto context = mockContext(); + context.limits.maxStorageBufferRange = 1u << 20u; + for (const bool known : {true, false}) { + const std::optional lastVertex = known ? std::optional(3u) : std::nullopt; + const auto expected = [&](std::uint32_t first) { return known ? bound : whole(first); }; + mock = MockVulkan{}; + mock.allowCopies = true; + { + DescriptorCache cache(context); + context.descriptorCache = &cache; + std::lock_guard lock(AgcDriver::GuestMemory::GpuMutex()); + Recorder recorder(context); + ShaderRecompiler::RecompileResult vertex, fragment; + vertex.bindings.push_back(ringBinding(vertices(0), extent)); + const auto state = AgcDriver::Graphics::DecodeState(makeState()); + const std::array built{{{ShaderRecompiler::ShaderStage::Vertex, &vertex, 0}, {ShaderRecompiler::ShaderStage::Fragment, &fragment, 0}}}; + ShaderResources resources(context, built, state.color, 1, 0, 0, {}, lastVertex); + Require(findWrite(0).buffers.at(0).range == expected(0), known ? "a vertex-indexed element was bound past the draw's vertices" : "an element of a draw without a vertex range was not bound whole"); + const auto shadersOf = [&](const ShaderRecompiler::RecompileResult& program) { return std::array{{{ShaderRecompiler::ShaderStage::Vertex, &program, 0}, {ShaderRecompiler::ShaderStage::Fragment, &fragment, 0}}}; }; + const auto same = resources.MovedReadOnlyBuffers(shadersOf(vertex), recorder, lastVertex); + Require(same.has_value() && same->empty(), "a vertex-indexed element at the same base and range was listed as moved"); + Require(resources.BindsVertexRange(shadersOf(vertex), lastVertex), "a template bound for the draw's vertex range was refused for the same range"); + Require(!resources.BindsVertexRange(shadersOf(vertex), 7u), "a template bound for another vertex range served a draw of eight vertices"); + auto advanced = vertex; + advanced.bindings[0].guestDescriptor = vertices(4); + const auto moved = resources.MovedReadOnlyBuffers(shadersOf(advanced), recorder, lastVertex); + Require(moved.has_value() && moved->size() == 1 && moved->front().address == address(bytes + quad) && moved->front().size == expected(4), known ? "a vertex ring advanced by one quad was not listed at the draw's vertices" : "a moved element without a vertex range was not listed whole"); + const auto draw = resources.PrepareDrawBindings(recorder, *moved); + Require(draw != nullptr && draw->snapshots.size() == 1 && draw->snapshots.front().buffer->Bytes().size() == expected(4) && sameBytes(draw->snapshots.front().buffer->Bytes(), bytes + quad, expected(4)), known ? "a moved vertex ring was not snapshotted at the draw's vertices" : "a moved element without a vertex range was not snapshotted whole"); + if (known) { + const auto wider = resources.MovedReadOnlyBuffers(shadersOf(vertex), recorder, 7u); + Require(wider.has_value() && wider->size() == 1 && wider->front().size == 192u, "a draw reaching more vertices than the template was not listed at its own range"); + } + recorder.Sync(); + } + context.descriptorCache = nullptr; + Require(mock.live == 0, "vertex-range resources leaked Vulkan objects"); + } + { + auto* mutation = GuestAllocations::GuestAllocationsBegin_nid_postfix(); + GuestAllocations::GuestAllocationsRemove_nid_postfix(mutation, ring); + GuestAllocations::GuestAllocationsEnd_nid_postfix(mutation); + } + ::operator delete(ring, std::align_val_t{ringBytes}); +} + void resourceTests() { mock = MockVulkan{}; const auto context = mockContext(); @@ -7804,6 +7905,11 @@ int main(int argc, char** argv) { stencilReferenceUnusedTests(); return 0; } + if (argc == 2 && std::string_view(argv[1]) == "--vertex-range-bindings") { + vertexRangeBindingTests(); + std::cout << "vertex-indexed guest buffers are bound and snapshotted up to the draw's last vertex\n"; + return 0; + } if (argc == 2 && std::string_view(argv[1]) == "--pipeline-journal") { pipelineJournalTests(); std::cout << "pipeline journal recipe, record and replay tests passed\n"; @@ -7987,6 +8093,7 @@ int main(int argc, char** argv) { resourceTests(); oversizedDescriptorTests(); descriptorSnapshotTests(); + vertexRangeBindingTests(); descriptorCacheTests(); bufferBudgetPlacementTests(); imageTableAllocationTests(); diff --git a/core/libs/prx/libSceAgcDriver/tests/ShaderDiskCache.cpp b/core/libs/prx/libSceAgcDriver/tests/ShaderDiskCache.cpp index 2ac7728dfd62..c507f7811f19 100644 --- a/core/libs/prx/libSceAgcDriver/tests/ShaderDiskCache.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/ShaderDiskCache.cpp @@ -57,7 +57,7 @@ void setEnvironment(const char* name, const std::string& value) { } bool sameBinding(const DescriptorBinding& left, const DescriptorBinding& right) { - return left.kind == right.kind && left.role == right.role && left.descriptorSet == right.descriptorSet && left.binding == right.binding && left.count == right.count && left.guestDescriptor == right.guestDescriptor && left.readOnly == right.readOnly && left.imageShape == right.imageShape && left.samplerDepthCompare == right.samplerDepthCompare && left.imageWritten == right.imageWritten && left.imageDepthCompare == right.imageDepthCompare && left.imageAtomic == right.imageAtomic && left.imageShapes == right.imageShapes && left.bufferAtomic == right.bufferAtomic && left.bufferWritten == right.bufferWritten && left.bufferRead == right.bufferRead && left.samplerUnnormalized == right.samplerUnnormalized && left.samplerIntegerBorder == right.samplerIntegerBorder && left.imageUnnormalized == right.imageUnnormalized && left.imageUnnormalizedBaseLevel == right.imageUnnormalizedBaseLevel && left.imageSamplers == right.imageSamplers; + return left.kind == right.kind && left.role == right.role && left.descriptorSet == right.descriptorSet && left.binding == right.binding && left.count == right.count && left.guestDescriptor == right.guestDescriptor && left.readOnly == right.readOnly && left.imageShape == right.imageShape && left.samplerDepthCompare == right.samplerDepthCompare && left.imageWritten == right.imageWritten && left.imageDepthCompare == right.imageDepthCompare && left.imageAtomic == right.imageAtomic && left.imageShapes == right.imageShapes && left.bufferAtomic == right.bufferAtomic && left.bufferWritten == right.bufferWritten && left.bufferRead == right.bufferRead && left.bufferVertexExtent == right.bufferVertexExtent && left.samplerUnnormalized == right.samplerUnnormalized && left.samplerIntegerBorder == right.samplerIntegerBorder && left.imageUnnormalized == right.imageUnnormalized && left.imageUnnormalizedBaseLevel == right.imageUnnormalizedBaseLevel && left.imageSamplers == right.imageSamplers; } bool sameBindings(const std::vector& left, const std::vector& right) { @@ -153,6 +153,7 @@ DescriptorBinding sampleBinding(std::uint32_t seed) { binding.imageUnnormalizedBaseLevel = {false, true, seed % 3 == 0}; binding.imageSamplers = {0x5u, 0u, 0x80000000u}; binding.bufferRead = {true, false, false, true, true, false}; + binding.bufferVertexExtent = {0u, 16u * seed, 0xffffffffu}; return binding; } diff --git a/core/libs/prx/libSceAgcDriver/tests/ShaderMemory.cpp b/core/libs/prx/libSceAgcDriver/tests/ShaderMemory.cpp index 6ad15f3495e9..1e15f4305132 100644 --- a/core/libs/prx/libSceAgcDriver/tests/ShaderMemory.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/ShaderMemory.cpp @@ -22,6 +22,7 @@ #include "BdaAbi.hpp" #include "ImageTableAbi.hpp" #include "ShaderDiskCache.hpp" +#include "RdnaDecoder/RdnaInstructionDecoder.hpp" #include #include #include @@ -723,6 +724,64 @@ void verifyTypeZeroImageMaterialization() { } } +void verifyVertexIndexExtents() { + using namespace ShaderRecompiler; + const std::array userData{0x10000000u, 0x00180000u, 0x00100000u, 0x00027facu}; + constexpr std::uint32_t FormatLoad = 0xe00c2000u; + constexpr std::uint32_t PairLoad = 0xe0342008u; + constexpr std::uint32_t Export = 0xf80008cfu; + constexpr std::uint32_t ExportQuad = 0x04030201u; + constexpr std::uint32_t ExportPair = 0x02010201u; + constexpr std::uint32_t End = 0xbf810000u; + struct Isa { + const char* name; + bool gcn; + std::uint32_t vertexIndex; + std::uint32_t wait; + std::uint32_t addOne; + }; + const std::array isas{{ + {"RDNA", false, 5u, 0xbf8c3f70u, 0x4a0c0a81u}, + {"GCN", true, 0u, 0xbf8c0f70u, 0x4a0c0081u}, + }}; + for (const auto& isa : isas) { + SetGcnGuestShaders(isa.gcn); + const auto data = [](std::uint32_t soffset, std::uint32_t address) { return (soffset << 24u) | 0x100u | address; }; + struct Case { + const char* name; + std::vector code; + std::uint32_t extent; + }; + const std::array cases{{ + {"buffer_load_format_xyzw indexed by the vertex index", {FormatLoad, data(0x80u, isa.vertexIndex), isa.wait, Export, ExportQuad, End}, 16u}, + {"buffer_load_dwordx2 indexed by the vertex index at offset 8 and SOFFSET 4", {PairLoad, data(0x84u, isa.vertexIndex), isa.wait, Export, ExportPair, End}, 20u}, + {"buffer_load_format_xyzw indexed by the vertex index plus one", {isa.addOne, FormatLoad, data(0x80u, 6u), isa.wait, Export, ExportQuad, End}, 0u}, + {"a vertex-indexed load and a load indexed by the vertex index plus one", {isa.addOne, FormatLoad, data(0x80u, isa.vertexIndex), PairLoad, data(0x80u, 6u), isa.wait, Export, ExportQuad, End}, 0u}, + }}; + for (const auto& item : cases) { + RecompileRequest request{}; + request.shader = {ShaderStage::Vertex, 0x10000u, item.code, 0, {}}; + request.context.waveSize = 64; + request.context.userDataBaseRegister = 0; + request.context.userData = userData; + request.context.vertex = ShaderVertexStageInfo{}; + request.target = BufferTarget(); + request.target.vulkanVersion = 0x00401000u; + request.target.spirvVersion = 0x00010300u; + request.target.subgroupSize = 64u; + request.target.fragmentShaderBarycentricEnabled = false; + request.layout.pushConstantSizeBytes = 128; + request.useCache = false; + const auto prefix = std::string("vertex index extents (") + isa.name + "): " + item.name; + const auto result = Recompile(request); + const auto guest = std::ranges::find_if(result.bindings, [](const DescriptorBinding& binding) { return binding.role == DescriptorRole::GuestBuffers; }); + require(guest != result.bindings.end() && guest->count == 1u && guest->bufferVertexExtent.size() == 1u, (prefix + ": the program does not bind its V# with a vertex extent").c_str()); + require(guest->bufferVertexExtent[0] == item.extent, (prefix + ": vertex extent " + std::to_string(guest->bufferVertexExtent[0]) + ", expected " + std::to_string(item.extent)).c_str()); + } + } + SetGcnGuestShaders(false); +} + void verifyOutOfRangeConstantReads() { std::vector code{0xf40c0200u, 0xfa000000u, 0xf4080500u, 0xfa000020u, 0xf4080600u, 0xfa000040u, 0xf4000400u, 0xfa000050u, 0xf4080a00u, 0xfa000080u, 0xbf8cc07fu, 0xf42c0814u, 0xfa000000u, 0xbf8cc07fu, 0xbf068010u, 0xbf850008u}; for (std::uint32_t dword = 0; dword < 8u; dword++) { @@ -5154,6 +5213,11 @@ int main(int argc, char** argv) { std::cout << "Quad masks preserve neighbour-lane helpers or refuse without demote\n"; return 0; } + if (argc == 2 && std::string_view(argv[1]) == "--vertex-index-extents") { + verifyVertexIndexExtents(); + std::cout << "Loads indexed by the vertex index report how far past index * stride they read\n"; + return 0; + } if (argc == 2 && std::string_view(argv[1]) == "--frontend-pair") { verifyFrontendPair(); std::cout << "Prepared frontend reuse preserves full and partial-thread programs\n"; @@ -5198,6 +5262,7 @@ int main(int argc, char** argv) { verifySignedSrtComparison(); verifyTypeZeroImageMaterialization(); verifyOutOfRangeConstantReads(); + verifyVertexIndexExtents(); verifySignedMinimum(); verifyMayEvaluate(); verifyPureFlatSlots(); diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/VertexIndexedRing.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/VertexIndexedRing.cpp new file mode 100644 index 000000000000..bd3310d5e6fe --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/tests/execution/VertexIndexedRing.cpp @@ -0,0 +1,149 @@ +#include "prx/libSceAgcDriver/Execution/include/VulkanDevice.hpp" +#include "prx/libSceAgcDriver/Graphics/include/Draw.hpp" +#include "Recompiler.hpp" +#include "VulkanTestDevice.hpp" +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +using AgcDriver::Graphics::Require; +using ShaderRecompiler::ShaderStage; + +constexpr std::uint32_t Width = 64; +constexpr std::uint32_t Height = 32; +constexpr std::uint32_t Records = 4096; +constexpr std::uint32_t OutputVertices = 32; +alignas(256) std::array Pixels{}; +alignas(256) std::array Output{}; +alignas(256) std::array Ring{}; +alignas(256) std::array Indices{0, 2, 1, 0}; + +alignas(256) constexpr std::array VertexCode{ + 0xe00c2000u, 0x80020805u, 0xbf8c3f70u, 0x34020a84u, 0xe0781000u, 0x80010801u, 0xf80008cfu, 0x0b0a0908u, 0xbf810000u, 0xbf810000u, +}; + +alignas(256) constexpr std::array PixelCode{ + 0x7e0e02f2u, 0xf800180fu, 0x07070707u, 0xbf810000u, +}; + +struct Case { + const char* what; + bool indexed; + std::uint32_t count; + std::uint32_t firstVertex; + std::array vertices; +}; + +std::array Descriptor(const void* pointer, std::uint32_t stride, std::uint32_t records, std::uint32_t word3) { + const auto address = reinterpret_cast(pointer); + return {static_cast(address), (static_cast(address >> 32u) & 0xffffu) | (stride << 16u), records, word3}; +} + +void Draw(AgcDriver::VulkanDevice& device, const Case& value) { + Pixels.fill(std::byte{0x40}); + Output.fill(0xdeadbeefu); + std::vector userData(12, 0u); + const auto output = Descriptor(Output.data(), 0u, static_cast(sizeof(Output)), 0x31016facu); + const auto ring = Descriptor(Ring.data(), 16u, Records, 0x1104bfacu); + std::copy(output.begin(), output.end(), userData.begin() + 4); + std::copy(ring.begin(), ring.end(), userData.begin() + 8); + const std::array vertexMemory{{{reinterpret_cast(VertexCode.data()), std::as_bytes(std::span(VertexCode))}}}; + ShaderRecompiler::RecompileRequest vertexRequest{ + {ShaderStage::Vertex, reinterpret_cast(VertexCode.data()), VertexCode, 0, {}}, + {64u, 0, userData, std::nullopt, std::nullopt, ShaderRecompiler::ShaderVertexStageInfo{}, vertexMemory}, + device.Target(), + {0, 0, 0, 64} + }; + vertexRequest.useCache = false; + const auto vertexResult = ShaderRecompiler::Recompile(vertexRequest); + const auto guest = std::ranges::find_if(vertexResult.bindings, [](const ShaderRecompiler::DescriptorBinding& binding) { return binding.role == ShaderRecompiler::DescriptorRole::GuestBuffers; }); + Require(guest != vertexResult.bindings.end() && guest->count == 2u && guest->bufferVertexExtent.size() == 2u, std::string(value.what) + ": the vertex shader does not bind its two V#s with vertex extents"); + for (std::uint32_t element = 0; element < 2u; ++element) { + const bool ringElement = guest->guestDescriptor[element * 4u + 2u] == Records; + Require(guest->bufferVertexExtent[element] == (ringElement ? 16u : 0u), std::string(value.what) + ": " + (ringElement ? "the ring read by the vertex index has no vertex extent" : "the output written at a VGPR offset has a vertex extent")); + } + const auto vertexPush = static_cast(vertexResult.pushConstants.size()); + + ShaderRecompiler::ShaderPixelStageInfo pixel{}; + pixel.inputAddr = ShaderRecompiler::PixelInputBit(ShaderRecompiler::PixelInput::PositionX) | ShaderRecompiler::PixelInputBit(ShaderRecompiler::PixelInput::PositionY); + pixel.posX = true; + pixel.posY = true; + pixel.targetOutputMode[0] = 9; + pixel.targetExportMapping.fill(0xe4u); + const std::vector pixelUserData(8, 0u); + const std::array pixelMemory{{{reinterpret_cast(PixelCode.data()), std::as_bytes(std::span(PixelCode))}}}; + ShaderRecompiler::RecompileRequest fragment{ + {ShaderStage::Fragment, reinterpret_cast(PixelCode.data()), PixelCode, 0, {}}, + {64u, 0, pixelUserData, std::nullopt, pixel, std::nullopt, pixelMemory}, + device.Target(), + PixelPushLayout(vertexPush, device.Target()) + }; + fragment.useCache = false; + const auto pixelResult = ShaderRecompiler::Recompile(fragment); + const std::array shaders{{ + {ShaderStage::Vertex, &vertexResult, 0}, + {ShaderStage::Fragment, &pixelResult, PixelPushOffset(vertexPush, device.Target())} + }}; + + AgcDriver::Graphics::State state{}; + state.stages = {AgcDriver::Graphics::ShaderPath::Vertex, 0u, 64u, 64u, std::nullopt, std::nullopt}; + state.color = {reinterpret_cast(Pixels.data()), {Width, Height}, VK_FORMAT_R8G8B8A8_UNORM, Pixels.size(), 0xe4u}; + state.colors = {state.color}; + state.hasColorTarget = true; + state.renderExtent = {Width, Height}; + state.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST; + state.viewport = {0, static_cast(Height), static_cast(Width), -static_cast(Height), 0, 1}; + state.negativeOneToOne = false; + state.scissor = {{0, 0}, {Width, Height}}; + state.cullMode = VK_CULL_MODE_NONE; + state.frontFace = VK_FRONT_FACE_COUNTER_CLOCKWISE; + state.blend.colorWriteMask = 15; + state.blends = {state.blend}; + state.blendConstants = {}; + AgcDriver::Pm4::DrawParameters draw{value.indexed ? reinterpret_cast(Indices.data()) : 0u, value.count, value.indexed ? 2u : 0u, 1, 0, value.indexed}; + draw.firstVertex = value.firstVertex; + device.Draw(state, draw, shaders); + device.WaitIdle(); +} + +void Check(const Case& value) { + for (std::uint32_t vertex = 0; vertex < OutputVertices; ++vertex) { + const bool drawn = std::ranges::find(value.vertices, vertex) != value.vertices.end(); + for (std::uint32_t component = 0; component < 4u; ++component) { + const auto expected = drawn ? Ring[vertex * 4u + component] : 0xdeadbeefu; + const auto actual = Output[vertex * 4u + component]; + Require(actual == expected, std::string(value.what) + ": vertex " + std::to_string(vertex) + " component " + std::to_string(component) + " is " + std::to_string(actual) + ", expected " + std::to_string(expected)); + } + } +} + +} + +int main() { + try { + const auto device = OpenVulkanTestDevice(); + if (!device) return VulkanTestSkipped; + for (std::uint32_t index = 0; index < Ring.size(); ++index) Ring[index] = 0x01000000u + index * 0x10001u; + constexpr std::array cases{{ + {"auto draw from vertex 5", false, 3u, 5u, {5u, 6u, 7u}}, + {"indexed draw with base vertex 20", true, 3u, 20u, {20u, 22u, 21u}}, + {"auto draw from vertex 0", false, 3u, 0u, {0u, 1u, 2u}}, + }}; + for (const auto& value : cases) { + Draw(*device, value); + Check(value); + } + std::puts("vertex-indexed ring tests passed"); + return 0; + } catch (const std::exception& error) { + std::cerr << error.what() << '\n'; + return 1; + } +} diff --git a/core/shader/recompiler/IntermediateRepresentation/include/IntermediateRepresentation/IrMetadata/Resources.hpp b/core/shader/recompiler/IntermediateRepresentation/include/IntermediateRepresentation/IrMetadata/Resources.hpp index 85c985a879a7..b12c7c6531ac 100644 --- a/core/shader/recompiler/IntermediateRepresentation/include/IntermediateRepresentation/IrMetadata/Resources.hpp +++ b/core/shader/recompiler/IntermediateRepresentation/include/IntermediateRepresentation/IrMetadata/Resources.hpp @@ -26,6 +26,7 @@ struct BufferResource { std::uint32_t formattedReadMask = 0; bool scalar = false; std::uint8_t typedAlignment = 1; + std::uint32_t vertexExtent = 0; bool operator==(const BufferResource& other) const = default; }; diff --git a/core/shader/recompiler/Optimization/src/DescriptorBindingBuilder.cpp b/core/shader/recompiler/Optimization/src/DescriptorBindingBuilder.cpp index fb6e05b76f62..10d0292ef85f 100644 --- a/core/shader/recompiler/Optimization/src/DescriptorBindingBuilder.cpp +++ b/core/shader/recompiler/Optimization/src/DescriptorBindingBuilder.cpp @@ -418,6 +418,7 @@ DescriptorBindingPlan DescriptorBindingBuilder::Prepare(const IrBindingLayout& l physical.bufferAtomic.push_back(buffer.atomic); physical.bufferWritten.push_back(buffer.written || buffer.atomic); physical.bufferRead.push_back(buffer.read); + physical.bufferVertexExtent.push_back(buffer.vertexExtent); if (buffer.written || buffer.atomic) ++entry.writtenBuffers; else ++entry.readOnlyBuffers; } diff --git a/core/shader/recompiler/Optimization/src/ResourceTracker.cpp b/core/shader/recompiler/Optimization/src/ResourceTracker.cpp index 3900471a2f54..621b9292cbc8 100644 --- a/core/shader/recompiler/Optimization/src/ResourceTracker.cpp +++ b/core/shader/recompiler/Optimization/src/ResourceTracker.cpp @@ -95,6 +95,26 @@ std::uint32_t byteExtent(const MemoryInfo& memory) { return end > std::numeric_limits::max() ? std::numeric_limits::max() : static_cast(end); } +bool immediateU32(const IrValue* value, std::uint32_t& result) { + value = value->Resolve(); + if (!value->HasImmediate() || value->Type() != IrType::U32) return false; + result = value->ImmediateU32(); + return true; +} + +std::uint32_t vertexIndexedExtent(const IrValue& inst, const MemoryInfo& memory) { + if (BufferAccessOf(inst.Opcode()) != BufferAccess::Read || inst.Opcode() == IrOpcode::ReadConstBuffer || memory.kind != ResourceKind::Buffer || !memory.idxen || inst.ArgumentCount() < 4u) return 0u; + const IrValue* index = inst.Argument(1)->Resolve(); + std::uint32_t kind = 0; + if (index->Opcode() != IrOpcode::GetBuiltin || index->ArgumentCount() == 0u || !immediateU32(index->Argument(0), kind) || kind != static_cast(StageInputKind::VertexIndex)) return 0u; + std::uint32_t offset = 0; + std::uint32_t soffset = 0; + if (!immediateU32(inst.Argument(2), offset) || !immediateU32(inst.Argument(3), soffset)) return 0u; + const auto bytes = static_cast(std::max((memory.dataBits + 7u) / 8u, 1u)) * std::max(memory.dataDwords, 1u); + const auto end = static_cast(memory.offset) + offset + soffset + (memory.formatted ? std::max(bytes, 16u) : bytes); + return end > std::numeric_limits::max() ? 0u : static_cast(end); +} + class Tracker { public: explicit Tracker(IrProgram& program) : m_program(program), m_info(program.Resources().info), m_builder(program) { @@ -1396,7 +1416,7 @@ class Tracker { const auto access = BufferAccessOf(inst.Opcode()); if (ValidateSource(descriptor, badDword)) { const auto source = InternSource(descriptor); - const auto resource = AddBuffer(source, memory, inst.Opcode(), inst.Flags().pc); + const auto resource = AddBuffer(source, memory, inst.Opcode(), inst.Flags().pc, vertexIndexedExtent(inst, memory)); if (resource == std::numeric_limits::max()) fail("buffer resource limit exceeded"); AddMemoryPatch(memoryIndex, resource, 0u, false); memory.gpuDescriptor = false; @@ -1419,16 +1439,19 @@ class Tracker { } } - std::uint32_t AddBuffer(std::uint32_t source, const MemoryInfo& memory, IrOpcode op, std::uint32_t pc) { + std::uint32_t AddBuffer(std::uint32_t source, const MemoryInfo& memory, IrOpcode op, std::uint32_t pc, std::uint32_t vertexExtent) { for (std::uint32_t i = 0; i < m_info.buffers.size(); i++) { if (m_info.buffers[i].source == source) { - Merge(m_info.buffers[i], memory, op, pc); + auto& buffer = m_info.buffers[i]; + Merge(buffer, memory, op, pc); + buffer.vertexExtent = buffer.vertexExtent == 0u || vertexExtent == 0u ? 0u : std::max(buffer.vertexExtent, vertexExtent); return i; } } BufferResource resource; resource.source = source; resource.firstUsePc = pc; + resource.vertexExtent = vertexExtent; Merge(resource, memory, op, pc); m_info.buffers.push_back(resource); return static_cast(m_info.buffers.size() - 1); diff --git a/core/shader/recompiler/Recompiler.hpp b/core/shader/recompiler/Recompiler.hpp index 123c488f40bf..b7d57c76b69f 100644 --- a/core/shader/recompiler/Recompiler.hpp +++ b/core/shader/recompiler/Recompiler.hpp @@ -429,6 +429,7 @@ struct DescriptorBinding { std::vector imageUnnormalizedBaseLevel; std::vector imageSamplers; std::vector bufferRead; + std::vector bufferVertexExtent; }; struct ImageTableEntryPoison { diff --git a/core/shader/recompiler/ShaderDiskCache.cpp b/core/shader/recompiler/ShaderDiskCache.cpp index 680e88181840..ff95b04c19d3 100644 --- a/core/shader/recompiler/ShaderDiskCache.cpp +++ b/core/shader/recompiler/ShaderDiskCache.cpp @@ -140,7 +140,7 @@ constexpr std::size_t fieldCount() { } static_assert(fieldCount() == 23, "ShaderInfo changed: update the info encoder"); -static_assert(fieldCount() == 12, "BufferResource changed: update the info encoder"); +static_assert(fieldCount() == 13, "BufferResource changed: update the info encoder"); static_assert(fieldCount() == 38, "ImageResource changed: update the info encoder"); static_assert(fieldCount() == 8, "SamplerResource changed: update the info encoder"); static_assert(fieldCount() == 3, "SampledResourcePair changed: update the info encoder"); @@ -430,6 +430,7 @@ void encodeBinding(Writer& writer, const DescriptorBinding& binding) { writer.Flags(binding.samplerIntegerBorder); writer.Values(std::span(binding.imageSamplers)); writer.Flags(binding.bufferRead); + writer.Values(std::span(binding.bufferVertexExtent)); } void decodeBinding(Reader& reader, DescriptorBinding& binding) { @@ -457,6 +458,7 @@ void decodeBinding(Reader& reader, DescriptorBinding& binding) { reader.Flags(binding.samplerIntegerBorder); reader.Values(binding.imageSamplers); reader.Flags(binding.bufferRead); + reader.Values(binding.bufferVertexExtent); } void encodeArtifact(Writer& writer, const CompiledShaderArtifact& result) { @@ -675,6 +677,7 @@ void encodeShaderInfo(Writer& writer, const ShaderInfo& info) { out.Value(buffer.formattedReadMask); out.Value(buffer.scalar); out.Value(buffer.typedAlignment); + out.Value(buffer.vertexExtent); }); writer.List(info.images, [](Writer& out, const ImageResource& image) { out.Value(image.source); @@ -764,7 +767,7 @@ void encodeShaderInfo(Writer& writer, const ShaderInfo& info) { void decodeShaderInfo(Reader& reader, ShaderInfo& info) { reader.Value(info.scratchDwords); reader.Value(info.sharedMemoryBytes); - reader.List(info.buffers, 27, [](Reader& in, BufferResource& buffer) { + reader.List(info.buffers, 31, [](Reader& in, BufferResource& buffer) { in.Value(buffer.source); in.Value(buffer.firstUsePc); in.Value(buffer.maxByteExtent); @@ -777,6 +780,7 @@ void decodeShaderInfo(Reader& reader, ShaderInfo& info) { in.Value(buffer.formattedReadMask); in.Value(buffer.scalar); in.Value(buffer.typedAlignment); + in.Value(buffer.vertexExtent); }); reader.List(info.images, 77, [](Reader& in, ImageResource& image) { in.Value(image.source); diff --git a/core/shader/recompiler/ShaderDiskCache.hpp b/core/shader/recompiler/ShaderDiskCache.hpp index 7322efa49639..592b11c3c70b 100644 --- a/core/shader/recompiler/ShaderDiskCache.hpp +++ b/core/shader/recompiler/ShaderDiskCache.hpp @@ -13,7 +13,7 @@ namespace ShaderRecompiler::ShaderDiskCache { -inline constexpr std::uint32_t FormatVersion = 36; +inline constexpr std::uint32_t FormatVersion = 37; enum class LoadStatus { Loaded, From edf584d5689fb6870ebf60d1322dc1879c50f9fb Mon Sep 17 00:00:00 2001 From: Savvanis Spyros Date: Tue, 20 Oct 2026 15:00:58 +0300 Subject: [PATCH 2/5] perf(agc): read recorded store bytes in captures instead of waiting for the GPU A COPY_DATA, DMA_DATA or DUMP_CONST_RAM store of up to 64 KiB that the driver resolves while GPU work is open is recorded into the batch as a vkCmdUpdateBuffer into the host import, and its range becomes a pending write. The next draw's resource capture reads the dumped descriptor table through the flush hook, which submits the batch and waits for the GPU although the driver already holds the bytes. The recorder now keeps the bytes of stores wider than the 64-byte label table too, in record order, and flags them overwritten like table entries when later GPU work writes over them. Recorder::LookupStoredBytes composes a range from the newest store of each dword. It refuses a dword without a store, one a later GPU write covers, a label behind a completion action and a range under a queued label. Everything recorded before the store lands first and the store lands before anything recorded after it, so the bytes are what the next draw reads on the GPU. classifyPendingWrite answers KnownValue for such a range when the caller takes the bytes (captures, cached draw and dispatch validation), so the capture reads them without the wait. Callers that pass no buffer, and every other pending write, sync as before. APS5_NO_STORED_KNOWN_VALUES=1 turns the path off, and APS5_VERIFY_KNOWN_VALUES=1 checks each served word against the GPU's; the [capture] profile line now reports both counts. Monopoly Plus (CUSA03312) dumps 144- to 512-byte descriptor tables from constant RAM about 100 times per frame on its language screen, each followed by a draw whose capture waited about 1 to 2 ms for the GPU. That screen now runs at about 8.3 instead of 6.1 frames per second on an RX 9070 XT. Co-Authored-By: Claude Opus 5.5 --- core/libs/prx/libSceAgcDriver/CMakeLists.txt | 4 +- .../Execution/include/Driver/Driver.hpp | 1 + .../src/Driver/Memory/WriteEvidence.cpp | 6 + .../Execution/src/ShaderMemory.cpp | 2 +- .../Graphics/include/Recorder.hpp | 14 +- .../libSceAgcDriver/Graphics/src/Recorder.cpp | 47 +++- .../prx/libSceAgcDriver/tests/Recorder.cpp | 45 ++++ .../tests/execution/DumpedConstantCapture.cpp | 210 ++++++++++++++++++ 8 files changed, 322 insertions(+), 7 deletions(-) create mode 100644 core/libs/prx/libSceAgcDriver/tests/execution/DumpedConstantCapture.cpp diff --git a/core/libs/prx/libSceAgcDriver/CMakeLists.txt b/core/libs/prx/libSceAgcDriver/CMakeLists.txt index 7dbccd0debef..277ec41e4631 100644 --- a/core/libs/prx/libSceAgcDriver/CMakeLists.txt +++ b/core/libs/prx/libSceAgcDriver/CMakeLists.txt @@ -1131,6 +1131,8 @@ if(BUILD_TESTING) endif() add_test(NAME agc_recorder_read_list COMMAND agc_driver_recorder_tests --read-list-only) set_tests_properties(agc_recorder_read_list PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 30) + add_test(NAME agc_recorder_stored_bytes COMMAND agc_driver_recorder_tests --stored-bytes-only) + set_tests_properties(agc_recorder_stored_bytes PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 30) add_test(NAME agc_space_pending_writes COMMAND agc_driver_recorder_tests --space-pending-writes-only) set_tests_properties(agc_space_pending_writes PROPERTIES SKIP_RETURN_CODE 77) if(WIN32) @@ -1180,7 +1182,7 @@ if(BUILD_TESTING) add_test(NAME agc_metadata_pass COMMAND agc_driver_recorder_tests --metadata-pass-only) set_tests_properties(agc_metadata_pass PROPERTIES SKIP_RETURN_CODE 77) if(WIN32) - set_tests_properties(agc_recorder_read_list agc_host_import_unmap agc_parked_import_unmap agc_host_import_retirement agc_sparse_run_import agc_sparse_run_import_copied agc_unit_shadow agc_descriptor_pool_recycling agc_draw_snapshot_cap agc_draw_snapshot_epoch agc_multisample_guest_access agc_draw_inputs_in_place agc_resident_present agc_slice_dirty agc_queued_write_groups agc_metadata_pass agc_tiled_resolve PROPERTIES ENVIRONMENT_MODIFICATION + set_tests_properties(agc_recorder_read_list agc_recorder_stored_bytes agc_host_import_unmap agc_parked_import_unmap agc_host_import_retirement agc_sparse_run_import agc_sparse_run_import_copied agc_unit_shadow agc_descriptor_pool_recycling agc_draw_snapshot_cap agc_draw_snapshot_epoch agc_multisample_guest_access agc_draw_inputs_in_place agc_resident_present agc_slice_dirty agc_queued_write_groups agc_metadata_pass agc_tiled_resolve PROPERTIES ENVIRONMENT_MODIFICATION "PATH=path_list_prepend:$") add_test(NAME agc_host_import_second_mapping COMMAND agc_driver_recorder_tests --host-import-second-mapping-only) set_tests_properties(agc_host_import_second_mapping PROPERTIES SKIP_RETURN_CODE 77 ENVIRONMENT_MODIFICATION diff --git a/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Driver.hpp b/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Driver.hpp index 4bceb20d24e2..425dc9c47698 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Driver.hpp +++ b/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Driver.hpp @@ -189,6 +189,7 @@ class Driver { static void countCopy(int path, std::size_t bytes, std::chrono::steady_clock::time_point started, std::chrono::steady_clock::time_point locked, const VulkanDevice::CopyOutcome* outcome = nullptr); void noteCopyWriter(std::uint64_t program, std::uint64_t begin, std::uint64_t end, std::uint32_t queue, std::span value = {}, std::uint64_t generation = 0); static bool copyKnownValues(); + static bool storedKnownValues(); static bool knownValueVerify(); bool copyBuffer(QueueState& queue, std::uint32_t queueId, std::span packet, std::span code, const std::vector& userData, const ShaderRecompiler::ShaderComputeStageInfo& compute, const std::shared_ptr& localDevice, std::uint64_t programAddress); void traceCopyRefused(const VulkanDevice::CopyOutcome& outcome, std::uint64_t source, std::uint64_t destination, std::size_t bytes, const std::shared_ptr& localDevice); diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Memory/WriteEvidence.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Memory/WriteEvidence.cpp index fa2ca447d58f..cf5ba8a088f9 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Memory/WriteEvidence.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Memory/WriteEvidence.cpp @@ -41,6 +41,11 @@ bool Driver::writerKeyedEvidence() { return keyed; } +bool Driver::storedKnownValues() { + static const bool enabled = std::getenv("APS5_NO_STORED_KNOWN_VALUES") == nullptr; + return enabled; +} + bool Driver::foreignWriters() { static const bool noted = std::getenv("APS5_NO_FOREIGN_WRITERS") == nullptr; return noted; @@ -149,6 +154,7 @@ ShaderMemory::PendingWrite Driver::classifyPendingWrite(std::uint64_t address, s reason = &ValidateCounters::syncedShadow; return Policy::Sync; } + if (storedKnownValues() && !known.empty() && known.size() == bytes && Graphics::Recorder::LookupStoredBytes(address, known)) return knownValueVerify() ? Policy::VerifyKnownValue : Policy::KnownValue; reason = &ValidateCounters::syncedOff; if (!writeEvidenceEnabled()) return Policy::Sync; const auto writer = newestWriter(address, address + bytes); diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/ShaderMemory.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/ShaderMemory.cpp index ffbecd5b702d..7a8a813a3cc4 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/ShaderMemory.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/ShaderMemory.cpp @@ -408,7 +408,7 @@ std::shared_ptr ShaderMemory::capture(c const auto materializeNs = ShaderRecompiler::ResourceMaterializer::MaterializeNanoseconds(); const auto evaluateNs = ShaderRecompiler::ResourceMaterializer::EvaluateNanoseconds(); const auto walkNs = captureNs > resolveNs + pageNs + wordNs + specializationNs ? captureNs - resolveNs - pageNs - wordNs - specializationNs : 0; - AgcDriver::ProfilePrint_nid_no_patch( "[capture] %llu captures: %llu word reads, %llu pages fetched (%llu read word by word over pending GPU writes: %llu words waited %.2f s, %llu read raw on evidence, %llu verified with %llu mismatches, %llu served from known values, %llu hook reads not observed: no GPU wait), capture (plan lookup + materialize) %.1f s, %llu KiB registered code this capture; sub-phases (s, us per capture): source resolve %.2f/%.1f, walk %.2f/%.1f, specialization (every materialize) %.2f/%.1f, page reads %.2f/%.1f, word reads %.2f/%.1f, hook GPU waits inside %.2f/%.1f, materialize %.2f/%.1f (SRT evaluate %.2f/%.1f); source handle memo %llu hits, %llu resolves\n", static_cast(totals.captures.load()), static_cast(totals.reads.load()), static_cast(totals.pages.load()), static_cast(totals.pagesWordwise.load()), static_cast(totals.wordWaits.load()), totals.wordWaitNanoseconds.load() / 1e9, static_cast(totals.wordsRaw.load()), static_cast(totals.wordsVerified.load()), static_cast(totals.wordMismatches.load()), static_cast(totals.wordsKnown.load()), static_cast(totals.observationsSkipped.load()), captureNs / 1e9, static_cast(initialBytes / 1024), resolveNs / 1e9, resolveNs / captures / 1e3, walkNs / 1e9, walkNs / captures / 1e3, specializationNs / 1e9, specializationNs / captures / 1e3, pageNs / 1e9, pageNs / captures / 1e3, wordNs / 1e9, wordNs / captures / 1e3, hookNs / 1e9, hookNs / captures / 1e3, materializeNs / 1e9, materializeNs / captures / 1e3, evaluateNs / 1e9, evaluateNs / captures / 1e3, static_cast(totals.handleHits.load()), static_cast(totals.handleMisses.load())); + AgcDriver::ProfilePrint_nid_no_patch( "[capture] %llu captures: %llu word reads, %llu pages fetched (%llu read word by word over pending GPU writes: %llu words waited %.2f s, %llu read raw on evidence, %llu verified with %llu mismatches, %llu served from known values (%llu verified, %llu mismatches), %llu hook reads not observed: no GPU wait), capture (plan lookup + materialize) %.1f s, %llu KiB registered code this capture; sub-phases (s, us per capture): source resolve %.2f/%.1f, walk %.2f/%.1f, specialization (every materialize) %.2f/%.1f, page reads %.2f/%.1f, word reads %.2f/%.1f, hook GPU waits inside %.2f/%.1f, materialize %.2f/%.1f (SRT evaluate %.2f/%.1f); source handle memo %llu hits, %llu resolves\n", static_cast(totals.captures.load()), static_cast(totals.reads.load()), static_cast(totals.pages.load()), static_cast(totals.pagesWordwise.load()), static_cast(totals.wordWaits.load()), totals.wordWaitNanoseconds.load() / 1e9, static_cast(totals.wordsRaw.load()), static_cast(totals.wordsVerified.load()), static_cast(totals.wordMismatches.load()), static_cast(totals.wordsKnown.load()), static_cast(totals.wordsKnownVerified.load()), static_cast(totals.wordsKnownMismatches.load()), static_cast(totals.observationsSkipped.load()), captureNs / 1e9, static_cast(initialBytes / 1024), resolveNs / 1e9, resolveNs / captures / 1e3, walkNs / 1e9, walkNs / captures / 1e3, specializationNs / 1e9, specializationNs / captures / 1e3, pageNs / 1e9, pageNs / captures / 1e3, wordNs / 1e9, wordNs / captures / 1e3, hookNs / 1e9, hookNs / captures / 1e3, materializeNs / 1e9, materializeNs / captures / 1e3, evaluateNs / 1e9, evaluateNs / captures / 1e3, static_cast(totals.handleHits.load()), static_cast(totals.handleMisses.load())); } } return capture; diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/Recorder.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/Recorder.hpp index 30e547aaa622..0b58641645a4 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/Recorder.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/Recorder.hpp @@ -325,6 +325,7 @@ class Recorder { // The value alone, for callers asking whether any label is pending in a dword (afterStamp 0). static std::optional LookupLabelValue(std::uint64_t address, std::size_t bytes, std::uint64_t afterStamp); static bool WideLabelIn(std::uint64_t address, std::size_t bytes); + static bool LookupStoredBytes(std::uint64_t address, std::span bytes); // A label a queue worker decoded but has not recorded yet (Driver.cpp DeferredLabels): it // enters the table with no batch, and only a lookup made on the noting thread (a WAIT_REG_MEM // of the same queue) takes its value, since that queue's later work follows the label in queue @@ -526,6 +527,12 @@ class Recorder { static bool FlipReadCheck(); private: + struct WideLabel { + std::uint64_t end; + std::vector bytes; + std::uint64_t sequence; + bool overwritten = false; + }; struct Batch { VkCommandBuffer commands = VK_NULL_HANDLE; VkFence fence = VK_NULL_HANDLE; @@ -577,7 +584,7 @@ class Recorder { std::uint64_t readGeneration = 0; // Dword addresses this batch noted in the label table (removed when it finishes). std::vector labelDwords; - std::vector::iterator> wideLabels; + std::vector::iterator> wideLabels; // Labels stored by this batch's completion actions (see AfterCompletions); subtracted from // the lock-free pending count when the batch finishes, whether or not its completions ran. std::uint32_t completionLabelCount = 0; @@ -780,6 +787,7 @@ class Recorder { std::uint64_t writtenBackSequence = 0; // PendingLabel without the table mutex (the caller holds it, or the GPU mutex). std::optional lookupLabel(std::uint64_t address, std::size_t bytes, std::uint64_t afterStamp, LabelRefusal* refusal) const; + bool storedBytesLocked(std::uint64_t address, std::span bytes) const; // Whether the in-flight batch with that serial has not signaled its fence (false when it is // not in flight any more): what makes a wait for it a real GPU wait (ThreadHookWaits). bool unsignaled(std::uint64_t serial) const; @@ -796,8 +804,10 @@ class Recorder { // The queued entries (batch always null), by dword; a lookup on the noting queue's thread // prefers them (its newest store in program order), every other lookup sees `labels` alone. std::map queuedLabels; - std::multimap wideLabels; + std::multimap wideLabels; std::uint64_t wideLabelBytes = 0; + std::uint64_t wideLabelSequence = 0; + std::atomic recordedWideLabels{0}; bool wideLabelInLocked(std::uint64_t address, std::size_t bytes) const; // labels.size(), readable without the table mutex: a noted write skips the mutex while the // table is empty (most of the time between label groups). diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp index 1f03eea4438a..4de3b0edc091 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp @@ -1239,11 +1239,47 @@ bool Recorder::wideLabelInLocked(std::uint64_t address, std::size_t bytes) const if (wideLabels.empty() || bytes == 0) return false; const auto end = address + bytes; for (auto it = wideLabels.lower_bound(address >= wideLabelBytes ? address - wideLabelBytes + 1 : 0); it != wideLabels.end() && it->first < end; ++it) { - if (it->second > address) return true; + if (it->second.end > address) return true; } return false; } +bool Recorder::LookupStoredBytes(std::uint64_t address, std::span bytes) { + std::lock_guard tableLock(labelTableMutex); + return labelTableOwner != nullptr && labelTableOwner->storedBytesLocked(address, bytes); +} + +bool Recorder::storedBytesLocked(std::uint64_t address, std::span bytes) const { + if (bytes.empty() || bytes.size() % 4 != 0 || address % 4 != 0 || address > std::numeric_limits::max() - bytes.size()) return false; + const auto end = address + bytes.size(); + if (const auto queued = queuedLabels.lower_bound(address); queued != queuedLabels.end() && queued->first < end) return false; + const auto dwords = bytes.size() / 4; + std::vector*> newest(dwords, nullptr); + for (auto it = wideLabels.lower_bound(address >= wideLabelBytes ? address - wideLabelBytes + 1 : 0); it != wideLabels.end() && it->first < end; ++it) { + if (it->second.end <= address) continue; + const auto from = std::max(it->first, address); + const auto to = std::min(it->second.end, end); + for (auto dword = (from - address) / 4; dword < (to - address + 3) / 4; ++dword) { + if (newest[dword] == nullptr || newest[dword]->second.sequence < it->second.sequence) newest[dword] = &*it; + } + } + std::vector composed(bytes.size()); + for (std::size_t dword = 0; dword < dwords; ++dword) { + const auto at = address + dword * 4; + if (const auto found = labels.find(at); found != labels.end()) { + const auto& entry = found->second; + if (entry.batch == nullptr || entry.overwritten || entry.behindCompletion) return false; + std::memcpy(composed.data() + dword * 4, &entry.value, 4); + continue; + } + const auto* wide = newest[dword]; + if (wide == nullptr || at < wide->first || wide->second.end - at < 4 || wide->second.overwritten) return false; + std::memcpy(composed.data() + dword * 4, wide->second.bytes.data() + (at - wide->first), 4); + } + std::copy(composed.begin(), composed.end(), bytes.begin()); + return true; +} + std::optional Recorder::LookupLabelValue(std::uint64_t address, std::size_t bytes, std::uint64_t afterStamp) { const auto hit = LookupLabel(address, bytes, afterStamp); if (!hit.has_value()) return std::nullopt; @@ -2738,10 +2774,13 @@ void Recorder::noteWriteOn(Batch& batch, std::uint64_t address, std::size_t byte } void Recorder::markOverwritten(std::uint64_t address, std::uint64_t end) { - if (recordedLabels.load(std::memory_order_relaxed) == 0) return; + if (recordedLabels.load(std::memory_order_relaxed) == 0 && recordedWideLabels.load(std::memory_order_relaxed) == 0) return; std::lock_guard tableLock(labelTableMutex); // A dword overlaps the range when it starts before the end and ends after the start. for (auto it = labels.lower_bound(address >= 3 ? address - 3 : 0); it != labels.end() && it->first < end; ++it) it->second.overwritten = true; + for (auto it = wideLabels.lower_bound(address >= wideLabelBytes ? address - wideLabelBytes + 1 : 0); it != wideLabels.end() && it->first < end; ++it) { + if (it->second.end > address) it->second.overwritten = true; + } } void Recorder::NotePendingWrite(std::uint64_t address, std::size_t bytes) { @@ -3088,8 +3127,9 @@ void Recorder::NoteLabel(std::uint64_t address, std::span bytes std::lock_guard tableLock(labelTableMutex); labels.erase(labels.lower_bound(address), labels.lower_bound(address + bytes.size())); recordedLabels.store(labels.size(), std::memory_order_relaxed); - open->wideLabels.push_back(wideLabels.emplace(address, address + bytes.size())); + open->wideLabels.push_back(wideLabels.emplace(address, WideLabel{address + bytes.size(), {bytes.begin(), bytes.end()}, ++wideLabelSequence})); wideLabelBytes = std::max(wideLabelBytes, bytes.size()); + recordedWideLabels.store(wideLabels.size(), std::memory_order_relaxed); } if (activeRecorder == this && pendingLabelSince.load(std::memory_order_relaxed) == NoPendingLabel) { pendingLabelSince.store(std::chrono::steady_clock::now().time_since_epoch().count(), std::memory_order_release); @@ -3898,6 +3938,7 @@ void Recorder::removeLabels(Batch& batch) { } for (const auto entry : batch.wideLabels) wideLabels.erase(entry); recordedLabels.store(labels.size(), std::memory_order_relaxed); + recordedWideLabels.store(wideLabels.size(), std::memory_order_relaxed); } batch.labelDwords.clear(); batch.wideLabels.clear(); diff --git a/core/libs/prx/libSceAgcDriver/tests/Recorder.cpp b/core/libs/prx/libSceAgcDriver/tests/Recorder.cpp index 6d9e99fff43a..c3c3ec257056 100644 --- a/core/libs/prx/libSceAgcDriver/tests/Recorder.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/Recorder.cpp @@ -1235,6 +1235,44 @@ void largeLabelTests(Recorder& recorder) { Require(recorder.PendingLabels() == 0 && !Recorder::WideLabelIn(0, ~0ull) && !recorder.PendingLabelIn(slot, clear.size()) && !recorder.PendingWriteOverlaps(slot, clear.size()), "large label tests left entries, ranges or writes behind"); } +void storedBytesTests(Recorder& recorder) { + constexpr std::uint64_t ring = 0x74000; + std::array table{}; + for (std::size_t i = 0; i < table.size(); ++i) table[i] = static_cast(i + 1); + std::array next{}; + next.fill(std::byte{0x5a}); + const std::array one{std::byte{1}, std::byte{0}, std::byte{0}, std::byte{0}}; + std::array out{}; + const auto served = [](std::uint64_t address, std::span bytes) { return Recorder::LookupStoredBytes(address, bytes); }; + recorder.Sync(); + Require(!served(ring, out), "stored bytes are served from an empty table"); + recorder.NoteLabel(ring, table, 200, 0); + Require(served(ring + 0x40, out) && std::equal(out.begin(), out.end(), table.begin() + 0x40), "a wide store is not served"); + std::array whole{}; + Require(served(ring, whole) && whole == table, "a whole wide store is not served"); + Require(!served(ring + table.size() - 4, out), "bytes past a wide store are served"); + Require(!served(ring + 2, std::span(out).first(4)) && !served(ring, std::span(out).first(2)), "a partial dword is served"); + recorder.NoteLabel(ring + 0x80, next, 201, 0); + std::array straddle{}; + Require(served(ring + 0x78, straddle) && std::equal(straddle.begin(), straddle.begin() + 8, table.begin() + 0x78) && std::all_of(straddle.begin() + 8, straddle.end(), [](std::byte value) { return value == std::byte{0x5a}; }), "overlapping wide stores do not compose newest first"); + recorder.NoteLabel(ring + 0x10, one, 202, 0); + Require(served(ring + 0x0c, out) && std::equal(out.begin(), out.begin() + 4, table.begin() + 0x0c) && std::equal(out.begin() + 4, out.end(), one.begin()), "a label inside a wide store does not win"); + recorder.NoteLabel(ring, next, 203, 0); + Require(!Recorder::LookupLabel(ring + 0x10, 4, 0).has_value() && served(ring + 0x10, out) && std::all_of(out.begin(), out.end(), [](std::byte value) { return value == std::byte{0x5a}; }), "a wide store over a label does not replace it"); + const auto tag = AgcDriver::GuestMemory::GpuLockThreadTag(); + Recorder::NoteQueuedLabel(ring + 0x104, one, 204, tag); + Require(!served(ring + 0x100, out), "a store with a queued label over it is served"); + Recorder::ForgetQueuedLabels(); + Require(served(ring + 0x100, out), "a forgotten queued label still refuses the store"); + recorder.NotePendingWrite(ring + 0x20, 4); + Require(!served(ring, std::span(out).first(4)), "an overwritten wide store is served"); + Require(served(ring + 0x100, out), "a write over other stores refused this one"); + recorder.NotePendingWrite(ring + 0x14c, 4); + Require(!served(ring + 0x148, out), "a write inside a wide store did not refuse it"); + recorder.Sync(); + Require(!served(ring + 0x100, out) && !Recorder::WideLabelIn(ring, 0x400), "stored bytes outlived their batch"); +} + // (6) GuestMemory::UnchangedSinceCollected: false outside the watched arena, and around a // MarkWritten or a CPU write of the block inside it. void unchangedSinceTests() { @@ -8155,6 +8193,11 @@ int main(int argc, char** argv) { settledBaselineTests(device, recorder); return 0; } + if (argc == 2 && std::string_view(argv[1]) == "--stored-bytes-only") { + storedBytesTests(recorder); + std::cout << "stored bytes tests passed\n"; + return 0; + } if (argc == 2 && std::string_view(argv[1]) == "--completion-labels-only") { completionCountTests(device, recorder); afterRecordedWorkTests(device, recorder); @@ -8162,6 +8205,7 @@ int main(int argc, char** argv) { labelTests(recorder); lateLabelTests(recorder); largeLabelTests(recorder); + storedBytesTests(recorder); std::cout << "Completion label storage and ordering tests passed\n"; return 0; } @@ -8303,6 +8347,7 @@ int main(int argc, char** argv) { labelTests(recorder); lateLabelTests(recorder); largeLabelTests(recorder); + storedBytesTests(recorder); unchangedSinceTests(); closeRaceTests(device, recorder); keyProofTests(device, recorder); diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/DumpedConstantCapture.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/DumpedConstantCapture.cpp new file mode 100644 index 000000000000..a2a3d8844b0d --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/tests/execution/DumpedConstantCapture.cpp @@ -0,0 +1,210 @@ +#include "prx/libSceAgcDriver/Execution/include/Driver/Driver.hpp" +#include "prx/libSceAgcDriver/Execution/include/GuestMemory.hpp" +#include "prx/libSceAgcDriver/Execution/include/ShaderMemory.hpp" +#include "prx/libSceAgcDriver/Graphics/include/Recorder.hpp" +#include "prx/libSceAgcDriver/Graphics/include/Texture.hpp" +#include "prx/libSceAgcDriver/Submit/include/Dcb.hpp" +#include "prx/libc/include/GuestAllocations.hpp" +#include "VulkanTestDevice.hpp" +#ifdef _WIN32 +#ifndef NOMINMAX +#define NOMINMAX +#endif +#include +#endif +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +using AgcDriver::Graphics::Require; + +constexpr std::size_t BlockBytes = 0x40000; +constexpr std::uint64_t TableOffset = 0x1000; +constexpr std::uint32_t TableWords = 36; +constexpr std::uint64_t ColorOffset = 0x8000; +constexpr std::size_t ColorBytes = 1024; +constexpr std::uint64_t FillOffset = 0x20000; +constexpr std::uint32_t FillBytes = 0x20000; + +alignas(256) constexpr std::array TriangleVertexCode{ + 0x7e000d05u, 0x080200f4u, 0x10020300u, 0x100202f4u, 0x060202f3u, 0x060400f3u, 0x10040500u, 0x060404f3u, + 0x7e060280u, 0x7e0802f2u, 0xf80008cfu, 0x04030201u, 0xbf810000u, +}; +alignas(256) constexpr std::array ConstantPixelCode{0xf4000080u, 0xfa000000u, 0xbf8cc07fu, 0x7e000202u, 0x7e020280u, 0xf800180fu, 0x00010100u, 0xbf810000u}; +alignas(256) std::array FirstConstant{0.25f, 0.0f, 0.0f, 0.0f}; + +struct Header { + Shader shader{}; + ShaderUserData userData{}; +}; + +alignas(8) Header VertexHeader{}; +alignas(8) Header PixelHeader{}; + +void Register(Header& header, const std::uint32_t* code, std::size_t bytes, std::uint8_t type) { + header.shader.file_header = 0x34333231u; + header.shader.version = 0x18u; + header.shader.header_size = sizeof(Header); + header.shader.shader_size = static_cast(bytes); + header.shader.code = code; + header.shader.type = type; + header.shader.user_data = &header.userData; + AgcDriverRegisterShader_nid_postfix(&header.shader); +} + +class GuestBlock { +public: + GuestBlock() { +#ifdef _WIN32 + block = static_cast(VirtualAlloc(nullptr, BlockBytes, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)); +#else + block = static_cast(std::aligned_alloc(65536, BlockBytes)); +#endif + Require(block != nullptr, "dumped constant capture: cannot allocate the guest block"); + std::memset(block, 0, BlockBytes); + GuestAllocations::Mutation().Add(block, BlockBytes, true, true, true); + } + + ~GuestBlock() { + AgcDriver::Graphics::StorageTexture::FlushPending(Address(), BlockBytes, nullptr, "test release"); + GuestAllocations::Mutation().Remove(block); +#ifdef _WIN32 + VirtualFree(block, 0, MEM_RELEASE); +#else + std::free(block); +#endif + } + + GuestBlock(const GuestBlock&) = delete; + GuestBlock& operator=(const GuestBlock&) = delete; + + std::uint8_t* Data() const { return block; } + std::uint64_t Address() const { return static_cast(reinterpret_cast(block)); } + +private: + std::uint8_t* block = nullptr; +}; + +void Append(std::vector& commands, std::uint32_t opcode, std::initializer_list payload) { + commands.push_back(0xc0000000u | (static_cast(payload.size() - 1) << 16u) | (opcode << 8u)); + commands.insert(commands.end(), payload); +} + +void AppendState(std::vector& commands, std::uint64_t color) { + const auto vertex = reinterpret_cast(TriangleVertexCode.data()); + const auto pixel = reinterpret_cast(ConstantPixelCode.data()); + const std::vector> context{ + {0x2d5, 0x2000}, + {0x1b6, 0}, {0x207, 0}, {0x200, 0}, {0x203, 0x800}, + {0x2dc, 0xaa00}, {0x2f8, 0}, {0x292, 2}, {0x293, 0}, + {0x80, 0}, {0x8d, 0}, {0x83, 0xffff}, {0x8c, 0xa}, + {0x2f9, 0x2d}, {0x313, 0x6000}, {0x30e, 0xffffffff}, {0x30f, 0xffffffff}, + {0x206, 0x43f}, {0x204, 0x80000}, {0x205, 0x240}, + {0x8e, 0xf}, {0x8f, 0xf}, {0x202, 0xcc0010}, + {0x1c4, 0}, {0x1c5, 9}, {0x1c3, 4}, {0x31c, 0x28028}, + {0x31b, 0}, {0x31d, 0}, {0x3b0, (63u << 14u) | 3u}, + {0x3b8, 0x9000000}, {0x1e0, 0}, + {0xc, 0}, {0xd, 0x40040}, + {0x81, 0x80000000}, {0x82, 0x40040}, + {0x90, 0x80000000}, {0x91, 0x40040}, + {0x94, 0x80000000}, {0x95, 0x40040}, + {0x318, static_cast(color >> 8u)}, {0x390, static_cast(color >> 40u)}, + {0x10f, std::bit_cast(32.0f)}, {0x110, std::bit_cast(32.0f)}, + {0x111, std::bit_cast(-2.0f)}, {0x112, std::bit_cast(2.0f)}, + {0x113, std::bit_cast(1.0f)}, {0x114, 0}, + {0xb4, 0}, {0xb5, std::bit_cast(1.0f)}, + {0x2fe, 0}, {0x302, 0}, {0x306, 0}, {0x30a, 0}, + }; + const std::vector> shader{ + {0xc8, static_cast(vertex >> 8u)}, {0xc9, static_cast(vertex >> 40u)}, {0x8b, 0}, {0x8c, 0}, + {0x008, static_cast(pixel >> 8u)}, {0x009, static_cast(pixel >> 40u)}, {0x00b, 2u << 1u}, + }; + Append(commands, 0x79, {0x242, 4}); + for (const auto& [offset, value] : context) Append(commands, 0x69, {offset, value}); + for (const auto& [offset, value] : shader) Append(commands, 0x76, {offset, value}); +} + +void AppendConstantDraw(std::vector& commands, std::uint64_t constant) { + Append(commands, 0x76, {0x00c, static_cast(constant), static_cast(constant >> 32u)}); + Append(commands, 0x2d, {3, 2}); +} + +void AppendConstantRamDump(std::vector& commands, const std::vector& table, std::uint64_t destination) { + commands.push_back(0xc0000000u | (static_cast(table.size()) << 16u) | (0x81u << 8u)); + commands.push_back(0x100); + commands.insert(commands.end(), table.begin(), table.end()); + Append(commands, 0x83, {0x100, static_cast(table.size()), static_cast(destination), static_cast(destination >> 32u)}); +} + +int DumpedConstantIsServedFromTheStore() { + const GuestBlock block; + Register(VertexHeader, TriangleVertexCode.data(), sizeof(TriangleVertexCode), 2); + Register(PixelHeader, ConstantPixelCode.data(), sizeof(ConstantPixelCode), 1); + std::vector table(TableWords); + for (std::uint32_t word = 0; word < TableWords; ++word) table[word] = 0x10000u + word; + table[0] = std::bit_cast(1.0f); + const auto destination = block.Address() + TableOffset; + const auto fill = block.Address() + FillOffset; + std::vector commands; + AppendState(commands, block.Address() + ColorOffset); + AppendConstantDraw(commands, reinterpret_cast(FirstConstant.data())); + Append(commands, 0x50, {0x40000000u, 0x5a5a5a5au, 0, static_cast(fill), static_cast(fill >> 32u), FillBytes}); + AppendConstantRamDump(commands, table, destination); + AppendConstantDraw(commands, destination); + const auto storesBefore = AgcDriver::Graphics::Recorder::StoreCounts().stores; + const auto knownBefore = AgcDriver::ShaderMemory::KnownValues(); + Packet packet{commands.data(), static_cast(commands.size()), 0, {}}; + Require(sceAgcDriverSubmitDcb(&packet) == 0, "dumped constant capture: the submission failed"); + AgcDriverWaitIdle_nid_postfix(); + const auto stored = AgcDriver::Graphics::Recorder::StoreCounts().stores - storesBefore; + const auto known = AgcDriver::ShaderMemory::KnownValues(); + AgcDriver::GuestMemory::FlushGpuWrites(destination, TableWords * 4u); + Require(std::memcmp(block.Data() + TableOffset, table.data(), TableWords * 4u) == 0, "dumped constant capture: the constant RAM dump did not land in guest memory"); + AgcDriver::GuestMemory::FlushGpuWrites(block.Address() + ColorOffset, ColorBytes); + const auto brightest = *std::max_element(block.Data() + ColorOffset, block.Data() + ColorOffset + ColorBytes); + Require(brightest == 255, "dumped constant capture: the draw reading the dumped constant 1.0 wrote " + std::to_string(brightest) + ", expected 255"); + if (stored == 0) { + std::puts("skipped, the constant RAM dump was not recorded on the GPU (the guest block is not host-imported)"); + return VulkanTestSkipped; + } + Require(known.served > knownBefore.served, "dumped constant capture: the capture of the draw after a constant RAM dump recorded on the GPU waited for the GPU instead of reading the dumped words"); + if (std::getenv("APS5_VERIFY_KNOWN_VALUES") != nullptr) Require(known.mismatches == knownBefore.mismatches, "dumped constant capture: a word served from the recorded dump differs from what the GPU stored"); + std::cout << "a capture after a constant RAM dump read " << known.served - knownBefore.served << " dumped words without waiting for the GPU\n"; + return 0; +} + +} + +int main() { +#ifdef _WIN32 + _putenv_s("APS5_PIPELINED_DRAWS", "0"); +#else + setenv("APS5_PIPELINED_DRAWS", "0", 1); +#endif + try { + { + const auto device = OpenVulkanTestDevice(); + if (!device) return VulkanTestSkipped; + } + const auto result = DumpedConstantIsServedFromTheStore(); + AgcDriverShutdown_nid_postfix(); + return result; + } catch (const std::exception& error) { + std::cerr << error.what() << '\n'; + AgcDriverShutdown_nid_postfix(); + return 1; + } +} From 4e16f45972842bf17eb0af7bb2c9568053b0d0d3 Mon Sep 17 00:00:00 2001 From: Savvanis Spyros Date: Tue, 20 Oct 2026 16:23:55 +0300 Subject: [PATCH 3/5] perf(agc): store labels in unregistered host memory on the GPU A label or store into memory no host import covers made the recording thread wait for all recorded work and write it with the CPU (#1458). VideoOut's buffer labels live in host memory no guest allocation covers, so every PS4 flip label drained the device under the GPU lock: the draw committer waited about 63 ms per frame and the queue worker waited for the committer at the next DUMP_CONST_RAM. Such memory is now imported for the batch that stores into it, when its pages are committed private read-write memory of one allocation and no guest range overlaps them. The GPU stores the label in stream order, as the console's CP does. Memory that fails those checks or the import keeps the wait. Co-Authored-By: Claude Opus 5.5 --- .../Execution/src/VulkanDevice.cpp | 7 +- .../Graphics/include/GuestBufferMemory.hpp | 1 + .../Graphics/src/GuestBufferMemory.cpp | 24 ++++ .../execution/UnregisteredLabelOnGpu.cpp | 117 ++++++++++++++++++ docs/dev/debt/libSceAgcDriver.md | 2 +- 5 files changed, 149 insertions(+), 2 deletions(-) create mode 100644 core/libs/prx/libSceAgcDriver/tests/execution/UnregisteredLabelOnGpu.cpp diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp index e108c48790c6..b4bf57167895 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp @@ -2174,6 +2174,8 @@ int VulkanDevice::WriteLabelOnGpu(std::uint64_t address, std::spanbuffer, address - import->base, bytes, address); }; + const auto recordStore = [&] { + recorder.RecordStore(import->buffer, address - import->base, bytes, address); + if (unregistered != nullptr) recorder.Keep(unregistered); + }; // Only a write-back that can land over these bytes (a listed copied writer of the range, as // FillBuffer tests) puts the label behind the completions; any other pending completion // stores elsewhere. Debug aid: APS5_LABEL_GATE_ALL=1 gates on any completion, as before (a diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/GuestBufferMemory.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/GuestBufferMemory.hpp index 771319535347..f0f2c3dc44ef 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/GuestBufferMemory.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/GuestBufferMemory.hpp @@ -66,6 +66,7 @@ void SetImportWatch(const Context& context, ImportWatch watch); // (alignment and budget permitting), or null. Bytes at `address` are at `address - import->base` in // the import's buffer. const HostImport* HostImportFor(const Context& context, std::uint64_t address, std::size_t bytes); +std::shared_ptr UnregisteredHostImport(const Context& context, std::uint64_t address, std::size_t bytes); void SetHostImportWindow(std::uint64_t bytes); // Tests: the window of one large registered range (64 MiB) and the import budget (0: the configured one). void SetHostImportRangeWindow(std::uint64_t bytes); diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/GuestBufferMemory.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/GuestBufferMemory.cpp index 030ce590942e..ef894959c96a 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/GuestBufferMemory.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/GuestBufferMemory.cpp @@ -2613,6 +2613,30 @@ const HostImport* HostImportFor(const Context& context, std::uint64_t address, s return importAccess(context, state, address, address + bytes, lease); } +std::shared_ptr UnregisteredHostImport(const Context& context, std::uint64_t address, std::size_t bytes) { + const auto alignment = context.hostImportAlignment; + if (alignment == 0 || bytes == 0 || address > std::numeric_limits::max() - bytes - 2 * alignment) return nullptr; + const auto base = address / alignment * alignment; + const auto end = (address + bytes + alignment - 1) / alignment * alignment; + if (const auto range = GuestAllocations::GuestAllocationsLookup_nid_postfix(static_cast(base), true); range != nullptr && range->address < end) return nullptr; +#ifdef _WIN32 + const void* allocation = nullptr; + for (std::uint64_t cursor = base; cursor < end;) { + MEMORY_BASIC_INFORMATION info{}; + if (VirtualQuery(reinterpret_cast(cursor), &info, sizeof(info)) == 0 || info.State != MEM_COMMIT || info.Type != MEM_PRIVATE || info.Protect != PAGE_READWRITE) return nullptr; + if (allocation == nullptr) allocation = info.AllocationBase; + if (info.AllocationBase != allocation) return nullptr; + cursor = reinterpret_cast(info.BaseAddress) + info.RegionSize; + } +#endif + std::map made; + auto& entry = made.emplace(base, HostImport{base, end - base, VK_NULL_HANDLE, VK_NULL_HANDLE, 0}).first->second; + VkResult failure = VK_SUCCESS; + if (createHostPointerImport(context, entry, failure) != nullptr) return nullptr; + auto holder = std::make_shared(context.device, context.Function("vkDestroyBuffer"), context.Function("vkFreeMemory"), made.extract(base)); + return std::shared_ptr(holder, &holder->node.mapped()); +} + bool ImportMappedRanges(const Context& context, const GuestAllocations::Mapped& ranges, std::uint64_t generation, bool adoptDevice) { if (context.hostImportAlignment == 0) return true; ensurePinWaiter(); diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/UnregisteredLabelOnGpu.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/UnregisteredLabelOnGpu.cpp new file mode 100644 index 000000000000..f1286bb5f0d3 --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/tests/execution/UnregisteredLabelOnGpu.cpp @@ -0,0 +1,117 @@ +#include "prx/libSceAgcDriver/Execution/include/GuestMemory.hpp" +#include "prx/libSceAgcDriver/Execution/include/VulkanDevice.hpp" +#include "prx/libSceAgcDriver/Graphics/include/Context.hpp" +#include "prx/libc/include/GuestAllocations.hpp" +#include "VulkanTestDevice.hpp" +#ifdef _WIN32 +#ifndef NOMINMAX +#define NOMINMAX +#endif +#include +#endif +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +using AgcDriver::Graphics::Require; + +constexpr std::size_t BlockBytes = 65536; + +class HostBlock { +public: + HostBlock() { +#ifdef _WIN32 + block = static_cast(VirtualAlloc(nullptr, BlockBytes, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)); +#else + block = static_cast(std::aligned_alloc(BlockBytes, BlockBytes)); +#endif + Require(block != nullptr, "unregistered label: cannot allocate a host block"); + std::memset(block, 0, BlockBytes); + } + + ~HostBlock() { + if (registered) GuestAllocations::Mutation().Remove(block); +#ifdef _WIN32 + VirtualFree(block, 0, MEM_RELEASE); +#else + std::free(block); +#endif + } + + HostBlock(const HostBlock&) = delete; + HostBlock& operator=(const HostBlock&) = delete; + + void Register() { + GuestAllocations::Mutation().Add(block, BlockBytes, true, true, true); + registered = true; + } + + volatile std::uint32_t* Words() { return reinterpret_cast(block); } + + std::uint64_t Address() const { return static_cast(reinterpret_cast(block)); } + +private: + std::uint8_t* block = nullptr; + bool registered = false; +}; + +int StoreLabel(AgcDriver::VulkanDevice& device, std::uint64_t address, std::uint32_t value, std::uint64_t stamp) { + return device.WriteLabelOnGpu(address, std::as_bytes(std::span(&value, 1)), stamp, 0); +} + +void RequireReason(int reason, int expected, const char* what) { + Require(reason == expected, ("unregistered label: " + std::string(what) + " returned reason " + std::to_string(reason) + " instead of " + std::to_string(expected)).c_str()); +} + +} + +int main() { + try { + HostBlock labels; + labels.Register(); + HostBlock unregistered; + auto device = OpenVulkanTestDevice(); + if (!device) return VulkanTestSkipped; + std::lock_guard lock(AgcDriver::GuestMemory::GpuMutex()); + const std::array pattern{0x11111111u, 0x22222222u, 0x33333333u, 0x44444444u}; + if (!device->FillBuffer(labels.Address() + 4096, 4096, pattern)) { + std::printf("skipped, the device does not import guest memory\n"); + return VulkanTestSkipped; + } + RequireReason(StoreLabel(*device, unregistered.Address() + 8, 0x5a5a0001u, 1), 0, "a label in unregistered host memory"); + Require(unregistered.Words()[2] == 0, "unregistered label: the label landed before its batch was submitted"); +#ifdef _WIN32 + DWORD previous = 0; + Require(VirtualProtect(reinterpret_cast(unregistered.Address() + 4096), 4096, PAGE_READONLY, &previous) != 0, "unregistered label: cannot protect the read-only page"); + RequireReason(StoreLabel(*device, unregistered.Address() + 4096 + 8, 0x5a5a0003u, 3), 3, "a label in read-only unregistered memory"); +#endif + RequireReason(StoreLabel(*device, labels.Address() + 4, 0x5a5a0004u, 4), 0, "a label in registered GPU memory"); + device->SubmitRecorded(true); + const auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(10); + while (labels.Words()[1] != 0x5a5a0004u) { + Require(std::chrono::steady_clock::now() < deadline, "unregistered label: the later label never landed"); + std::this_thread::sleep_for(std::chrono::microseconds(100)); + } + const std::uint32_t seen = unregistered.Words()[2]; + device->WaitIdle(); + std::array message{}; + std::snprintf(message.data(), message.size(), "unregistered label: the label held 0x%08x when a later label had landed, 0x%08x after the device went idle", seen, unregistered.Words()[2]); + Require(seen == 0x5a5a0001u && unregistered.Words()[2] == 0x5a5a0001u, message.data()); + Require(unregistered.Words()[1024 + 2] == 0, "unregistered label: the refused label was stored"); + std::puts("unregistered label tests passed"); + return 0; + } catch (const std::exception& error) { + std::cerr << error.what() << '\n'; + return 1; + } +} diff --git a/docs/dev/debt/libSceAgcDriver.md b/docs/dev/debt/libSceAgcDriver.md index 017849c1327a..f9bd6290af57 100644 --- a/docs/dev/debt/libSceAgcDriver.md +++ b/docs/dev/debt/libSceAgcDriver.md @@ -93,7 +93,7 @@ - A [flip inside a COND_EXEC range](../../../core/libs/prx/libSceAgcDriver/Execution/src/Driver/Packets/CommandValidation.cpp) throws: the flip is reserved with the video output when the buffer is submitted, and how the console withdraws a skipped one is unknown. - A [COND_EXEC range](../../../core/libs/prx/libSceAgcDriver/Execution/src/Driver/Queues/Submission.cpp) must hold whole packets and end inside its command buffer. A chained INDIRECT_BUFFER or a REWIND inside a range throws, as what the CP does with the skipped dwords then is unknown. - A [COND_INDIRECT_BUFFER](../../../core/libs/prx/libSceAgcDriver/Execution/src/Driver/Queues/Submission.cpp) (`sceAgcCbBranch`) runs only with the always-pass compare function; a comparison or a predicated packet throws. Modes 1 and 2 run the first buffer, assumed to be the if-then and if-then-else modes of AMD's PM4 packet. [sceAgcCbBranch](../../../core/libs/prx/libSceAgc/Cb/src/Branch.cpp) does not check the compare address of an always-pass branch or the address of an empty buffer, as PPSA14632 passes an uninitialised compare address and a null else buffer of 0 dwords. -- A [label or store](../../../core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp) (`RELEASE_MEM`, `WRITE_DATA`, `DMA_DATA`) into guest memory the device has no host import of waits for all recorded work and is then written by the CPU, so the queue worker stalls once per such label. The console's CP stores it in stream order without that stall. +- A [label or store](../../../core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp) (`RELEASE_MEM`, `WRITE_DATA`, `DMA_DATA`) into memory the device cannot import waits for all recorded work and is then written by the CPU, so the queue worker stalls once per such label. The console's CP stores it in stream order without that stall. Host memory no guest allocation covers (VideoOut's buffer labels, a native thread stack) is imported for the batch that stores into it when its pages are committed private read-write memory of one allocation; memory that fails those checks or the import still takes the wait. - [WRITE_DATA to thread-trace user-data registers](../../../core/libs/prx/libSceAgcDriver/Execution/src/Pm4.cpp) (libSceAgcDriver) updates the queue's UCONFIG values for register destinations `0xc340..0xc347`, including repeated writes to one address; these are not guest-memory labels. The range follows AMD's GFX10 `SQ_THREAD_TRACE_USERDATA_0..7` definitions in [the Linux register header](https://github.com/torvalds/linux/blob/master/drivers/gpu/drm/amd/include/asic_reg/gc/gc_10_1_0_offset.h) and the packets emitted by PPSA21564's bundled AGC driver before its EOP flip. Other register destinations throw. GPU thread-trace capture and its user-data stream are not emitted; only the final register state is retained. Console trace behavior is unverified. - [WRITE_DATA with DST_SEL 3](../../../core/libs/prx/libSceAgcDriver/Execution/src/Pm4.cpp) (libSceAgcDriver) writes guest memory like DST_SEL 5. AMD's GFX10 header names 3 the GDS, but Killzone: Liberation (PPSA11142) writes its frame fence with `sceAgcDcbWriteData(dst 6, cache policy 3, write confirm)`, which the SPRX-confirmed encoding ([OpenAGC](https://github.com/OpenAGC/OpenAGC/blob/main/src/cb_builders.c)) turns into DST_SEL 3 with a 40-bit label address in the title's own memory that `RELEASE_MEM` and `WAIT_REG_MEM` then use; the console must write that label or the title would wait on it forever. Whether the console routes it through the GDS or a cache is unknown - [SET_*_REG_INDIRECT](../../../core/libs/prx/libSceAgcDriver/Execution/src/Driver/Queues/Submission.cpp) (libSceAgcDriver) reads its register list when the command buffer is submitted, with the packets. The console's graphics PFP reads it when it reaches the packet, so a list written after the submission (by the CPU, or by GPU work ahead of the packet behind PFP_SYNC_ME) is read here before that write. From 75bc9a49b765d2bb909a4217c52c84fae3058e4f Mon Sep 17 00:00:00 2001 From: Savvanis Spyros Date: Wed, 21 Oct 2026 14:07:46 +0300 Subject: [PATCH 4/5] fix(agc): wait for stores into a host copy's destination instead of draining A DMA_DATA copy into host memory that no import covers waits for the batches that write its source (Recorder::SyncThrough) and copies on the CPU, unless something can still store over its destination; then it drains the device. Until the previous commit a label into such memory was written by the CPU after a drain, so nothing was pending there. Now that label is a GPU store in the open batch, and a copy behind a label into its destination drained: agc_driver failed in its label case with "a copy into host memory drained instead of syncing its source". The copy now waits for the batches that store into its destination as it does for its source, then checks again. Only what still stores there after that wait (a storage image's write-back, a unit shadow, a label another queue has not recorded yet) drains as before. Co-Authored-By: Claude Opus 5.5 --- .../src/Driver/Packets/PacketMemory.cpp | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Packets/PacketMemory.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Packets/PacketMemory.cpp index 452c674ab325..272082c4beed 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Packets/PacketMemory.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Packets/PacketMemory.cpp @@ -157,12 +157,16 @@ bool Driver::preparePacketMemory(const Submission& submission, QueueState& queue if (outcome.path == 1 || outcome.path == 3) { wroteOnGpu = true; drained = false; - } else if (outcome.path == 2 && !Graphics::RegisteredReadableCovers(copy->destination, copy->bytes) && !localDevice->StoresPendingOver(copy->destination, copy->bytes)) { - Graphics::StorageTexture::FlushPending(copy->source, copy->bytes, nullptr, "buffer copy source", Graphics::PublishScope::Whole); - if (auto* recorder = Graphics::Recorder::Active()) recorder->SyncThrough(copy->source, copy->bytes); - ++copiesToHostMemory; - orderedAlready = true; - drained = false; + } else if (outcome.path == 2 && !Graphics::RegisteredReadableCovers(copy->destination, copy->bytes)) { + auto* recorder = Graphics::Recorder::Active(); + if (recorder != nullptr && localDevice->StoresPendingOver(copy->destination, copy->bytes)) recorder->SyncThrough(copy->destination, copy->bytes); + if (!localDevice->StoresPendingOver(copy->destination, copy->bytes)) { + Graphics::StorageTexture::FlushPending(copy->source, copy->bytes, nullptr, "buffer copy source", Graphics::PublishScope::Whole); + if (recorder != nullptr) recorder->SyncThrough(copy->source, copy->bytes); + ++copiesToHostMemory; + orderedAlready = true; + drained = false; + } } } } From 369c2c3d43dd15986737bc04cc9a734166a6ae3f Mon Sep 17 00:00:00 2001 From: Savvanis Spyros Date: Tue, 20 Oct 2026 18:50:15 +0300 Subject: [PATCH 5/5] perf(recompiler): translate GCN buffer formats without a private table Registration modules read a GCN V#'s word 3 in the shader, and gcnWord3 mapped its DATA_FORMAT and NUM_FORMAT through a 128-entry Private array that every buffer access stored again before indexing it. Drivers keep that array in per-invocation scratch: on the RX 9070 XT each pixel shader of Monopoly Plus's language screen used 528 bytes of scratch and wrote the table up to 60 times per invocation. The lookup is now a helper function that packs the table four entries to a word and picks the word with a select tree, so it stays in registers and each access calls it once. Co-Authored-By: Claude Opus 5.5 --- core/libs/prx/libSceAgcDriver/CMakeLists.txt | 2 + .../tests/execution/GcnBufferFormatLookup.cpp | 211 ++++++++++++++++++ .../SpirvBackend/SpirvEmitterState.hpp | 2 +- .../SpirvBackend/src/SpirvRuntimeBuffer.cpp | 54 ++++- 4 files changed, 258 insertions(+), 11 deletions(-) create mode 100644 core/libs/prx/libSceAgcDriver/tests/execution/GcnBufferFormatLookup.cpp diff --git a/core/libs/prx/libSceAgcDriver/CMakeLists.txt b/core/libs/prx/libSceAgcDriver/CMakeLists.txt index 277ec41e4631..142974ed3012 100644 --- a/core/libs/prx/libSceAgcDriver/CMakeLists.txt +++ b/core/libs/prx/libSceAgcDriver/CMakeLists.txt @@ -1480,6 +1480,8 @@ target_include_directories(agc_driver_pipeline_journal_tests PRIVATE $) +target_include_directories(agc_driver_gcn_buffer_format_lookup_tests PRIVATE $) + target_include_directories(agc_driver_prepared_publication_tests PRIVATE $) target_include_directories(agc_driver_prepared_graphics_tests PRIVATE $) diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/GcnBufferFormatLookup.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/GcnBufferFormatLookup.cpp new file mode 100644 index 000000000000..4673891179b9 --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/tests/execution/GcnBufferFormatLookup.cpp @@ -0,0 +1,211 @@ +#include "prx/libSceAgcDriver/Execution/include/VulkanDevice.hpp" +#include "prx/libSceAgcDriver/Graphics/include/Draw.hpp" +#include "Recompiler.hpp" +#include "RdnaDecoder/RdnaDescriptorFormat.hpp" +#include "RdnaDecoder/RdnaInstructionDecoder.hpp" +#include "VulkanTestDevice.hpp" +#ifdef _WIN32 +#ifndef NOMINMAX +#define NOMINMAX +#endif +#include +#else +#include +#endif +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +using AgcDriver::Graphics::Require; +using ShaderRecompiler::ShaderStage; + +constexpr std::uint32_t Width = 64; +constexpr std::uint32_t Height = 32; +constexpr std::uint32_t Vertices = 3; +constexpr std::uint32_t Fill = 0xdeadbeefu; +constexpr std::size_t BlockBytes = 65536; +constexpr std::uintptr_t GcnAddressLimit = std::uintptr_t{1} << 44u; +constexpr std::array InputWords{0x12345678u, 0x9abcdef0u, 0x0badf00du, 0x600dcafeu}; +alignas(256) std::array Pixels{}; + +alignas(256) constexpr std::array VertexCode{ + 0xe0300000u, 0x80010100u, 0xbf8c0f70u, 0xe0700000u, 0x80020100u, 0xf80008cfu, 0x03020100u, 0xbf810000u, +}; + +alignas(256) constexpr std::array PixelCode{ + 0x7e0e02f2u, 0xf800180fu, 0x07070707u, 0xbf810000u, +}; + +class LowBlock { +public: + LowBlock() { +#ifdef _WIN32 + block = static_cast(VirtualAlloc(nullptr, BlockBytes, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)); +#else + void* mapped = mmap(reinterpret_cast(std::uintptr_t{1} << 36u), BlockBytes, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); + block = mapped == MAP_FAILED ? nullptr : static_cast(mapped); +#endif + Require(block != nullptr, "GCN buffer format lookup: cannot allocate the buffer block"); + Require(reinterpret_cast(block) + BlockBytes <= GcnAddressLimit, "GCN buffer format lookup: the buffer block lies above the 44-bit GCN V# address range"); + } + + ~LowBlock() { +#ifdef _WIN32 + VirtualFree(block, 0, MEM_RELEASE); +#else + munmap(block, BlockBytes); +#endif + } + + LowBlock(const LowBlock&) = delete; + LowBlock& operator=(const LowBlock&) = delete; + + std::span Input() const { return std::span(block, 4); } + std::span Output() const { return std::span(block + 64, 4); } + +private: + std::uint32_t* block = nullptr; +}; + +std::array BufferDescriptor(const void* data, std::uint32_t bytes, std::uint32_t dataFormat, std::uint32_t numberFormat) { + const auto address = reinterpret_cast(data); + return {static_cast(address), static_cast((address >> 32u) & 0xffffu), bytes, 0xfacu | (numberFormat << 12u) | (dataFormat << 15u)}; +} + +std::vector UserData(const LowBlock& block, std::uint32_t dataFormat, std::uint32_t numberFormat) { + std::vector userData(12, 0u); + const auto input = BufferDescriptor(block.Input().data(), 16u, dataFormat, numberFormat); + const auto output = BufferDescriptor(block.Output().data(), 16u, 4u, 4u); + std::copy(input.begin(), input.end(), userData.begin() + 4); + std::copy(output.begin(), output.end(), userData.begin() + 8); + return userData; +} + +ShaderRecompiler::RecompileRequest VertexRequest(std::span userData, const ShaderRecompiler::SpirvTarget& target, std::span memory) { + ShaderRecompiler::RecompileRequest request{ + {ShaderStage::Vertex, reinterpret_cast(VertexCode.data()), VertexCode, 0, {}}, + {64u, 0, userData, std::nullopt, std::nullopt, ShaderRecompiler::ShaderVertexStageInfo{}, memory}, + target, + {0, 0, 0, 64} + }; + request.useCache = false; + return request; +} + +std::uint32_t PrivateStores(std::span words) { + std::set privateMemory; + std::uint32_t stores = 0; + for (std::size_t offset = 5; offset < words.size();) { + const auto count = words[offset] >> spv::WordCountShift; + Require(count != 0 && count <= words.size() - offset, "GCN buffer format lookup: malformed SPIR-V instruction"); + const auto opcode = words[offset] & spv::OpCodeMask; + if (opcode == spv::OpVariable && count >= 4 && words[offset + 3] == spv::StorageClassPrivate) privateMemory.insert(words[offset + 2]); + if ((opcode == spv::OpAccessChain || opcode == spv::OpInBoundsAccessChain) && count >= 4 && privateMemory.contains(words[offset + 3])) privateMemory.insert(words[offset + 2]); + if (opcode == spv::OpStore && count >= 3 && privateMemory.contains(words[offset + 1])) ++stores; + offset += count; + } + return stores; +} + +void CheckModule(const AgcDriver::VulkanDevice& device, const LowBlock& block, std::span memory) { + auto target = device.Target(); + target.registrationModules = true; + const auto userData = UserData(block, 4u, 4u); + const auto result = ShaderRecompiler::Recompile(VertexRequest(userData, target, memory)); + Require(result.registrationModule, "GCN buffer format lookup: the vertex shader was not emitted in registration form"); + const auto stores = PrivateStores(result.spirv.Words()); + Require(stores == 0u, "GCN buffer format lookup: the registration module stores " + std::to_string(stores) + " times into private memory to translate DATA_FORMAT and NUM_FORMAT, which drivers keep in per-invocation scratch"); +} + +void Draw(AgcDriver::VulkanDevice& device, const LowBlock& block, std::uint32_t dataFormat, std::uint32_t numberFormat, std::span vertexMemory, const ShaderRecompiler::RecompileResult& pixelResult, std::uint32_t vertexPush, std::vector& registrationModule) { + Pixels.fill(std::byte{0x40}); + std::copy(InputWords.begin(), InputWords.end(), block.Input().begin()); + std::fill(block.Output().begin(), block.Output().end(), Fill); + const auto userData = UserData(block, dataFormat, numberFormat); + const auto vertexResult = ShaderRecompiler::Recompile(VertexRequest(userData, device.Target(), vertexMemory)); + const auto what = "DATA_FORMAT " + std::to_string(dataFormat) + " NUM_FORMAT " + std::to_string(numberFormat); + Require(static_cast(vertexResult.pushConstants.size()) == vertexPush, "GCN buffer format lookup, " + what + ": the vertex push constants changed size"); + if (device.Target().registrationModules) { + if (registrationModule.empty()) registrationModule = vertexResult.spirv.Copy(); + Require(std::ranges::equal(vertexResult.spirv.Words(), registrationModule), "GCN buffer format lookup, " + what + ": registration modules: the V# specialized the vertex module"); + } + const std::array shaders{{ + {ShaderStage::Vertex, &vertexResult, 0}, + {ShaderStage::Fragment, &pixelResult, PixelPushOffset(vertexPush, device.Target())} + }}; + AgcDriver::Graphics::State state{}; + state.stages = {AgcDriver::Graphics::ShaderPath::Vertex, 0u, 64u, 64u, std::nullopt, std::nullopt}; + state.color = {reinterpret_cast(Pixels.data()), {Width, Height}, VK_FORMAT_R8G8B8A8_UNORM, Pixels.size(), 0xe4u}; + state.colors = {state.color}; + state.hasColorTarget = true; + state.renderExtent = {Width, Height}; + state.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST; + state.viewport = {0, static_cast(Height), static_cast(Width), -static_cast(Height), 0, 1}; + state.negativeOneToOne = false; + state.scissor = {{0, 0}, {Width, Height}}; + state.cullMode = VK_CULL_MODE_NONE; + state.frontFace = VK_FRONT_FACE_COUNTER_CLOCKWISE; + state.blend.colorWriteMask = 15; + state.blends = {state.blend}; + state.blendConstants = {}; + const AgcDriver::Pm4::DrawParameters draw{0, Vertices, 0, 1, 0, false}; + device.Draw(state, draw, shaders); + device.WaitIdle(); + const auto translated = ShaderRecompiler::GcnBufferFormats()[(dataFormat << 3u) | numberFormat]; + const auto expected = translated != 0u ? InputWords[0] : 0u; + const auto output = block.Output(); + char text[96]; + std::snprintf(text, sizeof(text), ": translated format %u, loaded 0x%08x, expected 0x%08x", translated, output[0], expected); + Require(output[0] == expected, "GCN buffer format lookup, " + what + text); + Require(std::all_of(output.begin() + 1, output.end(), [](std::uint32_t value) { return value == Fill; }), "GCN buffer format lookup, " + what + ": the store wrote past its dword"); +} + +} + +int main() { + try { + ShaderRecompiler::SetGcnGuestShaders(true); + const auto device = OpenVulkanTestDevice(); + if (!device) return VulkanTestSkipped; + const LowBlock block; + const std::array vertexMemory{{{reinterpret_cast(VertexCode.data()), std::as_bytes(std::span(VertexCode))}}}; + CheckModule(*device, block, vertexMemory); + const auto firstUserData = UserData(block, 4u, 4u); + const auto vertexPush = static_cast(ShaderRecompiler::Recompile(VertexRequest(firstUserData, device->Target(), vertexMemory)).pushConstants.size()); + ShaderRecompiler::ShaderPixelStageInfo pixel{}; + pixel.inputAddr = ShaderRecompiler::PixelInputBit(ShaderRecompiler::PixelInput::PositionX) | ShaderRecompiler::PixelInputBit(ShaderRecompiler::PixelInput::PositionY); + pixel.posX = true; + pixel.posY = true; + pixel.targetOutputMode[0] = 9; + pixel.targetExportMapping.fill(0xe4u); + const std::vector pixelUserData(8, 0u); + const std::array pixelMemory{{{reinterpret_cast(PixelCode.data()), std::as_bytes(std::span(PixelCode))}}}; + ShaderRecompiler::RecompileRequest fragment{ + {ShaderStage::Fragment, reinterpret_cast(PixelCode.data()), PixelCode, 0, {}}, + {64u, 0, pixelUserData, std::nullopt, pixel, std::nullopt, pixelMemory}, + device->Target(), + PixelPushLayout(vertexPush, device->Target()) + }; + fragment.useCache = false; + const auto pixelResult = ShaderRecompiler::Recompile(fragment); + std::vector registrationModule; + for (std::uint32_t dataFormat = 0; dataFormat < 16u; ++dataFormat) { + for (std::uint32_t numberFormat = 0; numberFormat < 8u; ++numberFormat) Draw(*device, block, dataFormat, numberFormat, vertexMemory, pixelResult, vertexPush, registrationModule); + } + std::puts("GCN buffer format lookup tests passed"); + return 0; + } catch (const std::exception& error) { + std::cerr << error.what() << '\n'; + return 1; + } +} diff --git a/core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvEmitterState.hpp b/core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvEmitterState.hpp index 8040f9e304ea..8d9245d3ee71 100644 --- a/core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvEmitterState.hpp +++ b/core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvEmitterState.hpp @@ -155,7 +155,7 @@ struct SpirvEmitterState { std::uint32_t loopGuardVisits = 0; std::uint32_t loopGuardPc = 0; std::uint32_t srgbTableVariable = 0; - std::uint32_t gcnBufferFormatVariable = 0; + std::uint32_t gcnBufferFormatFunction = 0; std::uint32_t gdsVariable = 0; std::uint32_t gdsLength = 0; std::uint32_t pushConstantVariable = 0; diff --git a/core/shader/recompiler/SpirvBackend/src/SpirvRuntimeBuffer.cpp b/core/shader/recompiler/SpirvBackend/src/SpirvRuntimeBuffer.cpp index f26550187337..9cb63b033818 100644 --- a/core/shader/recompiler/SpirvBackend/src/SpirvRuntimeBuffer.cpp +++ b/core/shader/recompiler/SpirvBackend/src/SpirvRuntimeBuffer.cpp @@ -50,18 +50,52 @@ std::uint32_t nonzero(SpirvEmitterState& state, std::uint32_t value) { return Binary(state, spv::OpINotEqual, TypeBool(state), value, ConstantU32(state, 0u)); } +std::uint32_t gcnBufferFormat(SpirvEmitterState& state, std::uint32_t index) { + const auto u32 = TypeU32(state); + if (state.gcnBufferFormatFunction == 0u) { + const auto id = state.module.AllocateId(); + struct Restore { + SpirvEmitterState& state; + std::uint32_t label; + ~Restore() { + state.module.EndHelperFunction(); + state.currentLabel = label; + } + }; + state.module.BeginHelperFunction(); + const Restore restore{state, state.currentLabel}; + state.module.AddName(id, "gcn_buffer_format"); + state.module.AddFunction(spv::OpFunction, u32, id, spv::FunctionControlMaskNone, state.module.Type(spv::OpTypeFunction, u32, u32)); + const auto parameter = state.module.AllocateId(); + state.module.AddFunction(spv::OpFunctionParameter, u32, parameter); + EmitLabel(state, state.module.AllocateId()); + const auto& formats = GcnBufferFormats(); + std::vector words; + for (std::size_t entry = 0; entry < formats.size(); entry += 4u) { + std::uint32_t packed = 0; + for (std::uint32_t byte = 0; byte < 4u; ++byte) packed |= static_cast(formats[entry + byte]) << (byte * 8u); + words.push_back(ConstantU32(state, packed)); + } + const auto word = Binary(state, spv::OpShiftRightLogical, u32, parameter, ConstantU32(state, 2u)); + for (std::uint32_t bit = 0; words.size() > 1u; ++bit) { + const auto odd = nonzero(state, Binary(state, spv::OpBitwiseAnd, u32, word, ConstantU32(state, 1u << bit))); + std::vector halves; + for (std::size_t pair = 0; pair < words.size(); pair += 2u) halves.push_back(words[pair] == words[pair + 1u] ? words[pair] : Select(state, u32, odd, words[pair + 1u], words[pair])); + words = std::move(halves); + } + const auto shift = Binary(state, spv::OpShiftLeftLogical, u32, Binary(state, spv::OpBitwiseAnd, u32, parameter, ConstantU32(state, 3u)), ConstantU32(state, 3u)); + state.module.AddFunction(spv::OpReturnValue, EmitBitFieldUExtract(state, words.front(), shift, ConstantU32(state, 8u))); + state.module.AddFunction(spv::OpFunctionEnd); + state.gcnBufferFormatFunction = id; + } + const auto result = state.module.AllocateId(); + state.module.AddFunction(spv::OpFunctionCall, u32, result, state.gcnBufferFormatFunction, index); + return result; +} + std::uint32_t gcnWord3(SpirvEmitterState& state, std::uint32_t word1, std::uint32_t word3) { const auto u32 = TypeU32(state); - const auto& formats = GcnBufferFormats(); - std::array words{}; - for (std::size_t index = 0; index < words.size(); ++index) words[index] = ConstantU32(state, formats[index]); - const auto arrayType = state.module.Type(spv::OpTypeArray, u32, ConstantU32(state, static_cast(words.size()))); - if (state.gcnBufferFormatVariable == 0) state.gcnBufferFormatVariable = state.module.DefineGlobalVariable(TypePointer(state, spv::StorageClassPrivate, arrayType), spv::StorageClassPrivate); - state.module.AddFunction(spv::OpStore, state.gcnBufferFormatVariable, state.module.Constant(spv::OpConstantComposite, arrayType, std::span(words))); - const auto pointer = state.module.AllocateId(); - state.module.AddFunction(spv::OpAccessChain, TypePointer(state, spv::StorageClassPrivate, u32), pointer, state.gcnBufferFormatVariable, field(state, word3, 12u, 7u)); - const auto format = state.module.AllocateId(); - state.module.AddFunction(spv::OpLoad, u32, format, pointer); + const auto format = gcnBufferFormat(state, field(state, word3, 12u, 7u)); const auto outOfBounds = Select(state, u32, nonzero(state, field(state, word1, 16u, 14u)), ConstantU32(state, 1u << 28u), ConstantU32(state, 3u << 28u)); const auto kept = Binary(state, spv::OpBitwiseAnd, u32, word3, ConstantU32(state, 0xc0e00fffu)); return Binary(state, spv::OpBitwiseOr, u32, Binary(state, spv::OpBitwiseOr, u32, kept, Binary(state, spv::OpShiftLeftLogical, u32, format, ConstantU32(state, 12u))), outOfBounds);